@timber-js/app 0.2.0-alpha.222 → 0.2.0-alpha.224
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-vBHr2vqd.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-DdcDLpBj.js → cache-api-TDZ4hlDc.js} +190 -38
- 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-BchW_AtW.js → chains-Dgm3PrMe.js} +3 -4
- package/dist/_chunks/{chains-BchW_AtW.js.map → chains-Dgm3PrMe.js.map} +1 -1
- package/dist/_chunks/{classify-IqzMpxMs.js → classify--_kINHQV.js} +4 -5
- package/dist/_chunks/{classify-IqzMpxMs.js.map → classify--_kINHQV.js.map} +1 -1
- package/dist/_chunks/{cli-check-DQne_YhU.js → cli-check-Dv3f8d2j.js} +5 -6
- package/dist/_chunks/{cli-check-DQne_YhU.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-BS-RFGE2.js → cli-schema-sync-DIPurq7X.js} +4 -5
- package/dist/_chunks/{cli-schema-sync-BS-RFGE2.js.map → cli-schema-sync-DIPurq7X.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-v872sHms.js → cli-schema-sync-uq72EZmD.js} +1 -1
- package/dist/_chunks/{client-dep-entries-BJyP9SIu.js → client-dep-entries-CP7AkMCM.js} +4 -5
- package/dist/_chunks/{client-dep-entries-BJyP9SIu.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-VwzrtjIt.js → convention-lint-hZwz5wd4.js} +8 -11
- package/dist/_chunks/{convention-lint-VwzrtjIt.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-BNr5drEO.js → dev-server-B7o4As0l.js} +383 -55
- package/dist/_chunks/dev-server-B7o4As0l.js.map +1 -0
- package/dist/_chunks/dev-server-hZzmbMvK.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-BdHUOUqg.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-B9PFncvb.js → global-context-DbxNWeBP.js} +2 -3
- package/dist/_chunks/{global-context-B9PFncvb.js.map → global-context-DbxNWeBP.js.map} +1 -1
- 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-C3Sht92C.js → json-lossy-check-DVkLUlfC.js} +3 -4
- package/dist/_chunks/{json-lossy-check-C3Sht92C.js.map → json-lossy-check-DVkLUlfC.js.map} +1 -1
- package/dist/_chunks/{live-graph-DEu_GWbc.js → live-graph-BcVjQ1Te.js} +6 -7
- package/dist/_chunks/{live-graph-DEu_GWbc.js.map → live-graph-BcVjQ1Te.js.map} +1 -1
- package/dist/_chunks/{logger-CI_hThfy.js → logger-CWk44DLp.js} +89 -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-bF0bKoig.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-DTWIfNgD.js → poison-scan-DJYxZc_7.js} +4 -5
- package/dist/_chunks/{poison-scan-DTWIfNgD.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-Ln_u7fX-.js → render-timeout-MrrqD1wd.js} +2 -3
- package/dist/_chunks/{render-timeout-Ln_u7fX-.js.map → render-timeout-MrrqD1wd.js.map} +1 -1
- package/dist/_chunks/{resolve-schema-CkAInout.js → resolve-schema-B-aCuTu3.js} +3 -4
- package/dist/_chunks/{resolve-schema-CkAInout.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-C8fdKvKG.js → scanner-CJC-ScJU.js} +15 -23
- package/dist/_chunks/{scanner-C8fdKvKG.js.map → scanner-CJC-ScJU.js.map} +1 -1
- package/dist/_chunks/{schema-bridge-DpOmvZlI.js → schema-bridge-DyRs3cqy.js} +2 -3
- package/dist/_chunks/{schema-bridge-DpOmvZlI.js.map → schema-bridge-DyRs3cqy.js.map} +1 -1
- 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-D3DNxKFq.js → segment-context-CYiGTi3K.js} +4 -6
- package/dist/_chunks/{segment-context-D3DNxKFq.js.map → segment-context-CYiGTi3K.js.map} +1 -1
- 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-CO3dk0V1.js → sizeof-DG4W40lv.js} +3 -4
- package/dist/_chunks/{sizeof-CO3dk0V1.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-BqzxnwGC.js → walkers-DIE203ir.js} +6 -8
- package/dist/_chunks/{walkers-BqzxnwGC.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/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/index.js +22 -34
- 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/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 +40 -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.d.ts.map +1 -1
- package/dist/index.js +698 -237
- 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 +5 -1
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/dev-store-clear.d.ts +59 -4
- package/dist/plugins/dev-store-clear.d.ts.map +1 -1
- package/dist/plugins/graph-endpoint.d.ts +4 -2
- package/dist/plugins/graph-endpoint.d.ts.map +1 -1
- package/dist/plugins/optimize-package-imports-defaults.d.ts +13 -0
- package/dist/plugins/optimize-package-imports-defaults.d.ts.map +1 -0
- package/dist/plugins/optimize-package-imports.d.ts +113 -0
- package/dist/plugins/optimize-package-imports.d.ts.map +1 -0
- 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/search-params/index.js +5 -7
- package/dist/search-params/index.js.map +1 -1
- 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 +1061 -943
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +17 -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 +8 -0
- 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/34-api-config.mdx +42 -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 +2 -2
- 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/key-discipline.ts +218 -0
- package/src/cache/timber-cache.ts +42 -5
- 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/use-cookie.ts +33 -21
- package/src/config-types.ts +40 -5
- package/src/config-validation.ts +37 -0
- package/src/cookies/define-cookie.ts +10 -46
- package/src/cookies/json-cookie.ts +4 -4
- package/src/index.ts +2 -0
- 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 +96 -37
- package/src/plugins/dev-store-clear.ts +105 -7
- package/src/plugins/graph-endpoint.ts +15 -3
- package/src/plugins/optimize-package-imports-defaults.ts +88 -0
- package/src/plugins/optimize-package-imports.ts +439 -0
- 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 +9 -0
- package/src/server/access-gate.tsx +32 -20
- package/src/server/action-handler.ts +40 -34
- 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 +23 -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 +18 -0
- package/src/server/prebuilt-runtime.ts +43 -44
- 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-vBHr2vqd.js.map +0 -1
- package/dist/_chunks/build-output-helper-RV_BRcF1.js.map +0 -1
- package/dist/_chunks/cache-api-DdcDLpBj.js.map +0 -1
- package/dist/_chunks/chains-B8TCLved.js +0 -1
- package/dist/_chunks/cli-context-BJQB6rtF.js +0 -1
- package/dist/_chunks/dev-server-BNr5drEO.js.map +0 -1
- package/dist/_chunks/dev-server-CUg7Mqh_.js +0 -1
- package/dist/_chunks/dev-store-BOa304m_.js.map +0 -1
- package/dist/_chunks/flight-source-node-BdHUOUqg.js.map +0 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +0 -1
- package/dist/_chunks/logger-CI_hThfy.js.map +0 -1
- package/dist/_chunks/node-response-bF0bKoig.js.map +0 -1
- package/dist/_chunks/plugin-context-DxMMvjUt.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,40 +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 { A as
|
|
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 {
|
|
19
|
-
import { t as createGlobalContext } from "../_chunks/global-context-
|
|
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";
|
|
20
20
|
import { createHash } from "node:crypto";
|
|
21
21
|
import { readFile } from "node:fs/promises";
|
|
22
22
|
import { createElement, useContext } from "react";
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Check if an error is an abort error (connection closed by client).
|
|
26
|
-
*
|
|
27
|
-
* When the browser aborts a request (page refresh, navigation away),
|
|
28
|
-
* the AbortSignal fires and React/streams throw an AbortError. This
|
|
29
|
-
* is not an application error — suppress it from error boundaries and logs.
|
|
30
|
-
*/
|
|
31
|
-
function isAbortError(error) {
|
|
32
|
-
if (error instanceof DOMException && error.name === "AbortError") return true;
|
|
33
|
-
if (error instanceof Error && error.name === "AbortError") return true;
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
36
|
-
//#endregion
|
|
37
|
-
//#region src/server/server-timing.ts
|
|
23
|
+
// src/server/server-timing.ts
|
|
38
24
|
/**
|
|
39
25
|
* Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
|
|
40
26
|
*
|
|
@@ -109,8 +95,7 @@ function getServerTimingHeader() {
|
|
|
109
95
|
}
|
|
110
96
|
return result || null;
|
|
111
97
|
}
|
|
112
|
-
|
|
113
|
-
//#region src/server/instrumentation.ts
|
|
98
|
+
// src/server/instrumentation.ts
|
|
114
99
|
/**
|
|
115
100
|
* Instrumentation — loads and runs the user's instrumentation.ts file.
|
|
116
101
|
*
|
|
@@ -189,8 +174,7 @@ async function callOnRequestError(error, request, context) {
|
|
|
189
174
|
function hasOnRequestError() {
|
|
190
175
|
return _onRequestError !== null;
|
|
191
176
|
}
|
|
192
|
-
|
|
193
|
-
//#region src/server/safe-load.ts
|
|
177
|
+
// src/server/safe-load.ts
|
|
194
178
|
/**
|
|
195
179
|
* Custom error class for module load failures.
|
|
196
180
|
*
|
|
@@ -222,8 +206,38 @@ async function loadModule(loader) {
|
|
|
222
206
|
throw new ModuleLoadError(loader.filePath, error);
|
|
223
207
|
}
|
|
224
208
|
}
|
|
225
|
-
|
|
226
|
-
|
|
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
|
+
}
|
|
227
241
|
/**
|
|
228
242
|
* Whether a matched chain renders as an API route: its leaf has a
|
|
229
243
|
* `route.ts` and no `page.tsx`. The same test `renderRoute` dispatches on,
|
|
@@ -247,8 +261,7 @@ function isCsrfExemptRoute(segments) {
|
|
|
247
261
|
var SERVE_PATH_TO_CONVENTION = /* @__PURE__ */ new Map();
|
|
248
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);
|
|
249
263
|
else SERVE_PATH_TO_CONVENTION.set(convention.servePath, baseName);
|
|
250
|
-
|
|
251
|
-
//#region src/shared/csrf-reject.ts
|
|
264
|
+
// src/shared/csrf-reject.ts
|
|
252
265
|
/**
|
|
253
266
|
* Marker header on CSRF rejections.
|
|
254
267
|
*
|
|
@@ -264,8 +277,7 @@ else SERVE_PATH_TO_CONVENTION.set(convention.servePath, baseName);
|
|
|
264
277
|
*/
|
|
265
278
|
var CSRF_REJECT_HEADER = "X-Timber-Reject";
|
|
266
279
|
var CSRF_REJECT_VALUE = "csrf";
|
|
267
|
-
|
|
268
|
-
//#region src/server/csrf.ts
|
|
280
|
+
// src/server/csrf.ts
|
|
269
281
|
/**
|
|
270
282
|
* CSRF protection — Fetch Metadata first, Origin as the fallback.
|
|
271
283
|
*
|
|
@@ -446,8 +458,7 @@ function csrfRejectionResponse(req, rejection) {
|
|
|
446
458
|
}
|
|
447
459
|
});
|
|
448
460
|
}
|
|
449
|
-
|
|
450
|
-
//#region src/server/pipeline-helpers.ts
|
|
461
|
+
// src/server/pipeline-helpers.ts
|
|
451
462
|
/**
|
|
452
463
|
* The pipeline-boundary CSRF gate: the 403 to answer with, or null to go on.
|
|
453
464
|
*
|
|
@@ -782,8 +793,7 @@ function reportedPhase(source, apiRoute) {
|
|
|
782
793
|
default: return source;
|
|
783
794
|
}
|
|
784
795
|
}
|
|
785
|
-
|
|
786
|
-
//#region src/server/proxy.ts
|
|
796
|
+
// src/server/proxy.ts
|
|
787
797
|
/**
|
|
788
798
|
* Run the proxy pipeline.
|
|
789
799
|
*
|
|
@@ -803,8 +813,7 @@ async function runProxy(proxyExport, req, next) {
|
|
|
803
813
|
}
|
|
804
814
|
return composed();
|
|
805
815
|
}
|
|
806
|
-
|
|
807
|
-
//#region src/server/middleware-runner.ts
|
|
816
|
+
// src/server/middleware-runner.ts
|
|
808
817
|
/**
|
|
809
818
|
* Run a route's middleware function.
|
|
810
819
|
*
|
|
@@ -836,8 +845,7 @@ async function runMiddlewareChain(chain, ctx) {
|
|
|
836
845
|
if (result instanceof Response) return result;
|
|
837
846
|
}
|
|
838
847
|
}
|
|
839
|
-
|
|
840
|
-
//#region src/server/csp-nonce.ts
|
|
848
|
+
// src/server/csp-nonce.ts
|
|
841
849
|
/**
|
|
842
850
|
* CSP nonce — per-request, generated on demand.
|
|
843
851
|
*
|
|
@@ -884,516 +892,636 @@ function requestCspNonce() {
|
|
|
884
892
|
store.cspNonce ??= generateNonce();
|
|
885
893
|
return store.cspNonce;
|
|
886
894
|
}
|
|
887
|
-
|
|
888
|
-
//#region src/server/param-coercion.ts
|
|
889
|
-
/**
|
|
890
|
-
* Thrown when an app/schema.ts segment-param codec's parse() fails.
|
|
891
|
-
* The pipeline catches this and responds with 404.
|
|
892
|
-
*/
|
|
893
|
-
var ParamCoercionError = class extends Error {
|
|
894
|
-
constructor(message) {
|
|
895
|
-
super(message);
|
|
896
|
-
this.name = "ParamCoercionError";
|
|
897
|
-
}
|
|
898
|
-
};
|
|
899
|
-
/** Global schema codecs, set once at startup from virtual:timber-schema. */
|
|
900
|
-
var _globalCodecs = null;
|
|
895
|
+
// src/server/response-cache-policy.ts
|
|
901
896
|
/**
|
|
902
|
-
*
|
|
903
|
-
*
|
|
904
|
-
*
|
|
905
|
-
*
|
|
906
|
-
* repeatable — coercing a match twice runs every codec on the URL value both
|
|
907
|
-
* times, never on its own output.
|
|
908
|
-
*
|
|
909
|
-
* Codecs come from `app/schema.ts` and nowhere else (TIM-1342 completed
|
|
910
|
-
* design/41-global-params.md migration step 9). A route with no schema, or
|
|
911
|
-
* a param the schema does not declare, keeps its raw string — which is the
|
|
912
|
-
* honest type for an uninterpreted URL segment.
|
|
913
|
-
*
|
|
914
|
-
* Throws ParamCoercionError if any codec fails (→ 404).
|
|
915
|
-
*
|
|
916
|
-
* This runs BEFORE middleware, so ctx.segmentParams is already typed.
|
|
917
|
-
* See design/07-routing.md §"Where Coercion Runs"
|
|
918
|
-
* 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`.
|
|
919
901
|
*
|
|
920
|
-
*
|
|
921
|
-
*
|
|
922
|
-
* it. Making it synchronous would
|
|
923
|
-
* change that contract and remove a microtask boundary the pipeline's
|
|
924
|
-
* 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.
|
|
925
904
|
*/
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
const segment = effectiveUrlSegment(node);
|
|
932
|
-
if (!segment.paramName) continue;
|
|
933
|
-
const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
|
|
934
|
-
const codec = globalCodecs[bracketKey];
|
|
935
|
-
if (!codec) continue;
|
|
936
|
-
const key = segment.paramName;
|
|
937
|
-
if (!(key in mergeTarget)) continue;
|
|
938
|
-
let parsed;
|
|
939
|
-
try {
|
|
940
|
-
parsed = codec.parse(mergeTarget[key]);
|
|
941
|
-
} catch (err) {
|
|
942
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
943
|
-
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}'.`);
|
|
944
|
-
throw new ParamCoercionError(message);
|
|
945
|
-
}
|
|
946
|
-
mergeTarget[key] = normalizeParamValue(parsed, key);
|
|
947
|
-
}
|
|
948
|
-
return mergeTarget;
|
|
949
|
-
}
|
|
950
|
-
//#endregion
|
|
951
|
-
//#region src/server/pipeline-metadata.ts
|
|
905
|
+
var LEGACY_CDN_CACHE_HEADERS = [
|
|
906
|
+
"Surrogate-Control",
|
|
907
|
+
"Edge-Control",
|
|
908
|
+
"X-Accel-Expires"
|
|
909
|
+
];
|
|
952
910
|
/**
|
|
953
|
-
*
|
|
954
|
-
*
|
|
955
|
-
* Handles serving static metadata files and serializing sitemap responses.
|
|
956
|
-
* Extracted from pipeline.ts to keep files under 500 lines.
|
|
911
|
+
* Whether a response header overrides `Cache-Control` at a shared cache.
|
|
957
912
|
*
|
|
958
|
-
*
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
*
|
|
962
|
-
*
|
|
963
|
-
* the
|
|
964
|
-
* 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.
|
|
965
919
|
*
|
|
966
|
-
*
|
|
967
|
-
|
|
968
|
-
var METADATA_CACHE_CONTROL = "public, max-age=14400, must-revalidate";
|
|
969
|
-
/**
|
|
970
|
-
* Content types that are text-based and should include charset=utf-8.
|
|
971
|
-
* Binary formats (images) should not include charset.
|
|
920
|
+
* `Cache-Control` itself does not match (no `-` prefix) and is replaced
|
|
921
|
+
* separately.
|
|
972
922
|
*/
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
"
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
]
|
|
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
|
|
980
949
|
/**
|
|
981
|
-
*
|
|
982
|
-
*
|
|
983
|
-
* Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
|
|
984
|
-
* are served as-is with the appropriate Content-Type header.
|
|
985
|
-
* Text files include charset=utf-8; binary files do not.
|
|
950
|
+
* Build the hard-navigate envelope for a status code.
|
|
986
951
|
*
|
|
987
|
-
*
|
|
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).
|
|
988
957
|
*/
|
|
989
|
-
|
|
990
|
-
const
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
return new Response(body, {
|
|
999
|
-
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,
|
|
1000
967
|
headers
|
|
1001
968
|
});
|
|
1002
969
|
}
|
|
970
|
+
// src/server/pipeline-outcome.ts
|
|
1003
971
|
/**
|
|
1004
|
-
*
|
|
1005
|
-
*
|
|
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".
|
|
1006
981
|
*/
|
|
1007
|
-
function
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
}
|
|
1014
|
-
if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
|
|
1015
|
-
if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
|
|
1016
|
-
xml += "\n </url>";
|
|
1017
|
-
return xml;
|
|
1018
|
-
}).join("\n")}\n</urlset>`;
|
|
1019
|
-
}
|
|
1020
|
-
/** Escape special XML characters. */
|
|
1021
|
-
function escapeXml(str) {
|
|
1022
|
-
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
|
+
});
|
|
1023
988
|
}
|
|
1024
|
-
//#endregion
|
|
1025
|
-
//#region src/server/state-tree-diff.ts
|
|
1026
989
|
/**
|
|
1027
|
-
*
|
|
990
|
+
* Resolve the header bag a signal/error outcome is written onto, with the
|
|
991
|
+
* cookie jar applied exactly once.
|
|
1028
992
|
*
|
|
1029
|
-
*
|
|
1030
|
-
* the
|
|
1031
|
-
*
|
|
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).
|
|
1032
999
|
*
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1035
|
-
*
|
|
1036
|
-
*
|
|
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.
|
|
1037
1007
|
*
|
|
1038
|
-
*
|
|
1039
|
-
* See design/13-security.md §"State tree manipulation"
|
|
1008
|
+
* `fresh` creates the bag for an outcome that arrives without one.
|
|
1040
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
|
+
}
|
|
1041
1019
|
/**
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1044
|
-
*
|
|
1045
|
-
*
|
|
1046
|
-
* the header is missing, malformed, or empty. Parsing happens before
|
|
1047
|
-
* renderToReadableStream — not inside the React render pass.
|
|
1048
|
-
*
|
|
1049
|
-
* @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'`.
|
|
1050
1024
|
*/
|
|
1051
|
-
function
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
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
|
+
});
|
|
1067
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
|
+
};
|
|
1068
1076
|
}
|
|
1069
|
-
//#endregion
|
|
1070
|
-
//#region src/server/pipeline-interception.ts
|
|
1071
1077
|
/**
|
|
1072
|
-
*
|
|
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.
|
|
1073
1081
|
*
|
|
1074
|
-
*
|
|
1075
|
-
*
|
|
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.
|
|
1076
1152
|
*
|
|
1153
|
+
* Handles serving static metadata files and serializing sitemap responses.
|
|
1077
1154
|
* Extracted from pipeline.ts to keep files under 500 lines.
|
|
1078
1155
|
*
|
|
1079
|
-
* See design/
|
|
1156
|
+
* See design/16-metadata.md §"Metadata Routes"
|
|
1080
1157
|
*/
|
|
1081
1158
|
/**
|
|
1082
|
-
*
|
|
1083
|
-
*
|
|
1084
|
-
*
|
|
1085
|
-
*
|
|
1086
|
-
* 1. The **target** pathname matches the rewrite's intercepted pattern.
|
|
1087
|
-
* 2. The **source** route — the page the user is navigating FROM, per the
|
|
1088
|
-
* validated X-Timber-URL header — renders the segment that owns the slot
|
|
1089
|
-
* holding the intercepting page (`interceptingScope`). Only then does that
|
|
1090
|
-
* slot exist in the rendered tree, so only then can the intercepting page
|
|
1091
|
-
* render.
|
|
1092
|
-
*
|
|
1093
|
-
* Condition 2 replaced a URL-prefix check (TIM-1279). A prefix cannot
|
|
1094
|
-
* distinguish a route-group-scoped interception from a genuinely root-level
|
|
1095
|
-
* one — route groups are invisible in `urlPath`, so both collapse to "/" and
|
|
1096
|
-
* the guard degenerates to always-true. Tree paths carry group identity.
|
|
1097
|
-
* The scope check also subsumes the old segment-boundary rule: a source route
|
|
1098
|
-
* under /feed-private has no "/feed" in its chain.
|
|
1099
|
-
*
|
|
1100
|
-
* A third condition lives with the caller, which owns route matching, and it
|
|
1101
|
-
* applies to the `'slot'` shape only: the route produced by re-matching
|
|
1102
|
-
* `interceptingPrefix` must pass through the scope too. Conditions 1–2 are
|
|
1103
|
-
* about the route the user is leaving; the slot has to exist in the tree that
|
|
1104
|
-
* actually renders. The `'children'` shape resolves its owner from the scope
|
|
1105
|
-
* directly rather than from a pathname, so it satisfies that by construction.
|
|
1106
|
-
*
|
|
1107
|
-
* `resolveSourceScopes` is a thunk so its inputs are only resolved when some
|
|
1108
|
-
* rewrite's pattern actually matches the target — the common case is no match
|
|
1109
|
-
* at all. It returns the two client-supplied answers to "what is on screen?"
|
|
1110
|
-
* as **separate sets, most authoritative first**: the tree paths the client
|
|
1111
|
-
* says it has mounted, then those of the route the departing URL matches. It
|
|
1112
|
-
* returns null only when neither yields anything, which is not a soft
|
|
1113
|
-
* navigation this can reason about.
|
|
1114
|
-
*
|
|
1115
|
-
* They are two sets rather than one union because ranking needs a chain
|
|
1116
|
-
* (TIM-1318). Each channel describes a single rendered chain, so within one the
|
|
1117
|
-
* scopes are strictly nested and the deepest is the innermost owner. Unioned
|
|
1118
|
-
* they are not: once a modal is open the address bar holds the *intercepted*
|
|
1119
|
-
* URL, so the second channel describes the canonical branch — possibly an
|
|
1120
|
-
* exclusive route group the client never mounted — and a deeper scope from
|
|
1121
|
-
* there would outrank the owner actually on screen. Trying the mounted channel
|
|
1122
|
-
* to exhaustion first keeps the fallback the union was there to provide while
|
|
1123
|
-
* 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.
|
|
1124
1163
|
*
|
|
1125
|
-
*
|
|
1126
|
-
|
|
1127
|
-
|
|
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.
|
|
1128
1180
|
*
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1131
|
-
*
|
|
1132
|
-
*
|
|
1133
|
-
* 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.
|
|
1134
1185
|
*
|
|
1135
|
-
*
|
|
1136
|
-
* `collectInterceptionRewrites` sorts it at build time, so the deepest owner a
|
|
1137
|
-
* single chain passes through wins and nothing here has to score (TIM-1318).
|
|
1138
|
-
* Tree-walk order used to decide it, which meant renaming a route group flipped
|
|
1139
|
-
* which modal opened. The precondition is a property of the manifest this reads
|
|
1140
|
-
* rather than something it can re-derive, so it is asserted at its source:
|
|
1141
|
-
* `tests/interception.test.ts` §"rewrite order is decided by scope depth".
|
|
1186
|
+
* See design/16-metadata.md §"Metadata Routes"
|
|
1142
1187
|
*/
|
|
1143
|
-
function
|
|
1144
|
-
const
|
|
1145
|
-
|
|
1146
|
-
const
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
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
|
+
});
|
|
1150
1201
|
}
|
|
1151
1202
|
/**
|
|
1152
|
-
*
|
|
1153
|
-
*
|
|
1154
|
-
* Supports [param] (single segment) and [...param] (one or more segments).
|
|
1155
|
-
* Static segments must match exactly.
|
|
1203
|
+
* Serialize a sitemap array to XML.
|
|
1204
|
+
* Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
|
|
1156
1205
|
*/
|
|
1157
|
-
function
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
switch (seg.kind) {
|
|
1164
|
-
case "catch-all": return pi < pathParts.length;
|
|
1165
|
-
case "optional-catch-all": return true;
|
|
1166
|
-
case "dynamic": {
|
|
1167
|
-
if (pi >= pathParts.length) return false;
|
|
1168
|
-
const prefix = seg.prefix ?? "";
|
|
1169
|
-
const suffix = seg.suffix ?? "";
|
|
1170
|
-
const pathPart = pathParts[pi];
|
|
1171
|
-
if (prefix || suffix) {
|
|
1172
|
-
if (pathPart.length <= prefix.length + suffix.length || prefix && !pathPart.startsWith(prefix) || suffix && !pathPart.endsWith(suffix)) return false;
|
|
1173
|
-
}
|
|
1174
|
-
pi++;
|
|
1175
|
-
continue;
|
|
1176
|
-
}
|
|
1177
|
-
case "static":
|
|
1178
|
-
if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
|
|
1179
|
-
pi++;
|
|
1180
|
-
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>`;
|
|
1181
1212
|
}
|
|
1182
|
-
|
|
1183
|
-
|
|
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, "'");
|
|
1184
1222
|
}
|
|
1223
|
+
// src/server/param-coercion.ts
|
|
1185
1224
|
/**
|
|
1186
|
-
*
|
|
1187
|
-
*
|
|
1188
|
-
*
|
|
1189
|
-
* 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.
|
|
1190
1227
|
*/
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
if (isRscRequest(req) && config.interceptionRewrites?.length) {
|
|
1196
|
-
const rawSourceUrl = req.headers.get("X-Timber-URL");
|
|
1197
|
-
const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
|
|
1198
|
-
if (validatedSourceUrl) {
|
|
1199
|
-
const resolveSourceScopes = () => {
|
|
1200
|
-
const mounted = new Set(parseClientStateTree(req)?.treePaths ?? []);
|
|
1201
|
-
const sourceRoute = config.matchRoute(validatedSourceUrl);
|
|
1202
|
-
const scopes = [mounted, new Set(sourceRoute ? computeSegmentTreePaths(sourceRoute.segments) : [])].filter((scope) => scope.size > 0);
|
|
1203
|
-
return scopes.length > 0 ? scopes : null;
|
|
1204
|
-
};
|
|
1205
|
-
const rewrite = findInterceptionMatch(canonicalPathname, resolveSourceScopes, config.interceptionRewrites);
|
|
1206
|
-
if (rewrite?.mode === "children") {
|
|
1207
|
-
const interceptedMatch = config.matchInterceptedRoute?.(canonicalPathname, rewrite.interceptingScope);
|
|
1208
|
-
if (interceptedMatch) match = interceptedMatch;
|
|
1209
|
-
} else if (rewrite) {
|
|
1210
|
-
const sourceMatch = config.matchRoute(rewrite.interceptingPrefix);
|
|
1211
|
-
if (sourceMatch !== null && computeSegmentTreePaths(sourceMatch.segments).includes(rewrite.interceptingScope)) {
|
|
1212
|
-
match = sourceMatch;
|
|
1213
|
-
interception = { targetPathname: canonicalPathname };
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1228
|
+
var ParamCoercionError = class extends Error {
|
|
1229
|
+
constructor(message) {
|
|
1230
|
+
super(message);
|
|
1231
|
+
this.name = "ParamCoercionError";
|
|
1217
1232
|
}
|
|
1218
|
-
|
|
1219
|
-
match,
|
|
1220
|
-
interception
|
|
1221
|
-
};
|
|
1222
|
-
}
|
|
1233
|
+
};
|
|
1223
1234
|
/**
|
|
1224
|
-
*
|
|
1225
|
-
*
|
|
1226
|
-
*
|
|
1227
|
-
* - Must start with '/' (relative pathname, no scheme/authority)
|
|
1228
|
-
* - Must not contain control characters
|
|
1229
|
-
* - 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.
|
|
1230
1238
|
*/
|
|
1231
|
-
function
|
|
1232
|
-
if (!
|
|
1233
|
-
|
|
1234
|
-
for
|
|
1235
|
-
const code = raw.charCodeAt(i);
|
|
1236
|
-
if (code <= 31 || code === 127) return null;
|
|
1237
|
-
}
|
|
1238
|
-
const result = canonicalize(raw, stripTrailingSlash);
|
|
1239
|
-
if (!result.ok) return null;
|
|
1240
|
-
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.`);
|
|
1241
1243
|
}
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
+
/** Global schema codecs, set once at startup from virtual:timber-schema. */
|
|
1245
|
+
var _globalCodecs = null;
|
|
1244
1246
|
/**
|
|
1245
|
-
*
|
|
1246
|
-
* follow the `<target>-Cache-Control` naming pattern — the one part of this
|
|
1247
|
-
* rule that cannot be matched by shape. `X-Accel-Expires` is nginx
|
|
1248
|
-
* `proxy_cache`, which gives it precedence over `Cache-Control`.
|
|
1247
|
+
* Coerce the matched route's raw segment params and return the result.
|
|
1249
1248
|
*
|
|
1250
|
-
*
|
|
1251
|
-
*
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
"Surrogate-Control",
|
|
1255
|
-
"Edge-Control",
|
|
1256
|
-
"X-Accel-Expires"
|
|
1257
|
-
];
|
|
1258
|
-
/**
|
|
1259
|
-
* 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.
|
|
1260
1253
|
*
|
|
1261
|
-
*
|
|
1262
|
-
*
|
|
1263
|
-
*
|
|
1264
|
-
*
|
|
1265
|
-
* extended twice during review, each time by one name, which is the signal
|
|
1266
|
-
* 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.
|
|
1267
1258
|
*
|
|
1268
|
-
*
|
|
1269
|
-
*
|
|
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.
|
|
1270
1270
|
*/
|
|
1271
|
-
function
|
|
1272
|
-
const
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
headers.delete("Age");
|
|
1295
|
-
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;
|
|
1296
1294
|
}
|
|
1297
|
-
|
|
1298
|
-
//#region src/server/rsc-error-envelope.ts
|
|
1295
|
+
// src/server/head-response.ts
|
|
1299
1296
|
/**
|
|
1300
|
-
*
|
|
1297
|
+
* HEAD body stripping — RFC 9110 §9.3.2.
|
|
1301
1298
|
*
|
|
1302
|
-
*
|
|
1303
|
-
*
|
|
1304
|
-
*
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
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.
|
|
1307
1318
|
*/
|
|
1308
|
-
function rscErrorEnvelope(status, responseHeaders) {
|
|
1309
|
-
const headers = errorResponseHeaders(responseHeaders);
|
|
1310
|
-
headers.set(TIMBER_ERROR_HEADER, "1");
|
|
1311
|
-
headers.set("content-type", "application/json; charset=utf-8");
|
|
1312
|
-
return new Response(JSON.stringify({
|
|
1313
|
-
error: true,
|
|
1314
|
-
status
|
|
1315
|
-
}), {
|
|
1316
|
-
status,
|
|
1317
|
-
headers
|
|
1318
|
-
});
|
|
1319
|
-
}
|
|
1320
|
-
//#endregion
|
|
1321
|
-
//#region src/server/pipeline-outcome.ts
|
|
1322
1319
|
/**
|
|
1323
|
-
*
|
|
1324
|
-
* each phase function returns) into a final `Response`.
|
|
1320
|
+
* Return a bodyless copy of `response` when `method` is HEAD.
|
|
1325
1321
|
*
|
|
1326
|
-
*
|
|
1327
|
-
*
|
|
1328
|
-
* their own file. The phases produce values; this module is the single
|
|
1329
|
-
* 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.
|
|
1330
1324
|
*
|
|
1331
|
-
*
|
|
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).
|
|
1332
1328
|
*/
|
|
1333
|
-
function
|
|
1334
|
-
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);
|
|
1335
1334
|
return new Response(null, {
|
|
1336
|
-
status,
|
|
1337
|
-
|
|
1335
|
+
status: response.status,
|
|
1336
|
+
statusText: response.statusText,
|
|
1337
|
+
headers: response.headers
|
|
1338
1338
|
});
|
|
1339
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
|
+
];
|
|
1340
1351
|
/**
|
|
1341
|
-
* Resolve the
|
|
1342
|
-
* cookie jar applied exactly once.
|
|
1343
|
-
*
|
|
1344
|
-
* Ownership rule (design/49 §P0b): the phase that owns `responseHeaders`
|
|
1345
|
-
* applies the jar to it once; the translator applies it only for outcomes
|
|
1346
|
-
* that arrive without it. Render-phase outcomes already carry the jar —
|
|
1347
|
-
* `runRenderPhase()` applies it on entry, with or without a middleware
|
|
1348
|
-
* chain — so re-applying here emitted every middleware `Set-Cookie` twice
|
|
1349
|
-
* (TIM-1491).
|
|
1352
|
+
* Resolve the full list of allowed methods for a route module.
|
|
1350
1353
|
*
|
|
1351
|
-
*
|
|
1352
|
-
*
|
|
1353
|
-
*
|
|
1354
|
-
*
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
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.
|
|
1358
1373
|
*
|
|
1359
|
-
*
|
|
1374
|
+
* Dispatches to the named method handler, auto-generates 405/OPTIONS,
|
|
1375
|
+
* and merges response headers from ctx.headers.
|
|
1360
1376
|
*/
|
|
1361
|
-
function
|
|
1362
|
-
const
|
|
1363
|
-
|
|
1364
|
-
|
|
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);
|
|
1365
1397
|
}
|
|
1366
|
-
/**
|
|
1367
|
-
|
|
1368
|
-
|
|
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);
|
|
1369
1426
|
}
|
|
1370
1427
|
/**
|
|
1371
|
-
*
|
|
1372
|
-
*
|
|
1373
|
-
*
|
|
1374
|
-
*
|
|
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.
|
|
1375
1432
|
*/
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
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({
|
|
1397
1525
|
method,
|
|
1398
1526
|
path,
|
|
1399
1527
|
error
|
|
@@ -1403,102 +1531,355 @@ async function reportError(config, error, phase, ctx) {
|
|
|
1403
1531
|
path,
|
|
1404
1532
|
error
|
|
1405
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");
|
|
1406
1572
|
}
|
|
1407
|
-
await fireOnRequestError(error, ctx.req, phase, ctx.match?.segments);
|
|
1408
|
-
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, phase);
|
|
1409
1573
|
}
|
|
1410
|
-
/**
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
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
|
+
});
|
|
1427
1600
|
}
|
|
1428
1601
|
/**
|
|
1429
|
-
*
|
|
1430
|
-
*
|
|
1431
|
-
*
|
|
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.
|
|
1432
1644
|
*
|
|
1433
|
-
*
|
|
1434
|
-
*
|
|
1435
|
-
*
|
|
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"
|
|
1436
1656
|
*/
|
|
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
|
-
|
|
1471
|
-
|
|
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;
|
|
1472
1791
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
});
|
|
1792
|
+
case "static":
|
|
1793
|
+
if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
|
|
1794
|
+
pi++;
|
|
1795
|
+
continue;
|
|
1478
1796
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
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
|
+
}
|
|
1495
1830
|
}
|
|
1496
|
-
return rscErrorResponse(false, 500, headers);
|
|
1497
1831
|
}
|
|
1498
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;
|
|
1499
1871
|
}
|
|
1500
|
-
|
|
1501
|
-
|
|
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);
|
|
1881
|
+
}
|
|
1882
|
+
// src/server/pipeline-phases.ts
|
|
1502
1883
|
/**
|
|
1503
1884
|
* Pipeline phase functions — module-level free functions that take their
|
|
1504
1885
|
* dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
|
|
@@ -1538,17 +1919,24 @@ async function runProxyPhase(config, getProxy, req, method, path, next) {
|
|
|
1538
1919
|
}
|
|
1539
1920
|
/**
|
|
1540
1921
|
* Run the middleware chain phase. If the chain short-circuits with a Response,
|
|
1541
|
-
* returns it as a 'response' outcome
|
|
1542
|
-
* 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).
|
|
1543
1930
|
*/
|
|
1544
|
-
async function runMiddlewarePhase(config, req, match, responseHeaders
|
|
1931
|
+
async function runMiddlewarePhase(config, req, match, responseHeaders) {
|
|
1932
|
+
const route = match.canonical ?? match;
|
|
1545
1933
|
const detailed = config.serverTiming === "detailed";
|
|
1546
1934
|
const requestHeaderOverlay = new Headers();
|
|
1547
1935
|
const ctx = {
|
|
1548
1936
|
req,
|
|
1549
1937
|
requestHeaders: requestHeaderOverlay,
|
|
1550
1938
|
headers: responseHeaders,
|
|
1551
|
-
segmentParams:
|
|
1939
|
+
segmentParams: route.segmentParams,
|
|
1552
1940
|
get nonce() {
|
|
1553
1941
|
return requestCspNonce();
|
|
1554
1942
|
},
|
|
@@ -1564,7 +1952,8 @@ async function runMiddlewarePhase(config, req, match, responseHeaders, renderCon
|
|
|
1564
1952
|
}
|
|
1565
1953
|
};
|
|
1566
1954
|
try {
|
|
1567
|
-
const
|
|
1955
|
+
const runChain = () => runMiddlewareChain(route.middlewareChain, ctx);
|
|
1956
|
+
const chainFn = match.canonical ? () => runWithRouteParams(route, runChain) : runChain;
|
|
1568
1957
|
const middlewareResponse = await (async () => {
|
|
1569
1958
|
setMutableCookieContext(true);
|
|
1570
1959
|
try {
|
|
@@ -1579,7 +1968,7 @@ async function runMiddlewarePhase(config, req, match, responseHeaders, renderCon
|
|
|
1579
1968
|
response: middlewareResponse
|
|
1580
1969
|
};
|
|
1581
1970
|
applyRequestHeaderOverlay(requestHeaderOverlay);
|
|
1582
|
-
return
|
|
1971
|
+
return null;
|
|
1583
1972
|
} catch (error) {
|
|
1584
1973
|
return thrownOutcome("middleware", error);
|
|
1585
1974
|
}
|
|
@@ -1640,47 +2029,8 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1640
2029
|
}
|
|
1641
2030
|
canonicalPathname = result.pathname;
|
|
1642
2031
|
}
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
if (metaMatch) try {
|
|
1646
|
-
if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
|
|
1647
|
-
setSegmentParams(metaMatch.segmentParams);
|
|
1648
|
-
const mod = await loadModule(metaMatch.file);
|
|
1649
|
-
if (typeof mod.default !== "function") {
|
|
1650
|
-
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.`);
|
|
1651
|
-
return new Response("Metadata route must export a default function", { status: 500 });
|
|
1652
|
-
}
|
|
1653
|
-
const handlerResult = await mod.default();
|
|
1654
|
-
if (handlerResult instanceof Response) return cloneWithMutableHeaders(handlerResult);
|
|
1655
|
-
const contentType = metaMatch.contentType;
|
|
1656
|
-
let body;
|
|
1657
|
-
if (typeof handlerResult === "string") body = handlerResult;
|
|
1658
|
-
else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
|
|
1659
|
-
else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
|
|
1660
|
-
else body = String(handlerResult);
|
|
1661
|
-
return new Response(body, {
|
|
1662
|
-
status: 200,
|
|
1663
|
-
headers: {
|
|
1664
|
-
"Content-Type": `${contentType}; charset=utf-8`,
|
|
1665
|
-
"Cache-Control": METADATA_CACHE_CONTROL
|
|
1666
|
-
}
|
|
1667
|
-
});
|
|
1668
|
-
} catch (error) {
|
|
1669
|
-
if (isRedirectSignal(error)) return new Response(null, {
|
|
1670
|
-
status: error.status,
|
|
1671
|
-
headers: { Location: error.location }
|
|
1672
|
-
});
|
|
1673
|
-
if (isDenySignal(error)) return new Response(null, { status: error.status });
|
|
1674
|
-
logRenderError({
|
|
1675
|
-
method,
|
|
1676
|
-
path,
|
|
1677
|
-
error
|
|
1678
|
-
});
|
|
1679
|
-
await fireOnRequestError(error, req, "route");
|
|
1680
|
-
if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
|
|
1681
|
-
return new Response(null, { status: 500 });
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
2032
|
+
const metaMatch = config.matchMetadataRoute?.(canonicalPathname);
|
|
2033
|
+
if (metaMatch) return serveMetadataRoute(config, req, method, path, canonicalPathname, metaMatch);
|
|
1684
2034
|
if (config.autoSitemapHandler) try {
|
|
1685
2035
|
const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
|
|
1686
2036
|
if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
|
|
@@ -1723,7 +2073,8 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1723
2073
|
let interception;
|
|
1724
2074
|
try {
|
|
1725
2075
|
match = config.matchRoute(canonicalPathname);
|
|
1726
|
-
|
|
2076
|
+
let canonical;
|
|
2077
|
+
({match, interception, canonical} = resolveInterceptedRoute(config, req, canonicalPathname, match));
|
|
1727
2078
|
if (!match) {
|
|
1728
2079
|
if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
|
|
1729
2080
|
return await renderNotFound(responseHeaders);
|
|
@@ -1738,20 +2089,27 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1738
2089
|
...match,
|
|
1739
2090
|
segmentParams: await coerceSegmentParams(match)
|
|
1740
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
|
+
}
|
|
1741
2103
|
} catch (error) {
|
|
1742
2104
|
if (error instanceof ParamCoercionError) {
|
|
1743
|
-
|
|
1744
|
-
const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
|
|
1745
|
-
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.`);
|
|
1746
|
-
}
|
|
2105
|
+
warnParamCoercionFailure(method, canonicalPathname, match.segments, error);
|
|
1747
2106
|
if (isApiRouteChain(match.segments)) return new Response(null, { status: 404 });
|
|
1748
2107
|
return await renderNotFound(responseHeaders);
|
|
1749
2108
|
}
|
|
1750
2109
|
throw error;
|
|
1751
2110
|
}
|
|
1752
2111
|
setSegmentParams(match.segmentParams);
|
|
1753
|
-
|
|
1754
|
-
setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
|
|
2112
|
+
setMatchedSegmentPath(matchedSegmentPath(match.segments));
|
|
1755
2113
|
} catch (error) {
|
|
1756
2114
|
return outcomeToResponse(config, thrownOutcome("setup", error), {
|
|
1757
2115
|
req,
|
|
@@ -1761,22 +2119,32 @@ async function handleRequest(config, req, method, path, pathIsCanonical) {
|
|
|
1761
2119
|
match: match ?? void 0
|
|
1762
2120
|
});
|
|
1763
2121
|
}
|
|
1764
|
-
|
|
1765
|
-
canonicalPathname,
|
|
1766
|
-
interception
|
|
1767
|
-
}) : await runRenderPhase(config, req, match, responseHeaders, {
|
|
1768
|
-
canonicalPathname,
|
|
1769
|
-
interception
|
|
1770
|
-
}), {
|
|
2122
|
+
const outcomeContext = {
|
|
1771
2123
|
req,
|
|
1772
2124
|
method,
|
|
1773
2125
|
path,
|
|
1774
|
-
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,
|
|
1775
2144
|
match
|
|
1776
2145
|
});
|
|
1777
2146
|
}
|
|
1778
|
-
|
|
1779
|
-
//#region src/server/rsc-cache-key-guard.ts
|
|
2147
|
+
// src/server/rsc-cache-key-guard.ts
|
|
1780
2148
|
/**
|
|
1781
2149
|
* Origin-side binding of the `_rsc` cache key to the request that produced
|
|
1782
2150
|
* the response (TIM-1268).
|
|
@@ -1873,54 +2241,7 @@ async function enforceRscCacheKey(req, response) {
|
|
|
1873
2241
|
if (await hasValidRscCacheKey(req)) return;
|
|
1874
2242
|
preventResponseCaching(response.headers);
|
|
1875
2243
|
}
|
|
1876
|
-
|
|
1877
|
-
//#region src/server/head-response.ts
|
|
1878
|
-
/**
|
|
1879
|
-
* HEAD body stripping — RFC 9110 §9.3.2.
|
|
1880
|
-
*
|
|
1881
|
-
* "The HEAD method is identical to GET except that the server MUST NOT send
|
|
1882
|
-
* content in the response." The headers, however, must be the ones the
|
|
1883
|
-
* corresponding GET would have produced — which is why timber renders the
|
|
1884
|
-
* route in full and discards the body here rather than short-circuiting the
|
|
1885
|
-
* render. Content-Type, Content-Length, Set-Cookie, cache directives and
|
|
1886
|
-
* everything else ride through untouched.
|
|
1887
|
-
*
|
|
1888
|
-
* Node's `ServerResponse` happens to discard writes for HEAD, so the wire is
|
|
1889
|
-
* usually correct even without this. That is a property of one adapter, not of
|
|
1890
|
-
* the `Response` object: static generation, the Cloudflare and Nitro adapters,
|
|
1891
|
-
* tests, and anything calling the pipeline handler as a function all observe
|
|
1892
|
-
* the `Response` directly and saw the full body before TIM-1324.
|
|
1893
|
-
*
|
|
1894
|
-
* The pipeline applies this at its single exit so every response shape is
|
|
1895
|
-
* covered — page render, API route, metadata route, deny page, error page,
|
|
1896
|
-
* proxy short-circuit. The unit-level producer that is also reachable as a
|
|
1897
|
-
* standalone function (`handleRouteRequest`) calls it too, so it honours HEAD
|
|
1898
|
-
* on its own; it shares this implementation rather than repeating it, and
|
|
1899
|
-
* applying it twice is a no-op.
|
|
1900
|
-
*/
|
|
1901
|
-
/**
|
|
1902
|
-
* Return a bodyless copy of `response` when `method` is HEAD.
|
|
1903
|
-
*
|
|
1904
|
-
* A no-op for every other method and for responses that already carry no body
|
|
1905
|
-
* (204, 304, redirects), so callers do not need to pre-check either.
|
|
1906
|
-
*
|
|
1907
|
-
* The discarded stream is cancelled: an SSR render that reached this point has
|
|
1908
|
-
* a live producer attached, and dropping the reference without cancelling
|
|
1909
|
-
* leaks it for the lifetime of the render (design/13-security.md A4).
|
|
1910
|
-
*/
|
|
1911
|
-
function stripHeadBody(response, method) {
|
|
1912
|
-
if (method.toUpperCase() !== "HEAD") return response;
|
|
1913
|
-
const nodeBody = nodeBodyOps(response);
|
|
1914
|
-
if (nodeBody ? !nodeBody.hasBody : response.body === null) return response;
|
|
1915
|
-
discardResponseBody(response);
|
|
1916
|
-
return new Response(null, {
|
|
1917
|
-
status: response.status,
|
|
1918
|
-
statusText: response.statusText,
|
|
1919
|
-
headers: response.headers
|
|
1920
|
-
});
|
|
1921
|
-
}
|
|
1922
|
-
//#endregion
|
|
1923
|
-
//#region src/server/pipeline.ts
|
|
2244
|
+
// src/server/pipeline.ts
|
|
1924
2245
|
/**
|
|
1925
2246
|
* Create the request handler from a pipeline configuration.
|
|
1926
2247
|
*
|
|
@@ -2050,8 +2371,7 @@ function createPipeline(config) {
|
|
|
2050
2371
|
});
|
|
2051
2372
|
};
|
|
2052
2373
|
}
|
|
2053
|
-
|
|
2054
|
-
//#region src/server/early-hints.ts
|
|
2374
|
+
// src/server/early-hints.ts
|
|
2055
2375
|
/**
|
|
2056
2376
|
* 103 Early Hints utilities.
|
|
2057
2377
|
*
|
|
@@ -2134,8 +2454,7 @@ function collectEarlyHintHeaders(segments, manifest, options) {
|
|
|
2134
2454
|
}));
|
|
2135
2455
|
return result;
|
|
2136
2456
|
}
|
|
2137
|
-
|
|
2138
|
-
//#region src/server/early-hints-sender.ts
|
|
2457
|
+
// src/server/early-hints-sender.ts
|
|
2139
2458
|
/**
|
|
2140
2459
|
* Per-request 103 Early Hints sender — ALS bridge for platform adapters.
|
|
2141
2460
|
*
|
|
@@ -2182,8 +2501,7 @@ function sendEarlyHints103(links) {
|
|
|
2182
2501
|
swallow(err, "early hints 103 send failed");
|
|
2183
2502
|
}
|
|
2184
2503
|
}
|
|
2185
|
-
|
|
2186
|
-
//#region src/client/error-reconstituter.tsx
|
|
2504
|
+
// src/client/error-reconstituter.tsx
|
|
2187
2505
|
/**
|
|
2188
2506
|
* Reconstitutes a SerializableError into a real Error instance before
|
|
2189
2507
|
* passing to the user's error component.
|
|
@@ -2216,8 +2534,7 @@ function ErrorReconstituter({ error: serialized, digest, reset, component, statu
|
|
|
2216
2534
|
} : {}
|
|
2217
2535
|
});
|
|
2218
2536
|
}
|
|
2219
|
-
|
|
2220
|
-
//#region src/server/deny-boundary.ts
|
|
2537
|
+
// src/server/deny-boundary.ts
|
|
2221
2538
|
/**
|
|
2222
2539
|
* Deny boundary subsystem — the in-tree DenySignal flow.
|
|
2223
2540
|
*
|
|
@@ -2428,8 +2745,7 @@ function setFirstDeniedSegmentIndex(index) {
|
|
|
2428
2745
|
const store = requestContextAls.getStore();
|
|
2429
2746
|
if (store && store._firstDeniedSegmentIndex === void 0) store._firstDeniedSegmentIndex = index;
|
|
2430
2747
|
}
|
|
2431
|
-
|
|
2432
|
-
//#region src/server/access-gate.tsx
|
|
2748
|
+
// src/server/access-gate.tsx
|
|
2433
2749
|
/**
|
|
2434
2750
|
* Framework-injected access gate for segments.
|
|
2435
2751
|
*
|
|
@@ -2454,33 +2770,29 @@ function setFirstDeniedSegmentIndex(index) {
|
|
|
2454
2770
|
* in-tree — the client's cached layout chrome would wrap them incorrectly.
|
|
2455
2771
|
* Instead, the deny is recorded in ALS and rethrown so the response path
|
|
2456
2772
|
* can return rscErrorEnvelope for a client hard-navigate.
|
|
2773
|
+
*
|
|
2774
|
+
* For a segment outside the rendered tree (outsideTree=true), see
|
|
2775
|
+
* `DenySignal._leaveSpa`.
|
|
2457
2776
|
*/
|
|
2458
2777
|
function AccessGate(props) {
|
|
2459
|
-
const { accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children } = props;
|
|
2460
|
-
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);
|
|
2461
2780
|
}
|
|
2462
2781
|
/**
|
|
2463
2782
|
* Calls accessFn during render with OTEL instrumentation.
|
|
2464
2783
|
* Records the first denied segment index in ALS for post-render consumers.
|
|
2465
2784
|
*/
|
|
2466
|
-
async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children) {
|
|
2785
|
+
async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, outsideTree, children) {
|
|
2467
2786
|
try {
|
|
2468
|
-
await
|
|
2469
|
-
try {
|
|
2470
|
-
await accessFn();
|
|
2471
|
-
await setSpanAttribute("timber.result", "pass");
|
|
2472
|
-
} catch (error) {
|
|
2473
|
-
if (isDenySignal(error)) {
|
|
2474
|
-
await setSpanAttribute("timber.result", "deny");
|
|
2475
|
-
await setSpanAttribute("timber.deny_status", error.status);
|
|
2476
|
-
if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
|
|
2477
|
-
} else if (isRedirectSignal(error)) await setSpanAttribute("timber.result", "redirect");
|
|
2478
|
-
throw error;
|
|
2479
|
-
}
|
|
2480
|
-
});
|
|
2787
|
+
await runTracedAccess(accessFn, segmentName);
|
|
2481
2788
|
} catch (error) {
|
|
2482
2789
|
if (isDenySignal(error)) {
|
|
2483
2790
|
if (segmentIndex !== void 0) setFirstDeniedSegmentIndex(segmentIndex);
|
|
2791
|
+
if (outsideTree) {
|
|
2792
|
+
error._hardNavigate = true;
|
|
2793
|
+
error._leaveSpa = true;
|
|
2794
|
+
throw error;
|
|
2795
|
+
}
|
|
2484
2796
|
if (skippedSegment) {
|
|
2485
2797
|
error._hardNavigate = true;
|
|
2486
2798
|
throw error;
|
|
@@ -2531,8 +2843,7 @@ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
|
|
|
2531
2843
|
data
|
|
2532
2844
|
});
|
|
2533
2845
|
}
|
|
2534
|
-
|
|
2535
|
-
//#region src/server/status-code-resolver.ts
|
|
2846
|
+
// src/server/status-code-resolver.ts
|
|
2536
2847
|
/**
|
|
2537
2848
|
* Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
|
|
2538
2849
|
* status-file group on a single segment. Shared by all three fallback
|
|
@@ -2674,8 +2985,7 @@ function resolveSlotDenied(slotNode) {
|
|
|
2674
2985
|
};
|
|
2675
2986
|
return null;
|
|
2676
2987
|
}
|
|
2677
|
-
|
|
2678
|
-
//#region src/server/body-limits.ts
|
|
2988
|
+
// src/server/body-limits.ts
|
|
2679
2989
|
var KB = 1024;
|
|
2680
2990
|
var MB = 1024 * KB;
|
|
2681
2991
|
var GB = 1024 * MB;
|
|
@@ -2726,8 +3036,7 @@ function resolveLimit(kind, config) {
|
|
|
2726
3036
|
if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
|
|
2727
3037
|
return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
|
|
2728
3038
|
}
|
|
2729
|
-
|
|
2730
|
-
//#region src/server/metadata-social.ts
|
|
3039
|
+
// src/server/metadata-social.ts
|
|
2731
3040
|
/**
|
|
2732
3041
|
* Render Open Graph metadata into head element descriptors.
|
|
2733
3042
|
*
|
|
@@ -2928,8 +3237,7 @@ function renderTwitter(tw, elements) {
|
|
|
2928
3237
|
}
|
|
2929
3238
|
}
|
|
2930
3239
|
}
|
|
2931
|
-
|
|
2932
|
-
//#region src/server/metadata-platform.ts
|
|
3240
|
+
// src/server/metadata-platform.ts
|
|
2933
3241
|
/**
|
|
2934
3242
|
* Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
|
|
2935
3243
|
*/
|
|
@@ -3154,8 +3462,7 @@ function renderItunes(itunes, elements) {
|
|
|
3154
3462
|
}
|
|
3155
3463
|
});
|
|
3156
3464
|
}
|
|
3157
|
-
|
|
3158
|
-
//#region src/server/metadata-render.ts
|
|
3465
|
+
// src/server/metadata-render.ts
|
|
3159
3466
|
/**
|
|
3160
3467
|
* Convert resolved metadata into an array of head element descriptors.
|
|
3161
3468
|
*
|
|
@@ -3294,8 +3601,7 @@ function renderRobotsObject(robots) {
|
|
|
3294
3601
|
if (robots.follow === false) parts.push("nofollow");
|
|
3295
3602
|
return parts.join(", ");
|
|
3296
3603
|
}
|
|
3297
|
-
|
|
3298
|
-
//#region src/server/metadata.ts
|
|
3604
|
+
// src/server/metadata.ts
|
|
3299
3605
|
/**
|
|
3300
3606
|
* Resolve a title value with an optional template.
|
|
3301
3607
|
*
|
|
@@ -3425,123 +3731,7 @@ function resolveMetadataUrls(metadata) {
|
|
|
3425
3731
|
}
|
|
3426
3732
|
return result;
|
|
3427
3733
|
}
|
|
3428
|
-
|
|
3429
|
-
//#region src/server/route-handler.ts
|
|
3430
|
-
/** All recognized HTTP method export names. */
|
|
3431
|
-
var HTTP_METHODS = [
|
|
3432
|
-
"GET",
|
|
3433
|
-
"POST",
|
|
3434
|
-
"PUT",
|
|
3435
|
-
"PATCH",
|
|
3436
|
-
"DELETE",
|
|
3437
|
-
"HEAD",
|
|
3438
|
-
"OPTIONS"
|
|
3439
|
-
];
|
|
3440
|
-
/**
|
|
3441
|
-
* Resolve the full list of allowed methods for a route module.
|
|
3442
|
-
*
|
|
3443
|
-
* Includes:
|
|
3444
|
-
* - All explicitly exported methods
|
|
3445
|
-
* - HEAD (implicit when GET is exported)
|
|
3446
|
-
* - OPTIONS (always implicit)
|
|
3447
|
-
*/
|
|
3448
|
-
function resolveAllowedMethods(mod) {
|
|
3449
|
-
const methods = [];
|
|
3450
|
-
for (const method of HTTP_METHODS) {
|
|
3451
|
-
if (method === "HEAD" || method === "OPTIONS") continue;
|
|
3452
|
-
if (mod[method]) methods.push(method);
|
|
3453
|
-
}
|
|
3454
|
-
if (mod.GET && !mod.HEAD) methods.push("HEAD");
|
|
3455
|
-
else if (mod.HEAD) methods.push("HEAD");
|
|
3456
|
-
if (!mod.OPTIONS) methods.push("OPTIONS");
|
|
3457
|
-
else methods.push("OPTIONS");
|
|
3458
|
-
return methods;
|
|
3459
|
-
}
|
|
3460
|
-
/**
|
|
3461
|
-
* Handle an incoming request against a route.ts module.
|
|
3462
|
-
*
|
|
3463
|
-
* Dispatches to the named method handler, auto-generates 405/OPTIONS,
|
|
3464
|
-
* and merges response headers from ctx.headers.
|
|
3465
|
-
*/
|
|
3466
|
-
async function handleRouteRequest(mod, ctx) {
|
|
3467
|
-
const method = ctx.req.method.toUpperCase();
|
|
3468
|
-
const allowHeader = resolveAllowedMethods(mod).join(", ");
|
|
3469
|
-
if (method === "OPTIONS") {
|
|
3470
|
-
if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
|
|
3471
|
-
return mergeResponseHeaders(new Response(null, {
|
|
3472
|
-
status: 204,
|
|
3473
|
-
headers: { Allow: allowHeader }
|
|
3474
|
-
}), ctx.headers);
|
|
3475
|
-
}
|
|
3476
|
-
if (method === "HEAD") {
|
|
3477
|
-
if (mod.HEAD) return stripHeadBody(await runHandler(mod.HEAD, ctx), method);
|
|
3478
|
-
if (mod.GET) return stripHeadBody(await runHandler(mod.GET, ctx), method);
|
|
3479
|
-
}
|
|
3480
|
-
const handler = mod[method];
|
|
3481
|
-
if (!handler) return mergeResponseHeaders(new Response(null, {
|
|
3482
|
-
status: 405,
|
|
3483
|
-
headers: { Allow: allowHeader }
|
|
3484
|
-
}), ctx.headers);
|
|
3485
|
-
return runHandler(handler, ctx);
|
|
3486
|
-
}
|
|
3487
|
-
/**
|
|
3488
|
-
* Run a handler with cookie writes enabled and merge ctx.headers into its
|
|
3489
|
-
* response.
|
|
3490
|
-
*
|
|
3491
|
-
* Cookies (design/29-cookies.md §"Where Cookies Can Be Set"): the render
|
|
3492
|
-
* phase applied the jar to `ctx.headers` before the handler ran, so on the
|
|
3493
|
-
* way out only what the handler changed is synced onto that bag. It happens
|
|
3494
|
-
* whether the handler returns or throws, so a cookie set before `redirect()`
|
|
3495
|
-
* rides the redirect, and the pipeline's 500 for a throw carries the same
|
|
3496
|
-
* bag.
|
|
3497
|
-
*
|
|
3498
|
-
* Nothing is caught. A signal goes to the pipeline, whose deny fallback
|
|
3499
|
-
* answers a route.ts match in JSON and whose redirect outcome sends the 3xx
|
|
3500
|
-
* (TIM-1533). Any other error goes to the pipeline, which logs it,
|
|
3501
|
-
* reports it to `onRequestError` as phase `'route'`, and answers it in the
|
|
3502
|
-
* same format as every other route.ts error (TIM-1537).
|
|
3503
|
-
*/
|
|
3504
|
-
async function runHandler(handler, ctx) {
|
|
3505
|
-
const applied = getSetCookieHeaders();
|
|
3506
|
-
setMutableCookieContext(true);
|
|
3507
|
-
let res;
|
|
3508
|
-
try {
|
|
3509
|
-
res = await handler(ctx);
|
|
3510
|
-
} finally {
|
|
3511
|
-
setMutableCookieContext(false);
|
|
3512
|
-
syncCookieJar(ctx.headers, applied);
|
|
3513
|
-
}
|
|
3514
|
-
return mergeResponseHeaders(res, ctx.headers);
|
|
3515
|
-
}
|
|
3516
|
-
/**
|
|
3517
|
-
* Merge response headers from ctx.headers into the handler's response.
|
|
3518
|
-
* ctx.headers (set by middleware or the handler) are applied to the final response.
|
|
3519
|
-
* Handler-set headers take precedence over ctx.headers.
|
|
3520
|
-
*/
|
|
3521
|
-
function mergeResponseHeaders(res, ctxHeaders) {
|
|
3522
|
-
let hasCtxHeaders = false;
|
|
3523
|
-
ctxHeaders.forEach(() => {
|
|
3524
|
-
hasCtxHeaders = true;
|
|
3525
|
-
});
|
|
3526
|
-
if (!hasCtxHeaders) return res;
|
|
3527
|
-
const merged = new Headers();
|
|
3528
|
-
ctxHeaders.forEach((value, key) => {
|
|
3529
|
-
if (key.toLowerCase() === "set-cookie") merged.append(key, value);
|
|
3530
|
-
else merged.set(key, value);
|
|
3531
|
-
});
|
|
3532
|
-
const resCookies = res.headers.getSetCookie();
|
|
3533
|
-
for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
|
|
3534
|
-
res.headers.forEach((value, key) => {
|
|
3535
|
-
if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
|
|
3536
|
-
});
|
|
3537
|
-
return new Response(res.body, {
|
|
3538
|
-
status: res.status,
|
|
3539
|
-
statusText: res.statusText,
|
|
3540
|
-
headers: merged
|
|
3541
|
-
});
|
|
3542
|
-
}
|
|
3543
|
-
//#endregion
|
|
3544
|
-
//#region src/server/prebuilt/cache-key.ts
|
|
3734
|
+
// src/server/prebuilt/cache-key.ts
|
|
3545
3735
|
/**
|
|
3546
3736
|
* Component cache-key hashing for prebuilt (cache.component) entries.
|
|
3547
3737
|
*
|
|
@@ -3758,8 +3948,7 @@ function resolveKeyParams(store) {
|
|
|
3758
3948
|
}
|
|
3759
3949
|
return main;
|
|
3760
3950
|
}
|
|
3761
|
-
|
|
3762
|
-
//#region src/client/slot-context.ts
|
|
3951
|
+
// src/client/slot-context.ts
|
|
3763
3952
|
/**
|
|
3764
3953
|
* SlotContext — delivers live slot content to SlotOutlet holes inside
|
|
3765
3954
|
* cached component shells (TIM-1173).
|
|
@@ -3788,8 +3977,7 @@ function resolveKeyParams(store) {
|
|
|
3788
3977
|
* See design/45-cache-lifetimes.md §Slot Components.
|
|
3789
3978
|
*/
|
|
3790
3979
|
var SlotContext = createGlobalContext(Symbol.for("__timber_slot_ctx"), null);
|
|
3791
|
-
|
|
3792
|
-
//#region src/client/slot-outlet.tsx
|
|
3980
|
+
// src/client/slot-outlet.tsx
|
|
3793
3981
|
/**
|
|
3794
3982
|
* SlotOutlet — the hole in a cached component shell (TIM-1173).
|
|
3795
3983
|
*
|
|
@@ -3806,8 +3994,7 @@ function SlotOutlet({ slot }) {
|
|
|
3806
3994
|
const values = useContext(SlotContext);
|
|
3807
3995
|
return values ? values[slot] ?? null : null;
|
|
3808
3996
|
}
|
|
3809
|
-
|
|
3810
|
-
//#region src/client/slot-provider.tsx
|
|
3997
|
+
// src/client/slot-provider.tsx
|
|
3811
3998
|
/**
|
|
3812
3999
|
* SlotsProvider — wraps a revived cached shell to supply live slot content
|
|
3813
4000
|
* to the SlotOutlet holes inside it (TIM-1173).
|
|
@@ -3832,8 +4019,7 @@ function SlotsProvider({ values, children }) {
|
|
|
3832
4019
|
} : values;
|
|
3833
4020
|
return createElement(SlotContext.Provider, { value: merged }, children);
|
|
3834
4021
|
}
|
|
3835
|
-
|
|
3836
|
-
//#region src/server/prebuilt/lifetime.ts
|
|
4022
|
+
// src/server/prebuilt/lifetime.ts
|
|
3837
4023
|
/**
|
|
3838
4024
|
* Lifetime declarations of a `cache.component` — `prerender`, `ttl`,
|
|
3839
4025
|
* `tags` (design/45-cache-lifetimes.md) — and the nesting clamp between
|
|
@@ -3933,8 +4119,7 @@ function warnNestingClamps(outer, nested, warnedPairs, log) {
|
|
|
3933
4119
|
}
|
|
3934
4120
|
return count;
|
|
3935
4121
|
}
|
|
3936
|
-
|
|
3937
|
-
//#region src/server/prebuilt/slots.ts
|
|
4122
|
+
// src/server/prebuilt/slots.ts
|
|
3938
4123
|
/**
|
|
3939
4124
|
* Slot-component helpers for cache.component (TIM-1173).
|
|
3940
4125
|
*
|
|
@@ -4079,66 +4264,7 @@ function wrapInSlotsProvider(shell, slotValues) {
|
|
|
4079
4264
|
children: shell
|
|
4080
4265
|
});
|
|
4081
4266
|
}
|
|
4082
|
-
|
|
4083
|
-
//#region src/server/prebuilt/key-discipline.ts
|
|
4084
|
-
var REQUEST_CONTEXT_FIELDS = {
|
|
4085
|
-
headers: "headers()",
|
|
4086
|
-
parsedCookies: "cookies()",
|
|
4087
|
-
searchParams: "searchParams"
|
|
4088
|
-
};
|
|
4089
|
-
/** Rate-limit interval: one diagnostic per component per 60 seconds. */
|
|
4090
|
-
var RATE_LIMIT_MS = 6e4;
|
|
4091
|
-
/** Last emission timestamp per component ID. */
|
|
4092
|
-
var lastEmitted = /* @__PURE__ */ new Map();
|
|
4093
|
-
var strict = false;
|
|
4094
|
-
/**
|
|
4095
|
-
* Whether the proxy should be created for this component on this render.
|
|
4096
|
-
* Returns true when strict mode is on (always check) or enough time has
|
|
4097
|
-
* elapsed since the last diagnostic for this component.
|
|
4098
|
-
*/
|
|
4099
|
-
function shouldCheckKeyDiscipline(id) {
|
|
4100
|
-
if (strict) return true;
|
|
4101
|
-
const last = lastEmitted.get(id);
|
|
4102
|
-
if (last === void 0) return true;
|
|
4103
|
-
return Date.now() - last >= RATE_LIMIT_MS;
|
|
4104
|
-
}
|
|
4105
|
-
/**
|
|
4106
|
-
* Wrap a store with a proxy that records per-request field access.
|
|
4107
|
-
* The proxy forwards all reads/writes transparently — it only observes.
|
|
4108
|
-
*/
|
|
4109
|
-
function createKeyDisciplineProxy(store) {
|
|
4110
|
-
const accessedApis = /* @__PURE__ */ new Set();
|
|
4111
|
-
return {
|
|
4112
|
-
proxy: new Proxy(store, { get(target, prop, receiver) {
|
|
4113
|
-
const api = REQUEST_CONTEXT_FIELDS[prop];
|
|
4114
|
-
if (api) accessedApis.add(api);
|
|
4115
|
-
return Reflect.get(target, prop, receiver);
|
|
4116
|
-
} }),
|
|
4117
|
-
accessedApis
|
|
4118
|
-
};
|
|
4119
|
-
}
|
|
4120
|
-
/**
|
|
4121
|
-
* Emit the key-discipline diagnostic or throw in strict mode.
|
|
4122
|
-
*
|
|
4123
|
-
* In strict mode: throws an error so the tainted payload is never cached.
|
|
4124
|
-
* In default mode: emits a structured error-level diagnostic through the
|
|
4125
|
-
* logger (same path as render errors), rate-limited per component.
|
|
4126
|
-
*/
|
|
4127
|
-
function emitKeyDisciplineWarning(id, apis) {
|
|
4128
|
-
const apiList = Array.from(apis).join(", ");
|
|
4129
|
-
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.`);
|
|
4130
|
-
const now = Date.now();
|
|
4131
|
-
const last = lastEmitted.get(id);
|
|
4132
|
-
if (last !== void 0 && now - last < RATE_LIMIT_MS) return;
|
|
4133
|
-
lastEmitted.set(id, now);
|
|
4134
|
-
getLogger().error("cache.component cross-user data leak risk", {
|
|
4135
|
-
component: id,
|
|
4136
|
-
accessedApis: Array.from(apis),
|
|
4137
|
-
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.`
|
|
4138
|
-
});
|
|
4139
|
-
}
|
|
4140
|
-
//#endregion
|
|
4141
|
-
//#region src/server/prebuilt/capture-state.ts
|
|
4267
|
+
// src/server/prebuilt/capture-state.ts
|
|
4142
4268
|
/**
|
|
4143
4269
|
* Capture state — the channel between a payload capture and the
|
|
4144
4270
|
* `__prebuilt` wrappers that render inside it (server/prebuilt-runtime.ts).
|
|
@@ -4267,9 +4393,8 @@ function noteWrapperRender(innerId, options, props) {
|
|
|
4267
4393
|
}
|
|
4268
4394
|
}
|
|
4269
4395
|
}
|
|
4270
|
-
|
|
4271
|
-
|
|
4272
|
-
var nodeFlight = typeof process !== "undefined" && process.release?.name === "node" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") ? await import("../_chunks/flight-source-node-BdHUOUqg.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;
|
|
4273
4398
|
/** The Node helpers, which a `kind: 'node'` source can only exist alongside. */
|
|
4274
4399
|
function requireNodeFlight() {
|
|
4275
4400
|
if (!nodeFlight) throw new Error("[timber] a Node Flight source reached a runtime without node:stream");
|
|
@@ -4286,7 +4411,7 @@ function openFlightReader(source) {
|
|
|
4286
4411
|
return {
|
|
4287
4412
|
read: () => reader.read(),
|
|
4288
4413
|
takeBuffered: () => [],
|
|
4289
|
-
cancel: (reason) => void reader.cancel(reason).catch(() => {})
|
|
4414
|
+
cancel: (reason) => void reader.cancel(releaseReason(reason)).catch(() => {})
|
|
4290
4415
|
};
|
|
4291
4416
|
}
|
|
4292
4417
|
const { destroyNodeFlight } = requireNodeFlight();
|
|
@@ -4329,8 +4454,7 @@ async function collectFlightBytes(source, timeoutMs, label) {
|
|
|
4329
4454
|
const chunks = await drainWithDeadline(openFlightReader(source), timeoutMs, label);
|
|
4330
4455
|
return concatBytes(chunks.map(flightChunkBytes));
|
|
4331
4456
|
}
|
|
4332
|
-
|
|
4333
|
-
//#region src/server/prebuilt/synthetic-store.ts
|
|
4457
|
+
// src/server/prebuilt/synthetic-store.ts
|
|
4334
4458
|
/**
|
|
4335
4459
|
* Thrown when a prerendered component touches per-request context at
|
|
4336
4460
|
* build time. The capture pass treats this as a HARD build error —
|
|
@@ -4391,8 +4515,7 @@ function createBuildTimeStore(componentId, segmentParams) {
|
|
|
4391
4515
|
handle.store = store;
|
|
4392
4516
|
return handle;
|
|
4393
4517
|
}
|
|
4394
|
-
|
|
4395
|
-
//#region src/server/prebuilt/capture-render.ts
|
|
4518
|
+
// src/server/prebuilt/capture-render.ts
|
|
4396
4519
|
/**
|
|
4397
4520
|
* One build-time capture entry: render a registered component in isolation
|
|
4398
4521
|
* under the synthetic build store and drain its flight payload under a
|
|
@@ -4456,8 +4579,7 @@ async function renderEntry(registration, props, coercedParams, timeoutMs, isLayo
|
|
|
4456
4579
|
segmentParamsRead
|
|
4457
4580
|
};
|
|
4458
4581
|
}
|
|
4459
|
-
|
|
4460
|
-
//#region src/server/prebuilt-runtime.ts
|
|
4582
|
+
// src/server/prebuilt-runtime.ts
|
|
4461
4583
|
/**
|
|
4462
4584
|
* Prebuilt component runtime — registration target for the timber-prebuilt
|
|
4463
4585
|
* transform (plugins/prebuilt.ts) and the request-time half of
|
|
@@ -4573,8 +4695,6 @@ async function captureComponentPayload(id, component, props, options) {
|
|
|
4573
4695
|
const element = createElement(component, props);
|
|
4574
4696
|
const capture = createCaptureScope(id, options, props);
|
|
4575
4697
|
let renderError;
|
|
4576
|
-
const store = requestContextAls.getStore();
|
|
4577
|
-
const discipline = store && shouldCheckKeyDiscipline(id) ? createKeyDisciplineProxy(store) : null;
|
|
4578
4698
|
const doCapture = () => capture.run(async () => {
|
|
4579
4699
|
const bytes = await collectFlightBytes(runOutsideReactCacheScope(() => renderFlight(element, { onError(error) {
|
|
4580
4700
|
renderError ??= { error };
|
|
@@ -4583,10 +4703,11 @@ async function captureComponentPayload(id, component, props, options) {
|
|
|
4583
4703
|
if (renderError) throw renderError.error;
|
|
4584
4704
|
return bytes;
|
|
4585
4705
|
});
|
|
4586
|
-
const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
|
|
4587
|
-
if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
|
|
4588
4706
|
return {
|
|
4589
|
-
bytes
|
|
4707
|
+
bytes: await observeKeyDiscipline({
|
|
4708
|
+
tier: "cache.component",
|
|
4709
|
+
id
|
|
4710
|
+
}, doCapture),
|
|
4590
4711
|
nested: capture.nestedRenders()
|
|
4591
4712
|
};
|
|
4592
4713
|
}
|
|
@@ -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,
|
|
@@ -4819,7 +4938,7 @@ function __prebuilt(id, component, options = {}) {
|
|
|
4819
4938
|
options
|
|
4820
4939
|
};
|
|
4821
4940
|
if (isDevPrebuiltStoreActive()) {
|
|
4822
|
-
if (devRegisteredIds.has(id)) clearDevPrebuiltStore();
|
|
4941
|
+
if (devRegisteredIds.has(id)) clearDevPrebuiltStore([id]);
|
|
4823
4942
|
devRegisteredIds.add(id);
|
|
4824
4943
|
} else registry.set(id, registration);
|
|
4825
4944
|
const wrapper = async (props) => {
|
|
@@ -4842,7 +4961,6 @@ function getPrebuiltRegistration(id) {
|
|
|
4842
4961
|
function getPrebuiltRegistry() {
|
|
4843
4962
|
return registry;
|
|
4844
4963
|
}
|
|
4845
|
-
//#endregion
|
|
4846
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 };
|
|
4847
4965
|
|
|
4848
4966
|
//# sourceMappingURL=internal.js.map
|