@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
package/dist/server/internal.js
CHANGED
|
@@ -1,39 +1,26 @@
|
|
|
1
|
-
import { c as drainWithDeadline, d as
|
|
2
|
-
import { r as RenderTimeoutError, t as DEFAULT_RENDER_TIMEOUT_MS } from "../_chunks/render-timeout-
|
|
3
|
-
import { n as isRscContentType, r as isRscRequest } from "../_chunks/rsc-media-type-
|
|
4
|
-
import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-
|
|
5
|
-
import { i as canonicalize, r as canonicalRequestPath } from "../_chunks/canonicalize-
|
|
6
|
-
import { a as
|
|
7
|
-
import { n as classifyUrlSegment, r as effectiveUrlSegment } from "../_chunks/segment-classify-
|
|
8
|
-
import { t as computeSegmentTreePaths } from "../_chunks/segment-keys-
|
|
9
|
-
import { i as requestContextAls, n as prebuiltCaptureAls, o as timingAls, t as earlyHintsSenderAls } from "../_chunks/als-registry-
|
|
10
|
-
import {
|
|
11
|
-
import { i as collectRouteModulepreloads, n as collectRouteCss, r as collectRouteFonts } from "../_chunks/build-manifest-
|
|
12
|
-
import { i as isRscCacheKeyShape, n as RSC_KEY_PARAM, r as appVisibleSearch, s as rscCacheKey, t as RSC_KEY_HEADERS } from "../_chunks/rsc-cache-key-
|
|
13
|
-
import { C as
|
|
14
|
-
import { a as
|
|
15
|
-
import { n as createSingleflight } from "../_chunks/singleflight-
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
1
|
+
import { c as drainWithDeadline, d as isAbortError, f as releaseReason, i as withResponseInit, n as discardResponseBody, o as concatBytes, p as onAbortUntil, r as nodeBodyOps, u as wrapResponseWithStreamTiming } from "../_chunks/node-response-B9aviPDa.js";
|
|
2
|
+
import { i as resolveRenderTimeoutMs, r as RenderTimeoutError, t as DEFAULT_RENDER_TIMEOUT_MS } from "../_chunks/render-timeout-MrrqD1wd.js";
|
|
3
|
+
import { n as isRscContentType, r as isRscRequest } from "../_chunks/rsc-media-type-m8jz9u6_.js";
|
|
4
|
+
import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-BL26HCDd.js";
|
|
5
|
+
import { i as canonicalize, r as canonicalRequestPath } from "../_chunks/canonicalize-CqK135BN.js";
|
|
6
|
+
import { _ as wasInvalidatedSince, a as devEntryKey, c as getDevSeed, d as isDevPrebuiltStoreActive, f as isHardReload, h as lastInvalidationEpochFor, m as currentInvalidationEpoch, n as clearDevPrebuiltStore, p as setDevSeed, r as devComponentTag, s as discardDevEntry, u as isDevPrebuiltCacheBypassed } from "../_chunks/dev-store-BvdqtHvK.js";
|
|
7
|
+
import { n as classifyUrlSegment, r as effectiveUrlSegment } from "../_chunks/segment-classify-Ho8jXWeC.js";
|
|
8
|
+
import { t as computeSegmentTreePaths } from "../_chunks/segment-keys-Y60KNc8C.js";
|
|
9
|
+
import { i as requestContextAls, n as prebuiltCaptureAls, o as timingAls, t as earlyHintsSenderAls } from "../_chunks/als-registry-DpygwCp0.js";
|
|
10
|
+
import { A as runWithTraceId, E as getOtelTraceId, F as isControlFlowSignal, I as isDenySignal, L as isRedirectSignal, M as withSpan, O as getTraceId, T as generateTraceId, _ as logWaitUntilRejected, b as swallow, c as logMiddlewareShortCircuit, d as logRequestCompleted, f as logRequestReceived, g as logSwrRefetchFailed, h as logSlowRequest, i as logCsrfRejected, j as setSpanAttribute, k as replaceTraceId, l as logProxyError, m as logRouteSetupError, n as logCacheMiss, p as logRouteError, s as logMiddlewareError, t as getLogger, u as logRenderError, v as logWaitUntilUnsupported, x as isDebug, y as setLogger } from "../_chunks/logger-CWk44DLp.js";
|
|
11
|
+
import { i as collectRouteModulepreloads, n as collectRouteCss, r as collectRouteFonts } from "../_chunks/build-manifest-Y4jl7nwU.js";
|
|
12
|
+
import { i as isRscCacheKeyShape, n as RSC_KEY_PARAM, r as appVisibleSearch, s as rscCacheKey, t as RSC_KEY_HEADERS } from "../_chunks/rsc-cache-key-D0cb0Gmc.js";
|
|
13
|
+
import { C as setMatchedSegmentPath, E as runOutsideReactCacheScope, S as runWithSegmentParams, T as setSegmentParams, b as markResponseFlushed, f as getCookie, g as getHeader, h as applyRequestHeaderOverlay, i as coerce, m as getSetCookieHeaders, o as DenySignal, s as RedirectSignal, t as executeAction, v as getSearchParams, w as setMutableCookieContext, x as runWithRequestContext, y as getSegmentParams } from "../_chunks/actions-7dTXYJfu.js";
|
|
14
|
+
import { _ as getWaitUntil, a as storeOverlayEntry, c as lookupArtifactSeed, d as checkVersionSkew, g as observeKeyDiscipline, i as overlayKey, l as setPrebuiltPayloadSource, n as lookupOverlay, o as hasPrebuiltPayloadSource, r as mayStoreRerender, s as isParamIndependent, u as applyReloadHeaders } from "../_chunks/cache-api-TDZ4hlDc.js";
|
|
15
|
+
import { n as createSingleflight } from "../_chunks/singleflight-BChPMjwH.js";
|
|
16
|
+
import { l as TIMBER_ERROR_HEADER, t as StatusPageMarker } from "../_chunks/status-page-marker-XIQXlTOb.js";
|
|
17
|
+
import { n as toBracketKey } from "../_chunks/resolve-schema-B-aCuTu3.js";
|
|
18
|
+
import { t as normalizeParamValue } from "../_chunks/param-value-DqlGfF57.js";
|
|
19
|
+
import { t as createGlobalContext } from "../_chunks/global-context-DbxNWeBP.js";
|
|
19
20
|
import { createHash } from "node:crypto";
|
|
20
21
|
import { readFile } from "node:fs/promises";
|
|
21
|
-
import
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Check if an error is an abort error (connection closed by client).
|
|
25
|
-
*
|
|
26
|
-
* When the browser aborts a request (page refresh, navigation away),
|
|
27
|
-
* the AbortSignal fires and React/streams throw an AbortError. This
|
|
28
|
-
* is not an application error — suppress it from error boundaries and logs.
|
|
29
|
-
*/
|
|
30
|
-
function isAbortError(error) {
|
|
31
|
-
if (error instanceof DOMException && error.name === "AbortError") return true;
|
|
32
|
-
if (error instanceof Error && error.name === "AbortError") return true;
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
//#endregion
|
|
36
|
-
//#region src/server/server-timing.ts
|
|
22
|
+
import { createElement, useContext } from "react";
|
|
23
|
+
// src/server/server-timing.ts
|
|
37
24
|
/**
|
|
38
25
|
* Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
|
|
39
26
|
*
|
|
@@ -108,8 +95,7 @@ function getServerTimingHeader() {
|
|
|
108
95
|
}
|
|
109
96
|
return result || null;
|
|
110
97
|
}
|
|
111
|
-
|
|
112
|
-
//#region src/server/instrumentation.ts
|
|
98
|
+
// src/server/instrumentation.ts
|
|
113
99
|
/**
|
|
114
100
|
* Instrumentation — loads and runs the user's instrumentation.ts file.
|
|
115
101
|
*
|
|
@@ -188,8 +174,7 @@ async function callOnRequestError(error, request, context) {
|
|
|
188
174
|
function hasOnRequestError() {
|
|
189
175
|
return _onRequestError !== null;
|
|
190
176
|
}
|
|
191
|
-
|
|
192
|
-
//#region src/server/safe-load.ts
|
|
177
|
+
// src/server/safe-load.ts
|
|
193
178
|
/**
|
|
194
179
|
* Custom error class for module load failures.
|
|
195
180
|
*
|
|
@@ -221,8 +206,38 @@ async function loadModule(loader) {
|
|
|
221
206
|
throw new ModuleLoadError(loader.filePath, error);
|
|
222
207
|
}
|
|
223
208
|
}
|
|
224
|
-
|
|
225
|
-
|
|
209
|
+
// src/server/route-matcher.ts
|
|
210
|
+
/**
|
|
211
|
+
* The matched segment path of a chain — its segment names, groups and slots
|
|
212
|
+
* included — as `getSegmentParams()`'s dev-mode validation compares against.
|
|
213
|
+
* See design/41-global-params.md §Runtime Validation.
|
|
214
|
+
*/
|
|
215
|
+
function matchedSegmentPath(chain) {
|
|
216
|
+
const path = chain.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
|
|
217
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Collect middleware from a matched segment chain, root to leaf.
|
|
221
|
+
*
|
|
222
|
+
* Each entry is lazy-loaded via dynamic import on first invocation.
|
|
223
|
+
*
|
|
224
|
+
* Shared with the children-path interception resolver
|
|
225
|
+
* (`children-interception.ts`), which assembles a chain from the tree rather
|
|
226
|
+
* than from a pathname but produces the same kind of `RouteMatch` — every
|
|
227
|
+
* `middleware.ts` above an intercepted page must run exactly as it does for
|
|
228
|
+
* the canonical route.
|
|
229
|
+
*/
|
|
230
|
+
function collectMiddlewareChain(chain) {
|
|
231
|
+
const middlewareChain = [];
|
|
232
|
+
for (const segment of chain) if (segment.middleware) {
|
|
233
|
+
const loader = segment.middleware.load;
|
|
234
|
+
middlewareChain.push(async (ctx) => {
|
|
235
|
+
const mod = await loader();
|
|
236
|
+
if (mod.default) return mod.default(ctx);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
return middlewareChain;
|
|
240
|
+
}
|
|
226
241
|
/**
|
|
227
242
|
* Whether a matched chain renders as an API route: its leaf has a
|
|
228
243
|
* `route.ts` and no `page.tsx`. The same test `renderRoute` dispatches on,
|
|
@@ -246,8 +261,7 @@ function isCsrfExemptRoute(segments) {
|
|
|
246
261
|
var SERVE_PATH_TO_CONVENTION = /* @__PURE__ */ new Map();
|
|
247
262
|
for (const [baseName, convention] of Object.entries(METADATA_ROUTE_CONVENTIONS)) if (convention.serveExtension) for (const ext of [...convention.staticExtensions, convention.serveExtension]) SERVE_PATH_TO_CONVENTION.set(`${convention.servePath}.${ext}`, baseName);
|
|
248
263
|
else SERVE_PATH_TO_CONVENTION.set(convention.servePath, baseName);
|
|
249
|
-
|
|
250
|
-
//#region src/shared/csrf-reject.ts
|
|
264
|
+
// src/shared/csrf-reject.ts
|
|
251
265
|
/**
|
|
252
266
|
* Marker header on CSRF rejections.
|
|
253
267
|
*
|
|
@@ -263,8 +277,7 @@ else SERVE_PATH_TO_CONVENTION.set(convention.servePath, baseName);
|
|
|
263
277
|
*/
|
|
264
278
|
var CSRF_REJECT_HEADER = "X-Timber-Reject";
|
|
265
279
|
var CSRF_REJECT_VALUE = "csrf";
|
|
266
|
-
|
|
267
|
-
//#region src/server/csrf.ts
|
|
280
|
+
// src/server/csrf.ts
|
|
268
281
|
/**
|
|
269
282
|
* CSRF protection — Fetch Metadata first, Origin as the fallback.
|
|
270
283
|
*
|
|
@@ -445,8 +458,7 @@ function csrfRejectionResponse(req, rejection) {
|
|
|
445
458
|
}
|
|
446
459
|
});
|
|
447
460
|
}
|
|
448
|
-
|
|
449
|
-
//#region src/server/pipeline-helpers.ts
|
|
461
|
+
// src/server/pipeline-helpers.ts
|
|
450
462
|
/**
|
|
451
463
|
* The pipeline-boundary CSRF gate: the 403 to answer with, or null to go on.
|
|
452
464
|
*
|
|
@@ -781,8 +793,7 @@ function reportedPhase(source, apiRoute) {
|
|
|
781
793
|
default: return source;
|
|
782
794
|
}
|
|
783
795
|
}
|
|
784
|
-
|
|
785
|
-
//#region src/server/proxy.ts
|
|
796
|
+
// src/server/proxy.ts
|
|
786
797
|
/**
|
|
787
798
|
* Run the proxy pipeline.
|
|
788
799
|
*
|
|
@@ -802,8 +813,7 @@ async function runProxy(proxyExport, req, next) {
|
|
|
802
813
|
}
|
|
803
814
|
return composed();
|
|
804
815
|
}
|
|
805
|
-
|
|
806
|
-
//#region src/server/middleware-runner.ts
|
|
816
|
+
// src/server/middleware-runner.ts
|
|
807
817
|
/**
|
|
808
818
|
* Run a route's middleware function.
|
|
809
819
|
*
|
|
@@ -835,8 +845,7 @@ async function runMiddlewareChain(chain, ctx) {
|
|
|
835
845
|
if (result instanceof Response) return result;
|
|
836
846
|
}
|
|
837
847
|
}
|
|
838
|
-
|
|
839
|
-
//#region src/server/csp-nonce.ts
|
|
848
|
+
// src/server/csp-nonce.ts
|
|
840
849
|
/**
|
|
841
850
|
* CSP nonce — per-request, generated on demand.
|
|
842
851
|
*
|
|
@@ -883,516 +892,636 @@ function requestCspNonce() {
|
|
|
883
892
|
store.cspNonce ??= generateNonce();
|
|
884
893
|
return store.cspNonce;
|
|
885
894
|
}
|
|
886
|
-
|
|
887
|
-
//#region src/server/param-coercion.ts
|
|
888
|
-
/**
|
|
889
|
-
* Thrown when an app/schema.ts segment-param codec's parse() fails.
|
|
890
|
-
* The pipeline catches this and responds with 404.
|
|
891
|
-
*/
|
|
892
|
-
var ParamCoercionError = class extends Error {
|
|
893
|
-
constructor(message) {
|
|
894
|
-
super(message);
|
|
895
|
-
this.name = "ParamCoercionError";
|
|
896
|
-
}
|
|
897
|
-
};
|
|
898
|
-
/** Global schema codecs, set once at startup from virtual:timber-schema. */
|
|
899
|
-
var _globalCodecs = null;
|
|
895
|
+
// src/server/response-cache-policy.ts
|
|
900
896
|
/**
|
|
901
|
-
*
|
|
902
|
-
*
|
|
903
|
-
*
|
|
904
|
-
*
|
|
905
|
-
* repeatable — coercing a match twice runs every codec on the URL value both
|
|
906
|
-
* times, never on its own output.
|
|
907
|
-
*
|
|
908
|
-
* Codecs come from `app/schema.ts` and nowhere else (TIM-1342 completed
|
|
909
|
-
* design/41-global-params.md migration step 9). A route with no schema, or
|
|
910
|
-
* a param the schema does not declare, keeps its raw string — which is the
|
|
911
|
-
* honest type for an uninterpreted URL segment.
|
|
912
|
-
*
|
|
913
|
-
* Throws ParamCoercionError if any codec fails (→ 404).
|
|
914
|
-
*
|
|
915
|
-
* This runs BEFORE middleware, so ctx.segmentParams is already typed.
|
|
916
|
-
* See design/07-routing.md §"Where Coercion Runs"
|
|
917
|
-
* See design/41-global-params.md §"Pipeline Integration"
|
|
897
|
+
* Legacy shared-cache control fields that predate RFC 9213 and so do not
|
|
898
|
+
* follow the `<target>-Cache-Control` naming pattern — the one part of this
|
|
899
|
+
* rule that cannot be matched by shape. `X-Accel-Expires` is nginx
|
|
900
|
+
* `proxy_cache`, which gives it precedence over `Cache-Control`.
|
|
918
901
|
*
|
|
919
|
-
*
|
|
920
|
-
*
|
|
921
|
-
* it. Making it synchronous would
|
|
922
|
-
* change that contract and remove a microtask boundary the pipeline's
|
|
923
|
-
* ordering has always had, for no gain.
|
|
902
|
+
* A closed historical set, unlike the vendor `*-Cache-Control` names, which
|
|
903
|
+
* keep being minted and are handled by pattern below.
|
|
924
904
|
*/
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
const segment = effectiveUrlSegment(node);
|
|
931
|
-
if (!segment.paramName) continue;
|
|
932
|
-
const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
|
|
933
|
-
const codec = globalCodecs[bracketKey];
|
|
934
|
-
if (!codec) continue;
|
|
935
|
-
const key = segment.paramName;
|
|
936
|
-
if (!(key in mergeTarget)) continue;
|
|
937
|
-
let parsed;
|
|
938
|
-
try {
|
|
939
|
-
parsed = codec.parse(mergeTarget[key]);
|
|
940
|
-
} catch (err) {
|
|
941
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
942
|
-
if (isDebug()) console.warn(`[timber] Global schema codec rejected value for param "${key}"\n Error: ${message}\n Raw value: ${JSON.stringify(mergeTarget[key])}\n Hint: check the codec in app/schema.ts for key '${bracketKey}'.`);
|
|
943
|
-
throw new ParamCoercionError(message);
|
|
944
|
-
}
|
|
945
|
-
mergeTarget[key] = normalizeParamValue(parsed, key);
|
|
946
|
-
}
|
|
947
|
-
return mergeTarget;
|
|
948
|
-
}
|
|
949
|
-
//#endregion
|
|
950
|
-
//#region src/server/pipeline-metadata.ts
|
|
905
|
+
var LEGACY_CDN_CACHE_HEADERS = [
|
|
906
|
+
"Surrogate-Control",
|
|
907
|
+
"Edge-Control",
|
|
908
|
+
"X-Accel-Expires"
|
|
909
|
+
];
|
|
951
910
|
/**
|
|
952
|
-
*
|
|
953
|
-
*
|
|
954
|
-
* Handles serving static metadata files and serializing sitemap responses.
|
|
955
|
-
* Extracted from pipeline.ts to keep files under 500 lines.
|
|
911
|
+
* Whether a response header overrides `Cache-Control` at a shared cache.
|
|
956
912
|
*
|
|
957
|
-
*
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
*
|
|
961
|
-
*
|
|
962
|
-
* the
|
|
963
|
-
* own headers only — the framework adds no default to it.
|
|
913
|
+
* Matched by *shape*, not by vendor name. RFC 9213 defines targeted fields
|
|
914
|
+
* as `<target>-Cache-Control`, and every CDN spells its own: `CDN-`,
|
|
915
|
+
* `Cloudflare-CDN-`, `Netlify-CDN-`, `Vercel-CDN-`, and whichever ships
|
|
916
|
+
* next. A vendor list here is a denylist with an unbounded tail — it was
|
|
917
|
+
* extended twice during review, each time by one name, which is the signal
|
|
918
|
+
* that enumeration is the wrong shape. The suffix rule is total.
|
|
964
919
|
*
|
|
965
|
-
*
|
|
966
|
-
|
|
967
|
-
var METADATA_CACHE_CONTROL = "public, max-age=14400, must-revalidate";
|
|
968
|
-
/**
|
|
969
|
-
* Content types that are text-based and should include charset=utf-8.
|
|
970
|
-
* Binary formats (images) should not include charset.
|
|
920
|
+
* `Cache-Control` itself does not match (no `-` prefix) and is replaced
|
|
921
|
+
* separately.
|
|
971
922
|
*/
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
"
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
]
|
|
923
|
+
function isSharedCacheOverride(name) {
|
|
924
|
+
const lowered = name.toLowerCase();
|
|
925
|
+
return lowered.endsWith("-cache-control") || LEGACY_CDN_CACHE_HEADERS.some((legacy) => legacy.toLowerCase() === lowered);
|
|
926
|
+
}
|
|
927
|
+
/** Disable caching, including CDN overrides that take precedence over Cache-Control. */
|
|
928
|
+
function preventResponseCaching(headers) {
|
|
929
|
+
const overrides = [];
|
|
930
|
+
for (const name of headers.keys()) if (isSharedCacheOverride(name)) overrides.push(name);
|
|
931
|
+
for (const name of overrides) headers.delete(name);
|
|
932
|
+
headers.set("Cache-Control", "private, no-store");
|
|
933
|
+
}
|
|
934
|
+
// src/server/error-response-headers.ts
|
|
935
|
+
/** Preserve request-wide metadata when replacing a failed response body. */
|
|
936
|
+
function errorResponseHeaders(responseHeaders) {
|
|
937
|
+
const headers = new Headers(responseHeaders);
|
|
938
|
+
headers.delete("Content-Length");
|
|
939
|
+
headers.delete("Content-Encoding");
|
|
940
|
+
headers.delete("Transfer-Encoding");
|
|
941
|
+
preventResponseCaching(headers);
|
|
942
|
+
headers.delete("ETag");
|
|
943
|
+
headers.delete("Last-Modified");
|
|
944
|
+
headers.delete("Expires");
|
|
945
|
+
headers.delete("Age");
|
|
946
|
+
return headers;
|
|
947
|
+
}
|
|
948
|
+
// src/server/rsc-error-envelope.ts
|
|
979
949
|
/**
|
|
980
|
-
*
|
|
981
|
-
*
|
|
982
|
-
* Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
|
|
983
|
-
* are served as-is with the appropriate Content-Type header.
|
|
984
|
-
* Text files include charset=utf-8; binary files do not.
|
|
950
|
+
* Build the hard-navigate envelope for a status code.
|
|
985
951
|
*
|
|
986
|
-
*
|
|
952
|
+
* Preserve middleware's request-wide headers and cookies, but discard the
|
|
953
|
+
* abandoned body's framing, validators, and cache policy. Every producer,
|
|
954
|
+
* including errors returned normally during render, gets this cleanup here.
|
|
955
|
+
* The input header bag is left intact. The body deliberately carries no message —
|
|
956
|
+
* only the status already on the wire (design/13-security.md principle 4).
|
|
987
957
|
*/
|
|
988
|
-
|
|
989
|
-
const
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
return new Response(body, {
|
|
998
|
-
status: 200,
|
|
958
|
+
function rscErrorEnvelope(status, responseHeaders) {
|
|
959
|
+
const headers = errorResponseHeaders(responseHeaders);
|
|
960
|
+
headers.set(TIMBER_ERROR_HEADER, "1");
|
|
961
|
+
headers.set("content-type", "application/json; charset=utf-8");
|
|
962
|
+
return new Response(JSON.stringify({
|
|
963
|
+
error: true,
|
|
964
|
+
status
|
|
965
|
+
}), {
|
|
966
|
+
status,
|
|
999
967
|
headers
|
|
1000
968
|
});
|
|
1001
969
|
}
|
|
970
|
+
// src/server/pipeline-outcome.ts
|
|
1002
971
|
/**
|
|
1003
|
-
*
|
|
1004
|
-
*
|
|
972
|
+
* Pipeline outcome translator — converts a `PhaseOutcome` (the value
|
|
973
|
+
* each phase function returns) into a final `Response`.
|
|
974
|
+
*
|
|
975
|
+
* Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
|
|
976
|
+
* catch logic and the terminal Response-building logic each live in
|
|
977
|
+
* their own file. The phases produce values; this module is the single
|
|
978
|
+
* source of truth for how those values become wire responses.
|
|
979
|
+
*
|
|
980
|
+
* See design/07-routing.md §"Request Lifecycle".
|
|
1005
981
|
*/
|
|
1006
|
-
function
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
}
|
|
1013
|
-
if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
|
|
1014
|
-
if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
|
|
1015
|
-
xml += "\n </url>";
|
|
1016
|
-
return xml;
|
|
1017
|
-
}).join("\n")}\n</urlset>`;
|
|
1018
|
-
}
|
|
1019
|
-
/** Escape special XML characters. */
|
|
1020
|
-
function escapeXml(str) {
|
|
1021
|
-
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
982
|
+
function rscErrorResponse(isRsc, status, headers) {
|
|
983
|
+
if (isRsc) return rscErrorEnvelope(status, headers);
|
|
984
|
+
return new Response(null, {
|
|
985
|
+
status,
|
|
986
|
+
headers: errorResponseHeaders(headers)
|
|
987
|
+
});
|
|
1022
988
|
}
|
|
1023
|
-
//#endregion
|
|
1024
|
-
//#region src/server/state-tree-diff.ts
|
|
1025
989
|
/**
|
|
1026
|
-
*
|
|
990
|
+
* Resolve the header bag a signal/error outcome is written onto, with the
|
|
991
|
+
* cookie jar applied exactly once.
|
|
1027
992
|
*
|
|
1028
|
-
*
|
|
1029
|
-
* the
|
|
1030
|
-
*
|
|
993
|
+
* Ownership rule (design/49 §P0b): the phase that owns `responseHeaders`
|
|
994
|
+
* applies the jar to it once; the translator applies it only for outcomes
|
|
995
|
+
* that arrive without it. Render-phase outcomes already carry the jar —
|
|
996
|
+
* `runRenderPhase()` applies it on entry, with or without a middleware
|
|
997
|
+
* chain — so re-applying here emitted every middleware `Set-Cookie` twice
|
|
998
|
+
* (TIM-1491).
|
|
1031
999
|
*
|
|
1032
|
-
*
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1035
|
-
*
|
|
1000
|
+
* The guard is "not render", not "only middleware": proxy-phase signals
|
|
1001
|
+
* reach the translator with no `responseHeaders` at all, and for a
|
|
1002
|
+
* `proxy.ts` that awaits `next()` and then throws, this is the only place
|
|
1003
|
+
* the cookies downstream middleware set can reach the wire
|
|
1004
|
+
* (design/29-cookies.md §"proxy.ts Cookie Access"). Middleware-phase
|
|
1005
|
+
* signals throw before that phase's own application, so they need it too,
|
|
1006
|
+
* and so do setup-phase outcomes, which come before any phase applied it.
|
|
1036
1007
|
*
|
|
1037
|
-
*
|
|
1038
|
-
* See design/13-security.md §"State tree manipulation"
|
|
1008
|
+
* `fresh` creates the bag for an outcome that arrives without one.
|
|
1039
1009
|
*/
|
|
1010
|
+
function outcomeHeaders(outcome, ctx, fresh = () => new Headers()) {
|
|
1011
|
+
const headers = ctx.responseHeaders ?? fresh();
|
|
1012
|
+
if (outcome.phase !== "render") applyCookieJar(headers);
|
|
1013
|
+
return headers;
|
|
1014
|
+
}
|
|
1015
|
+
/** Whether the outcome is for a route.ts match, which answers in its own format. */
|
|
1016
|
+
function isApiRouteMatch(ctx) {
|
|
1017
|
+
return ctx.match !== void 0 && isApiRouteChain(ctx.match.segments);
|
|
1018
|
+
}
|
|
1040
1019
|
/**
|
|
1041
|
-
*
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1044
|
-
*
|
|
1045
|
-
* the header is missing, malformed, or empty. Parsing happens before
|
|
1046
|
-
* renderToReadableStream — not inside the React render pass.
|
|
1047
|
-
*
|
|
1048
|
-
* @returns ClientStateTree with segments and slots, or null if no valid state tree
|
|
1020
|
+
* Report an error outcome once: log it under its phase, fire
|
|
1021
|
+
* `onRequestError`, and hand it to the dev overlay. An error from a
|
|
1022
|
+
* route.ts handler — or anything else in its render phase — logs as a route
|
|
1023
|
+
* error and reports as phase `'route'`.
|
|
1049
1024
|
*/
|
|
1050
|
-
function
|
|
1051
|
-
const
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1025
|
+
async function reportError(config, error, phase, ctx) {
|
|
1026
|
+
const { method, path } = ctx;
|
|
1027
|
+
switch (phase) {
|
|
1028
|
+
case "proxy":
|
|
1029
|
+
logProxyError({ error });
|
|
1030
|
+
break;
|
|
1031
|
+
case "setup":
|
|
1032
|
+
logRouteSetupError({
|
|
1033
|
+
method,
|
|
1034
|
+
path,
|
|
1035
|
+
error
|
|
1036
|
+
});
|
|
1037
|
+
break;
|
|
1038
|
+
case "middleware":
|
|
1039
|
+
logMiddlewareError({
|
|
1040
|
+
method,
|
|
1041
|
+
path,
|
|
1042
|
+
error
|
|
1043
|
+
});
|
|
1044
|
+
break;
|
|
1045
|
+
case "render": if (isApiRouteMatch(ctx)) logRouteError({
|
|
1046
|
+
method,
|
|
1047
|
+
path,
|
|
1048
|
+
error
|
|
1049
|
+
});
|
|
1050
|
+
else logRenderError({
|
|
1051
|
+
method,
|
|
1052
|
+
path,
|
|
1053
|
+
error
|
|
1054
|
+
});
|
|
1066
1055
|
}
|
|
1056
|
+
await fireOnRequestError(error, ctx.req, phase, ctx.match?.segments);
|
|
1057
|
+
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, phase);
|
|
1058
|
+
}
|
|
1059
|
+
/** The outcome for a value a phase threw: a signal, or an error. */
|
|
1060
|
+
function thrownOutcome(phase, thrown) {
|
|
1061
|
+
if (isRedirectSignal(thrown)) return {
|
|
1062
|
+
kind: "redirect",
|
|
1063
|
+
phase,
|
|
1064
|
+
signal: thrown
|
|
1065
|
+
};
|
|
1066
|
+
if (isDenySignal(thrown)) return {
|
|
1067
|
+
kind: "deny",
|
|
1068
|
+
phase,
|
|
1069
|
+
signal: thrown
|
|
1070
|
+
};
|
|
1071
|
+
return {
|
|
1072
|
+
kind: "error",
|
|
1073
|
+
phase,
|
|
1074
|
+
error: thrown
|
|
1075
|
+
};
|
|
1067
1076
|
}
|
|
1068
|
-
//#endregion
|
|
1069
|
-
//#region src/server/pipeline-interception.ts
|
|
1070
1077
|
/**
|
|
1071
|
-
*
|
|
1078
|
+
* Terminal outcome handler — converts a `PhaseOutcome` into a final
|
|
1079
|
+
* `Response`, applying cookies, building redirects, rendering deny pages
|
|
1080
|
+
* and fallback error pages, and firing instrumentation hooks.
|
|
1072
1081
|
*
|
|
1073
|
-
*
|
|
1074
|
-
*
|
|
1082
|
+
* This is the single source of truth for how phase outputs become wire
|
|
1083
|
+
* responses; the per-phase try/catch blocks now produce values, not
|
|
1084
|
+
* Responses, so the conversion logic lives in exactly one place.
|
|
1085
|
+
*/
|
|
1086
|
+
async function outcomeToResponse(config, outcome, ctx) {
|
|
1087
|
+
switch (outcome.kind) {
|
|
1088
|
+
case "response": {
|
|
1089
|
+
const finalResponse = cloneWithMutableHeaders(outcome.response);
|
|
1090
|
+
if (outcome.phase === "proxy") return finalResponse;
|
|
1091
|
+
if (outcome.phase === "middleware" && ctx.responseHeaders) {
|
|
1092
|
+
applyCookieJar(finalResponse.headers);
|
|
1093
|
+
mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
|
|
1094
|
+
logMiddlewareShortCircuit({
|
|
1095
|
+
method: ctx.method,
|
|
1096
|
+
path: ctx.path,
|
|
1097
|
+
status: finalResponse.status
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
if (outcome.phase === "render") markResponseFlushed();
|
|
1101
|
+
return finalResponse;
|
|
1102
|
+
}
|
|
1103
|
+
case "redirect": {
|
|
1104
|
+
const headers = outcomeHeaders(outcome, ctx);
|
|
1105
|
+
const navigation = isRscRequest(ctx.req) && !isApiRouteMatch(ctx);
|
|
1106
|
+
return buildRedirectResponse(outcome.signal, headers, navigation);
|
|
1107
|
+
}
|
|
1108
|
+
case "deny": {
|
|
1109
|
+
const headers = outcomeHeaders(outcome, ctx, dynamicResponseHeaders);
|
|
1110
|
+
if (config.renderDenyFallback) try {
|
|
1111
|
+
return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
|
|
1112
|
+
} catch (denyRenderError) {
|
|
1113
|
+
logRenderError({
|
|
1114
|
+
method: ctx.method,
|
|
1115
|
+
path: ctx.path,
|
|
1116
|
+
error: denyRenderError
|
|
1117
|
+
});
|
|
1118
|
+
await fireOnRequestError(denyRenderError, ctx.req, "render", ctx.match?.segments);
|
|
1119
|
+
if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
|
|
1120
|
+
if (isRscRequest(ctx.req)) return rscErrorEnvelope(outcome.signal.status, headers);
|
|
1121
|
+
}
|
|
1122
|
+
if (isDebug()) console.warn(`[timber] DenySignal(${outcome.signal.status}) from ${outcome.phase} phase — no renderDenyFallback configured, returning bare ${outcome.signal.status} response\n Request: ${ctx.method} ${ctx.path}\n Add a status-code file (e.g. 404.tsx) or error.tsx to render a custom deny page.`);
|
|
1123
|
+
return new Response(null, {
|
|
1124
|
+
status: outcome.signal.status,
|
|
1125
|
+
headers
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
case "error": {
|
|
1129
|
+
const isRsc = isRscRequest(ctx.req);
|
|
1130
|
+
const headers = outcomeHeaders(outcome, ctx);
|
|
1131
|
+
await reportError(config, outcome.error, outcome.phase, ctx);
|
|
1132
|
+
if (outcome.phase === "proxy" || outcome.phase === "middleware") return rscErrorResponse(isRsc, 500, headers);
|
|
1133
|
+
if (isRsc && !isApiRouteMatch(ctx)) return rscErrorResponse(true, 500, headers);
|
|
1134
|
+
if (config.renderFallbackError) try {
|
|
1135
|
+
return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, errorResponseHeaders(headers), ctx.match));
|
|
1136
|
+
} catch (fallbackRenderError) {
|
|
1137
|
+
logRenderError({
|
|
1138
|
+
method: ctx.method,
|
|
1139
|
+
path: ctx.path,
|
|
1140
|
+
error: fallbackRenderError
|
|
1141
|
+
});
|
|
1142
|
+
await fireOnRequestError(fallbackRenderError, ctx.req, "render", ctx.match?.segments);
|
|
1143
|
+
if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
|
|
1144
|
+
}
|
|
1145
|
+
return rscErrorResponse(false, 500, headers);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
// src/server/pipeline-metadata.ts
|
|
1150
|
+
/**
|
|
1151
|
+
* Metadata route helpers for the request pipeline.
|
|
1075
1152
|
*
|
|
1153
|
+
* Handles serving static metadata files and serializing sitemap responses.
|
|
1076
1154
|
* Extracted from pipeline.ts to keep files under 500 lines.
|
|
1077
1155
|
*
|
|
1078
|
-
* See design/
|
|
1156
|
+
* See design/16-metadata.md §"Metadata Routes"
|
|
1079
1157
|
*/
|
|
1080
1158
|
/**
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1083
|
-
*
|
|
1084
|
-
*
|
|
1085
|
-
* 1. The **target** pathname matches the rewrite's intercepted pattern.
|
|
1086
|
-
* 2. The **source** route — the page the user is navigating FROM, per the
|
|
1087
|
-
* validated X-Timber-URL header — renders the segment that owns the slot
|
|
1088
|
-
* holding the intercepting page (`interceptingScope`). Only then does that
|
|
1089
|
-
* slot exist in the rendered tree, so only then can the intercepting page
|
|
1090
|
-
* render.
|
|
1091
|
-
*
|
|
1092
|
-
* Condition 2 replaced a URL-prefix check (TIM-1279). A prefix cannot
|
|
1093
|
-
* distinguish a route-group-scoped interception from a genuinely root-level
|
|
1094
|
-
* one — route groups are invisible in `urlPath`, so both collapse to "/" and
|
|
1095
|
-
* the guard degenerates to always-true. Tree paths carry group identity.
|
|
1096
|
-
* The scope check also subsumes the old segment-boundary rule: a source route
|
|
1097
|
-
* under /feed-private has no "/feed" in its chain.
|
|
1098
|
-
*
|
|
1099
|
-
* A third condition lives with the caller, which owns route matching, and it
|
|
1100
|
-
* applies to the `'slot'` shape only: the route produced by re-matching
|
|
1101
|
-
* `interceptingPrefix` must pass through the scope too. Conditions 1–2 are
|
|
1102
|
-
* about the route the user is leaving; the slot has to exist in the tree that
|
|
1103
|
-
* actually renders. The `'children'` shape resolves its owner from the scope
|
|
1104
|
-
* directly rather than from a pathname, so it satisfies that by construction.
|
|
1105
|
-
*
|
|
1106
|
-
* `resolveSourceScopes` is a thunk so its inputs are only resolved when some
|
|
1107
|
-
* rewrite's pattern actually matches the target — the common case is no match
|
|
1108
|
-
* at all. It returns the two client-supplied answers to "what is on screen?"
|
|
1109
|
-
* as **separate sets, most authoritative first**: the tree paths the client
|
|
1110
|
-
* says it has mounted, then those of the route the departing URL matches. It
|
|
1111
|
-
* returns null only when neither yields anything, which is not a soft
|
|
1112
|
-
* navigation this can reason about.
|
|
1113
|
-
*
|
|
1114
|
-
* They are two sets rather than one union because ranking needs a chain
|
|
1115
|
-
* (TIM-1318). Each channel describes a single rendered chain, so within one the
|
|
1116
|
-
* scopes are strictly nested and the deepest is the innermost owner. Unioned
|
|
1117
|
-
* they are not: once a modal is open the address bar holds the *intercepted*
|
|
1118
|
-
* URL, so the second channel describes the canonical branch — possibly an
|
|
1119
|
-
* exclusive route group the client never mounted — and a deeper scope from
|
|
1120
|
-
* there would outrank the owner actually on screen. Trying the mounted channel
|
|
1121
|
-
* to exhaustion first keeps the fallback the union was there to provide while
|
|
1122
|
-
* ranking only within one chain.
|
|
1159
|
+
* Cache-Control the framework sets on metadata route responses it produces:
|
|
1160
|
+
* static files, serialized handler results (sitemap, robots, manifest) and
|
|
1161
|
+
* the auto-generated sitemap. A Response a handler returns is sent with its
|
|
1162
|
+
* own headers only — the framework adds no default to it.
|
|
1123
1163
|
*
|
|
1124
|
-
*
|
|
1125
|
-
|
|
1126
|
-
|
|
1164
|
+
* See design/16-metadata.md §"Caching" (under "Metadata Routes")
|
|
1165
|
+
*/
|
|
1166
|
+
var METADATA_CACHE_CONTROL = "public, max-age=14400, must-revalidate";
|
|
1167
|
+
/**
|
|
1168
|
+
* Content types that are text-based and should include charset=utf-8.
|
|
1169
|
+
* Binary formats (images) should not include charset.
|
|
1170
|
+
*/
|
|
1171
|
+
var TEXT_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1172
|
+
"application/xml",
|
|
1173
|
+
"text/plain",
|
|
1174
|
+
"application/json",
|
|
1175
|
+
"application/manifest+json",
|
|
1176
|
+
"image/svg+xml"
|
|
1177
|
+
]);
|
|
1178
|
+
/**
|
|
1179
|
+
* Serve a static metadata file by reading it from disk.
|
|
1127
1180
|
*
|
|
1128
|
-
*
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1131
|
-
*
|
|
1132
|
-
* instead would be harder to explain than rendering the canonical route.
|
|
1181
|
+
* Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
|
|
1182
|
+
* are served as-is with the appropriate Content-Type header.
|
|
1183
|
+
* Text files include charset=utf-8; binary files do not. `cacheControl` is
|
|
1184
|
+
* omitted for a file behind gates, whose answer depends on who asked.
|
|
1133
1185
|
*
|
|
1134
|
-
*
|
|
1135
|
-
* `collectInterceptionRewrites` sorts it at build time, so the deepest owner a
|
|
1136
|
-
* single chain passes through wins and nothing here has to score (TIM-1318).
|
|
1137
|
-
* Tree-walk order used to decide it, which meant renaming a route group flipped
|
|
1138
|
-
* which modal opened. The precondition is a property of the manifest this reads
|
|
1139
|
-
* rather than something it can re-derive, so it is asserted at its source:
|
|
1140
|
-
* `tests/interception.test.ts` §"rewrite order is decided by scope depth".
|
|
1186
|
+
* See design/16-metadata.md §"Metadata Routes"
|
|
1141
1187
|
*/
|
|
1142
|
-
function
|
|
1143
|
-
const
|
|
1144
|
-
|
|
1145
|
-
const
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1188
|
+
async function serveStaticMetadataFile(metaMatch, cacheControl) {
|
|
1189
|
+
const { contentType, file } = metaMatch;
|
|
1190
|
+
const isText = TEXT_CONTENT_TYPES.has(contentType);
|
|
1191
|
+
const body = await readFile(file.filePath);
|
|
1192
|
+
const headers = new Headers({
|
|
1193
|
+
"Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
|
|
1194
|
+
"Content-Length": String(body.byteLength)
|
|
1195
|
+
});
|
|
1196
|
+
if (cacheControl) headers.set("Cache-Control", cacheControl);
|
|
1197
|
+
return new Response(body, {
|
|
1198
|
+
status: 200,
|
|
1199
|
+
headers
|
|
1200
|
+
});
|
|
1149
1201
|
}
|
|
1150
1202
|
/**
|
|
1151
|
-
*
|
|
1152
|
-
*
|
|
1153
|
-
* Supports [param] (single segment) and [...param] (one or more segments).
|
|
1154
|
-
* Static segments must match exactly.
|
|
1203
|
+
* Serialize a sitemap array to XML.
|
|
1204
|
+
* Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
|
|
1155
1205
|
*/
|
|
1156
|
-
function
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
switch (seg.kind) {
|
|
1163
|
-
case "catch-all": return pi < pathParts.length;
|
|
1164
|
-
case "optional-catch-all": return true;
|
|
1165
|
-
case "dynamic": {
|
|
1166
|
-
if (pi >= pathParts.length) return false;
|
|
1167
|
-
const prefix = seg.prefix ?? "";
|
|
1168
|
-
const suffix = seg.suffix ?? "";
|
|
1169
|
-
const pathPart = pathParts[pi];
|
|
1170
|
-
if (prefix || suffix) {
|
|
1171
|
-
if (pathPart.length <= prefix.length + suffix.length || prefix && !pathPart.startsWith(prefix) || suffix && !pathPart.endsWith(suffix)) return false;
|
|
1172
|
-
}
|
|
1173
|
-
pi++;
|
|
1174
|
-
continue;
|
|
1175
|
-
}
|
|
1176
|
-
case "static":
|
|
1177
|
-
if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
|
|
1178
|
-
pi++;
|
|
1179
|
-
continue;
|
|
1206
|
+
function serializeSitemap(entries) {
|
|
1207
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
|
|
1208
|
+
let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
|
|
1209
|
+
if (e.lastModified) {
|
|
1210
|
+
const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
|
|
1211
|
+
xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
|
|
1180
1212
|
}
|
|
1181
|
-
|
|
1182
|
-
|
|
1213
|
+
if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
|
|
1214
|
+
if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
|
|
1215
|
+
xml += "\n </url>";
|
|
1216
|
+
return xml;
|
|
1217
|
+
}).join("\n")}\n</urlset>`;
|
|
1218
|
+
}
|
|
1219
|
+
/** Escape special XML characters. */
|
|
1220
|
+
function escapeXml(str) {
|
|
1221
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1183
1222
|
}
|
|
1223
|
+
// src/server/param-coercion.ts
|
|
1184
1224
|
/**
|
|
1185
|
-
*
|
|
1186
|
-
*
|
|
1187
|
-
*
|
|
1188
|
-
* Runs during route setup, so anything it throws is a `'setup'` outcome.
|
|
1225
|
+
* Thrown when an app/schema.ts segment-param codec's parse() fails.
|
|
1226
|
+
* The pipeline catches this and responds with 404.
|
|
1189
1227
|
*/
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
if (isRscRequest(req) && config.interceptionRewrites?.length) {
|
|
1195
|
-
const rawSourceUrl = req.headers.get("X-Timber-URL");
|
|
1196
|
-
const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
|
|
1197
|
-
if (validatedSourceUrl) {
|
|
1198
|
-
const resolveSourceScopes = () => {
|
|
1199
|
-
const mounted = new Set(parseClientStateTree(req)?.treePaths ?? []);
|
|
1200
|
-
const sourceRoute = config.matchRoute(validatedSourceUrl);
|
|
1201
|
-
const scopes = [mounted, new Set(sourceRoute ? computeSegmentTreePaths(sourceRoute.segments) : [])].filter((scope) => scope.size > 0);
|
|
1202
|
-
return scopes.length > 0 ? scopes : null;
|
|
1203
|
-
};
|
|
1204
|
-
const rewrite = findInterceptionMatch(canonicalPathname, resolveSourceScopes, config.interceptionRewrites);
|
|
1205
|
-
if (rewrite?.mode === "children") {
|
|
1206
|
-
const interceptedMatch = config.matchInterceptedRoute?.(canonicalPathname, rewrite.interceptingScope);
|
|
1207
|
-
if (interceptedMatch) match = interceptedMatch;
|
|
1208
|
-
} else if (rewrite) {
|
|
1209
|
-
const sourceMatch = config.matchRoute(rewrite.interceptingPrefix);
|
|
1210
|
-
if (sourceMatch !== null && computeSegmentTreePaths(sourceMatch.segments).includes(rewrite.interceptingScope)) {
|
|
1211
|
-
match = sourceMatch;
|
|
1212
|
-
interception = { targetPathname: canonicalPathname };
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1228
|
+
var ParamCoercionError = class extends Error {
|
|
1229
|
+
constructor(message) {
|
|
1230
|
+
super(message);
|
|
1231
|
+
this.name = "ParamCoercionError";
|
|
1216
1232
|
}
|
|
1217
|
-
|
|
1218
|
-
match,
|
|
1219
|
-
interception
|
|
1220
|
-
};
|
|
1221
|
-
}
|
|
1233
|
+
};
|
|
1222
1234
|
/**
|
|
1223
|
-
*
|
|
1224
|
-
*
|
|
1225
|
-
*
|
|
1226
|
-
* - Must start with '/' (relative pathname, no scheme/authority)
|
|
1227
|
-
* - Must not contain control characters
|
|
1228
|
-
* - Must pass canonicalization (no encoded separators, null bytes, etc.)
|
|
1235
|
+
* The dev diagnostic for a match whose params a codec rejected; the caller
|
|
1236
|
+
* answers 404. Shared by page/route.ts matches and metadata routes, so a
|
|
1237
|
+
* silent coercion 404 explains itself the same way on either.
|
|
1229
1238
|
*/
|
|
1230
|
-
function
|
|
1231
|
-
if (!
|
|
1232
|
-
|
|
1233
|
-
for
|
|
1234
|
-
const code = raw.charCodeAt(i);
|
|
1235
|
-
if (code <= 31 || code === 127) return null;
|
|
1236
|
-
}
|
|
1237
|
-
const result = canonicalize(raw, stripTrailingSlash);
|
|
1238
|
-
if (!result.ok) return null;
|
|
1239
|
-
return result.pathname;
|
|
1239
|
+
function warnParamCoercionFailure(method, pathname, segments, error) {
|
|
1240
|
+
if (!isDebug()) return;
|
|
1241
|
+
const segmentChain = segments.map((s) => s.segmentName || "/").join(" → ");
|
|
1242
|
+
console.warn(`[timber] Param coercion failed for ${method} ${pathname} — responding with 404\n Matched segments: ${segmentChain}\n Error: ${error.message}\n This usually means a codec in app/schema.ts rejected the URL value.\n Check the codec for the bracket key of the segment named above.`);
|
|
1240
1243
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1244
|
+
/** Global schema codecs, set once at startup from virtual:timber-schema. */
|
|
1245
|
+
var _globalCodecs = null;
|
|
1243
1246
|
/**
|
|
1244
|
-
*
|
|
1245
|
-
* follow the `<target>-Cache-Control` naming pattern — the one part of this
|
|
1246
|
-
* rule that cannot be matched by shape. `X-Accel-Expires` is nginx
|
|
1247
|
-
* `proxy_cache`, which gives it precedence over `Cache-Control`.
|
|
1247
|
+
* Coerce the matched route's raw segment params and return the result.
|
|
1248
1248
|
*
|
|
1249
|
-
*
|
|
1250
|
-
*
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
"Surrogate-Control",
|
|
1254
|
-
"Edge-Control",
|
|
1255
|
-
"X-Accel-Expires"
|
|
1256
|
-
];
|
|
1257
|
-
/**
|
|
1258
|
-
* Whether a response header overrides `Cache-Control` at a shared cache.
|
|
1249
|
+
* Reads `match.rawSegmentParams` and never writes to `match`: the caller
|
|
1250
|
+
* decides where the coerced params go. Reading the raw record makes the call
|
|
1251
|
+
* repeatable — coercing a match twice runs every codec on the URL value both
|
|
1252
|
+
* times, never on its own output.
|
|
1259
1253
|
*
|
|
1260
|
-
*
|
|
1261
|
-
*
|
|
1262
|
-
*
|
|
1263
|
-
*
|
|
1264
|
-
* extended twice during review, each time by one name, which is the signal
|
|
1265
|
-
* that enumeration is the wrong shape. The suffix rule is total.
|
|
1254
|
+
* Codecs come from `app/schema.ts` and nowhere else (TIM-1342 completed
|
|
1255
|
+
* design/41-global-params.md migration step 9). A route with no schema, or
|
|
1256
|
+
* a param the schema does not declare, keeps its raw string — which is the
|
|
1257
|
+
* honest type for an uninterpreted URL segment.
|
|
1266
1258
|
*
|
|
1267
|
-
*
|
|
1268
|
-
*
|
|
1259
|
+
* Throws ParamCoercionError if any codec fails (→ 404).
|
|
1260
|
+
*
|
|
1261
|
+
* This runs BEFORE middleware, so ctx.segmentParams is already typed.
|
|
1262
|
+
* See design/07-routing.md §"Where Coercion Runs"
|
|
1263
|
+
* See design/41-global-params.md §"Pipeline Integration"
|
|
1264
|
+
*
|
|
1265
|
+
* Stays `async` with nothing to await: it is injected as a
|
|
1266
|
+
* `CoerceSegmentParamsFn` into the revalidation renderer, which awaits
|
|
1267
|
+
* it. Making it synchronous would
|
|
1268
|
+
* change that contract and remove a microtask boundary the pipeline's
|
|
1269
|
+
* ordering has always had, for no gain.
|
|
1269
1270
|
*/
|
|
1270
|
-
function
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
headers.delete("Age");
|
|
1294
|
-
return headers;
|
|
1271
|
+
async function coerceSegmentParams(match) {
|
|
1272
|
+
const globalCodecs = _globalCodecs;
|
|
1273
|
+
const mergeTarget = Object.create(null);
|
|
1274
|
+
for (const key of Object.keys(match.rawSegmentParams)) if (key !== "__proto__") mergeTarget[key] = match.rawSegmentParams[key];
|
|
1275
|
+
if (globalCodecs) for (const node of match.segments) {
|
|
1276
|
+
const segment = effectiveUrlSegment(node);
|
|
1277
|
+
if (!segment.paramName) continue;
|
|
1278
|
+
const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
|
|
1279
|
+
const codec = globalCodecs[bracketKey];
|
|
1280
|
+
if (!codec) continue;
|
|
1281
|
+
const key = segment.paramName;
|
|
1282
|
+
if (!(key in mergeTarget)) continue;
|
|
1283
|
+
let parsed;
|
|
1284
|
+
try {
|
|
1285
|
+
parsed = codec.parse(mergeTarget[key]);
|
|
1286
|
+
} catch (err) {
|
|
1287
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1288
|
+
if (isDebug()) console.warn(`[timber] Global schema codec rejected value for param "${key}"\n Error: ${message}\n Raw value: ${JSON.stringify(mergeTarget[key])}\n Hint: check the codec in app/schema.ts for key '${bracketKey}'.`);
|
|
1289
|
+
throw new ParamCoercionError(message);
|
|
1290
|
+
}
|
|
1291
|
+
mergeTarget[key] = normalizeParamValue(parsed, key);
|
|
1292
|
+
}
|
|
1293
|
+
return mergeTarget;
|
|
1295
1294
|
}
|
|
1296
|
-
|
|
1297
|
-
//#region src/server/rsc-error-envelope.ts
|
|
1295
|
+
// src/server/head-response.ts
|
|
1298
1296
|
/**
|
|
1299
|
-
*
|
|
1297
|
+
* HEAD body stripping — RFC 9110 §9.3.2.
|
|
1300
1298
|
*
|
|
1301
|
-
*
|
|
1302
|
-
*
|
|
1303
|
-
*
|
|
1304
|
-
*
|
|
1305
|
-
*
|
|
1299
|
+
* "The HEAD method is identical to GET except that the server MUST NOT send
|
|
1300
|
+
* content in the response." The headers, however, must be the ones the
|
|
1301
|
+
* corresponding GET would have produced — which is why timber renders the
|
|
1302
|
+
* route in full and discards the body here rather than short-circuiting the
|
|
1303
|
+
* render. Content-Type, Content-Length, Set-Cookie, cache directives and
|
|
1304
|
+
* everything else ride through untouched.
|
|
1305
|
+
*
|
|
1306
|
+
* Node's `ServerResponse` happens to discard writes for HEAD, so the wire is
|
|
1307
|
+
* usually correct even without this. That is a property of one adapter, not of
|
|
1308
|
+
* the `Response` object: static generation, the Cloudflare and Nitro adapters,
|
|
1309
|
+
* tests, and anything calling the pipeline handler as a function all observe
|
|
1310
|
+
* the `Response` directly and saw the full body before TIM-1324.
|
|
1311
|
+
*
|
|
1312
|
+
* The pipeline applies this at its single exit so every response shape is
|
|
1313
|
+
* covered — page render, API route, metadata route, deny page, error page,
|
|
1314
|
+
* proxy short-circuit. The unit-level producer that is also reachable as a
|
|
1315
|
+
* standalone function (`handleRouteRequest`) calls it too, so it honours HEAD
|
|
1316
|
+
* on its own; it shares this implementation rather than repeating it, and
|
|
1317
|
+
* applying it twice is a no-op.
|
|
1306
1318
|
*/
|
|
1307
|
-
function rscErrorEnvelope(status, responseHeaders) {
|
|
1308
|
-
const headers = errorResponseHeaders(responseHeaders);
|
|
1309
|
-
headers.set(TIMBER_ERROR_HEADER, "1");
|
|
1310
|
-
headers.set("content-type", "application/json; charset=utf-8");
|
|
1311
|
-
return new Response(JSON.stringify({
|
|
1312
|
-
error: true,
|
|
1313
|
-
status
|
|
1314
|
-
}), {
|
|
1315
|
-
status,
|
|
1316
|
-
headers
|
|
1317
|
-
});
|
|
1318
|
-
}
|
|
1319
|
-
//#endregion
|
|
1320
|
-
//#region src/server/pipeline-outcome.ts
|
|
1321
1319
|
/**
|
|
1322
|
-
*
|
|
1323
|
-
* each phase function returns) into a final `Response`.
|
|
1320
|
+
* Return a bodyless copy of `response` when `method` is HEAD.
|
|
1324
1321
|
*
|
|
1325
|
-
*
|
|
1326
|
-
*
|
|
1327
|
-
* their own file. The phases produce values; this module is the single
|
|
1328
|
-
* source of truth for how those values become wire responses.
|
|
1322
|
+
* A no-op for every other method and for responses that already carry no body
|
|
1323
|
+
* (204, 304, redirects), so callers do not need to pre-check either.
|
|
1329
1324
|
*
|
|
1330
|
-
*
|
|
1325
|
+
* The discarded stream is cancelled: an SSR render that reached this point has
|
|
1326
|
+
* a live producer attached, and dropping the reference without cancelling
|
|
1327
|
+
* leaks it for the lifetime of the render (design/13-security.md A4).
|
|
1331
1328
|
*/
|
|
1332
|
-
function
|
|
1333
|
-
if (
|
|
1329
|
+
function stripHeadBody(response, method) {
|
|
1330
|
+
if (method.toUpperCase() !== "HEAD") return response;
|
|
1331
|
+
const nodeBody = nodeBodyOps(response);
|
|
1332
|
+
if (nodeBody ? !nodeBody.hasBody : response.body === null) return response;
|
|
1333
|
+
discardResponseBody(response);
|
|
1334
1334
|
return new Response(null, {
|
|
1335
|
-
status,
|
|
1336
|
-
|
|
1335
|
+
status: response.status,
|
|
1336
|
+
statusText: response.statusText,
|
|
1337
|
+
headers: response.headers
|
|
1337
1338
|
});
|
|
1338
1339
|
}
|
|
1340
|
+
// src/server/route-handler.ts
|
|
1341
|
+
/** All recognized HTTP method export names. */
|
|
1342
|
+
var HTTP_METHODS = [
|
|
1343
|
+
"GET",
|
|
1344
|
+
"POST",
|
|
1345
|
+
"PUT",
|
|
1346
|
+
"PATCH",
|
|
1347
|
+
"DELETE",
|
|
1348
|
+
"HEAD",
|
|
1349
|
+
"OPTIONS"
|
|
1350
|
+
];
|
|
1339
1351
|
/**
|
|
1340
|
-
* Resolve the
|
|
1341
|
-
* cookie jar applied exactly once.
|
|
1342
|
-
*
|
|
1343
|
-
* Ownership rule (design/49 §P0b): the phase that owns `responseHeaders`
|
|
1344
|
-
* applies the jar to it once; the translator applies it only for outcomes
|
|
1345
|
-
* that arrive without it. Render-phase outcomes already carry the jar —
|
|
1346
|
-
* `runRenderPhase()` applies it on entry, with or without a middleware
|
|
1347
|
-
* chain — so re-applying here emitted every middleware `Set-Cookie` twice
|
|
1348
|
-
* (TIM-1491).
|
|
1352
|
+
* Resolve the full list of allowed methods for a route module.
|
|
1349
1353
|
*
|
|
1350
|
-
*
|
|
1351
|
-
*
|
|
1352
|
-
*
|
|
1353
|
-
*
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1354
|
+
* Includes:
|
|
1355
|
+
* - All explicitly exported methods
|
|
1356
|
+
* - HEAD (implicit when GET is exported)
|
|
1357
|
+
* - OPTIONS (always implicit)
|
|
1358
|
+
*/
|
|
1359
|
+
function resolveAllowedMethods(mod) {
|
|
1360
|
+
const methods = [];
|
|
1361
|
+
for (const method of HTTP_METHODS) {
|
|
1362
|
+
if (method === "HEAD" || method === "OPTIONS") continue;
|
|
1363
|
+
if (mod[method]) methods.push(method);
|
|
1364
|
+
}
|
|
1365
|
+
if (mod.GET && !mod.HEAD) methods.push("HEAD");
|
|
1366
|
+
else if (mod.HEAD) methods.push("HEAD");
|
|
1367
|
+
if (!mod.OPTIONS) methods.push("OPTIONS");
|
|
1368
|
+
else methods.push("OPTIONS");
|
|
1369
|
+
return methods;
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Handle an incoming request against a route.ts module.
|
|
1357
1373
|
*
|
|
1358
|
-
*
|
|
1374
|
+
* Dispatches to the named method handler, auto-generates 405/OPTIONS,
|
|
1375
|
+
* and merges response headers from ctx.headers.
|
|
1359
1376
|
*/
|
|
1360
|
-
function
|
|
1361
|
-
const
|
|
1362
|
-
|
|
1363
|
-
|
|
1377
|
+
async function handleRouteRequest(mod, ctx) {
|
|
1378
|
+
const method = ctx.req.method.toUpperCase();
|
|
1379
|
+
const allowHeader = resolveAllowedMethods(mod).join(", ");
|
|
1380
|
+
if (method === "OPTIONS") {
|
|
1381
|
+
if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
|
|
1382
|
+
return mergeResponseHeaders(new Response(null, {
|
|
1383
|
+
status: 204,
|
|
1384
|
+
headers: { Allow: allowHeader }
|
|
1385
|
+
}), ctx.headers);
|
|
1386
|
+
}
|
|
1387
|
+
if (method === "HEAD") {
|
|
1388
|
+
if (mod.HEAD) return stripHeadBody(await runHandler(mod.HEAD, ctx), method);
|
|
1389
|
+
if (mod.GET) return stripHeadBody(await runHandler(mod.GET, ctx), method);
|
|
1390
|
+
}
|
|
1391
|
+
const handler = mod[method];
|
|
1392
|
+
if (!handler) return mergeResponseHeaders(new Response(null, {
|
|
1393
|
+
status: 405,
|
|
1394
|
+
headers: { Allow: allowHeader }
|
|
1395
|
+
}), ctx.headers);
|
|
1396
|
+
return runHandler(handler, ctx);
|
|
1364
1397
|
}
|
|
1365
|
-
/**
|
|
1366
|
-
|
|
1367
|
-
|
|
1398
|
+
/**
|
|
1399
|
+
* Run a handler with cookie writes enabled and merge ctx.headers into its
|
|
1400
|
+
* response.
|
|
1401
|
+
*
|
|
1402
|
+
* Cookies (design/29-cookies.md §"Where Cookies Can Be Set"): the render
|
|
1403
|
+
* phase applied the jar to `ctx.headers` before the handler ran, so on the
|
|
1404
|
+
* way out only what the handler changed is synced onto that bag. It happens
|
|
1405
|
+
* whether the handler returns or throws, so a cookie set before `redirect()`
|
|
1406
|
+
* rides the redirect, and the pipeline's 500 for a throw carries the same
|
|
1407
|
+
* bag.
|
|
1408
|
+
*
|
|
1409
|
+
* Nothing is caught. A signal goes to the pipeline, whose deny fallback
|
|
1410
|
+
* answers a route.ts match in JSON and whose redirect outcome sends the 3xx
|
|
1411
|
+
* (TIM-1533). Any other error goes to the pipeline, which logs it,
|
|
1412
|
+
* reports it to `onRequestError` as phase `'route'`, and answers it in the
|
|
1413
|
+
* same format as every other route.ts error (TIM-1537).
|
|
1414
|
+
*/
|
|
1415
|
+
async function runHandler(handler, ctx) {
|
|
1416
|
+
const applied = getSetCookieHeaders();
|
|
1417
|
+
setMutableCookieContext(true);
|
|
1418
|
+
let res;
|
|
1419
|
+
try {
|
|
1420
|
+
res = await handler(ctx);
|
|
1421
|
+
} finally {
|
|
1422
|
+
setMutableCookieContext(false);
|
|
1423
|
+
syncCookieJar(ctx.headers, applied);
|
|
1424
|
+
}
|
|
1425
|
+
return mergeResponseHeaders(res, ctx.headers);
|
|
1368
1426
|
}
|
|
1369
1427
|
/**
|
|
1370
|
-
*
|
|
1371
|
-
*
|
|
1372
|
-
*
|
|
1373
|
-
*
|
|
1428
|
+
* Merge response headers from ctx.headers into the handler's response.
|
|
1429
|
+
* ctx.headers (set by middleware or the handler) are applied to the final response.
|
|
1430
|
+
* Handler-set headers take precedence over ctx.headers. Metadata routes
|
|
1431
|
+
* behind gates merge their middleware's headers the same way.
|
|
1374
1432
|
*/
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1433
|
+
function mergeResponseHeaders(res, ctxHeaders) {
|
|
1434
|
+
let hasCtxHeaders = false;
|
|
1435
|
+
ctxHeaders.forEach(() => {
|
|
1436
|
+
hasCtxHeaders = true;
|
|
1437
|
+
});
|
|
1438
|
+
if (!hasCtxHeaders) return res;
|
|
1439
|
+
const merged = new Headers();
|
|
1440
|
+
ctxHeaders.forEach((value, key) => {
|
|
1441
|
+
if (key.toLowerCase() === "set-cookie") merged.append(key, value);
|
|
1442
|
+
else merged.set(key, value);
|
|
1443
|
+
});
|
|
1444
|
+
const resCookies = res.headers.getSetCookie();
|
|
1445
|
+
for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
|
|
1446
|
+
res.headers.forEach((value, key) => {
|
|
1447
|
+
if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
|
|
1448
|
+
});
|
|
1449
|
+
return new Response(res.body, {
|
|
1450
|
+
status: res.status,
|
|
1451
|
+
statusText: res.statusText,
|
|
1452
|
+
headers: merged
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
// src/server/traced-access.ts
|
|
1456
|
+
/**
|
|
1457
|
+
* Run each segment's `access.ts`, root to leaf, outside a render. Each one
|
|
1458
|
+
* is independent; a deny() or redirect() propagates as a signal.
|
|
1459
|
+
*/
|
|
1460
|
+
async function runAccessChain(segments) {
|
|
1461
|
+
for (const segment of segments) {
|
|
1462
|
+
if (!segment.access) continue;
|
|
1463
|
+
const { default: accessFn } = await loadModule(segment.access);
|
|
1464
|
+
if (accessFn) await runTracedAccess(accessFn, segment.segmentName);
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Call one access function inside a `timber.access` span that records its
|
|
1469
|
+
* result. Signals and errors propagate unchanged.
|
|
1470
|
+
*/
|
|
1471
|
+
async function runTracedAccess(accessFn, segmentName) {
|
|
1472
|
+
await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
|
|
1473
|
+
try {
|
|
1474
|
+
await accessFn();
|
|
1475
|
+
await setSpanAttribute("timber.result", "pass");
|
|
1476
|
+
} catch (error) {
|
|
1477
|
+
if (isDenySignal(error)) {
|
|
1478
|
+
await setSpanAttribute("timber.result", "deny");
|
|
1479
|
+
await setSpanAttribute("timber.deny_status", error.status);
|
|
1480
|
+
if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
|
|
1481
|
+
} else if (isRedirectSignal(error)) await setSpanAttribute("timber.result", "redirect");
|
|
1482
|
+
throw error;
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
// src/server/pipeline-metadata-route.ts
|
|
1487
|
+
/**
|
|
1488
|
+
* Stage 1b of the request pipeline: serving a matched metadata route
|
|
1489
|
+
* (sitemap, robots, manifest, favicon, icon, apple-icon, opengraph-image).
|
|
1490
|
+
*
|
|
1491
|
+
* A metadata route runs the per-segment stages a page at its segment runs,
|
|
1492
|
+
* in the same order: param coercion through `app/schema.ts`, then the
|
|
1493
|
+
* `middleware.ts` chain, then the `access.ts` chain — then the file or
|
|
1494
|
+
* handler. Files owned by the root segment are the one exception: they are
|
|
1495
|
+
* the app's public crawler surface (`/robots.txt`, `/sitemap.xml`, the app
|
|
1496
|
+
* icons), so no gate runs for them, not even a root `access.ts` that gates
|
|
1497
|
+
* every page. A file anywhere below the root, a route group included, sits
|
|
1498
|
+
* in its segments' authorization scope like any page there (TIM-1609).
|
|
1499
|
+
*
|
|
1500
|
+
* Signals answer with a bare status, never a deny page: a metadata route is
|
|
1501
|
+
* an image, a sitemap or a text file, not a document.
|
|
1502
|
+
*
|
|
1503
|
+
* See design/16-metadata.md §"Pipeline Integration",
|
|
1504
|
+
* design/13-security.md threat 11b.
|
|
1505
|
+
*/
|
|
1506
|
+
/** Answer a request whose canonical pathname matched a metadata route. */
|
|
1507
|
+
async function serveMetadataRoute(config, req, method, path, pathname, metaMatch) {
|
|
1508
|
+
const { segments } = metaMatch;
|
|
1509
|
+
const middlewareChain = segments.length > 1 ? collectMiddlewareChain(segments) : [];
|
|
1510
|
+
const gated = segments.length > 1 && (middlewareChain.length > 0 || segments.some((s) => s.access));
|
|
1511
|
+
const route = {
|
|
1512
|
+
segments,
|
|
1513
|
+
segmentParams: metaMatch.segmentParams,
|
|
1514
|
+
rawSegmentParams: metaMatch.segmentParams,
|
|
1515
|
+
middlewareChain
|
|
1516
|
+
};
|
|
1517
|
+
const responseHeaders = gated ? dynamicResponseHeaders() : void 0;
|
|
1518
|
+
const finish = (response) => {
|
|
1519
|
+
if (!responseHeaders) return cloneWithMutableHeaders(response);
|
|
1520
|
+
applyCookieJar(responseHeaders);
|
|
1521
|
+
return mergeResponseHeaders(response, responseHeaders);
|
|
1522
|
+
};
|
|
1523
|
+
const fail = async (error, phase) => {
|
|
1524
|
+
if (phase === "setup") logRouteSetupError({
|
|
1396
1525
|
method,
|
|
1397
1526
|
path,
|
|
1398
1527
|
error
|
|
@@ -1402,102 +1531,355 @@ async function reportError(config, error, phase, ctx) {
|
|
|
1402
1531
|
path,
|
|
1403
1532
|
error
|
|
1404
1533
|
});
|
|
1534
|
+
await fireOnRequestError(error, req, phase, segments);
|
|
1535
|
+
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
|
|
1536
|
+
if (responseHeaders) applyCookieJar(responseHeaders);
|
|
1537
|
+
return new Response(null, {
|
|
1538
|
+
status: 500,
|
|
1539
|
+
headers: errorResponseHeaders(responseHeaders)
|
|
1540
|
+
});
|
|
1541
|
+
};
|
|
1542
|
+
try {
|
|
1543
|
+
route.segmentParams = await coerceSegmentParams(route);
|
|
1544
|
+
} catch (error) {
|
|
1545
|
+
if (!(error instanceof ParamCoercionError)) return fail(error, "setup");
|
|
1546
|
+
warnParamCoercionFailure(method, pathname, segments, error);
|
|
1547
|
+
return new Response(null, { status: 404 });
|
|
1548
|
+
}
|
|
1549
|
+
setSegmentParams(route.segmentParams);
|
|
1550
|
+
setMatchedSegmentPath(matchedSegmentPath(segments));
|
|
1551
|
+
try {
|
|
1552
|
+
if (responseHeaders && middlewareChain.length > 0) {
|
|
1553
|
+
const stopped = await runMiddlewarePhase(config, req, route, responseHeaders);
|
|
1554
|
+
if (stopped?.kind === "redirect" || stopped?.kind === "deny") throw stopped.signal;
|
|
1555
|
+
if (stopped) return await outcomeToResponse(config, stopped, {
|
|
1556
|
+
req,
|
|
1557
|
+
method,
|
|
1558
|
+
path,
|
|
1559
|
+
responseHeaders
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
if (gated) await runAccessChain(segments);
|
|
1563
|
+
const cacheControl = gated ? void 0 : METADATA_CACHE_CONTROL;
|
|
1564
|
+
if (metaMatch.isStatic) return finish(await serveStaticMetadataFile(metaMatch, cacheControl));
|
|
1565
|
+
const response = await runMetadataHandler(metaMatch, cacheControl);
|
|
1566
|
+
if (method === "HEAD" || !metaMatch.contentType.startsWith("image/")) return finish(response);
|
|
1567
|
+
return finish(await bufferResponse(response, resolveRenderTimeoutMs(config.renderTimeoutMs), req.signal));
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
if (isRedirectSignal(error)) return finish(buildRedirectResponse(error, new Headers(), false));
|
|
1570
|
+
if (isDenySignal(error)) return finish(new Response(null, { status: error.status }));
|
|
1571
|
+
return fail(error, "route");
|
|
1405
1572
|
}
|
|
1406
|
-
await fireOnRequestError(error, ctx.req, phase, ctx.match?.segments);
|
|
1407
|
-
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, phase);
|
|
1408
1573
|
}
|
|
1409
|
-
/**
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1574
|
+
/**
|
|
1575
|
+
* Call a dynamic metadata route's default export and turn its result into a
|
|
1576
|
+
* Response. `cacheControl` is set on a result the framework serializes; a
|
|
1577
|
+
* Response the handler returns gets no framework default (a gated route then
|
|
1578
|
+
* merges its middleware headers and page policy under the handler's own).
|
|
1579
|
+
*/
|
|
1580
|
+
async function runMetadataHandler(metaMatch, cacheControl) {
|
|
1581
|
+
const mod = await loadModule(metaMatch.file);
|
|
1582
|
+
if (typeof mod.default !== "function") {
|
|
1583
|
+
if (isDebug()) console.warn(`[timber] Metadata route ${metaMatch.file} does not export a default function — responding with 500\n Metadata routes must export a default function that returns the metadata content.`);
|
|
1584
|
+
return new Response("Metadata route must export a default function", { status: 500 });
|
|
1585
|
+
}
|
|
1586
|
+
const handlerResult = await mod.default();
|
|
1587
|
+
if (handlerResult instanceof Response) return handlerResult;
|
|
1588
|
+
const contentType = metaMatch.contentType;
|
|
1589
|
+
let body;
|
|
1590
|
+
if (typeof handlerResult === "string") body = handlerResult;
|
|
1591
|
+
else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
|
|
1592
|
+
else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
|
|
1593
|
+
else body = String(handlerResult);
|
|
1594
|
+
const headers = new Headers({ "Content-Type": `${contentType}; charset=utf-8` });
|
|
1595
|
+
if (cacheControl) headers.set("Cache-Control", cacheControl);
|
|
1596
|
+
return new Response(body, {
|
|
1597
|
+
status: 200,
|
|
1598
|
+
headers
|
|
1599
|
+
});
|
|
1426
1600
|
}
|
|
1427
1601
|
/**
|
|
1428
|
-
*
|
|
1429
|
-
*
|
|
1430
|
-
*
|
|
1602
|
+
* Read an image route's Response body to the end, under `renderTimeoutMs`
|
|
1603
|
+
* and until the client leaves, and answer with the bytes and their
|
|
1604
|
+
* Content-Length.
|
|
1605
|
+
*
|
|
1606
|
+
* An `ImageResponse` renders lazily: the handler returns at once and the
|
|
1607
|
+
* image fails, if it fails, on the body's first read. Passed through, that
|
|
1608
|
+
* read happens after the status is committed, and the Web→Node bridge
|
|
1609
|
+
* (srvx's `sendNodeResponse`) destroys the socket before any byte is
|
|
1610
|
+
* written — an empty reply with no status line (TIM-1602). Read here, the
|
|
1611
|
+
* failure throws inside `serveMetadataRoute`'s catch and answers 500.
|
|
1612
|
+
* Icons and social cards are small, bounded assets, so holding one is
|
|
1613
|
+
* cheap; a route.ts body is never buffered.
|
|
1614
|
+
*/
|
|
1615
|
+
async function bufferResponse(response, timeoutMs, signal) {
|
|
1616
|
+
if (!response.body) return response;
|
|
1617
|
+
const reader = response.body.getReader();
|
|
1618
|
+
const readDone = new AbortController();
|
|
1619
|
+
const clientLeft = new Promise((_, reject) => {
|
|
1620
|
+
onAbortUntil(signal, () => reject(signal.reason), readDone.signal);
|
|
1621
|
+
});
|
|
1622
|
+
clientLeft.catch(() => {});
|
|
1623
|
+
let chunks;
|
|
1624
|
+
try {
|
|
1625
|
+
chunks = await drainWithDeadline({
|
|
1626
|
+
read: () => Promise.race([reader.read(), clientLeft]),
|
|
1627
|
+
cancel: (reason) => void reader.cancel(reason).catch(() => {})
|
|
1628
|
+
}, timeoutMs, "Metadata route body");
|
|
1629
|
+
} finally {
|
|
1630
|
+
readDone.abort();
|
|
1631
|
+
}
|
|
1632
|
+
const bytes = concatBytes(chunks);
|
|
1633
|
+
const headers = new Headers(response.headers);
|
|
1634
|
+
headers.set("Content-Length", String(bytes.byteLength));
|
|
1635
|
+
return new Response(bytes, {
|
|
1636
|
+
status: response.status,
|
|
1637
|
+
statusText: response.statusText,
|
|
1638
|
+
headers
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
// src/server/state-tree-diff.ts
|
|
1642
|
+
/**
|
|
1643
|
+
* State Tree Diffing — Server-side parsing and diffing of X-Timber-State-Tree.
|
|
1431
1644
|
*
|
|
1432
|
-
*
|
|
1433
|
-
*
|
|
1434
|
-
*
|
|
1645
|
+
* The client sends X-Timber-State-Tree on navigation requests, listing
|
|
1646
|
+
* the sync segments it has cached. The server diffs this against the
|
|
1647
|
+
* target route's segments to skip re-rendering unchanged sync layouts.
|
|
1648
|
+
*
|
|
1649
|
+
* This is a performance optimization only — NOT a security boundary.
|
|
1650
|
+
* All access.ts files run regardless of the state tree content.
|
|
1651
|
+
* A fabricated state tree can only cause extra rendering work or stale
|
|
1652
|
+
* layouts — never auth bypass.
|
|
1653
|
+
*
|
|
1654
|
+
* See design/19-client-navigation.md §"X-Timber-State-Tree Header"
|
|
1655
|
+
* See design/13-security.md §"State tree manipulation"
|
|
1435
1656
|
*/
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1657
|
+
/**
|
|
1658
|
+
* Parse the X-Timber-State-Tree header from a request.
|
|
1659
|
+
*
|
|
1660
|
+
* Returns a Set of segment paths the client has cached (with an
|
|
1661
|
+
* additional `slots` property for cached slot paths), or null if
|
|
1662
|
+
* the header is missing, malformed, or empty. Parsing happens before
|
|
1663
|
+
* renderToReadableStream — not inside the React render pass.
|
|
1664
|
+
*
|
|
1665
|
+
* @returns ClientStateTree with segments and slots, or null if no valid state tree
|
|
1666
|
+
*/
|
|
1667
|
+
function parseClientStateTree(req) {
|
|
1668
|
+
const header = req.headers.get("X-Timber-State-Tree");
|
|
1669
|
+
if (!header) return null;
|
|
1670
|
+
try {
|
|
1671
|
+
const parsed = JSON.parse(header);
|
|
1672
|
+
const hasSegments = Array.isArray(parsed.segments) && parsed.segments.length > 0;
|
|
1673
|
+
const hasSlots = Array.isArray(parsed.slots) && parsed.slots.length > 0;
|
|
1674
|
+
const hasTreePaths = Array.isArray(parsed.treePaths) && parsed.treePaths.length > 0;
|
|
1675
|
+
if (!hasSegments && !hasSlots && !hasTreePaths) return null;
|
|
1676
|
+
const result = new Set(hasSegments ? parsed.segments : []);
|
|
1677
|
+
result.slots = hasSlots ? new Set(parsed.slots) : null;
|
|
1678
|
+
result.treePaths = hasTreePaths ? new Set(parsed.treePaths) : null;
|
|
1679
|
+
return result;
|
|
1680
|
+
} catch (err) {
|
|
1681
|
+
swallow(err, "malformed X-Timber-State-Tree header");
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
// src/server/pipeline-interception.ts
|
|
1686
|
+
/**
|
|
1687
|
+
* Interception route matching for the request pipeline.
|
|
1688
|
+
*
|
|
1689
|
+
* Matches target URLs against interception rewrites to support the
|
|
1690
|
+
* modal route pattern (soft navigation intercepts).
|
|
1691
|
+
*
|
|
1692
|
+
* Extracted from pipeline.ts to keep files under 500 lines.
|
|
1693
|
+
*
|
|
1694
|
+
* See design/07-routing.md §"Intercepting Routes"
|
|
1695
|
+
*/
|
|
1696
|
+
/**
|
|
1697
|
+
* Check if an intercepting route applies for this soft navigation.
|
|
1698
|
+
*
|
|
1699
|
+
* Two conditions must hold:
|
|
1700
|
+
*
|
|
1701
|
+
* 1. The **target** pathname matches the rewrite's intercepted pattern.
|
|
1702
|
+
* 2. The **source** route — the page the user is navigating FROM, per the
|
|
1703
|
+
* validated X-Timber-URL header — renders the segment that owns the slot
|
|
1704
|
+
* holding the intercepting page (`interceptingScope`). Only then does that
|
|
1705
|
+
* slot exist in the rendered tree, so only then can the intercepting page
|
|
1706
|
+
* render.
|
|
1707
|
+
*
|
|
1708
|
+
* Condition 2 replaced a URL-prefix check (TIM-1279). A prefix cannot
|
|
1709
|
+
* distinguish a route-group-scoped interception from a genuinely root-level
|
|
1710
|
+
* one — route groups are invisible in `urlPath`, so both collapse to "/" and
|
|
1711
|
+
* the guard degenerates to always-true. Tree paths carry group identity.
|
|
1712
|
+
* The scope check also subsumes the old segment-boundary rule: a source route
|
|
1713
|
+
* under /feed-private has no "/feed" in its chain.
|
|
1714
|
+
*
|
|
1715
|
+
* A third condition lives with the caller, which owns route matching, and it
|
|
1716
|
+
* applies to the `'slot'` shape only: the route produced by re-matching
|
|
1717
|
+
* `interceptingPrefix` must pass through the scope too. Conditions 1–2 are
|
|
1718
|
+
* about the route the user is leaving; the slot has to exist in the tree that
|
|
1719
|
+
* actually renders. The `'children'` shape resolves its owner from the scope
|
|
1720
|
+
* directly rather than from a pathname, so it satisfies that by construction.
|
|
1721
|
+
*
|
|
1722
|
+
* `resolveSourceScopes` is a thunk so its inputs are only resolved when some
|
|
1723
|
+
* rewrite's pattern actually matches the target — the common case is no match
|
|
1724
|
+
* at all. It returns the two client-supplied answers to "what is on screen?"
|
|
1725
|
+
* as **separate sets, most authoritative first**: the tree paths the client
|
|
1726
|
+
* says it has mounted, then those of the route the departing URL matches. It
|
|
1727
|
+
* returns null only when neither yields anything, which is not a soft
|
|
1728
|
+
* navigation this can reason about.
|
|
1729
|
+
*
|
|
1730
|
+
* They are two sets rather than one union because ranking needs a chain
|
|
1731
|
+
* (TIM-1318). Each channel describes a single rendered chain, so within one the
|
|
1732
|
+
* scopes are strictly nested and the deepest is the innermost owner. Unioned
|
|
1733
|
+
* they are not: once a modal is open the address bar holds the *intercepted*
|
|
1734
|
+
* URL, so the second channel describes the canonical branch — possibly an
|
|
1735
|
+
* exclusive route group the client never mounted — and a deeper scope from
|
|
1736
|
+
* there would outrank the owner actually on screen. Trying the mounted channel
|
|
1737
|
+
* to exhaustion first keeps the fallback the union was there to provide while
|
|
1738
|
+
* ranking only within one chain.
|
|
1739
|
+
*
|
|
1740
|
+
* Returns the winning build-time rewrite, or null. Only build-time values ever
|
|
1741
|
+
* reach the renderer: the client-supplied header selects a rewrite but never
|
|
1742
|
+
* becomes a rendered route or pathname.
|
|
1743
|
+
*
|
|
1744
|
+
* The **first** matching rewrite wins, and the caller does not fall back to the
|
|
1745
|
+
* next one when the winner fails to resolve. That is deliberate and pre-dates
|
|
1746
|
+
* the two shapes: a rewrite that matched the target and the scope described the
|
|
1747
|
+
* author's intent, and quietly rendering some other author's interception
|
|
1748
|
+
* instead would be harder to explain than rendering the canonical route.
|
|
1749
|
+
*
|
|
1750
|
+
* "First" is meaningful because the list arrives **deepest scope first** —
|
|
1751
|
+
* `collectInterceptionRewrites` sorts it at build time, so the deepest owner a
|
|
1752
|
+
* single chain passes through wins and nothing here has to score (TIM-1318).
|
|
1753
|
+
* Tree-walk order used to decide it, which meant renaming a route group flipped
|
|
1754
|
+
* which modal opened. The precondition is a property of the manifest this reads
|
|
1755
|
+
* rather than something it can re-derive, so it is asserted at its source:
|
|
1756
|
+
* `tests/interception.test.ts` §"rewrite order is decided by scope depth".
|
|
1757
|
+
*/
|
|
1758
|
+
function findInterceptionMatch(targetPathname, resolveSourceScopes, rewrites) {
|
|
1759
|
+
const candidates = rewrites.filter((rewrite) => pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern));
|
|
1760
|
+
if (candidates.length === 0) return null;
|
|
1761
|
+
const scopes = resolveSourceScopes();
|
|
1762
|
+
if (!scopes) return null;
|
|
1763
|
+
for (const scope of scopes) for (const rewrite of candidates) if (scope.has(rewrite.interceptingScope)) return rewrite;
|
|
1764
|
+
return null;
|
|
1765
|
+
}
|
|
1766
|
+
/**
|
|
1767
|
+
* Check if a pathname matches a URL pattern with dynamic segments.
|
|
1768
|
+
*
|
|
1769
|
+
* Supports [param] (single segment) and [...param] (one or more segments).
|
|
1770
|
+
* Static segments must match exactly.
|
|
1771
|
+
*/
|
|
1772
|
+
function pathnameMatchesPattern(pathname, pattern) {
|
|
1773
|
+
const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
|
|
1774
|
+
const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
|
|
1775
|
+
let pi = 0;
|
|
1776
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1777
|
+
const seg = classifyUrlSegment(patternParts[i]);
|
|
1778
|
+
switch (seg.kind) {
|
|
1779
|
+
case "catch-all": return pi < pathParts.length;
|
|
1780
|
+
case "optional-catch-all": return true;
|
|
1781
|
+
case "dynamic": {
|
|
1782
|
+
if (pi >= pathParts.length) return false;
|
|
1783
|
+
const prefix = seg.prefix ?? "";
|
|
1784
|
+
const suffix = seg.suffix ?? "";
|
|
1785
|
+
const pathPart = pathParts[pi];
|
|
1786
|
+
if (prefix || suffix) {
|
|
1787
|
+
if (pathPart.length <= prefix.length + suffix.length || prefix && !pathPart.startsWith(prefix) || suffix && !pathPart.endsWith(suffix)) return false;
|
|
1788
|
+
}
|
|
1789
|
+
pi++;
|
|
1790
|
+
continue;
|
|
1471
1791
|
}
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
});
|
|
1792
|
+
case "static":
|
|
1793
|
+
if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
|
|
1794
|
+
pi++;
|
|
1795
|
+
continue;
|
|
1477
1796
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1797
|
+
}
|
|
1798
|
+
return pi === pathParts.length;
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Resolve which route renders a soft navigation that an intercepting route
|
|
1802
|
+
* may claim. Returns the canonical match unchanged when no rewrite applies.
|
|
1803
|
+
*
|
|
1804
|
+
* Runs during route setup, so anything it throws is a `'setup'` outcome.
|
|
1805
|
+
*/
|
|
1806
|
+
function resolveInterceptedRoute(config, req, canonicalPathname, canonicalMatch) {
|
|
1807
|
+
const stripTrailingSlash = config.stripTrailingSlash ?? true;
|
|
1808
|
+
let match = canonicalMatch;
|
|
1809
|
+
let interception;
|
|
1810
|
+
if (isRscRequest(req) && config.interceptionRewrites?.length) {
|
|
1811
|
+
const rawSourceUrl = req.headers.get("X-Timber-URL");
|
|
1812
|
+
const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
|
|
1813
|
+
if (validatedSourceUrl) {
|
|
1814
|
+
const resolveSourceScopes = () => {
|
|
1815
|
+
const mounted = new Set(parseClientStateTree(req)?.treePaths ?? []);
|
|
1816
|
+
const sourceRoute = config.matchRoute(validatedSourceUrl);
|
|
1817
|
+
const scopes = [mounted, new Set(sourceRoute ? computeSegmentTreePaths(sourceRoute.segments) : [])].filter((scope) => scope.size > 0);
|
|
1818
|
+
return scopes.length > 0 ? scopes : null;
|
|
1819
|
+
};
|
|
1820
|
+
const rewrite = findInterceptionMatch(canonicalPathname, resolveSourceScopes, config.interceptionRewrites);
|
|
1821
|
+
if (rewrite?.mode === "children") {
|
|
1822
|
+
const interceptedMatch = config.matchInterceptedRoute?.(canonicalPathname, rewrite.interceptingScope);
|
|
1823
|
+
if (interceptedMatch) match = interceptedMatch;
|
|
1824
|
+
} else if (rewrite) {
|
|
1825
|
+
const sourceMatch = config.matchRoute(rewrite.interceptingPrefix);
|
|
1826
|
+
if (sourceMatch !== null && computeSegmentTreePaths(sourceMatch.segments).includes(rewrite.interceptingScope)) {
|
|
1827
|
+
match = sourceMatch;
|
|
1828
|
+
interception = { targetPathname: canonicalPathname };
|
|
1829
|
+
}
|
|
1494
1830
|
}
|
|
1495
|
-
return rscErrorResponse(false, 500, headers);
|
|
1496
1831
|
}
|
|
1497
1832
|
}
|
|
1833
|
+
if (match === canonicalMatch || !canonicalMatch) return {
|
|
1834
|
+
match,
|
|
1835
|
+
interception
|
|
1836
|
+
};
|
|
1837
|
+
return {
|
|
1838
|
+
match,
|
|
1839
|
+
interception,
|
|
1840
|
+
canonical: canonicalMatch
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* The middleware an intercepted navigation runs: the URL's chain, then each
|
|
1845
|
+
* middleware.ts only the rendered chain has. Shared ancestors are the same
|
|
1846
|
+
* manifest nodes on both chains, so each file runs once, and each chain keeps
|
|
1847
|
+
* its own root-to-leaf order (TIM-1607).
|
|
1848
|
+
*/
|
|
1849
|
+
function interceptedMiddlewareChain(canonical, rendered) {
|
|
1850
|
+
const onCanonical = new Set(canonical.segments);
|
|
1851
|
+
return collectMiddlewareChain([...canonical.segments, ...rendered.segments.filter((segment) => !onCanonical.has(segment))]);
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Validate and canonicalize the X-Timber-URL header value.
|
|
1855
|
+
*
|
|
1856
|
+
* Returns the canonical pathname if valid, or null if rejected:
|
|
1857
|
+
* - Must start with '/' (relative pathname, no scheme/authority)
|
|
1858
|
+
* - Must not contain control characters
|
|
1859
|
+
* - Must pass canonicalization (no encoded separators, null bytes, etc.)
|
|
1860
|
+
*/
|
|
1861
|
+
function validateInterceptionHeader(raw, stripTrailingSlash) {
|
|
1862
|
+
if (!raw.startsWith("/")) return null;
|
|
1863
|
+
if (raw.startsWith("//")) return null;
|
|
1864
|
+
for (let i = 0; i < raw.length; i++) {
|
|
1865
|
+
const code = raw.charCodeAt(i);
|
|
1866
|
+
if (code <= 31 || code === 127) return null;
|
|
1867
|
+
}
|
|
1868
|
+
const result = canonicalize(raw, stripTrailingSlash);
|
|
1869
|
+
if (!result.ok) return null;
|
|
1870
|
+
return result.pathname;
|
|
1871
|
+
}
|
|
1872
|
+
/**
|
|
1873
|
+
* Run `fn` with a route's own params as what `getSegmentParams()` returns.
|
|
1874
|
+
*
|
|
1875
|
+
* An intercepted request publishes the rendered route's params. The URL's
|
|
1876
|
+
* middleware and access.ts were written for the URL's route, and run under
|
|
1877
|
+
* this so they read its params (TIM-1607).
|
|
1878
|
+
*/
|
|
1879
|
+
function runWithRouteParams(route, fn) {
|
|
1880
|
+
return runWithSegmentParams(matchedSegmentPath(route.segments), route.segmentParams, fn);
|
|
1498
1881
|
}
|
|
1499
|
-
|
|
1500
|
-
//#region src/server/pipeline-phases.ts
|
|
1882
|
+
// src/server/pipeline-phases.ts
|
|
1501
1883
|
/**
|
|
1502
1884
|
* Pipeline phase functions — module-level free functions that take their
|
|
1503
1885
|
* dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
|
|
@@ -1537,17 +1919,24 @@ async function runProxyPhase(config, getProxy, req, method, path, next) {
|
|
|
1537
1919
|
}
|
|
1538
1920
|
/**
|
|
1539
1921
|
* Run the middleware chain phase. If the chain short-circuits with a Response,
|
|
1540
|
-
* returns it as a 'response' outcome
|
|
1541
|
-
* overlay and
|
|
1922
|
+
* returns it as a 'response' outcome, and a thrown signal or error as its
|
|
1923
|
+
* outcome. Otherwise applies the request header overlay and returns null: the
|
|
1924
|
+
* request continues to the render phase.
|
|
1925
|
+
*
|
|
1926
|
+
* The chain is the URL's. On an intercepted navigation that is
|
|
1927
|
+
* `match.canonical`'s, not the rendered route's: the URL's middleware
|
|
1928
|
+
* followed by any only the rendered chain has, run with the URL's params
|
|
1929
|
+
* (TIM-1607).
|
|
1542
1930
|
*/
|
|
1543
|
-
async function runMiddlewarePhase(config, req, match, responseHeaders
|
|
1931
|
+
async function runMiddlewarePhase(config, req, match, responseHeaders) {
|
|
1932
|
+
const route = match.canonical ?? match;
|
|
1544
1933
|
const detailed = config.serverTiming === "detailed";
|
|
1545
1934
|
const requestHeaderOverlay = new Headers();
|
|
1546
1935
|
const ctx = {
|
|
1547
1936
|
req,
|
|
1548
1937
|
requestHeaders: requestHeaderOverlay,
|
|
1549
1938
|
headers: responseHeaders,
|
|
1550
|
-
segmentParams:
|
|
1939
|
+
segmentParams: route.segmentParams,
|
|
1551
1940
|
get nonce() {
|
|
1552
1941
|
return requestCspNonce();
|
|
1553
1942
|
},
|
|
@@ -1563,7 +1952,8 @@ async function runMiddlewarePhase(config, req, match, responseHeaders, renderCon
|
|
|
1563
1952
|
}
|
|
1564
1953
|
};
|
|
1565
1954
|
try {
|
|
1566
|
-
const
|
|
1955
|
+
const runChain = () => runMiddlewareChain(route.middlewareChain, ctx);
|
|
1956
|
+
const chainFn = match.canonical ? () => runWithRouteParams(route, runChain) : runChain;
|
|
1567
1957
|
const middlewareResponse = await (async () => {
|
|
1568
1958
|
setMutableCookieContext(true);
|
|
1569
1959
|
try {
|
|
@@ -1578,7 +1968,7 @@ async function runMiddlewarePhase(config, req, match, responseHeaders, renderCon
|
|
|
1578
1968
|
response: middlewareResponse
|
|
1579
1969
|
};
|
|
1580
1970
|
applyRequestHeaderOverlay(requestHeaderOverlay);
|
|
1581
|
-
return
|
|
1971
|
+
return null;
|
|
1582
1972
|
} catch (error) {
|
|
1583
1973
|
return thrownOutcome("middleware", error);
|
|
1584
1974
|
}
|
|
@@ -1639,47 +2029,8 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1639
2029
|
}
|
|
1640
2030
|
canonicalPathname = result.pathname;
|
|
1641
2031
|
}
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
if (metaMatch) try {
|
|
1645
|
-
if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
|
|
1646
|
-
setSegmentParams(metaMatch.segmentParams);
|
|
1647
|
-
const mod = await loadModule(metaMatch.file);
|
|
1648
|
-
if (typeof mod.default !== "function") {
|
|
1649
|
-
if (isDebug()) console.warn(`[timber] Metadata route ${metaMatch.file} does not export a default function — responding with 500\n Metadata routes must export a default function that returns the metadata content.`);
|
|
1650
|
-
return new Response("Metadata route must export a default function", { status: 500 });
|
|
1651
|
-
}
|
|
1652
|
-
const handlerResult = await mod.default();
|
|
1653
|
-
if (handlerResult instanceof Response) return cloneWithMutableHeaders(handlerResult);
|
|
1654
|
-
const contentType = metaMatch.contentType;
|
|
1655
|
-
let body;
|
|
1656
|
-
if (typeof handlerResult === "string") body = handlerResult;
|
|
1657
|
-
else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
|
|
1658
|
-
else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
|
|
1659
|
-
else body = String(handlerResult);
|
|
1660
|
-
return new Response(body, {
|
|
1661
|
-
status: 200,
|
|
1662
|
-
headers: {
|
|
1663
|
-
"Content-Type": `${contentType}; charset=utf-8`,
|
|
1664
|
-
"Cache-Control": METADATA_CACHE_CONTROL
|
|
1665
|
-
}
|
|
1666
|
-
});
|
|
1667
|
-
} catch (error) {
|
|
1668
|
-
if (isRedirectSignal(error)) return new Response(null, {
|
|
1669
|
-
status: error.status,
|
|
1670
|
-
headers: { Location: error.location }
|
|
1671
|
-
});
|
|
1672
|
-
if (isDenySignal(error)) return new Response(null, { status: error.status });
|
|
1673
|
-
logRenderError({
|
|
1674
|
-
method,
|
|
1675
|
-
path,
|
|
1676
|
-
error
|
|
1677
|
-
});
|
|
1678
|
-
await fireOnRequestError(error, req, "route");
|
|
1679
|
-
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
|
|
1680
|
-
return new Response(null, { status: 500 });
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
2032
|
+
const metaMatch = config.matchMetadataRoute?.(canonicalPathname);
|
|
2033
|
+
if (metaMatch) return serveMetadataRoute(config, req, method, path, canonicalPathname, metaMatch);
|
|
1683
2034
|
if (config.autoSitemapHandler) try {
|
|
1684
2035
|
const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
|
|
1685
2036
|
if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
|
|
@@ -1722,7 +2073,8 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1722
2073
|
let interception;
|
|
1723
2074
|
try {
|
|
1724
2075
|
match = config.matchRoute(canonicalPathname);
|
|
1725
|
-
|
|
2076
|
+
let canonical;
|
|
2077
|
+
({match, interception, canonical} = resolveInterceptedRoute(config, req, canonicalPathname, match));
|
|
1726
2078
|
if (!match) {
|
|
1727
2079
|
if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
|
|
1728
2080
|
return await renderNotFound(responseHeaders);
|
|
@@ -1737,20 +2089,27 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1737
2089
|
...match,
|
|
1738
2090
|
segmentParams: await coerceSegmentParams(match)
|
|
1739
2091
|
};
|
|
2092
|
+
if (canonical) {
|
|
2093
|
+
canonical = {
|
|
2094
|
+
...canonical,
|
|
2095
|
+
segmentParams: await coerceSegmentParams(canonical),
|
|
2096
|
+
middlewareChain: interceptedMiddlewareChain(canonical, match)
|
|
2097
|
+
};
|
|
2098
|
+
match = {
|
|
2099
|
+
...match,
|
|
2100
|
+
canonical
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
1740
2103
|
} catch (error) {
|
|
1741
2104
|
if (error instanceof ParamCoercionError) {
|
|
1742
|
-
|
|
1743
|
-
const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
|
|
1744
|
-
console.warn(`[timber] Param coercion failed for ${method} ${canonicalPathname} — responding with 404\n Matched segments: ${segmentChain}\n Error: ${error.message}\n This usually means a codec in app/schema.ts rejected the URL value.\n Check the codec for the bracket key of the segment named above.`);
|
|
1745
|
-
}
|
|
2105
|
+
warnParamCoercionFailure(method, canonicalPathname, match.segments, error);
|
|
1746
2106
|
if (isApiRouteChain(match.segments)) return new Response(null, { status: 404 });
|
|
1747
2107
|
return await renderNotFound(responseHeaders);
|
|
1748
2108
|
}
|
|
1749
2109
|
throw error;
|
|
1750
2110
|
}
|
|
1751
2111
|
setSegmentParams(match.segmentParams);
|
|
1752
|
-
|
|
1753
|
-
setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
|
|
2112
|
+
setMatchedSegmentPath(matchedSegmentPath(match.segments));
|
|
1754
2113
|
} catch (error) {
|
|
1755
2114
|
return outcomeToResponse(config, thrownOutcome("setup", error), {
|
|
1756
2115
|
req,
|
|
@@ -1760,22 +2119,32 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1760
2119
|
match: match ?? void 0
|
|
1761
2120
|
});
|
|
1762
2121
|
}
|
|
1763
|
-
|
|
1764
|
-
canonicalPathname,
|
|
1765
|
-
interception
|
|
1766
|
-
}) : await runRenderPhase(config, req, match, responseHeaders, {
|
|
1767
|
-
canonicalPathname,
|
|
1768
|
-
interception
|
|
1769
|
-
}), {
|
|
2122
|
+
const outcomeContext = {
|
|
1770
2123
|
req,
|
|
1771
2124
|
method,
|
|
1772
2125
|
path,
|
|
1773
|
-
responseHeaders
|
|
2126
|
+
responseHeaders
|
|
2127
|
+
};
|
|
2128
|
+
const route = match.canonical ?? match;
|
|
2129
|
+
if (route.middlewareChain.length > 0) {
|
|
2130
|
+
const stopped = await runMiddlewarePhase(config, req, match, responseHeaders);
|
|
2131
|
+
if (stopped) {
|
|
2132
|
+
const answer = () => outcomeToResponse(config, stopped, {
|
|
2133
|
+
...outcomeContext,
|
|
2134
|
+
match: route
|
|
2135
|
+
});
|
|
2136
|
+
return match.canonical ? runWithRouteParams(route, answer) : answer();
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
return outcomeToResponse(config, await runRenderPhase(config, req, match, responseHeaders, {
|
|
2140
|
+
canonicalPathname,
|
|
2141
|
+
interception
|
|
2142
|
+
}), {
|
|
2143
|
+
...outcomeContext,
|
|
1774
2144
|
match
|
|
1775
2145
|
});
|
|
1776
2146
|
}
|
|
1777
|
-
|
|
1778
|
-
//#region src/server/rsc-cache-key-guard.ts
|
|
2147
|
+
// src/server/rsc-cache-key-guard.ts
|
|
1779
2148
|
/**
|
|
1780
2149
|
* Origin-side binding of the `_rsc` cache key to the request that produced
|
|
1781
2150
|
* the response (TIM-1268).
|
|
@@ -1872,54 +2241,7 @@ async function enforceRscCacheKey(req, response) {
|
|
|
1872
2241
|
if (await hasValidRscCacheKey(req)) return;
|
|
1873
2242
|
preventResponseCaching(response.headers);
|
|
1874
2243
|
}
|
|
1875
|
-
|
|
1876
|
-
//#region src/server/head-response.ts
|
|
1877
|
-
/**
|
|
1878
|
-
* HEAD body stripping — RFC 9110 §9.3.2.
|
|
1879
|
-
*
|
|
1880
|
-
* "The HEAD method is identical to GET except that the server MUST NOT send
|
|
1881
|
-
* content in the response." The headers, however, must be the ones the
|
|
1882
|
-
* corresponding GET would have produced — which is why timber renders the
|
|
1883
|
-
* route in full and discards the body here rather than short-circuiting the
|
|
1884
|
-
* render. Content-Type, Content-Length, Set-Cookie, cache directives and
|
|
1885
|
-
* everything else ride through untouched.
|
|
1886
|
-
*
|
|
1887
|
-
* Node's `ServerResponse` happens to discard writes for HEAD, so the wire is
|
|
1888
|
-
* usually correct even without this. That is a property of one adapter, not of
|
|
1889
|
-
* the `Response` object: static generation, the Cloudflare and Nitro adapters,
|
|
1890
|
-
* tests, and anything calling the pipeline handler as a function all observe
|
|
1891
|
-
* the `Response` directly and saw the full body before TIM-1324.
|
|
1892
|
-
*
|
|
1893
|
-
* The pipeline applies this at its single exit so every response shape is
|
|
1894
|
-
* covered — page render, API route, metadata route, deny page, error page,
|
|
1895
|
-
* proxy short-circuit. The unit-level producer that is also reachable as a
|
|
1896
|
-
* standalone function (`handleRouteRequest`) calls it too, so it honours HEAD
|
|
1897
|
-
* on its own; it shares this implementation rather than repeating it, and
|
|
1898
|
-
* applying it twice is a no-op.
|
|
1899
|
-
*/
|
|
1900
|
-
/**
|
|
1901
|
-
* Return a bodyless copy of `response` when `method` is HEAD.
|
|
1902
|
-
*
|
|
1903
|
-
* A no-op for every other method and for responses that already carry no body
|
|
1904
|
-
* (204, 304, redirects), so callers do not need to pre-check either.
|
|
1905
|
-
*
|
|
1906
|
-
* The discarded stream is cancelled: an SSR render that reached this point has
|
|
1907
|
-
* a live producer attached, and dropping the reference without cancelling
|
|
1908
|
-
* leaks it for the lifetime of the render (design/13-security.md A4).
|
|
1909
|
-
*/
|
|
1910
|
-
function stripHeadBody(response, method) {
|
|
1911
|
-
if (method.toUpperCase() !== "HEAD") return response;
|
|
1912
|
-
const nodeBody = nodeBodyOps(response);
|
|
1913
|
-
if (nodeBody ? !nodeBody.hasBody : response.body === null) return response;
|
|
1914
|
-
discardResponseBody(response);
|
|
1915
|
-
return new Response(null, {
|
|
1916
|
-
status: response.status,
|
|
1917
|
-
statusText: response.statusText,
|
|
1918
|
-
headers: response.headers
|
|
1919
|
-
});
|
|
1920
|
-
}
|
|
1921
|
-
//#endregion
|
|
1922
|
-
//#region src/server/pipeline.ts
|
|
2244
|
+
// src/server/pipeline.ts
|
|
1923
2245
|
/**
|
|
1924
2246
|
* Create the request handler from a pipeline configuration.
|
|
1925
2247
|
*
|
|
@@ -2049,8 +2371,7 @@ function createPipeline(config) {
|
|
|
2049
2371
|
});
|
|
2050
2372
|
};
|
|
2051
2373
|
}
|
|
2052
|
-
|
|
2053
|
-
//#region src/server/early-hints.ts
|
|
2374
|
+
// src/server/early-hints.ts
|
|
2054
2375
|
/**
|
|
2055
2376
|
* 103 Early Hints utilities.
|
|
2056
2377
|
*
|
|
@@ -2133,8 +2454,7 @@ function collectEarlyHintHeaders(segments, manifest, options) {
|
|
|
2133
2454
|
}));
|
|
2134
2455
|
return result;
|
|
2135
2456
|
}
|
|
2136
|
-
|
|
2137
|
-
//#region src/server/early-hints-sender.ts
|
|
2457
|
+
// src/server/early-hints-sender.ts
|
|
2138
2458
|
/**
|
|
2139
2459
|
* Per-request 103 Early Hints sender — ALS bridge for platform adapters.
|
|
2140
2460
|
*
|
|
@@ -2181,8 +2501,7 @@ function sendEarlyHints103(links) {
|
|
|
2181
2501
|
swallow(err, "early hints 103 send failed");
|
|
2182
2502
|
}
|
|
2183
2503
|
}
|
|
2184
|
-
|
|
2185
|
-
//#region src/client/error-reconstituter.tsx
|
|
2504
|
+
// src/client/error-reconstituter.tsx
|
|
2186
2505
|
/**
|
|
2187
2506
|
* Reconstitutes a SerializableError into a real Error instance before
|
|
2188
2507
|
* passing to the user's error component.
|
|
@@ -2215,8 +2534,7 @@ function ErrorReconstituter({ error: serialized, digest, reset, component, statu
|
|
|
2215
2534
|
} : {}
|
|
2216
2535
|
});
|
|
2217
2536
|
}
|
|
2218
|
-
|
|
2219
|
-
//#region src/server/deny-boundary.ts
|
|
2537
|
+
// src/server/deny-boundary.ts
|
|
2220
2538
|
/**
|
|
2221
2539
|
* Deny boundary subsystem — the in-tree DenySignal flow.
|
|
2222
2540
|
*
|
|
@@ -2427,8 +2745,7 @@ function setFirstDeniedSegmentIndex(index) {
|
|
|
2427
2745
|
const store = requestContextAls.getStore();
|
|
2428
2746
|
if (store && store._firstDeniedSegmentIndex === void 0) store._firstDeniedSegmentIndex = index;
|
|
2429
2747
|
}
|
|
2430
|
-
|
|
2431
|
-
//#region src/server/access-gate.tsx
|
|
2748
|
+
// src/server/access-gate.tsx
|
|
2432
2749
|
/**
|
|
2433
2750
|
* Framework-injected access gate for segments.
|
|
2434
2751
|
*
|
|
@@ -2453,33 +2770,29 @@ function setFirstDeniedSegmentIndex(index) {
|
|
|
2453
2770
|
* in-tree — the client's cached layout chrome would wrap them incorrectly.
|
|
2454
2771
|
* Instead, the deny is recorded in ALS and rethrown so the response path
|
|
2455
2772
|
* can return rscErrorEnvelope for a client hard-navigate.
|
|
2773
|
+
*
|
|
2774
|
+
* For a segment outside the rendered tree (outsideTree=true), see
|
|
2775
|
+
* `DenySignal._leaveSpa`.
|
|
2456
2776
|
*/
|
|
2457
2777
|
function AccessGate(props) {
|
|
2458
|
-
const { accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children } = props;
|
|
2459
|
-
return accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, skippedSegment ? void 0 : denyPages, skippedSegment, children);
|
|
2778
|
+
const { accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, outsideTree, children } = props;
|
|
2779
|
+
return accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, skippedSegment ? void 0 : denyPages, skippedSegment, outsideTree, children);
|
|
2460
2780
|
}
|
|
2461
2781
|
/**
|
|
2462
2782
|
* Calls accessFn during render with OTEL instrumentation.
|
|
2463
2783
|
* Records the first denied segment index in ALS for post-render consumers.
|
|
2464
2784
|
*/
|
|
2465
|
-
async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children) {
|
|
2785
|
+
async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, outsideTree, children) {
|
|
2466
2786
|
try {
|
|
2467
|
-
await
|
|
2468
|
-
try {
|
|
2469
|
-
await accessFn();
|
|
2470
|
-
await setSpanAttribute("timber.result", "pass");
|
|
2471
|
-
} catch (error) {
|
|
2472
|
-
if (isDenySignal(error)) {
|
|
2473
|
-
await setSpanAttribute("timber.result", "deny");
|
|
2474
|
-
await setSpanAttribute("timber.deny_status", error.status);
|
|
2475
|
-
if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
|
|
2476
|
-
} else if (isRedirectSignal(error)) await setSpanAttribute("timber.result", "redirect");
|
|
2477
|
-
throw error;
|
|
2478
|
-
}
|
|
2479
|
-
});
|
|
2787
|
+
await runTracedAccess(accessFn, segmentName);
|
|
2480
2788
|
} catch (error) {
|
|
2481
2789
|
if (isDenySignal(error)) {
|
|
2482
2790
|
if (segmentIndex !== void 0) setFirstDeniedSegmentIndex(segmentIndex);
|
|
2791
|
+
if (outsideTree) {
|
|
2792
|
+
error._hardNavigate = true;
|
|
2793
|
+
error._leaveSpa = true;
|
|
2794
|
+
throw error;
|
|
2795
|
+
}
|
|
2483
2796
|
if (skippedSegment) {
|
|
2484
2797
|
error._hardNavigate = true;
|
|
2485
2798
|
throw error;
|
|
@@ -2530,8 +2843,7 @@ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
|
|
|
2530
2843
|
data
|
|
2531
2844
|
});
|
|
2532
2845
|
}
|
|
2533
|
-
|
|
2534
|
-
//#region src/server/status-code-resolver.ts
|
|
2846
|
+
// src/server/status-code-resolver.ts
|
|
2535
2847
|
/**
|
|
2536
2848
|
* Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
|
|
2537
2849
|
* status-file group on a single segment. Shared by all three fallback
|
|
@@ -2673,8 +2985,7 @@ function resolveSlotDenied(slotNode) {
|
|
|
2673
2985
|
};
|
|
2674
2986
|
return null;
|
|
2675
2987
|
}
|
|
2676
|
-
|
|
2677
|
-
//#region src/server/body-limits.ts
|
|
2988
|
+
// src/server/body-limits.ts
|
|
2678
2989
|
var KB = 1024;
|
|
2679
2990
|
var MB = 1024 * KB;
|
|
2680
2991
|
var GB = 1024 * MB;
|
|
@@ -2725,8 +3036,7 @@ function resolveLimit(kind, config) {
|
|
|
2725
3036
|
if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
|
|
2726
3037
|
return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
|
|
2727
3038
|
}
|
|
2728
|
-
|
|
2729
|
-
//#region src/server/metadata-social.ts
|
|
3039
|
+
// src/server/metadata-social.ts
|
|
2730
3040
|
/**
|
|
2731
3041
|
* Render Open Graph metadata into head element descriptors.
|
|
2732
3042
|
*
|
|
@@ -2927,8 +3237,7 @@ function renderTwitter(tw, elements) {
|
|
|
2927
3237
|
}
|
|
2928
3238
|
}
|
|
2929
3239
|
}
|
|
2930
|
-
|
|
2931
|
-
//#region src/server/metadata-platform.ts
|
|
3240
|
+
// src/server/metadata-platform.ts
|
|
2932
3241
|
/**
|
|
2933
3242
|
* Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
|
|
2934
3243
|
*/
|
|
@@ -3153,8 +3462,7 @@ function renderItunes(itunes, elements) {
|
|
|
3153
3462
|
}
|
|
3154
3463
|
});
|
|
3155
3464
|
}
|
|
3156
|
-
|
|
3157
|
-
//#region src/server/metadata-render.ts
|
|
3465
|
+
// src/server/metadata-render.ts
|
|
3158
3466
|
/**
|
|
3159
3467
|
* Convert resolved metadata into an array of head element descriptors.
|
|
3160
3468
|
*
|
|
@@ -3293,8 +3601,7 @@ function renderRobotsObject(robots) {
|
|
|
3293
3601
|
if (robots.follow === false) parts.push("nofollow");
|
|
3294
3602
|
return parts.join(", ");
|
|
3295
3603
|
}
|
|
3296
|
-
|
|
3297
|
-
//#region src/server/metadata.ts
|
|
3604
|
+
// src/server/metadata.ts
|
|
3298
3605
|
/**
|
|
3299
3606
|
* Resolve a title value with an optional template.
|
|
3300
3607
|
*
|
|
@@ -3424,123 +3731,7 @@ function resolveMetadataUrls(metadata) {
|
|
|
3424
3731
|
}
|
|
3425
3732
|
return result;
|
|
3426
3733
|
}
|
|
3427
|
-
|
|
3428
|
-
//#region src/server/route-handler.ts
|
|
3429
|
-
/** All recognized HTTP method export names. */
|
|
3430
|
-
var HTTP_METHODS = [
|
|
3431
|
-
"GET",
|
|
3432
|
-
"POST",
|
|
3433
|
-
"PUT",
|
|
3434
|
-
"PATCH",
|
|
3435
|
-
"DELETE",
|
|
3436
|
-
"HEAD",
|
|
3437
|
-
"OPTIONS"
|
|
3438
|
-
];
|
|
3439
|
-
/**
|
|
3440
|
-
* Resolve the full list of allowed methods for a route module.
|
|
3441
|
-
*
|
|
3442
|
-
* Includes:
|
|
3443
|
-
* - All explicitly exported methods
|
|
3444
|
-
* - HEAD (implicit when GET is exported)
|
|
3445
|
-
* - OPTIONS (always implicit)
|
|
3446
|
-
*/
|
|
3447
|
-
function resolveAllowedMethods(mod) {
|
|
3448
|
-
const methods = [];
|
|
3449
|
-
for (const method of HTTP_METHODS) {
|
|
3450
|
-
if (method === "HEAD" || method === "OPTIONS") continue;
|
|
3451
|
-
if (mod[method]) methods.push(method);
|
|
3452
|
-
}
|
|
3453
|
-
if (mod.GET && !mod.HEAD) methods.push("HEAD");
|
|
3454
|
-
else if (mod.HEAD) methods.push("HEAD");
|
|
3455
|
-
if (!mod.OPTIONS) methods.push("OPTIONS");
|
|
3456
|
-
else methods.push("OPTIONS");
|
|
3457
|
-
return methods;
|
|
3458
|
-
}
|
|
3459
|
-
/**
|
|
3460
|
-
* Handle an incoming request against a route.ts module.
|
|
3461
|
-
*
|
|
3462
|
-
* Dispatches to the named method handler, auto-generates 405/OPTIONS,
|
|
3463
|
-
* and merges response headers from ctx.headers.
|
|
3464
|
-
*/
|
|
3465
|
-
async function handleRouteRequest(mod, ctx) {
|
|
3466
|
-
const method = ctx.req.method.toUpperCase();
|
|
3467
|
-
const allowHeader = resolveAllowedMethods(mod).join(", ");
|
|
3468
|
-
if (method === "OPTIONS") {
|
|
3469
|
-
if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
|
|
3470
|
-
return mergeResponseHeaders(new Response(null, {
|
|
3471
|
-
status: 204,
|
|
3472
|
-
headers: { Allow: allowHeader }
|
|
3473
|
-
}), ctx.headers);
|
|
3474
|
-
}
|
|
3475
|
-
if (method === "HEAD") {
|
|
3476
|
-
if (mod.HEAD) return stripHeadBody(await runHandler(mod.HEAD, ctx), method);
|
|
3477
|
-
if (mod.GET) return stripHeadBody(await runHandler(mod.GET, ctx), method);
|
|
3478
|
-
}
|
|
3479
|
-
const handler = mod[method];
|
|
3480
|
-
if (!handler) return mergeResponseHeaders(new Response(null, {
|
|
3481
|
-
status: 405,
|
|
3482
|
-
headers: { Allow: allowHeader }
|
|
3483
|
-
}), ctx.headers);
|
|
3484
|
-
return runHandler(handler, ctx);
|
|
3485
|
-
}
|
|
3486
|
-
/**
|
|
3487
|
-
* Run a handler with cookie writes enabled and merge ctx.headers into its
|
|
3488
|
-
* response.
|
|
3489
|
-
*
|
|
3490
|
-
* Cookies (design/29-cookies.md §"Where Cookies Can Be Set"): the render
|
|
3491
|
-
* phase applied the jar to `ctx.headers` before the handler ran, so on the
|
|
3492
|
-
* way out only what the handler changed is synced onto that bag. It happens
|
|
3493
|
-
* whether the handler returns or throws, so a cookie set before `redirect()`
|
|
3494
|
-
* rides the redirect, and the pipeline's 500 for a throw carries the same
|
|
3495
|
-
* bag.
|
|
3496
|
-
*
|
|
3497
|
-
* Nothing is caught. A signal goes to the pipeline, whose deny fallback
|
|
3498
|
-
* answers a route.ts match in JSON and whose redirect outcome sends the 3xx
|
|
3499
|
-
* (TIM-1533). Any other error goes to the pipeline, which logs it,
|
|
3500
|
-
* reports it to `onRequestError` as phase `'route'`, and answers it in the
|
|
3501
|
-
* same format as every other route.ts error (TIM-1537).
|
|
3502
|
-
*/
|
|
3503
|
-
async function runHandler(handler, ctx) {
|
|
3504
|
-
const applied = getSetCookieHeaders();
|
|
3505
|
-
setMutableCookieContext(true);
|
|
3506
|
-
let res;
|
|
3507
|
-
try {
|
|
3508
|
-
res = await handler(ctx);
|
|
3509
|
-
} finally {
|
|
3510
|
-
setMutableCookieContext(false);
|
|
3511
|
-
syncCookieJar(ctx.headers, applied);
|
|
3512
|
-
}
|
|
3513
|
-
return mergeResponseHeaders(res, ctx.headers);
|
|
3514
|
-
}
|
|
3515
|
-
/**
|
|
3516
|
-
* Merge response headers from ctx.headers into the handler's response.
|
|
3517
|
-
* ctx.headers (set by middleware or the handler) are applied to the final response.
|
|
3518
|
-
* Handler-set headers take precedence over ctx.headers.
|
|
3519
|
-
*/
|
|
3520
|
-
function mergeResponseHeaders(res, ctxHeaders) {
|
|
3521
|
-
let hasCtxHeaders = false;
|
|
3522
|
-
ctxHeaders.forEach(() => {
|
|
3523
|
-
hasCtxHeaders = true;
|
|
3524
|
-
});
|
|
3525
|
-
if (!hasCtxHeaders) return res;
|
|
3526
|
-
const merged = new Headers();
|
|
3527
|
-
ctxHeaders.forEach((value, key) => {
|
|
3528
|
-
if (key.toLowerCase() === "set-cookie") merged.append(key, value);
|
|
3529
|
-
else merged.set(key, value);
|
|
3530
|
-
});
|
|
3531
|
-
const resCookies = res.headers.getSetCookie();
|
|
3532
|
-
for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
|
|
3533
|
-
res.headers.forEach((value, key) => {
|
|
3534
|
-
if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
|
|
3535
|
-
});
|
|
3536
|
-
return new Response(res.body, {
|
|
3537
|
-
status: res.status,
|
|
3538
|
-
statusText: res.statusText,
|
|
3539
|
-
headers: merged
|
|
3540
|
-
});
|
|
3541
|
-
}
|
|
3542
|
-
//#endregion
|
|
3543
|
-
//#region src/server/prebuilt/cache-key.ts
|
|
3734
|
+
// src/server/prebuilt/cache-key.ts
|
|
3544
3735
|
/**
|
|
3545
3736
|
* Component cache-key hashing for prebuilt (cache.component) entries.
|
|
3546
3737
|
*
|
|
@@ -3757,8 +3948,7 @@ function resolveKeyParams(store) {
|
|
|
3757
3948
|
}
|
|
3758
3949
|
return main;
|
|
3759
3950
|
}
|
|
3760
|
-
|
|
3761
|
-
//#region src/client/slot-context.ts
|
|
3951
|
+
// src/client/slot-context.ts
|
|
3762
3952
|
/**
|
|
3763
3953
|
* SlotContext — delivers live slot content to SlotOutlet holes inside
|
|
3764
3954
|
* cached component shells (TIM-1173).
|
|
@@ -3786,19 +3976,8 @@ function resolveKeyParams(store) {
|
|
|
3786
3976
|
*
|
|
3787
3977
|
* See design/45-cache-lifetimes.md §Slot Components.
|
|
3788
3978
|
*/
|
|
3789
|
-
var
|
|
3790
|
-
|
|
3791
|
-
const existing = globalThis[CTX_KEY];
|
|
3792
|
-
if (existing !== void 0) return existing;
|
|
3793
|
-
if (typeof React.createContext === "function") {
|
|
3794
|
-
const ctx = React.createContext(null);
|
|
3795
|
-
globalThis[CTX_KEY] = ctx;
|
|
3796
|
-
return ctx;
|
|
3797
|
-
}
|
|
3798
|
-
}
|
|
3799
|
-
var SlotContext = getOrCreateContext();
|
|
3800
|
-
//#endregion
|
|
3801
|
-
//#region src/client/slot-outlet.tsx
|
|
3979
|
+
var SlotContext = createGlobalContext(Symbol.for("__timber_slot_ctx"), null);
|
|
3980
|
+
// src/client/slot-outlet.tsx
|
|
3802
3981
|
/**
|
|
3803
3982
|
* SlotOutlet — the hole in a cached component shell (TIM-1173).
|
|
3804
3983
|
*
|
|
@@ -3815,8 +3994,7 @@ function SlotOutlet({ slot }) {
|
|
|
3815
3994
|
const values = useContext(SlotContext);
|
|
3816
3995
|
return values ? values[slot] ?? null : null;
|
|
3817
3996
|
}
|
|
3818
|
-
|
|
3819
|
-
//#region src/client/slot-provider.tsx
|
|
3997
|
+
// src/client/slot-provider.tsx
|
|
3820
3998
|
/**
|
|
3821
3999
|
* SlotsProvider — wraps a revived cached shell to supply live slot content
|
|
3822
4000
|
* to the SlotOutlet holes inside it (TIM-1173).
|
|
@@ -3841,8 +4019,7 @@ function SlotsProvider({ values, children }) {
|
|
|
3841
4019
|
} : values;
|
|
3842
4020
|
return createElement(SlotContext.Provider, { value: merged }, children);
|
|
3843
4021
|
}
|
|
3844
|
-
|
|
3845
|
-
//#region src/server/prebuilt/lifetime.ts
|
|
4022
|
+
// src/server/prebuilt/lifetime.ts
|
|
3846
4023
|
/**
|
|
3847
4024
|
* Lifetime declarations of a `cache.component` — `prerender`, `ttl`,
|
|
3848
4025
|
* `tags` (design/45-cache-lifetimes.md) — and the nesting clamp between
|
|
@@ -3942,8 +4119,7 @@ function warnNestingClamps(outer, nested, warnedPairs, log) {
|
|
|
3942
4119
|
}
|
|
3943
4120
|
return count;
|
|
3944
4121
|
}
|
|
3945
|
-
|
|
3946
|
-
//#region src/server/prebuilt/slots.ts
|
|
4122
|
+
// src/server/prebuilt/slots.ts
|
|
3947
4123
|
/**
|
|
3948
4124
|
* Slot-component helpers for cache.component (TIM-1173).
|
|
3949
4125
|
*
|
|
@@ -4088,66 +4264,7 @@ function wrapInSlotsProvider(shell, slotValues) {
|
|
|
4088
4264
|
children: shell
|
|
4089
4265
|
});
|
|
4090
4266
|
}
|
|
4091
|
-
|
|
4092
|
-
//#region src/server/prebuilt/key-discipline.ts
|
|
4093
|
-
var REQUEST_CONTEXT_FIELDS = {
|
|
4094
|
-
headers: "headers()",
|
|
4095
|
-
parsedCookies: "cookies()",
|
|
4096
|
-
searchParams: "searchParams"
|
|
4097
|
-
};
|
|
4098
|
-
/** Rate-limit interval: one diagnostic per component per 60 seconds. */
|
|
4099
|
-
var RATE_LIMIT_MS = 6e4;
|
|
4100
|
-
/** Last emission timestamp per component ID. */
|
|
4101
|
-
var lastEmitted = /* @__PURE__ */ new Map();
|
|
4102
|
-
var strict = false;
|
|
4103
|
-
/**
|
|
4104
|
-
* Whether the proxy should be created for this component on this render.
|
|
4105
|
-
* Returns true when strict mode is on (always check) or enough time has
|
|
4106
|
-
* elapsed since the last diagnostic for this component.
|
|
4107
|
-
*/
|
|
4108
|
-
function shouldCheckKeyDiscipline(id) {
|
|
4109
|
-
if (strict) return true;
|
|
4110
|
-
const last = lastEmitted.get(id);
|
|
4111
|
-
if (last === void 0) return true;
|
|
4112
|
-
return Date.now() - last >= RATE_LIMIT_MS;
|
|
4113
|
-
}
|
|
4114
|
-
/**
|
|
4115
|
-
* Wrap a store with a proxy that records per-request field access.
|
|
4116
|
-
* The proxy forwards all reads/writes transparently — it only observes.
|
|
4117
|
-
*/
|
|
4118
|
-
function createKeyDisciplineProxy(store) {
|
|
4119
|
-
const accessedApis = /* @__PURE__ */ new Set();
|
|
4120
|
-
return {
|
|
4121
|
-
proxy: new Proxy(store, { get(target, prop, receiver) {
|
|
4122
|
-
const api = REQUEST_CONTEXT_FIELDS[prop];
|
|
4123
|
-
if (api) accessedApis.add(api);
|
|
4124
|
-
return Reflect.get(target, prop, receiver);
|
|
4125
|
-
} }),
|
|
4126
|
-
accessedApis
|
|
4127
|
-
};
|
|
4128
|
-
}
|
|
4129
|
-
/**
|
|
4130
|
-
* Emit the key-discipline diagnostic or throw in strict mode.
|
|
4131
|
-
*
|
|
4132
|
-
* In strict mode: throws an error so the tainted payload is never cached.
|
|
4133
|
-
* In default mode: emits a structured error-level diagnostic through the
|
|
4134
|
-
* logger (same path as render errors), rate-limited per component.
|
|
4135
|
-
*/
|
|
4136
|
-
function emitKeyDisciplineWarning(id, apis) {
|
|
4137
|
-
const apiList = Array.from(apis).join(", ");
|
|
4138
|
-
if (strict) throw new Error(`[timber] cache.component key-discipline violation: "${id}" reads ${apiList} during a cache capture render. The cache key does not include request-derived values — caching this output would serve one user's data to another. Either pass request-derived values as props (included in the cache key) or remove the ${apiList} call. To downgrade this to a warning, set cache.strictKeyDiscipline: false in timber.config.ts.`);
|
|
4139
|
-
const now = Date.now();
|
|
4140
|
-
const last = lastEmitted.get(id);
|
|
4141
|
-
if (last !== void 0 && now - last < RATE_LIMIT_MS) return;
|
|
4142
|
-
lastEmitted.set(id, now);
|
|
4143
|
-
getLogger().error("cache.component cross-user data leak risk", {
|
|
4144
|
-
component: id,
|
|
4145
|
-
accessedApis: Array.from(apis),
|
|
4146
|
-
message: `cache.component "${id}" reads ${apiList} but the cache key is computed from props and segment params only. If the output varies by ${apiList}, different users may see each other's cached content. Either pass request-derived values as props (included in the cache key) or remove the ${apiList} call.`
|
|
4147
|
-
});
|
|
4148
|
-
}
|
|
4149
|
-
//#endregion
|
|
4150
|
-
//#region src/server/prebuilt/capture-state.ts
|
|
4267
|
+
// src/server/prebuilt/capture-state.ts
|
|
4151
4268
|
/**
|
|
4152
4269
|
* Capture state — the channel between a payload capture and the
|
|
4153
4270
|
* `__prebuilt` wrappers that render inside it (server/prebuilt-runtime.ts).
|
|
@@ -4276,9 +4393,8 @@ function noteWrapperRender(innerId, options, props) {
|
|
|
4276
4393
|
}
|
|
4277
4394
|
}
|
|
4278
4395
|
}
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
var nodeFlight = typeof process !== "undefined" && process.release?.name === "node" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") ? await import("../_chunks/flight-source-node-HptmGMT8.js") : null;
|
|
4396
|
+
// src/server/flight-source.ts
|
|
4397
|
+
var nodeFlight = typeof process !== "undefined" && process.release?.name === "node" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") ? await import("../_chunks/flight-source-node-0Tp6evlz.js") : null;
|
|
4282
4398
|
/** The Node helpers, which a `kind: 'node'` source can only exist alongside. */
|
|
4283
4399
|
function requireNodeFlight() {
|
|
4284
4400
|
if (!nodeFlight) throw new Error("[timber] a Node Flight source reached a runtime without node:stream");
|
|
@@ -4295,7 +4411,7 @@ function openFlightReader(source) {
|
|
|
4295
4411
|
return {
|
|
4296
4412
|
read: () => reader.read(),
|
|
4297
4413
|
takeBuffered: () => [],
|
|
4298
|
-
cancel: (reason) => void reader.cancel(reason).catch(() => {})
|
|
4414
|
+
cancel: (reason) => void reader.cancel(releaseReason(reason)).catch(() => {})
|
|
4299
4415
|
};
|
|
4300
4416
|
}
|
|
4301
4417
|
const { destroyNodeFlight } = requireNodeFlight();
|
|
@@ -4338,8 +4454,7 @@ async function collectFlightBytes(source, timeoutMs, label) {
|
|
|
4338
4454
|
const chunks = await drainWithDeadline(openFlightReader(source), timeoutMs, label);
|
|
4339
4455
|
return concatBytes(chunks.map(flightChunkBytes));
|
|
4340
4456
|
}
|
|
4341
|
-
|
|
4342
|
-
//#region src/server/prebuilt/synthetic-store.ts
|
|
4457
|
+
// src/server/prebuilt/synthetic-store.ts
|
|
4343
4458
|
/**
|
|
4344
4459
|
* Thrown when a prerendered component touches per-request context at
|
|
4345
4460
|
* build time. The capture pass treats this as a HARD build error —
|
|
@@ -4400,8 +4515,7 @@ function createBuildTimeStore(componentId, segmentParams) {
|
|
|
4400
4515
|
handle.store = store;
|
|
4401
4516
|
return handle;
|
|
4402
4517
|
}
|
|
4403
|
-
|
|
4404
|
-
//#region src/server/prebuilt/capture-render.ts
|
|
4518
|
+
// src/server/prebuilt/capture-render.ts
|
|
4405
4519
|
/**
|
|
4406
4520
|
* One build-time capture entry: render a registered component in isolation
|
|
4407
4521
|
* under the synthetic build store and drain its flight payload under a
|
|
@@ -4465,8 +4579,7 @@ async function renderEntry(registration, props, coercedParams, timeoutMs, isLayo
|
|
|
4465
4579
|
segmentParamsRead
|
|
4466
4580
|
};
|
|
4467
4581
|
}
|
|
4468
|
-
|
|
4469
|
-
//#region src/server/prebuilt-runtime.ts
|
|
4582
|
+
// src/server/prebuilt-runtime.ts
|
|
4470
4583
|
/**
|
|
4471
4584
|
* Prebuilt component runtime — registration target for the timber-prebuilt
|
|
4472
4585
|
* transform (plugins/prebuilt.ts) and the request-time half of
|
|
@@ -4582,8 +4695,6 @@ async function captureComponentPayload(id, component, props, options) {
|
|
|
4582
4695
|
const element = createElement(component, props);
|
|
4583
4696
|
const capture = createCaptureScope(id, options, props);
|
|
4584
4697
|
let renderError;
|
|
4585
|
-
const store = requestContextAls.getStore();
|
|
4586
|
-
const discipline = store && shouldCheckKeyDiscipline(id) ? createKeyDisciplineProxy(store) : null;
|
|
4587
4698
|
const doCapture = () => capture.run(async () => {
|
|
4588
4699
|
const bytes = await collectFlightBytes(runOutsideReactCacheScope(() => renderFlight(element, { onError(error) {
|
|
4589
4700
|
renderError ??= { error };
|
|
@@ -4592,10 +4703,11 @@ async function captureComponentPayload(id, component, props, options) {
|
|
|
4592
4703
|
if (renderError) throw renderError.error;
|
|
4593
4704
|
return bytes;
|
|
4594
4705
|
});
|
|
4595
|
-
const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
|
|
4596
|
-
if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
|
|
4597
4706
|
return {
|
|
4598
|
-
bytes
|
|
4707
|
+
bytes: await observeKeyDiscipline({
|
|
4708
|
+
tier: "cache.component",
|
|
4709
|
+
id
|
|
4710
|
+
}, doCapture),
|
|
4599
4711
|
nested: capture.nestedRenders()
|
|
4600
4712
|
};
|
|
4601
4713
|
}
|
|
@@ -4605,13 +4717,22 @@ async function captureComponentPayload(id, component, props, options) {
|
|
|
4605
4717
|
* warning follows the store: a capture that is discarded (aborted,
|
|
4606
4718
|
* invalidated mid-render, failed store) holds no clamped copy, and must
|
|
4607
4719
|
* not spend the pair's one warning.
|
|
4720
|
+
*
|
|
4721
|
+
* A failed store is swallowed, like a failed `cache.data` write (TIM-1046):
|
|
4722
|
+
* the captured payload is valid and still answers the request. Thrown, it
|
|
4723
|
+
* would discard the capture and render the component a second time.
|
|
4608
4724
|
*/
|
|
4609
4725
|
async function storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed) {
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4726
|
+
try {
|
|
4727
|
+
await storeOverlayEntry(id, cacheKey, captured.bytes, {
|
|
4728
|
+
ttl: options.ttl,
|
|
4729
|
+
tags,
|
|
4730
|
+
hasSeed
|
|
4731
|
+
});
|
|
4732
|
+
} catch (err) {
|
|
4733
|
+
swallow(err, `cache.component overlay store failed for "${id}"`);
|
|
4734
|
+
return;
|
|
4735
|
+
}
|
|
4615
4736
|
warnNestingClamps({
|
|
4616
4737
|
id,
|
|
4617
4738
|
options,
|
|
@@ -4625,12 +4746,12 @@ async function storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed
|
|
|
4625
4746
|
async function inlineRerender(id, component, props, cacheKey, options, hasSeed, outcome) {
|
|
4626
4747
|
const tags = resolveTags(options, props);
|
|
4627
4748
|
const oKey = overlayKey(id, cacheKey);
|
|
4628
|
-
const sfKey = `prebuilt:${
|
|
4749
|
+
const sfKey = `prebuilt:${oKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
|
|
4629
4750
|
try {
|
|
4630
4751
|
return await revivePayload(id, await componentSingleflight.do(sfKey, async (signal) => {
|
|
4631
4752
|
const startEpoch = currentInvalidationEpoch();
|
|
4632
4753
|
const captured = await captureComponentPayload(id, component, props, options);
|
|
4633
|
-
if (!signal.aborted && hasRuntimeLifetime(options) &&
|
|
4754
|
+
if (!signal.aborted && hasRuntimeLifetime(options) && mayStoreRerender(startEpoch, id, cacheKey, oKey, tags)) await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
|
|
4634
4755
|
return captured.bytes;
|
|
4635
4756
|
}), outcome);
|
|
4636
4757
|
} catch (error) {
|
|
@@ -4668,10 +4789,10 @@ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, sn
|
|
|
4668
4789
|
const tags = resolveTags(options, props);
|
|
4669
4790
|
const oKey = overlayKey(id, cacheKey);
|
|
4670
4791
|
const startEpoch = currentInvalidationEpoch();
|
|
4671
|
-
const sfKey = `prebuilt-bg:${
|
|
4792
|
+
const sfKey = `prebuilt-bg:${oKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
|
|
4672
4793
|
const work = requestContextAls.run(snapshot, () => componentSingleflight.do(sfKey, (signal) => runBackgroundFlight(signal, async () => {
|
|
4673
4794
|
const captured = await captureComponentPayload(id, component, props, options);
|
|
4674
|
-
if (!signal.aborted &&
|
|
4795
|
+
if (!signal.aborted && mayStoreRerender(startEpoch, id, cacheKey, oKey, tags)) await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
|
|
4675
4796
|
}, (error) => console.error(`[timber] cache.component background re-render failed for "${id}":`, error))).catch(() => {}));
|
|
4676
4797
|
if (waitUntil) waitUntil(work);
|
|
4677
4798
|
else if (!warnedNoWaitUntil) {
|
|
@@ -4679,8 +4800,6 @@ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, sn
|
|
|
4679
4800
|
console.warn("[timber] cache.component SWR background re-render has no waitUntil — the re-render may be killed when the handler returns on serverless platforms. Ensure the adapter wires runWithWaitUntil().");
|
|
4680
4801
|
}
|
|
4681
4802
|
}
|
|
4682
|
-
/** Components already announced by the one-time dev log. */
|
|
4683
|
-
var devLoggedIds = /* @__PURE__ */ new Set();
|
|
4684
4803
|
/**
|
|
4685
4804
|
* Dev: the seed for a prerender entry — the stored capture, or a new one
|
|
4686
4805
|
* rendered exactly as the build would render it (synthetic store, isolated
|
|
@@ -4700,8 +4819,10 @@ async function resolveDevSeed(registration, props, keyParams, cacheKey) {
|
|
|
4700
4819
|
capturedAt: stored.capturedAt
|
|
4701
4820
|
};
|
|
4702
4821
|
const tags = resolveTags(options, props);
|
|
4703
|
-
const
|
|
4704
|
-
const
|
|
4822
|
+
const isr = hasRuntimeLifetime(options);
|
|
4823
|
+
const guardKey = isr ? overlayKey(id, cacheKey) : devEntryKey(id, cacheKey);
|
|
4824
|
+
const guardTags = [...tags, devComponentTag(id)];
|
|
4825
|
+
const sfKey = `prebuilt-dev:${guardKey}\0${lastInvalidationEpochFor(guardKey, guardTags)}`;
|
|
4705
4826
|
try {
|
|
4706
4827
|
return await componentSingleflight.do(sfKey, async (signal) => {
|
|
4707
4828
|
const startEpoch = currentInvalidationEpoch();
|
|
@@ -4711,21 +4832,19 @@ async function resolveDevSeed(registration, props, keyParams, cacheKey) {
|
|
|
4711
4832
|
if (outcome.failure instanceof BuildTimeContextError) throw outcome.failure;
|
|
4712
4833
|
if (outcome.bytes === null) return null;
|
|
4713
4834
|
if (await revivePayload(id, outcome.bytes, "not storing the dev capture") === null) return null;
|
|
4714
|
-
|
|
4835
|
+
const moved = isr && overlayKey(id, cacheKey) !== guardKey;
|
|
4836
|
+
if (!signal.aborted && !moved && !wasInvalidatedSince(startEpoch, guardKey, guardTags)) {
|
|
4715
4837
|
setDevSeed(id, cacheKey, {
|
|
4716
4838
|
bytes: outcome.bytes,
|
|
4717
4839
|
tags,
|
|
4718
|
-
capturedAt
|
|
4840
|
+
capturedAt,
|
|
4841
|
+
isr
|
|
4719
4842
|
});
|
|
4720
4843
|
warnNestingClamps({
|
|
4721
4844
|
id,
|
|
4722
4845
|
options,
|
|
4723
4846
|
tags
|
|
4724
4847
|
}, outcome.nested, warnedNestingPairs, (m) => console.warn(m));
|
|
4725
|
-
if (!devLoggedIds.has(id)) {
|
|
4726
|
-
devLoggedIds.add(id);
|
|
4727
|
-
console.log(`[timber] cache.component "${id}": prerendered in dev — served from memory until a file changes. A hard reload (Cache-Control: no-cache) renders it again.`);
|
|
4728
|
-
}
|
|
4729
4848
|
}
|
|
4730
4849
|
return {
|
|
4731
4850
|
payload: outcome.bytes,
|
|
@@ -4758,11 +4877,13 @@ async function tryRevivePayload(registration, props, keyPropsOverride) {
|
|
|
4758
4877
|
if (cacheKey === null) return null;
|
|
4759
4878
|
const outcome = options.fallbackOnMissingSegmentParams === false ? "failing the render (fallbackOnMissingSegmentParams: false)" : "rendering dynamically";
|
|
4760
4879
|
if (devStore && isHardReload(store.originalHeaders)) await discardDevEntry(id, cacheKey, overlayKey(id, cacheKey));
|
|
4880
|
+
let overlayUnreadable = false;
|
|
4761
4881
|
if (hasRuntime) {
|
|
4762
4882
|
const overlayResult = await lookupOverlay(id, cacheKey);
|
|
4763
4883
|
if (overlayResult) {
|
|
4764
4884
|
const overlayHasSeed = overlayResult.record?.s ?? false;
|
|
4765
4885
|
if (overlayResult.kind === "tombstone") return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
|
|
4886
|
+
overlayUnreadable = overlayResult.kind === "unreadable";
|
|
4766
4887
|
if (overlayResult.kind === "fresh" && overlayResult.payload) return await revivePayload(id, overlayResult.payload, outcome);
|
|
4767
4888
|
if (overlayResult.kind === "stale" && overlayResult.payload) {
|
|
4768
4889
|
if (options.staleWhileRevalidate) {
|
|
@@ -4774,6 +4895,7 @@ async function tryRevivePayload(registration, props, keyPropsOverride) {
|
|
|
4774
4895
|
}
|
|
4775
4896
|
}
|
|
4776
4897
|
const seed = devStore ? options.prerender ? await resolveDevSeed(registration, props, keyParams, cacheKey) : null : hasSource ? await lookupArtifactSeed(id, cacheKey, options.ttl !== void 0) : null;
|
|
4898
|
+
if (seed !== null && overlayUnreadable) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
|
|
4777
4899
|
if (seed !== null) {
|
|
4778
4900
|
if (options.ttl !== void 0) {
|
|
4779
4901
|
if ((Date.now() - seed.capturedAt) / 1e3 > options.ttl) {
|
|
@@ -4816,7 +4938,7 @@ function __prebuilt(id, component, options = {}) {
|
|
|
4816
4938
|
options
|
|
4817
4939
|
};
|
|
4818
4940
|
if (isDevPrebuiltStoreActive()) {
|
|
4819
|
-
if (devRegisteredIds.has(id)) clearDevPrebuiltStore();
|
|
4941
|
+
if (devRegisteredIds.has(id)) clearDevPrebuiltStore([id]);
|
|
4820
4942
|
devRegisteredIds.add(id);
|
|
4821
4943
|
} else registry.set(id, registration);
|
|
4822
4944
|
const wrapper = async (props) => {
|
|
@@ -4839,7 +4961,6 @@ function getPrebuiltRegistration(id) {
|
|
|
4839
4961
|
function getPrebuiltRegistry() {
|
|
4840
4962
|
return registry;
|
|
4841
4963
|
}
|
|
4842
|
-
//#endregion
|
|
4843
4964
|
export { AccessGate, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RenderTimeoutError, SlotAccessGate, __prebuilt, callOnRequestError, canonicalize, classifyMetadataRoute, coerce, collectEarlyHintHeaders, computeComponentCacheKey, createPipeline, enforceBodyLimits, executeAction, formatLinkHeader, generateTraceId, getCookie, getHeader, getLogger, getMetadataRouteAutoLink, getMetadataRouteServePath, getPrebuiltRegistration, getPrebuiltRegistry, getSearchParams, getSegmentParams, getSetCookieHeaders, handleRouteRequest, hasOnRequestError, hasPrebuiltPayloadSource, loadInstrumentation, logCacheMiss, logMiddlewareError, logMiddlewareShortCircuit, logProxyError, logRenderError, logRequestCompleted, logRequestReceived, logSlowRequest, logSwrRefetchFailed, logWaitUntilRejected, logWaitUntilUnsupported, markResponseFlushed, parseBodySize, renderMetadataToElements, replaceTraceId, resolveAllowedMethods, resolveMetadata, resolveMetadataUrls, resolveSlotDenied, resolveStatusFile, resolveTitle, runMiddleware, runProxy, runWithEarlyHintsSender, runWithRequestContext, runWithTraceId, sendEarlyHints103, setLogger, setMutableCookieContext, setPrebuiltPayloadSource, setSegmentParams };
|
|
4844
4965
|
|
|
4845
4966
|
//# sourceMappingURL=internal.js.map
|