@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.js","names":["compressSource","canonicalizeSource"],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/canonicalize-module.ts","../../src/adapters/nitro-immutable-assets.ts","../../src/adapters/nitro-presets.ts","../../src/adapters/nitro-preview.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n//\n// The transform strips types; it does NOT bundle. The emitted file sits\n// alone in the build output, so any import specifier that survives into it\n// is a module resolution failure at runtime on the deployed server. Shared\n// constants are therefore interpolated here — the same treatment the\n// Cloudflare worker template gives `RSC_KEY_HEADERS` — and anything else\n// that reaches the output as an import is rejected with a build error\n// rather than shipped.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.ts';\n\n/**\n * The one import `server/compress.ts` is allowed to carry, and its inlined\n * form.\n *\n * The binding list is matched exactly rather than as `{…}`. A second binding\n * added to that import would otherwise be erased along with the statement and\n * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this\n * whole module exists to make impossible. Matching exactly means such an\n * import falls through to the rejection below instead.\n */\nconst INLINED_IMPORTS: ReadonlyArray<{ pattern: RegExp; replacement: string }> = [\n {\n pattern:\n /^import\\s*\\{\\s*RSC_CONTENT_TYPE\\s*,?\\s*\\}\\s*from\\s*[\"'][^\"']*shared\\/rsc-media-type\\.(?:js|ts)[\"'];?[ \\t]*$/m,\n replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`,\n },\n];\n\n/**\n * Every way a module specifier can reach the emitted file, minus Node\n * builtins.\n *\n * `node:*` is exempt because it resolves on the deployed server exactly as it\n * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,\n * and self-hosted (Node/Bun) is the only place this file runs. Everything\n * else — relative paths, bare packages — has no resolution target next to a\n * lone `.mjs` in the build output.\n *\n * All three forms are listed rather than the one `server/compress.ts` happens\n * to use, because a re-export or a lazy `await import()` fails in exactly the\n * same place and is exactly as invisible until deploy.\n */\nconst MODULE_SPECIFIERS: readonly RegExp[] = [\n // import … from '…' / export … from '…'\n /^[ \\t]*(?:import|export)\\b[^\\n]*\\bfrom\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import '…' (side effect only)\n /^[ \\t]*import\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import('…') (dynamic, literal specifier)\n /\\bimport\\s*\\(\\s*[\"'](?!node:)[^\"']+[\"']/,\n];\n\n/**\n * Replace the shared-module imports with their values and reject anything\n * else that would leave a dangling specifier in `_compress.mjs`.\n *\n * Exported separately from `generateCompressModule` so both branches can be\n * driven with fixtures: the source it normally compiles is fixed, so a test\n * of the generator alone can only ever exercise whichever branch that source\n * happens to take today.\n *\n * @internal Exported for testing.\n */\nexport function inlineCompressImports(code: string): string {\n let out = code;\n for (const { pattern, replacement } of INLINED_IMPORTS) {\n out = out.replace(pattern, replacement);\n }\n assertStandalone(out, 'server/compress.ts', '_compress.mjs');\n return out;\n}\n\n/**\n * Throw if type-stripped server source still imports anything but a Node\n * builtin. Such a module is emitted alone into the build output, where no\n * specifier has anything to resolve to.\n *\n * @internal Shared by the standalone-module generators.\n */\nexport function assertStandalone(code: string, source: string, emitted: string): void {\n const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(code)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] ${source} is emitted as a standalone ${emitted} (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in the generator in adapters/ or ` +\n `keep the dependency out of ${source}.`\n );\n }\n}\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n inlineCompressImports(result.code)\n );\n}\n","// Compiles server/canonicalize.ts into a standalone ESM module\n// (_canonicalize.mjs) for the Nitro preview server, so preview answers a\n// request path exactly as the runtime's request boundary does — the same\n// rejections (encoded separators, null bytes, malformed encoding, escaping\n// the root) and the same single decode — instead of a hand-kept copy of\n// those rules drifting from them. Same mechanism as compress-module.ts:\n// type-stripped, not bundled, so the source must stay import-free.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time (see\n// compress-module.ts).\nimport canonicalizeSource from '../server/canonicalize.ts?raw';\nimport { assertStandalone } from './compress-module.ts';\n\n/**\n * Compile server/canonicalize.ts into a standalone ESM module exporting\n * `canonicalize`.\n *\n * @internal Exported for testing.\n */\nexport async function generateCanonicalizeModule(): Promise<string> {\n const result = await transformWithOxc(canonicalizeSource, 'canonicalize.ts', { lang: 'ts' });\n assertStandalone(result.code, 'server/canonicalize.ts', '_canonicalize.mjs');\n return (\n '// Generated by @timber-js/app — compiled from server/canonicalize.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Immutable caching for the build's content-hashed directories on Nitro.\n//\n// A one-year `immutable` Cache-Control is correct only on a response that\n// served a file. Nitro route rules cannot tell a hit from a miss — their\n// headers land on every response under the path, the 404 for a file that is\n// not there included — so a CDN in front of a pod that lacked the file mid\n// rollout cached that 404 for a year (TIM-1578). Nitro's public-asset `maxAge`\n// option is a route rule underneath, with the same reach.\n//\n// Instead, three pieces, all keyed by one generated path matcher:\n//\n// - Each directory is its own non-fallthrough public-asset directory. Where\n// Nitro serves files itself, a GET or HEAD miss there is a 404 from its\n// static handler; Vercel and Netlify route such misses to a platform 404\n// instead of the function.\n// - timber's Nitro entry answers any request under those directories that\n// still reaches it with a plain `no-store` 404, before the app runs. Nothing\n// else answers there: a preset without Nitro's static handler (aws-lambda),\n// a method the static handler ignores, or a path it does not claim\n// (`/assets/`) gets the 404 rather than a page.\n// - A Nitro runtime plugin sets Cache-Control from the outcome. Since only a\n// served file can succeed under those directories, a successful GET or HEAD\n// is a hit.\n//\n// See design/25-production-deployments.md §\"Hashed assets\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { IMMUTABLE_CACHE } from './shared.ts';\n\n/** The generated module, written beside the Nitro entry that imports it. */\nconst IMMUTABLE_ASSETS_MODULE = '_immutable-assets.mjs';\n\n/** One Nitro `publicAssets` entry. */\ninterface NitroPublicAssetDir {\n dir: string;\n baseURL: string;\n fallthrough: false;\n}\n\n/** The Nitro config that serves `immutableDirs` from `<nitroDir>/public`. */\nexport interface ImmutableAssetsNitroConfig {\n publicAssets: NitroPublicAssetDir[];\n plugins: string[];\n}\n\n/**\n * Write the generated module into `nitroDir` and return the Nitro config that\n * serves the build's content-hashed directories from `<nitroDir>/public`.\n *\n * No `maxAge`: Nitro would turn it into a route rule (see the module header),\n * and Vercel already gives a non-fallthrough directory a one-year immutable\n * header on hits and `no-store` on misses by default.\n */\nexport async function prepareImmutableAssets(\n nitroDir: string,\n immutableDirs: readonly string[]\n): Promise<ImmutableAssetsNitroConfig> {\n if (immutableDirs.length === 0) return { publicAssets: [], plugins: [] };\n const plugin = join(nitroDir, IMMUTABLE_ASSETS_MODULE);\n await writeFile(plugin, generateImmutableAssetsModule(immutableDirs));\n return {\n publicAssets: immutableDirs.map((dir) => ({\n dir: join(nitroDir, 'public', dir),\n baseURL: `/${dir}`,\n fallthrough: false,\n })),\n plugins: [plugin],\n };\n}\n\n/**\n * The lines timber's Nitro entry needs to answer a request under the\n * content-hashed directories itself: an import, and a guard to run before\n * the handler, with the h3 event in scope as `event`. Empty when the build\n * has no such directories, which also means `prepareImmutableAssets()`\n * writes no module to import.\n */\nexport function immutableAssetsEntryGuard(immutableDirs: readonly string[]): {\n imports: string;\n guard: string;\n} {\n if (immutableDirs.length === 0) return { imports: '', guard: '' };\n return {\n imports: `import { isImmutableAssetPath } from './${IMMUTABLE_ASSETS_MODULE}'\\n`,\n guard: ` // Under a content-hashed directory only a served file may answer; the\n // static handler already sent any file there is. A no-store 404, never a\n // page — see _immutable-assets.mjs.\n if (isImmutableAssetPath(event.url.pathname)) {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n })\n }\n`,\n };\n}\n\n/**\n * Generate the module shared by the Nitro entry and runtime: the path matcher\n * for the content-hashed directories, and the runtime plugin that owns\n * Cache-Control under them — `IMMUTABLE_CACHE` on a GET or HEAD that served\n * the file (200, or 304 revalidating it), `no-store` on everything else.\n *\n * Status is a sound signal only because the entry answers everything else\n * under these directories with a 404 (see `immutableAssetsEntryGuard`). The\n * prefixes are matched against the decoded path, the one Nitro's static\n * handler looks the file up by.\n *\n * @internal Exported for testing.\n */\nexport function generateImmutableAssetsModule(immutableDirs: readonly string[]): string {\n const prefixes = immutableDirs.map((dir) => `/${dir}/`);\n return `// Generated by @timber-js/app — Cache-Control for content-hashed directories.\n// Do not edit — this file is regenerated on each build.\n\nconst PREFIXES = ${JSON.stringify(prefixes)};\nconst IMMUTABLE_CACHE = ${JSON.stringify(IMMUTABLE_CACHE)};\n\nexport function isImmutableAssetPath(pathname) {\n let path = pathname;\n try {\n path = decodeURI(pathname);\n } catch {\n // Malformed escapes: match the path as received.\n }\n return PREFIXES.some((prefix) => path.startsWith(prefix));\n}\n\nexport default function immutableAssets(nitroApp) {\n // Hooks are off only if a user's nitroConfig disables them; files then go\n // without the long-lived header rather than failing every request.\n nitroApp.hooks?.hook('response', (res, event) => {\n if (!isImmutableAssetPath(event.url.pathname)) return;\n const method = event.req.method;\n const served =\n (method === 'GET' || method === 'HEAD') && (res.status === 200 || res.status === 304);\n res.headers.set('Cache-Control', served ? IMMUTABLE_CACHE : 'no-store');\n });\n}\n`;\n}\n","// Nitro preset catalog — per-platform build configuration.\n//\n// Shared by the nitro adapter (build + entry generation) and the preview\n// module. See design/25-production-deployments.md for the preset matrix.\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\nexport interface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nexport const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n/** Presets that produce a locally-runnable server entry. */\nexport const LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n","// Nitro local preview — standalone server codegen and process spawning.\n//\n// `buildOutput` writes `_preview-server.mjs` into the Nitro output directory,\n// generated from the build's own artifacts; `timber preview` runs the\n// adapter's preview(), which spawns it. See design/25-production-deployments.md\n// §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { IMMUTABLE_CACHE, STATIC_CACHE } from './shared.ts';\n\n/**\n * Content-Type by file extension for the preview server. Static hosts decide\n * this themselves; the table covers the file types a web build ships so the\n * preview does not turn ordinary files into downloads. An extension missing\n * here is served as `application/octet-stream`.\n */\nconst PREVIEW_MIME_TYPES: Readonly<Record<string, string>> = {\n // Documents and code\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.cjs': 'text/javascript; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.jsonld': 'application/ld+json',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.rss': 'application/rss+xml',\n '.atom': 'application/atom+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n '.csv': 'text/csv; charset=utf-8',\n '.ics': 'text/calendar; charset=utf-8',\n '.vtt': 'text/vtt; charset=utf-8',\n '.pdf': 'application/pdf',\n '.wasm': 'application/wasm',\n '.zip': 'application/zip',\n '.gz': 'application/gzip',\n // Images\n '.png': 'image/png',\n '.apng': 'image/apng',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n // Fonts\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n // Audio and video\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.m4a': 'audio/mp4',\n '.flac': 'audio/flac',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.ogv': 'video/ogg',\n '.mov': 'video/quicktime',\n};\n\n/** What the generated preview server serves, as `buildOutput` knows it. */\nexport type PreviewScriptOptions = StaticPreviewScriptOptions | ServerPreviewScriptOptions;\n\ninterface PreviewScriptOptionsBase {\n /**\n * `BuildArtifacts.immutableDirs` — files there are served with a one-year\n * immutable `Cache-Control`, every other file with a revalidating one. In\n * a server build, a miss there is a plain `no-store` 404.\n */\n immutableDirs: readonly string[];\n /**\n * The deployment base, normalized (`/` or `/repo/`). Requests arrive in\n * deployed-URL space; files are laid out in route space, so the script\n * strips it before looking anything up.\n */\n base: string;\n}\n\n/** A static build: serve the pre-rendered site and nothing else. */\nexport interface StaticPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'static';\n /** `StaticBuildArtifacts.contentTypes` — extensionless API route outputs. */\n contentTypes: Readonly<Record<string, string>>;\n}\n\n/** A server build: serve `public/`, route everything else to the RSC handler. */\nexport interface ServerPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'server';\n /** Value for `TIMBER_RUNTIME`, set before the handler evaluates. */\n runtimeName: string;\n /** Import specifier of the RSC handler, relative to the script. */\n rscEntry: string;\n /**\n * Whether this build wrote `_timber-manifest-init.js` beside the script.\n * Recorded from the build, never probed: the Nitro output directory is not\n * cleaned between server builds, so a file on disk can be a stale one.\n */\n hasManifestInit: boolean;\n}\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and, in a server build, route requests\n * to the RSC handler.\n *\n * Generated at build time rather than at preview time, so everything it\n * serves comes from the build's artifacts instead of guesses about the\n * directory it runs in.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(options: PreviewScriptOptions): string {\n const immutablePrefixes = options.immutableDirs.map((dir) => `/${dir}/`);\n const contentTypes = options.output === 'static' ? options.contentTypes : {};\n\n // A server build loads its handler (after the runtime and manifest are in\n // place); a static build has no handler to load.\n const handlerSetup =\n options.output === 'server'\n ? `// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = ${JSON.stringify(options.runtimeName)};\n${\n options.hasManifestInit\n ? `\n// Load the build manifest before the handler reads it.\nawait import('./_timber-manifest-init.js');\n`\n : ''\n}\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import(${JSON.stringify(options.rscEntry)});\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n`\n : '';\n\n // What happens when no file matches: a static build answers with its own\n // 404 page, a server build hands the request to the RSC handler.\n const fallback =\n options.output === 'static'\n ? ` if (badPath) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\n const notFound = await findFile('/404.html');\n if (notFound) {\n await sendFile(req, res, notFound, 404, 'text/html', 'public, max-age=0, must-revalidate');\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n`\n : ` // A request under a content-hashed directory that names no file is a\n // plain no-store 404, never a render of the app — as timber's Nitro entry\n // answers it in production (TIM-1578).\n if (pathname !== null && IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });\n res.end('Not Found');\n return;\n }\n await handleDynamic(req, res, url);\n`;\n\n const dynamicHandler =\n options.output === 'server'\n ? `\nasync function handleDynamic(req, res, url) {\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n}\n`\n : '';\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Do not edit — this file is regenerated on each build.\n// Uses Node's built-in HTTP server to serve the build's files${\n options.output === 'server' ? ' and route\\n// dynamic requests through the RSC handler' : ''\n }. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { canonicalize } from './_canonicalize.mjs';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\n${handlerSetup}\nconst MIME_TYPES = ${JSON.stringify(PREVIEW_MIME_TYPES, null, 2)};\n\n// Recorded by the build: content-hashed directories, and the Content-Type of\n// each extensionless API route output (a file name cannot say it). Both are\n// decoded route-space paths, matched against the decoded request path.\nconst IMMUTABLE_PREFIXES = ${JSON.stringify(immutablePrefixes)};\nconst BASE = ${JSON.stringify(options.base)};\nconst CONTENT_TYPES = ${JSON.stringify(contentTypes)};\nconst SERVE_DIRECTORY_INDEX = ${options.output === 'static'};\n\nconst publicDir = join(__dirname, 'public');\n\n/**\n * The file under publicDir that a decoded URL path names, or null. A static\n * build lays its pages out as <path>/index.html, so a directory serves its\n * index there.\n */\nasync function findFile(pathname) {\n const filePath = join(publicDir, pathname);\n // Prevent path traversal (and a sibling like public-other/ passing a bare\n // prefix check).\n if (!filePath.startsWith(publicDir + sep)) return null;\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) return filePath;\n if (SERVE_DIRECTORY_INDEX && fileStat.isDirectory()) {\n const index = join(filePath, 'index.html');\n if ((await stat(index)).isFile()) return index;\n }\n } catch {\n // Not found.\n }\n return null;\n}\n\n/**\n * The route-space path for a request path, or null when the request is\n * outside the deployment base (it names no file of this build).\n */\nfunction stripBase(pathname) {\n if (BASE === '/') return pathname;\n if (pathname === BASE.slice(0, -1)) return '/';\n if (!pathname.startsWith(BASE)) return null;\n return pathname.slice(BASE.length - 1);\n}\n\nasync function sendFile(req, res, filePath, status, contentType, cacheControl) {\n const body = await readFile(filePath);\n res.writeHead(status, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(req.method === 'HEAD' ? undefined : body);\n}\n${dynamicHandler}\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n // An origin-form target ('/path') is concatenated, not resolved against\n // the base: resolved as a relative reference, '//evil.com/' names another\n // host, and the pipeline would see '/' instead of the path it must\n // redirect to '/evil.com' (TIM-1571). Any other form — 'OPTIONS *', an\n // absolute-form target — is resolved as before: concatenating '*' makes\n // an invalid URL, and this callback has no catch around it, so the\n // rejection would take the preview process down.\n const origin = \\`\\${scheme}://\\${host}:\\${boundPort}\\`;\n const target = req.url || '/';\n const url = target.startsWith('/') ? new URL(origin + target) : new URL(target, origin);\n\n // The runtime's own request-boundary canonicalizer (_canonicalize.mjs,\n // compiled from server/canonicalize.ts): one decode, and the same 400s for\n // encoded separators, null bytes, malformed encoding, and escaping the root\n // (design/13-security.md). The base is stripped from its canonical result,\n // so an encoded spelling of the base is the same path. What remains, in\n // route space, is looked up in public/; null names no file.\n const canonical = canonicalize(url.pathname, false);\n const badPath = !canonical.ok;\n const pathname = canonical.ok ? stripBase(canonical.pathname) : null;\n const filePath = pathname === null ? null : await findFile(pathname);\n if (filePath) {\n const contentType =\n CONTENT_TYPES[pathname] || MIME_TYPES[extname(filePath).toLowerCase()] || 'application/octet-stream';\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable = IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix));\n const cacheControl = isImmutable ? ${JSON.stringify(IMMUTABLE_CACHE)} : ${JSON.stringify(STATIC_CACHE)};\n await sendFile(req, res, filePath, 200, contentType, cacheControl);\n return;\n }\n\n${fallback}});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nexport function spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // A response with a Node body (timber's NodeBodyResponse, srvx's protocol):\n // pipe it straight to the socket, no Web Streams round trip. pipe() rather\n // than pipeline(), which allocates an AbortController and an error on every\n // finish; a client that disconnects early destroys the body (aborting the\n // render), and a body that errors destroys the socket.\n if (typeof webRes._toNodeResponse === 'function') {\n const res = webRes._toNodeResponse();\n if (res.body && typeof res.body.pipe === 'function') {\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(res.status, res.headers);\n } else {\n nodeRes.writeHead(res.status, res.statusText, res.headers);\n }\n }\n const body = res.body;\n // The client already left: 'close' has fired and will not again.\n if (nodeRes.destroyed) {\n body.destroy();\n return;\n }\n return new Promise((resolve) => {\n nodeRes.once('close', () => {\n if (!body.readableEnded) body.destroy();\n resolve();\n });\n nodeRes.on('error', () => body.destroy());\n body.once('error', (error) => nodeRes.destroy(error));\n body.pipe(nodeRes);\n });\n }\n webRes = new Response(res.body, { status: res.status, statusText: res.statusText, headers: pairs(res.headers) });\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n\nfunction pairs(flat) {\n const out = [];\n for (let i = 0; i < flat.length; i += 2) out.push([flat[i], flat[i + 1]]);\n return out;\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { existsSync } from 'node:fs';\nimport { cp, glob, readFile, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport type { NitroConfig } from 'nitro/types';\nimport {\n buildStaticDirectoryOutput,\n runSharedBuildSteps,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { generateCompressModule } from './compress-module.ts';\nimport { generateCanonicalizeModule } from './canonicalize-module.ts';\nimport { immutableAssetsEntryGuard, prepareImmutableAssets } from './nitro-immutable-assets.ts';\nimport { LOCALLY_PREVIEWABLE, PRESET_CONFIGS, type NitroPreset } from './nitro-presets.ts';\nimport {\n generatePreviewScript,\n generateSendResponseModule,\n spawnNitroPreview,\n} from './nitro-preview.ts';\nimport { adapterBase } from './shared.ts';\nimport type {\n BuildArtifacts,\n PreviewTarget,\n TimberConfig,\n TimberPlatformAdapter,\n} from './types.ts';\n\n// NitroPreset is part of the public adapter API (NitroAdapterOptions.preset),\n// so it stays importable from this module.\nexport type { NitroPreset } from './nitro-presets.ts';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: NitroConfig;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, artifacts: BuildArtifacts) {\n const outDir = join(artifacts.outputDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (artifacts.output === 'static') {\n await buildStaticDirectoryOutput(config, artifacts, outDir, 'public');\n const publicDir = join(outDir, 'public');\n\n // Write _headers for cache control + extensionless Content-Type.\n // Netlify supports the _headers convention just like Cloudflare.\n await writeHeadersFile(publicDir, config, artifacts);\n\n // Local preview serves the site as the build recorded it.\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'static',\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n contentTypes: artifacts.contentTypes,\n })\n );\n\n // Platform-specific files for static deploy targets.\n const target = options.staticTarget ?? 'generic';\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Standalone preview server for presets with a local runtime. It loads\n // the build's own RSC bundle — not the copy under nitro/rsc/ — because\n // the handler reads prebuilt payloads from ../prebuilt beside its\n // bundle, and the build's prebuilt/ is cleaned every build while\n // nitro/prebuilt/ is not: a build that captured nothing would otherwise\n // preview an earlier build's payloads.\n if (LOCALLY_PREVIEWABLE.has(preset)) {\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'server',\n runtimeName: PRESET_CONFIGS[preset].runtimeName,\n rscEntry: importSpecifier(outDir, join(artifacts.rsc.path, 'index.js')),\n hasManifestInit: !!artifacts.manifestInit,\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n })\n );\n }\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (artifacts.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${artifacts.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(\n outDir,\n preset,\n artifacts.immutableDirs,\n options.nitroConfig\n );\n\n // Copy prebuilt flight payloads into the Nitro output. The RSC entry\n // resolves `../prebuilt/` relative to its bundled chunk\n // (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n if (artifacts.prebuilt) {\n const prebuiltSrc = artifacts.prebuilt.path;\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), { recursive: true });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n }\n },\n\n // buildOutput wrote the preview server for this build: a static file\n // server for a static build, and for a server build on a preset with a\n // local runtime (node-server, bun), one that routes to the RSC handler.\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no local\n // runtime, so a server build on one has nothing to preview.\n async preview(_config: TimberConfig, { output, outputDir }: PreviewTarget) {\n if (output === 'server' && !LOCALLY_PREVIEWABLE.has(preset)) {\n throw new Error(\n `[timber] The nitro '${preset}' preset has no local runtime, so \\`timber preview\\` ` +\n `cannot run its server build. Preview with a node-server build, or with the ` +\n `platform's own tooling.`\n );\n }\n const nitroDir = join(outputDir, 'nitro');\n const script = join(nitroDir, PREVIEW_SCRIPT);\n if (!existsSync(script)) {\n throw new Error(\n `[timber] No preview server at ${script}. Run \\`timber build\\` before \\`timber preview\\`.`\n );\n }\n // Only a bun server build needs Bun. The static file server uses Node\n // built-ins, so it runs on the Node already running timber, as does a\n // node-server build — no PATH lookup for either.\n const command = output === 'server' && preset === 'bun' ? 'bun' : process.execPath;\n await spawnNitroPreview(command, [script], nitroDir);\n },\n };\n}\n\n/** The preview server buildOutput writes into the Nitro output directory. */\nconst PREVIEW_SCRIPT = '_preview-server.mjs';\n\n/** The request-path canonicalizer the preview server imports beside it. */\nconst CANONICALIZE_MODULE = '_canonicalize.mjs';\n\n/** A relative ESM import specifier for `file`, as imported from a module in `fromDir`. */\nfunction importSpecifier(fromDir: string, file: string): string {\n const path = relative(fromDir, file).split(sep).join('/');\n return path.startsWith('../') ? path : './' + path;\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n preset: NitroPreset,\n compress = true,\n immutableDirs: readonly string[] = []\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n const immutableAssets = immutableAssetsEntryGuard(immutableDirs);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n${immutableAssets.guard} // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Build Hint Filtering ────────────────────────────────────────────────────\n\n/**\n * Prefixes of nitro build-output lines that give wrong advice for timber\n * builds. Every nitro bundler path emits these hints via `logger.success` —\n * the rollup path hardcodes `npx nitro preview`; rolldown and vite default\n * to it. That command resolves `.output/nitro.json` relative to cwd, but\n * timber's nitro build lives at `.timber/dist/nitro/.output`, so the\n * suggested command can never work from the project root.\n * Prefix matching degrades gracefully: if upstream rewords the line\n * entirely, it passes through rather than being silently eaten.\n */\nconst NITRO_PREVIEW_HINT_PREFIX = 'You can preview this build using';\nconst NITRO_DEPLOY_HINT_PREFIX = 'You can deploy this build using';\nconst SUPPRESSED_NITRO_HINT_PREFIXES = [NITRO_PREVIEW_HINT_PREFIX, NITRO_DEPLOY_HINT_PREFIX];\n\n/** @internal Exported for testing. */\nexport function isSuppressedNitroHint(\n message: unknown,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): boolean {\n return typeof message === 'string' && prefixes.some((prefix) => message.startsWith(prefix));\n}\n\n/**\n * Nitro's rolldown and vite builders render `framework.previewCommand` /\n * `framework.deployCommand` into these hints. A user who explicitly set one\n * via `nitroConfig` has provided valid guidance — only suppress the hints\n * whose command is still nitro's broken default.\n *\n * @internal Exported for testing.\n */\nexport function selectSuppressedHintPrefixes(framework?: {\n previewCommand?: string;\n deployCommand?: string;\n}): string[] {\n return [\n ...(framework?.previewCommand ? [] : [NITRO_PREVIEW_HINT_PREFIX]),\n ...(framework?.deployCommand ? [] : [NITRO_DEPLOY_HINT_PREFIX]),\n ];\n}\n\n/** Minimal structural view of the nitro (consola) logger the wrap needs. */\ninterface NitroBuildLogger {\n success: (message: unknown, ...args: unknown[]) => void;\n}\n\n/**\n * Wrap a nitro logger's `success` so hardcoded preview/deploy hints are\n * dropped for this programmatic build only. Returns the original\n * (unfiltered) success fn so timber can print its own hint — which shares\n * the suppressed prefix on purpose, replacing nitro's wording.\n *\n * @internal Exported for testing.\n */\nexport function wrapNitroLoggerForBuild(\n logger: NitroBuildLogger,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): NitroBuildLogger['success'] {\n const originalSuccess = logger.success.bind(logger);\n const wrapped = (message: unknown, ...args: unknown[]) => {\n if (isSuppressedNitroHint(message, prefixes)) return;\n originalSuccess(message, ...args);\n };\n // Preserve consola LogFn properties (e.g. `.raw`) on the replacement.\n logger.success = Object.assign(wrapped, logger.success);\n return originalSuccess;\n}\n\n/**\n * Timber's own post-build hint. Locally-runnable presets are previewed via\n * `timber preview`, which invokes this adapter's `preview()` to run the\n * generated `_preview-server.mjs`. Serverless presets get no hint — their\n * output lives under `.timber/dist/nitro/`, so any cwd-relative deploy\n * command would be as wrong as the nitro hint this replaces.\n *\n * @internal Exported for testing.\n */\nexport function getPostBuildHint(preset: NitroPreset): string | null {\n return LOCALLY_PREVIEWABLE.has(preset)\n ? 'You can preview this build using `timber preview`'\n : null;\n}\n\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n *\n * @internal Exported for testing.\n */\nexport async function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n immutableDirs: readonly string[],\n userConfig?: NitroConfig\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const immutableAssets = await prepareImmutableAssets(nitroDir, immutableDirs);\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n // The content-hashed directories the build recorded: immutable on a hit,\n // a no-store 404 on a miss. Not route rules, which cannot tell the two\n // apart (TIM-1578) — see nitro-immutable-assets.ts. Set after the user's\n // config, which may add public-asset directories and plugins but not drop\n // these: without them a handler could answer 200 under a hashed directory\n // and be marked immutable.\n publicAssets: [...immutableAssets.publicAssets, ...(userConfig?.publicAssets ?? [])],\n plugins: [...immutableAssets.plugins, ...(userConfig?.plugins ?? [])],\n });\n\n // Drop nitro's `npx nitro preview` / `npx nitro deploy` hints —\n // they can never work from the project root (see TIM-1375). Hints whose\n // command the user explicitly configured via framework.previewCommand /\n // deployCommand pass through untouched — except on the rollup builder,\n // which ignores framework commands and unconditionally prints the broken\n // defaults (nitro/dist/_build/rollup.mjs), so user commands are treated\n // as absent there: defaults stay suppressed, timber's hint still prints.\n // logSuccess is the unfiltered fn used below to print timber's hint.\n const framework = nitro.options.builder === 'rollup' ? undefined : nitro.options.framework;\n const logSuccess = wrapNitroLoggerForBuild(nitro.logger, selectSuppressedHintPrefixes(framework));\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n // A user-configured previewCommand already printed via nitro's own hint —\n // don't print a second, conflicting one.\n const hint = framework?.previewCommand ? null : getPostBuildHint(preset);\n if (hint) logSuccess(hint);\n\n return { serverDir };\n}\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) => cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }))\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,kBAA2E,CAC/E;CACE,SACE;CACF,aAAa,4BAA4B,KAAK,UAAU,gBAAgB,EAAE;AAC5E,CACF;;;;;;;;;;;;;;;AAgBA,IAAM,oBAAuC;CAE3C;CAEA;CAEA;AACF;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,MAAsB;CAC1D,IAAI,MAAM;CACV,KAAK,MAAM,EAAE,SAAS,i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sources":["../../src/adapters/compress-module.ts","../../src/adapters/canonicalize-module.ts","../../src/adapters/nitro-immutable-assets.ts","../../src/adapters/nitro-presets.ts","../../src/adapters/nitro-preview.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n//\n// The transform strips types; it does NOT bundle. The emitted file sits\n// alone in the build output, so any import specifier that survives into it\n// is a module resolution failure at runtime on the deployed server. Shared\n// constants are therefore interpolated here — the same treatment the\n// Cloudflare worker template gives `RSC_KEY_HEADERS` — and anything else\n// that reaches the output as an import is rejected with a build error\n// rather than shipped.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.ts';\n\n/**\n * The one import `server/compress.ts` is allowed to carry, and its inlined\n * form.\n *\n * The binding list is matched exactly rather than as `{…}`. A second binding\n * added to that import would otherwise be erased along with the statement and\n * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this\n * whole module exists to make impossible. Matching exactly means such an\n * import falls through to the rejection below instead.\n */\nconst INLINED_IMPORTS: ReadonlyArray<{ pattern: RegExp; replacement: string }> = [\n {\n pattern:\n /^import\\s*\\{\\s*RSC_CONTENT_TYPE\\s*,?\\s*\\}\\s*from\\s*[\"'][^\"']*shared\\/rsc-media-type\\.(?:js|ts)[\"'];?[ \\t]*$/m,\n replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`,\n },\n];\n\n/**\n * Every way a module specifier can reach the emitted file, minus Node\n * builtins.\n *\n * `node:*` is exempt because it resolves on the deployed server exactly as it\n * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,\n * and self-hosted (Node/Bun) is the only place this file runs. Everything\n * else — relative paths, bare packages — has no resolution target next to a\n * lone `.mjs` in the build output.\n *\n * All three forms are listed rather than the one `server/compress.ts` happens\n * to use, because a re-export or a lazy `await import()` fails in exactly the\n * same place and is exactly as invisible until deploy.\n */\nconst MODULE_SPECIFIERS: readonly RegExp[] = [\n // import … from '…' / export … from '…'\n /^[ \\t]*(?:import|export)\\b[^\\n]*\\bfrom\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import '…' (side effect only)\n /^[ \\t]*import\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import('…') (dynamic, literal specifier)\n /\\bimport\\s*\\(\\s*[\"'](?!node:)[^\"']+[\"']/,\n];\n\n/**\n * Replace the shared-module imports with their values and reject anything\n * else that would leave a dangling specifier in `_compress.mjs`.\n *\n * Exported separately from `generateCompressModule` so both branches can be\n * driven with fixtures: the source it normally compiles is fixed, so a test\n * of the generator alone can only ever exercise whichever branch that source\n * happens to take today.\n *\n * @internal Exported for testing.\n */\nexport function inlineCompressImports(code: string): string {\n let out = code;\n for (const { pattern, replacement } of INLINED_IMPORTS) {\n out = out.replace(pattern, replacement);\n }\n assertStandalone(out, 'server/compress.ts', '_compress.mjs');\n return out;\n}\n\n/**\n * Throw if type-stripped server source still imports anything but a Node\n * builtin. Such a module is emitted alone into the build output, where no\n * specifier has anything to resolve to.\n *\n * @internal Shared by the standalone-module generators.\n */\nexport function assertStandalone(code: string, source: string, emitted: string): void {\n const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(code)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] ${source} is emitted as a standalone ${emitted} (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in the generator in adapters/ or ` +\n `keep the dependency out of ${source}.`\n );\n }\n}\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n inlineCompressImports(result.code)\n );\n}\n","// Compiles server/canonicalize.ts into a standalone ESM module\n// (_canonicalize.mjs) for the Nitro preview server, so preview answers a\n// request path exactly as the runtime's request boundary does — the same\n// rejections (encoded separators, null bytes, malformed encoding, escaping\n// the root) and the same single decode — instead of a hand-kept copy of\n// those rules drifting from them. Same mechanism as compress-module.ts:\n// type-stripped, not bundled, so the source must stay import-free.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time (see\n// compress-module.ts).\nimport canonicalizeSource from '../server/canonicalize.ts?raw';\nimport { assertStandalone } from './compress-module.ts';\n\n/**\n * Compile server/canonicalize.ts into a standalone ESM module exporting\n * `canonicalize`.\n *\n * @internal Exported for testing.\n */\nexport async function generateCanonicalizeModule(): Promise<string> {\n const result = await transformWithOxc(canonicalizeSource, 'canonicalize.ts', { lang: 'ts' });\n assertStandalone(result.code, 'server/canonicalize.ts', '_canonicalize.mjs');\n return (\n '// Generated by @timber-js/app — compiled from server/canonicalize.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Immutable caching for the build's content-hashed directories on Nitro.\n//\n// A one-year `immutable` Cache-Control is correct only on a response that\n// served a file. Nitro route rules cannot tell a hit from a miss — their\n// headers land on every response under the path, the 404 for a file that is\n// not there included — so a CDN in front of a pod that lacked the file mid\n// rollout cached that 404 for a year (TIM-1578). Nitro's public-asset `maxAge`\n// option is a route rule underneath, with the same reach.\n//\n// Instead, three pieces, all keyed by one generated path matcher:\n//\n// - Each directory is its own non-fallthrough public-asset directory. Where\n// Nitro serves files itself, a GET or HEAD miss there is a 404 from its\n// static handler; Vercel and Netlify route such misses to a platform 404\n// instead of the function.\n// - timber's Nitro entry answers any request under those directories that\n// still reaches it with a plain `no-store` 404, before the app runs. Nothing\n// else answers there: a preset without Nitro's static handler (aws-lambda),\n// a method the static handler ignores, or a path it does not claim\n// (`/assets/`) gets the 404 rather than a page.\n// - A Nitro runtime plugin sets Cache-Control from the outcome. Since only a\n// served file can succeed under those directories, a successful GET or HEAD\n// is a hit.\n//\n// See design/25-production-deployments.md §\"Hashed assets\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { IMMUTABLE_CACHE } from './shared.ts';\n\n/** The generated module, written beside the Nitro entry that imports it. */\nconst IMMUTABLE_ASSETS_MODULE = '_immutable-assets.mjs';\n\n/** One Nitro `publicAssets` entry. */\ninterface NitroPublicAssetDir {\n dir: string;\n baseURL: string;\n fallthrough: false;\n}\n\n/** The Nitro config that serves `immutableDirs` from `<nitroDir>/public`. */\nexport interface ImmutableAssetsNitroConfig {\n publicAssets: NitroPublicAssetDir[];\n plugins: string[];\n}\n\n/**\n * Write the generated module into `nitroDir` and return the Nitro config that\n * serves the build's content-hashed directories from `<nitroDir>/public`.\n *\n * No `maxAge`: Nitro would turn it into a route rule (see the module header),\n * and Vercel already gives a non-fallthrough directory a one-year immutable\n * header on hits and `no-store` on misses by default.\n */\nexport async function prepareImmutableAssets(\n nitroDir: string,\n immutableDirs: readonly string[]\n): Promise<ImmutableAssetsNitroConfig> {\n if (immutableDirs.length === 0) return { publicAssets: [], plugins: [] };\n const plugin = join(nitroDir, IMMUTABLE_ASSETS_MODULE);\n await writeFile(plugin, generateImmutableAssetsModule(immutableDirs));\n return {\n publicAssets: immutableDirs.map((dir) => ({\n dir: join(nitroDir, 'public', dir),\n baseURL: `/${dir}`,\n fallthrough: false,\n })),\n plugins: [plugin],\n };\n}\n\n/**\n * The lines timber's Nitro entry needs to answer a request under the\n * content-hashed directories itself: an import, and a guard to run before\n * the handler, with the h3 event in scope as `event`. Empty when the build\n * has no such directories, which also means `prepareImmutableAssets()`\n * writes no module to import.\n */\nexport function immutableAssetsEntryGuard(immutableDirs: readonly string[]): {\n imports: string;\n guard: string;\n} {\n if (immutableDirs.length === 0) return { imports: '', guard: '' };\n return {\n imports: `import { isImmutableAssetPath } from './${IMMUTABLE_ASSETS_MODULE}'\\n`,\n guard: ` // Under a content-hashed directory only a served file may answer; the\n // static handler already sent any file there is. A no-store 404, never a\n // page — see _immutable-assets.mjs.\n if (isImmutableAssetPath(event.url.pathname)) {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n })\n }\n`,\n };\n}\n\n/**\n * Generate the module shared by the Nitro entry and runtime: the path matcher\n * for the content-hashed directories, and the runtime plugin that owns\n * Cache-Control under them — `IMMUTABLE_CACHE` on a GET or HEAD that served\n * the file (200, or 304 revalidating it), `no-store` on everything else.\n *\n * Status is a sound signal only because the entry answers everything else\n * under these directories with a 404 (see `immutableAssetsEntryGuard`). The\n * prefixes are matched against the decoded path, the one Nitro's static\n * handler looks the file up by.\n *\n * @internal Exported for testing.\n */\nexport function generateImmutableAssetsModule(immutableDirs: readonly string[]): string {\n const prefixes = immutableDirs.map((dir) => `/${dir}/`);\n return `// Generated by @timber-js/app — Cache-Control for content-hashed directories.\n// Do not edit — this file is regenerated on each build.\n\nconst PREFIXES = ${JSON.stringify(prefixes)};\nconst IMMUTABLE_CACHE = ${JSON.stringify(IMMUTABLE_CACHE)};\n\nexport function isImmutableAssetPath(pathname) {\n let path = pathname;\n try {\n path = decodeURI(pathname);\n } catch {\n // Malformed escapes: match the path as received.\n }\n return PREFIXES.some((prefix) => path.startsWith(prefix));\n}\n\nexport default function immutableAssets(nitroApp) {\n // Hooks are off only if a user's nitroConfig disables them; files then go\n // without the long-lived header rather than failing every request.\n nitroApp.hooks?.hook('response', (res, event) => {\n if (!isImmutableAssetPath(event.url.pathname)) return;\n const method = event.req.method;\n const served =\n (method === 'GET' || method === 'HEAD') && (res.status === 200 || res.status === 304);\n res.headers.set('Cache-Control', served ? IMMUTABLE_CACHE : 'no-store');\n });\n}\n`;\n}\n","// Nitro preset catalog — per-platform build configuration.\n//\n// Shared by the nitro adapter (build + entry generation) and the preview\n// module. See design/25-production-deployments.md for the preset matrix.\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\nexport interface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /**\n * Whether the platform reads `_headers` and `_redirects` from the public\n * directory. Everywhere else they are just public files anyone can fetch,\n * so the build leaves them out (TIM-1605).\n */\n readsPlatformFiles: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nexport const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'bun',\n },\n};\n\n/** Presets that produce a locally-runnable server entry. */\nexport const LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n","// Nitro local preview — standalone server codegen and process spawning.\n//\n// `buildOutput` writes `_preview-server.mjs` into the Nitro output directory,\n// generated from the build's own artifacts; `timber preview` runs the\n// adapter's preview(), which spawns it. See design/25-production-deployments.md\n// §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { IMMUTABLE_CACHE, STATIC_CACHE } from './shared.ts';\n\n/**\n * Content-Type by file extension for the preview server. Static hosts decide\n * this themselves; the table covers the file types a web build ships so the\n * preview does not turn ordinary files into downloads. An extension missing\n * here is served as `application/octet-stream`.\n */\nconst PREVIEW_MIME_TYPES: Readonly<Record<string, string>> = {\n // Documents and code\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.cjs': 'text/javascript; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.jsonld': 'application/ld+json',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.rss': 'application/rss+xml',\n '.atom': 'application/atom+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n '.csv': 'text/csv; charset=utf-8',\n '.ics': 'text/calendar; charset=utf-8',\n '.vtt': 'text/vtt; charset=utf-8',\n '.pdf': 'application/pdf',\n '.wasm': 'application/wasm',\n '.zip': 'application/zip',\n '.gz': 'application/gzip',\n // Images\n '.png': 'image/png',\n '.apng': 'image/apng',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n // Fonts\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n // Audio and video\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.m4a': 'audio/mp4',\n '.flac': 'audio/flac',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.ogv': 'video/ogg',\n '.mov': 'video/quicktime',\n};\n\n/** What the generated preview server serves, as `buildOutput` knows it. */\nexport type PreviewScriptOptions = StaticPreviewScriptOptions | ServerPreviewScriptOptions;\n\ninterface PreviewScriptOptionsBase {\n /**\n * `BuildArtifacts.immutableDirs` — files there are served with a one-year\n * immutable `Cache-Control`, every other file with a revalidating one. In\n * a server build, a miss there is a plain `no-store` 404.\n */\n immutableDirs: readonly string[];\n /**\n * The deployment base, normalized (`/` or `/repo/`). Requests arrive in\n * deployed-URL space; files are laid out in route space, so the script\n * strips it before looking anything up.\n */\n base: string;\n}\n\n/** A static build: serve the pre-rendered site and nothing else. */\nexport interface StaticPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'static';\n /** `StaticBuildArtifacts.contentTypes` — extensionless API route outputs. */\n contentTypes: Readonly<Record<string, string>>;\n}\n\n/** A server build: serve `public/`, route everything else to the RSC handler. */\nexport interface ServerPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'server';\n /** Value for `TIMBER_RUNTIME`, set before the handler evaluates. */\n runtimeName: string;\n /** Import specifier of the RSC handler, relative to the script. */\n rscEntry: string;\n /**\n * Whether this build wrote `_timber-manifest-init.js` beside the script.\n * Recorded from the build, never probed: the Nitro output directory is not\n * cleaned between server builds, so a file on disk can be a stale one.\n */\n hasManifestInit: boolean;\n}\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and, in a server build, route requests\n * to the RSC handler.\n *\n * Generated at build time rather than at preview time, so everything it\n * serves comes from the build's artifacts instead of guesses about the\n * directory it runs in.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(options: PreviewScriptOptions): string {\n const immutablePrefixes = options.immutableDirs.map((dir) => `/${dir}/`);\n const contentTypes = options.output === 'static' ? options.contentTypes : {};\n\n // A server build loads its handler (after the runtime and manifest are in\n // place); a static build has no handler to load.\n const handlerSetup =\n options.output === 'server'\n ? `// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = ${JSON.stringify(options.runtimeName)};\n${\n options.hasManifestInit\n ? `\n// Load the build manifest before the handler reads it.\nawait import('./_timber-manifest-init.js');\n`\n : ''\n}\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import(${JSON.stringify(options.rscEntry)});\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n`\n : '';\n\n // What happens when no file matches: a static build answers with its own\n // 404 page, a server build hands the request to the RSC handler.\n const fallback =\n options.output === 'static'\n ? ` if (badPath) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\n const notFound = await findFile('/404.html');\n if (notFound) {\n await sendFile(req, res, notFound, 404, 'text/html', 'public, max-age=0, must-revalidate');\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n`\n : ` // A request under a content-hashed directory that names no file is a\n // plain no-store 404, never a render of the app — as timber's Nitro entry\n // answers it in production (TIM-1578).\n if (pathname !== null && IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });\n res.end('Not Found');\n return;\n }\n await handleDynamic(req, res, url);\n`;\n\n const dynamicHandler =\n options.output === 'server'\n ? `\nasync function handleDynamic(req, res, url) {\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n}\n`\n : '';\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Do not edit — this file is regenerated on each build.\n// Uses Node's built-in HTTP server to serve the build's files${\n options.output === 'server' ? ' and route\\n// dynamic requests through the RSC handler' : ''\n }. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { canonicalize, requestTargetUrl } from './_canonicalize.mjs';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\n${handlerSetup}\nconst MIME_TYPES = ${JSON.stringify(PREVIEW_MIME_TYPES, null, 2)};\n\n// Recorded by the build: content-hashed directories, and the Content-Type of\n// each extensionless API route output (a file name cannot say it). Both are\n// decoded route-space paths, matched against the decoded request path.\nconst IMMUTABLE_PREFIXES = ${JSON.stringify(immutablePrefixes)};\nconst BASE = ${JSON.stringify(options.base)};\nconst CONTENT_TYPES = ${JSON.stringify(contentTypes)};\nconst SERVE_DIRECTORY_INDEX = ${options.output === 'static'};\n\nconst publicDir = join(__dirname, 'public');\n\n/**\n * The file under publicDir that a decoded URL path names, or null. A static\n * build lays its pages out as <path>/index.html, so a directory serves its\n * index there.\n */\nasync function findFile(pathname) {\n const filePath = join(publicDir, pathname);\n // Prevent path traversal (and a sibling like public-other/ passing a bare\n // prefix check).\n if (!filePath.startsWith(publicDir + sep)) return null;\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) return filePath;\n if (SERVE_DIRECTORY_INDEX && fileStat.isDirectory()) {\n const index = join(filePath, 'index.html');\n if ((await stat(index)).isFile()) return index;\n }\n } catch {\n // Not found.\n }\n return null;\n}\n\n/**\n * The route-space path for a request path, or null when the request is\n * outside the deployment base (it names no file of this build).\n */\nfunction stripBase(pathname) {\n if (BASE === '/') return pathname;\n if (pathname === BASE.slice(0, -1)) return '/';\n if (!pathname.startsWith(BASE)) return null;\n return pathname.slice(BASE.length - 1);\n}\n\nasync function sendFile(req, res, filePath, status, contentType, cacheControl) {\n const body = await readFile(filePath);\n res.writeHead(status, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(req.method === 'HEAD' ? undefined : body);\n}\n${dynamicHandler}\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n// An IPv6 HOST ('::', '::1') binds as is but needs brackets in a URL;\n// unbracketed, every request URL is unparseable and answered 400.\nconst urlHost = host.includes(':') && !host.startsWith('[') ? \\`[\\${host}]\\` : host;\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n // requestTargetUrl() (server/canonicalize.ts) concatenates an origin-form\n // target and resolves any other form, so '//evil.com/' stays a path the\n // pipeline redirects (TIM-1571) and 'OPTIONS *' is '/*'. A target that\n // names no URL is answered here: thrown in this callback, which has no\n // catch around it, the rejection would take the preview process down.\n const url = requestTargetUrl(\\`\\${scheme}://\\${urlHost}:\\${boundPort}\\`, req.url || '/');\n if (!url) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\n\n // The runtime's own request-boundary canonicalizer (_canonicalize.mjs,\n // compiled from server/canonicalize.ts): one decode, and the same 400s for\n // encoded separators, null bytes, malformed encoding, and escaping the root\n // (design/13-security.md). The base is stripped from its canonical result,\n // so an encoded spelling of the base is the same path. What remains, in\n // route space, is looked up in public/; null names no file.\n const canonical = canonicalize(url.pathname, false);\n const badPath = !canonical.ok;\n const pathname = canonical.ok ? stripBase(canonical.pathname) : null;\n const filePath = pathname === null ? null : await findFile(pathname);\n if (filePath) {\n const contentType =\n CONTENT_TYPES[pathname] || MIME_TYPES[extname(filePath).toLowerCase()] || 'application/octet-stream';\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable = IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix));\n const cacheControl = isImmutable ? ${JSON.stringify(IMMUTABLE_CACHE)} : ${JSON.stringify(STATIC_CACHE)};\n await sendFile(req, res, filePath, 200, contentType, cacheControl);\n return;\n }\n\n${fallback}});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nexport function spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // A response with a Node body (timber's NodeBodyResponse, srvx's protocol):\n // pipe it straight to the socket, no Web Streams round trip. pipe() rather\n // than pipeline(), which allocates an AbortController and an error on every\n // finish; a client that disconnects early destroys the body (aborting the\n // render), and a body that errors mid-stream destroys the socket.\n //\n // As srvx's pipeBody does, the status line waits until the body is\n // readable: a body that errors before its first chunk answers a bare 500\n // instead of closing the socket with nothing written (TIM-1602).\n if (typeof webRes._toNodeResponse === 'function') {\n const res = webRes._toNodeResponse();\n if (res.body && typeof res.body.pipe === 'function') {\n const body = res.body;\n // The client already left: 'close' has fired and will not again.\n if (nodeRes.destroyed) {\n body.destroy();\n return;\n }\n // Already failed: its 'error' has fired and 'readable' never will.\n if (body.destroyed) {\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n return new Promise((resolve) => {\n function cleanup() {\n body.off('error', onEarlyError);\n body.off('readable', onReadable);\n nodeRes.off('close', onEarlyClose);\n }\n function onEarlyError() {\n cleanup();\n body.destroy();\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n nodeRes.end(resolve);\n }\n function onEarlyClose() {\n cleanup();\n body.destroy();\n resolve();\n }\n function onReadable() {\n cleanup();\n writeHead(nodeRes, res.status, res.statusText, res.headers);\n nodeRes.once('close', () => {\n if (!body.readableEnded) body.destroy();\n resolve();\n });\n nodeRes.on('error', () => body.destroy());\n body.once('error', (error) => nodeRes.destroy(error));\n body.pipe(nodeRes);\n }\n body.once('error', onEarlyError);\n body.once('readable', onReadable);\n nodeRes.once('close', onEarlyClose);\n });\n }\n webRes = new Response(res.body, { status: res.status, statusText: res.statusText, headers: pairs(res.headers) });\n }\n // A Web body's status line goes out before its first read, as in srvx:\n // one that errors before its first chunk closes the socket unanswered.\n writeHead(nodeRes, webRes.status, webRes.statusText, [...webRes.headers].flat());\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n\nfunction writeHead(nodeRes, status, statusText, headers) {\n if (nodeRes.headersSent) return;\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(status, headers);\n } else {\n nodeRes.writeHead(status, statusText, headers);\n }\n}\n\nfunction pairs(flat) {\n const out = [];\n for (let i = 0; i < flat.length; i += 2) out.push([flat[i], flat[i + 1]]);\n return out;\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { existsSync } from 'node:fs';\nimport { cp, glob, readFile, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport type { NitroConfig } from 'nitro/types';\nimport {\n buildStaticDirectoryOutput,\n runSharedBuildSteps,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { generateCompressModule } from './compress-module.ts';\nimport { generateCanonicalizeModule } from './canonicalize-module.ts';\nimport { immutableAssetsEntryGuard, prepareImmutableAssets } from './nitro-immutable-assets.ts';\nimport { LOCALLY_PREVIEWABLE, PRESET_CONFIGS, type NitroPreset } from './nitro-presets.ts';\nimport {\n generatePreviewScript,\n generateSendResponseModule,\n spawnNitroPreview,\n} from './nitro-preview.ts';\nimport { adapterBase } from './shared.ts';\nimport { HEADERS_FILE, REDIRECTS_FILE } from '../shared/static-platform-files.ts';\nimport type {\n BuildArtifacts,\n PreviewTarget,\n TimberConfig,\n TimberPlatformAdapter,\n} from './types.ts';\n\n// NitroPreset is part of the public adapter API (NitroAdapterOptions.preset),\n// so it stays importable from this module.\nexport type { NitroPreset } from './nitro-presets.ts';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: NitroConfig;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, artifacts: BuildArtifacts) {\n const outDir = join(artifacts.outputDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (artifacts.output === 'static') {\n await buildStaticDirectoryOutput(config, artifacts, outDir, 'public');\n const publicDir = join(outDir, 'public');\n const target = options.staticTarget ?? 'generic';\n\n // Write _headers for cache control + extensionless Content-Type, for\n // the hosts a generic static build lands on that read it (Netlify,\n // Cloudflare Pages). GitHub Pages reads neither platform file.\n if (target !== 'github-pages') await writeHeadersFile(publicDir, config, artifacts);\n\n // Local preview serves the site as the build recorded it.\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'static',\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n contentTypes: artifacts.contentTypes,\n })\n );\n\n // Platform-specific files for static deploy targets.\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n // With `.nojekyll` nothing hides `_`-prefixed files, so these would be\n // published as-is — the user's `public/` copies included (TIM-1605).\n for (const name of [HEADERS_FILE, REDIRECTS_FILE]) {\n await rm(join(publicDir, name), { force: true });\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers where the platform reads it, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n platformFiles: PRESET_CONFIGS[preset].readsPlatformFiles,\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Standalone preview server for presets with a local runtime. It loads\n // the build's own RSC bundle — not the copy under nitro/rsc/ — because\n // the handler reads prebuilt payloads from ../prebuilt beside its\n // bundle, and the build's prebuilt/ is cleaned every build while\n // nitro/prebuilt/ is not: a build that captured nothing would otherwise\n // preview an earlier build's payloads.\n if (LOCALLY_PREVIEWABLE.has(preset)) {\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'server',\n runtimeName: PRESET_CONFIGS[preset].runtimeName,\n rscEntry: importSpecifier(outDir, join(artifacts.rsc.path, 'index.js')),\n hasManifestInit: !!artifacts.manifestInit,\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n })\n );\n }\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (artifacts.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${artifacts.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(\n outDir,\n preset,\n artifacts.immutableDirs,\n options.nitroConfig\n );\n\n // Copy prebuilt flight payloads into the Nitro output. The RSC entry\n // resolves `../prebuilt/` relative to its bundled chunk\n // (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n if (artifacts.prebuilt) {\n const prebuiltSrc = artifacts.prebuilt.path;\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), { recursive: true });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n }\n },\n\n // buildOutput wrote the preview server for this build: a static file\n // server for a static build, and for a server build on a preset with a\n // local runtime (node-server, bun), one that routes to the RSC handler.\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no local\n // runtime, so a server build on one has nothing to preview.\n async preview(_config: TimberConfig, { output, outputDir }: PreviewTarget) {\n if (output === 'server' && !LOCALLY_PREVIEWABLE.has(preset)) {\n throw new Error(\n `[timber] The nitro '${preset}' preset has no local runtime, so \\`timber preview\\` ` +\n `cannot run its server build. Preview with a node-server build, or with the ` +\n `platform's own tooling.`\n );\n }\n const nitroDir = join(outputDir, 'nitro');\n const script = join(nitroDir, PREVIEW_SCRIPT);\n if (!existsSync(script)) {\n throw new Error(\n `[timber] No preview server at ${script}. Run \\`timber build\\` before \\`timber preview\\`.`\n );\n }\n // Only a bun server build needs Bun. The static file server uses Node\n // built-ins, so it runs on the Node already running timber, as does a\n // node-server build — no PATH lookup for either.\n const command = output === 'server' && preset === 'bun' ? 'bun' : process.execPath;\n await spawnNitroPreview(command, [script], nitroDir);\n },\n };\n}\n\n/** The preview server buildOutput writes into the Nitro output directory. */\nconst PREVIEW_SCRIPT = '_preview-server.mjs';\n\n/** The request-path canonicalizer the preview server imports beside it. */\nconst CANONICALIZE_MODULE = '_canonicalize.mjs';\n\n/** A relative ESM import specifier for `file`, as imported from a module in `fromDir`. */\nfunction importSpecifier(fromDir: string, file: string): string {\n const path = relative(fromDir, file).split(sep).join('/');\n return path.startsWith('../') ? path : './' + path;\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n preset: NitroPreset,\n compress = true,\n immutableDirs: readonly string[] = []\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n const immutableAssets = immutableAssetsEntryGuard(immutableDirs);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n${immutableAssets.guard} // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Build Hint Filtering ────────────────────────────────────────────────────\n\n/**\n * Prefixes of nitro build-output lines that give wrong advice for timber\n * builds. Every nitro bundler path emits these hints via `logger.success` —\n * the rollup path hardcodes `npx nitro preview`; rolldown and vite default\n * to it. That command resolves `.output/nitro.json` relative to cwd, but\n * timber's nitro build lives at `.timber/dist/nitro/.output`, so the\n * suggested command can never work from the project root.\n * Prefix matching degrades gracefully: if upstream rewords the line\n * entirely, it passes through rather than being silently eaten.\n */\nconst NITRO_PREVIEW_HINT_PREFIX = 'You can preview this build using';\nconst NITRO_DEPLOY_HINT_PREFIX = 'You can deploy this build using';\nconst SUPPRESSED_NITRO_HINT_PREFIXES = [NITRO_PREVIEW_HINT_PREFIX, NITRO_DEPLOY_HINT_PREFIX];\n\n/** @internal Exported for testing. */\nexport function isSuppressedNitroHint(\n message: unknown,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): boolean {\n return typeof message === 'string' && prefixes.some((prefix) => message.startsWith(prefix));\n}\n\n/**\n * Nitro's rolldown and vite builders render `framework.previewCommand` /\n * `framework.deployCommand` into these hints. A user who explicitly set one\n * via `nitroConfig` has provided valid guidance — only suppress the hints\n * whose command is still nitro's broken default.\n *\n * @internal Exported for testing.\n */\nexport function selectSuppressedHintPrefixes(framework?: {\n previewCommand?: string;\n deployCommand?: string;\n}): string[] {\n return [\n ...(framework?.previewCommand ? [] : [NITRO_PREVIEW_HINT_PREFIX]),\n ...(framework?.deployCommand ? [] : [NITRO_DEPLOY_HINT_PREFIX]),\n ];\n}\n\n/** Minimal structural view of the nitro (consola) logger the wrap needs. */\ninterface NitroBuildLogger {\n success: (message: unknown, ...args: unknown[]) => void;\n}\n\n/**\n * Wrap a nitro logger's `success` so hardcoded preview/deploy hints are\n * dropped for this programmatic build only. Returns the original\n * (unfiltered) success fn so timber can print its own hint — which shares\n * the suppressed prefix on purpose, replacing nitro's wording.\n *\n * @internal Exported for testing.\n */\nexport function wrapNitroLoggerForBuild(\n logger: NitroBuildLogger,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): NitroBuildLogger['success'] {\n const originalSuccess = logger.success.bind(logger);\n const wrapped = (message: unknown, ...args: unknown[]) => {\n if (isSuppressedNitroHint(message, prefixes)) return;\n originalSuccess(message, ...args);\n };\n // Preserve consola LogFn properties (e.g. `.raw`) on the replacement.\n logger.success = Object.assign(wrapped, logger.success);\n return originalSuccess;\n}\n\n/**\n * Timber's own post-build hint. Locally-runnable presets are previewed via\n * `timber preview`, which invokes this adapter's `preview()` to run the\n * generated `_preview-server.mjs`. Serverless presets get no hint — their\n * output lives under `.timber/dist/nitro/`, so any cwd-relative deploy\n * command would be as wrong as the nitro hint this replaces.\n *\n * @internal Exported for testing.\n */\nexport function getPostBuildHint(preset: NitroPreset): string | null {\n return LOCALLY_PREVIEWABLE.has(preset)\n ? 'You can preview this build using `timber preview`'\n : null;\n}\n\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n *\n * @internal Exported for testing.\n */\nexport async function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n immutableDirs: readonly string[],\n userConfig?: NitroConfig\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const immutableAssets = await prepareImmutableAssets(nitroDir, immutableDirs);\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n // The content-hashed directories the build recorded: immutable on a hit,\n // a no-store 404 on a miss. Not route rules, which cannot tell the two\n // apart (TIM-1578) — see nitro-immutable-assets.ts. Set after the user's\n // config, which may add public-asset directories and plugins but not drop\n // these: without them a handler could answer 200 under a hashed directory\n // and be marked immutable.\n publicAssets: [...immutableAssets.publicAssets, ...(userConfig?.publicAssets ?? [])],\n plugins: [...immutableAssets.plugins, ...(userConfig?.plugins ?? [])],\n });\n\n // Drop nitro's `npx nitro preview` / `npx nitro deploy` hints —\n // they can never work from the project root (see TIM-1375). Hints whose\n // command the user explicitly configured via framework.previewCommand /\n // deployCommand pass through untouched — except on the rollup builder,\n // which ignores framework commands and unconditionally prints the broken\n // defaults (nitro/dist/_build/rollup.mjs), so user commands are treated\n // as absent there: defaults stay suppressed, timber's hint still prints.\n // logSuccess is the unfiltered fn used below to print timber's hint.\n const framework = nitro.options.builder === 'rollup' ? undefined : nitro.options.framework;\n const logSuccess = wrapNitroLoggerForBuild(nitro.logger, selectSuppressedHintPrefixes(framework));\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n // A user-configured previewCommand already printed via nitro's own hint —\n // don't print a second, conflicting one.\n const hint = framework?.previewCommand ? null : getPostBuildHint(preset);\n if (hint) logSuccess(hint);\n\n return { serverDir };\n}\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) => cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }))\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,kBAA2E,CAC/E;CACE,SACE;CACF,aAAa,4BAA4B,KAAK,UAAU,gBAAgB,EAAE;AAC5E,CACF;;;;;;;;;;;;;;;AAgBA,IAAM,oBAAuC;CAE3C;CAEA;CAEA;AACF;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,MAAsB;CAC1D,IAAI,MAAM;CACV,KAAK,MAAM,EAAE,SAAS,iBAAiB,iBACrC,MAAM,IAAI,QAAQ,SAAS,WAAW;CAExC,iBA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AAC,GAC/D,IAAI,CAAC,MAAM,SAAS,YAAY,GAC9B,SAAS,KAAK,KAAK,cAAc,KAAK,CAAC;CAG7C,QAAQ;EACN;CACF;CACA,MAAM,QAAQ,IACZ,SAAS,KAAK,QAAQ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CACnF;AACF"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { i as scanProjectSourceFiles, n as isScannableSourceFile, t as buildSourceExtensions } from "../_chunks/scan-
|
|
2
|
-
import { s as isTimberPluginApi, u as resolveAppDir } from "../_chunks/plugin-context-
|
|
3
|
-
import { i as detectDirective, r as classifyModules } from "../_chunks/classify
|
|
4
|
-
import { n as stitchImportChains } from "../_chunks/chains-
|
|
5
|
-
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "../_chunks/poison-scan-
|
|
1
|
+
import { i as scanProjectSourceFiles, n as isScannableSourceFile, t as buildSourceExtensions } from "../_chunks/scan-CyizcBiX.js";
|
|
2
|
+
import { s as isTimberPluginApi, u as resolveAppDir } from "../_chunks/plugin-context-FCkaNLUB.js";
|
|
3
|
+
import { i as detectDirective, r as classifyModules } from "../_chunks/classify--_kINHQV.js";
|
|
4
|
+
import { n as stitchImportChains } from "../_chunks/chains-Dgm3PrMe.js";
|
|
5
|
+
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "../_chunks/poison-scan-DJYxZc_7.js";
|
|
6
6
|
import { normalizePath } from "vite";
|
|
7
7
|
import { join, resolve } from "node:path";
|
|
8
8
|
import { readFile, realpath, writeFile } from "node:fs/promises";
|
|
9
|
-
|
|
9
|
+
// src/analyze/crawl.ts
|
|
10
10
|
/**
|
|
11
11
|
* crawl — programmatic middleware-mode crawl (the cold path).
|
|
12
12
|
*
|
|
@@ -261,8 +261,7 @@ async function crawlProject(options) {
|
|
|
261
261
|
await Promise.race([server.close().catch(() => {}), new Promise((resolveTimer) => setTimeout(resolveTimer, 5e3))]);
|
|
262
262
|
}
|
|
263
263
|
}
|
|
264
|
-
|
|
265
|
-
//#region src/analyze/crawl-entry.ts
|
|
264
|
+
// src/analyze/crawl-entry.ts
|
|
266
265
|
/**
|
|
267
266
|
* crawl-entry — child-process entry point for the cold crawl.
|
|
268
267
|
*
|
|
@@ -309,6 +308,5 @@ main().then(() => {
|
|
|
309
308
|
process.stderr.write(`[timber] crawl failed: ${error?.stack ?? String(error)}\n`);
|
|
310
309
|
process.exit(1);
|
|
311
310
|
});
|
|
312
|
-
//#endregion
|
|
313
311
|
|
|
314
312
|
//# sourceMappingURL=crawl-entry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crawl-entry.js","names":[],"sources":["../../src/analyze/crawl.ts","../../src/analyze/crawl-entry.ts"],"sourcesContent":["/**\n * crawl — programmatic middleware-mode crawl (the cold path).\n *\n * Boots `createServer({ middlewareMode: true })` — no HTTP port, no route\n * rendering — and BFS-walks `env.transformRequest(url)` → importedModules\n * edges from `virtual:timber-rsc-entry`, then from every discovered\n * `'use client'` boundary through the SSR environment. This reuses Vite's\n * actual resolution (aliases, tsconfig paths, react-server export\n * conditions, virtual modules), so it cannot drift from what dev or the\n * build does; hand-rolled resolution was evaluated and rejected\n * (design/47 §\"Verified Prototype Findings\").\n *\n * Cost model (design/47 §6): 2.5 s on small apps to ~10 s on dep-heavy\n * plugin stacks, with a transient ~1.3 GB RSS — callers MUST run this in\n * a short-lived child process (see crawl-entry.ts) and cache the\n * classification output, not the Vite transforms. The crawl always\n * covers the full project: one crawl per project state, never per\n * question — marginal per-file cost is ~zero once booted.\n *\n * `TIMBER_ANALYZE=1` is set before the server boots so platform dev\n * plugins (wrangler bindings — a measured ~6.8 s remote-bindings\n * handshake on website) skip work the crawl never needs: classification\n * wants import edges, not live Cloudflare connections.\n *\n * Design docs: 47-module-environment-tooling.md §6, §8.\n */\n\nimport { readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { normalizePath } from 'vite';\nimport {\n classifyModules,\n detectDirective,\n type Directive,\n type ModuleClassification,\n} from './classify.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, isScannableSourceFile } from './scan.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { isTimberPluginApi, resolveAppDir } from '../plugin-context.ts';\n\nconst RSC_ENTRY_URL = 'virtual:timber-rsc-entry';\n\n/**\n * Marker preceding the JSON report on crawl-entry's stdout. Lives here\n * (not in crawl-entry.ts) so consumers can import it without executing\n * the child entry's main().\n */\nexport const CRAWL_RESULT_MARKER = '__TIMBER_CRAWL_RESULT__';\n\nexport interface CrawlOptions {\n /** Project root (the app directory containing vite.config). */\n root: string;\n /** Explicit Vite config file; discovered from root when omitted. */\n configFile?: string;\n /** Overall crawl deadline. Default 120s. */\n timeoutMs?: number;\n}\n\nexport interface CrawlError {\n /** 'scan' covers disk-scan and directive-read failures. */\n environment: 'rsc' | 'ssr' | 'scan';\n id: string;\n message: string;\n}\n\n/**\n * One project file's full graph answer — the classification plus the\n * remaining JSON-contract fields (`boundary`, `chains`, `poisonings`)\n * that need the open graphs / original sources to compute. This is the\n * per-module unit `timber graph` caches and serves.\n */\nexport interface GraphModuleReport extends ModuleClassification {\n /** True when the file itself carries `'use client'`. */\n boundary: boolean;\n /** Boundary-aware import chains (design/47 §7); [] when in no graph. */\n chains: ImportChain[];\n /** Report-only poisoning conflicts (design/47 §3); [] when clean. */\n poisonings: Poisoning[];\n}\n\nexport interface CrawlReport {\n root: string;\n /**\n * True when the crawl deadline expired mid-walk — the report is\n * truncated, not wrong, and the condition is transient (a slow\n * machine, a cold dep-optimizer). Consumers must not cache an\n * incomplete report: with unchanged files it would be served forever,\n * never retrying after the transient cause cleared. Deterministic\n * per-module transform failures do NOT set this — they recur on\n * retry, so caching them is correct.\n */\n incomplete: boolean;\n /** Classification of every project file, sorted by path. */\n modules: GraphModuleReport[];\n /**\n * Transform failures encountered during the BFS. These are classified,\n * not swallowed — CSS/asset URLs and non-transformable modules land\n * here (44 on website in the §6 measurement) and the crawl continues.\n */\n errors: CrawlError[];\n stats: {\n rscGraphModules: number;\n ssrGraphModules: number;\n projectFiles: number;\n durationMs: number;\n };\n}\n\n/** Marker error for deadline expiry — structurally distinguishable\n * from a deterministic transform failure (consumers must not cache a\n * deadline-truncated report; a transform failure recurs on retry and\n * caches fine). */\nclass CrawlDeadlineError extends Error {}\n\n/** Race a promise against the crawl deadline. */\nfunction withDeadline<T>(promise: Promise<T>, remainingMs: number, label: string): Promise<T> {\n return new Promise<T>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(\n () =>\n rejectPromise(\n new CrawlDeadlineError(`crawl deadline exceeded while transforming ${label}`)\n ),\n Math.max(remainingMs, 1)\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (error) => {\n clearTimeout(timer);\n rejectPromise(error);\n }\n );\n });\n}\n\n/** Duck-typed view of the Vite dev environment surface the crawl uses. */\nexport interface CrawlEnvironment {\n transformRequest(url: string): Promise<unknown>;\n moduleGraph: {\n getModuleByUrl(url: string): Promise<CrawlModuleNode | undefined>;\n };\n}\n\ninterface CrawlModuleNode {\n id: string | null;\n url: string;\n file: string | null;\n importedModules: Set<CrawlModuleNode>;\n transformResult: unknown;\n}\n\ninterface EnvCrawlResult {\n /** Absolute paths of project files reached in this environment. */\n projectFiles: Set<string>;\n /** Project files whose own transform failed (membership unconfirmed subtree). */\n failedFiles: Set<string>;\n /** Total graph modules visited (project + deps + virtual). */\n visited: number;\n /** The deadline expired mid-walk — the result is truncated. */\n deadlineHit: boolean;\n}\n\n/**\n * Whether a graph node's file belongs in the report. `root` must be\n * slash-normalized; module-node paths already are (Vite normalizes\n * them, even on Windows — comparing against a backslashed root would\n * reject every physical module there and misreport the whole app as\n * pending). The rule set is the scan's own (isScannableSourceFile), so\n * report membership, disk-scan coverage, and the cache fingerprint are\n * one set — a graph-reachable file the fingerprint never tracked would\n * let its edits serve a stale cache (codex review, PR #1056).\n */\nfunction isProjectFile(file: string | null, root: string, extensions?: RegExp): file is string {\n if (!file) return false;\n return isScannableSourceFile(normalizePath(file), root, extensions);\n}\n\n/**\n * BFS one environment from the given seed URLs, transforming every\n * discovered module unconditionally. Transforming (rather than reading\n * live graphs) is what closes the §8 blind spot: modules behind\n * unexecuted dynamic imports are transformed here like any other edge.\n *\n * Exported for tests (deadline behavior is exercised with a fake env).\n */\nexport async function crawlEnvironment(\n env: CrawlEnvironment,\n envName: 'rsc' | 'ssr',\n seeds: string[],\n root: string,\n deadlineAt: number,\n errors: CrawlError[],\n extensions?: RegExp\n): Promise<EnvCrawlResult> {\n const queue = [...seeds];\n const enqueued = new Set(queue);\n const projectFiles = new Set<string>();\n const failedFiles = new Set<string>();\n let visited = 0;\n let deadlineHit = false;\n\n // Index-cursor BFS — the queue only grows, so this walks each entry once.\n for (let cursor = 0; cursor < queue.length; cursor++) {\n const url = queue[cursor];\n const remaining = deadlineAt - Date.now();\n if (remaining <= 0) {\n errors.push({ environment: envName, id: url, message: 'crawl deadline exceeded' });\n deadlineHit = true;\n break;\n }\n\n let node: CrawlModuleNode | undefined;\n try {\n await withDeadline(env.transformRequest(url), remaining, url);\n node = await env.moduleGraph.getModuleByUrl(url);\n } catch (error) {\n if (error instanceof CrawlDeadlineError) deadlineHit = true;\n errors.push({\n environment: envName,\n id: url,\n message: error instanceof Error ? error.message : String(error),\n });\n // The URL may still have a graph node with a file — it IS a graph\n // member (reachable), its transform just failed. Record membership\n // AND the failure so classification reports it as reachable with\n // subtreeUnknown, not as pending/unreferenced.\n node = await env.moduleGraph.getModuleByUrl(url).catch(() => undefined);\n if (node && isProjectFile(node.file, root, extensions)) {\n projectFiles.add(node.file);\n failedFiles.add(node.file);\n }\n continue;\n }\n\n if (!node) continue;\n visited++;\n if (isProjectFile(node.file, root, extensions)) projectFiles.add(node.file);\n\n for (const child of node.importedModules) {\n const childUrl = child.url ?? child.id;\n if (!childUrl || enqueued.has(childUrl)) continue;\n enqueued.add(childUrl);\n queue.push(childUrl);\n }\n }\n\n return { projectFiles, failedFiles, visited, deadlineHit };\n}\n\n/** Root-relative Vite URL for an absolute project file path.\n * Both arguments must be slash-normalized (the crawl normalizes at\n * the boundary, so callers always satisfy this). */\nfunction fileToUrl(file: string, root: string): string {\n return file.slice(root.length);\n}\n\n/** What one read of a module's original source yields. */\ninterface SourceFacts {\n directive: Directive;\n /** Import-specifier exclusivity signals (poison-scan). */\n signals: Poisoning[];\n}\n\n/**\n * Read a file's first directive and poison signals from its original\n * source on disk, in one read. A failure is recorded, not swallowed —\n * a lost 'use client' here would silently drop the whole client\n * subtree from the SSR crawl.\n */\nasync function sourceFactsOf(file: string, errors: CrawlError[]): Promise<SourceFacts> {\n try {\n const code = await readFile(file, 'utf8');\n return {\n directive: detectDirective(code, file),\n signals: importSignals(collectImportSpecifiers(code, file)),\n };\n } catch (error) {\n errors.push({\n environment: 'scan',\n id: file,\n message: `directive read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { directive: null, signals: [] };\n }\n}\n\n/**\n * Crawl a project cold and classify every project file.\n *\n * Boots a middleware-mode Vite server with the app's own config (all\n * timber plugins, real resolution), crawls the RSC graph from the entry,\n * detects directives from original sources, crawls the SSR graph from\n * every `'use client'` boundary, and intersects the memberships.\n */\nexport async function crawlProject(options: CrawlOptions): Promise<CrawlReport> {\n const startedAt = Date.now();\n const deadlineAt = startedAt + (options.timeoutMs ?? 120_000);\n // Signal platform dev plugins (wrangler bindings) to skip boot work the\n // crawl never uses. Must be set before createServer runs plugin hooks.\n process.env.TIMBER_ANALYZE = '1';\n\n const { createServer } = await import('vite');\n const server: ViteDevServer = await createServer({\n root: options.root,\n configFile: options.configFile,\n server: { middlewareMode: true, watch: null },\n logLevel: 'error',\n });\n\n try {\n // The root must live in the same path space as the graph nodes.\n // By default Vite resolves through symlinks, so nodes carry\n // realpaths and a symlinked root (pnpm workspaces, ~ links) would\n // string-mismatch every file and misclassify the whole project as\n // unreferenced (design/43 open question 3). Under\n // resolve.preserveSymlinks the graphs keep the SYMLINK paths, and\n // realpathing would create exactly the mismatch it normally\n // prevents — honor the resolved setting. Slash-normalize either\n // way: module-node paths are slash-normalized even on Windows.\n const root = normalizePath(\n server.config.resolve.preserveSymlinks\n ? server.config.root\n : await realpath(server.config.root)\n );\n // Structural assignment, no cast: CrawlEnvironment/CrawlModuleNode\n // are supertypes of Vite's DevEnvironment/EnvironmentModuleNode for\n // the members the BFS reads, so an upstream shape change fails here\n // at compile time instead of inside the walk.\n const rscEnv: CrawlEnvironment | undefined = server.environments.rsc;\n const ssrEnv: CrawlEnvironment | undefined = server.environments.ssr;\n if (!rscEnv?.transformRequest || !ssrEnv?.transformRequest) {\n throw new Error('[timber] crawl requires the rsc and ssr Vite environments');\n }\n\n const errors: CrawlError[] = [];\n\n // appDir and pageExtensions come from the booted server's own\n // resolved timber config (the root-sync plugin api — the single\n // supported way to read it; cf. cli-check.ts). Resolved before\n // Phase 1 so the scan extension set is available to isProjectFile\n // and scanProjectSourceFiles — custom pageExtensions must be\n // admitted throughout, or graph membership disagrees with the\n // disk scan and fingerprint (TIM-1392).\n const rootSyncPlugin = server.config.plugins.find((p) => p.name === 'timber-root-sync');\n let appDir: string;\n let pageExtensions: readonly string[] | undefined;\n if (rootSyncPlugin && isTimberPluginApi(rootSyncPlugin.api)) {\n const pluginCtx = rootSyncPlugin.api.getContext();\n appDir = pluginCtx.appDir;\n pageExtensions = pluginCtx.config.pageExtensions;\n } else {\n try {\n appDir = resolveAppDir(root);\n } catch {\n // No app directory at all — provisional convention hints just\n // never fire; graph-membership classification is unaffected.\n appDir = join(root, 'app');\n }\n }\n // Normalize once at the boundary: appDir comes from node:path\n // join() (backslashes on Windows) but all downstream comparisons\n // — classify, chains, isRouteRoot — expect slash-normalized paths.\n appDir = normalizePath(appDir);\n const extensions = buildSourceExtensions(pageExtensions);\n\n // Phase 1 — RSC graph from the entry.\n const rsc = await crawlEnvironment(\n rscEnv,\n 'rsc',\n [RSC_ENTRY_URL],\n root,\n deadlineAt,\n errors,\n extensions\n );\n\n // Phase 2 — directives + poison signals for everything discovered so\n // far plus files on disk that no graph reached (the provisional/\n // pending set). The disk walk is the same one the graph cache\n // fingerprints (scan.ts) so cache validity covers exactly this set.\n const diskFiles: string[] = [];\n await scanProjectSourceFiles(\n root,\n diskFiles,\n (failure) => errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n // One path space throughout: graph paths are already slash-\n // normalized, disk-walk paths are node-joined (backslashed on\n // Windows) — mixing them in one Set would duplicate every file.\n const allFiles = new Set([...rsc.projectFiles, ...diskFiles.map(normalizePath)]);\n const facts = new Map<string, SourceFacts>();\n for (const file of allFiles) {\n facts.set(file, await sourceFactsOf(file, errors));\n }\n\n // Phase 3 — SSR graph from every RSC-REACHABLE 'use client'\n // boundary. SSR renders exactly the tree the browser hydrates, so\n // this yields the client tree (boundaries plus everything they\n // transitively import). Disk-only boundaries are deliberately NOT\n // seeded: an unreferenced 'use client' file must keep its\n // provisional pending classification, not get promoted to a\n // confirmed boundary (and drag its imports in as client-internal)\n // by the act of analyzing it.\n const boundarySeeds = [...rsc.projectFiles]\n .filter((file) => facts.get(file)?.directive === 'use client')\n .map((file) => fileToUrl(file, root));\n const ssr = await crawlEnvironment(\n ssrEnv,\n 'ssr',\n boundarySeeds,\n root,\n deadlineAt,\n errors,\n extensions\n );\n\n // SSR-only discoveries (client-internal files) need facts too.\n for (const file of ssr.projectFiles) {\n if (!facts.has(file)) {\n facts.set(file, await sourceFactsOf(file, errors));\n allFiles.add(file);\n }\n }\n\n const classifications = classifyModules(\n [...allFiles].map((file) => ({\n file,\n inRsc: rsc.projectFiles.has(file),\n inSsr: ssr.projectFiles.has(file),\n // The crawl transforms unconditionally, so the untransformed\n // frontier only arises where the transform itself failed.\n ssrTransformed: ssr.projectFiles.has(file) ? !ssr.failedFiles.has(file) : undefined,\n directive: facts.get(file)?.directive ?? null,\n })),\n { appDir, pageExtensions }\n );\n\n // Phase 4 — chains, from the live graphs of the still-open server.\n // ChainGraph is a structural supertype of Vite's module graphs\n // (TIM-1382), so the assignment is cast-free and an upstream shape\n // change fails at compile time.\n const rscChainGraph: ChainGraph = server.environments.rsc.moduleGraph;\n const ssrChainGraph: ChainGraph = server.environments.ssr.moduleGraph;\n const chainCtx = {\n rsc: rscChainGraph,\n ssr: ssrChainGraph,\n appDir,\n pageExtensions,\n // facts keys are already slash-normalized (allFiles is built from\n // graph membership + diskFiles.map(normalizePath)), so no\n // per-lookup normalization is needed.\n getDirective: (file: string) => facts.get(file)?.directive ?? null,\n };\n\n const modules: GraphModuleReport[] = classifications.map((classification) => ({\n ...classification,\n boundary: facts.get(classification.file)?.directive === 'use client',\n chains: stitchImportChains(classification.file, chainCtx),\n poisonings: poisoningsFor(\n classification.kind,\n classification.pending,\n facts.get(classification.file)?.signals ?? []\n ),\n }));\n\n return {\n root,\n incomplete: rsc.deadlineHit || ssr.deadlineHit,\n modules,\n errors,\n stats: {\n rscGraphModules: rsc.visited,\n ssrGraphModules: ssr.visited,\n projectFiles: allFiles.size,\n durationMs: Date.now() - startedAt,\n },\n };\n } finally {\n // Bound the cleanup: after a deadline expiry the very transforms\n // that hung are what server.close() waits on — an unbounded await\n // here would hang the child past its own --timeout and the report\n // would never be emitted. The child's process.exit reaps whatever\n // close left behind.\n await Promise.race([\n server.close().catch(() => {}),\n new Promise<void>((resolveTimer) => setTimeout(resolveTimer, 5_000)),\n ]);\n }\n}\n","/**\n * crawl-entry — child-process entry point for the cold crawl.\n *\n * The crawl's memory footprint is transient but large (~1.3 GB RSS on\n * plugin-heavy apps — design/47 §6), so consumers spawn this module as a\n * short-lived child process instead of crawling in-process:\n *\n * node --import tsx/esm crawl-entry.ts --root <dir> [--config <file>]\n * [--out <file>] [--timeout <ms>]\n *\n * With `--out`, the JSON report is written to that file. Otherwise it is\n * printed to stdout after a marker line — plugins in the booted app may\n * write their own stdout noise, so consumers parse everything after the\n * marker, not the whole stream.\n */\n\nimport { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { crawlProject, CRAWL_RESULT_MARKER } from './crawl.ts';\n\nfunction readFlag(argv: string[], name: string): string | undefined {\n const index = argv.indexOf(name);\n return index !== -1 ? argv[index + 1] : undefined;\n}\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n const rootArg = readFlag(argv, '--root');\n if (!rootArg) {\n process.stderr.write('usage: crawl-entry --root <dir> [--config <file>] [--out <file>]\\n');\n process.exitCode = 2;\n return;\n }\n\n const timeoutArg = readFlag(argv, '--timeout');\n const report = await crawlProject({\n root: resolve(rootArg),\n configFile: readFlag(argv, '--config'),\n timeoutMs: timeoutArg ? Number(timeoutArg) : undefined,\n });\n\n const json = JSON.stringify(report);\n const outFile = readFlag(argv, '--out');\n if (outFile) {\n await writeFile(resolve(outFile), json);\n } else {\n // Await the flush: stdout to a pipe is async, and process.exit()\n // below does NOT flush pending pipe writes — a large report would\n // be truncated right after the marker.\n await new Promise<void>((resolveWrite, rejectWrite) => {\n process.stdout.write(`\\n${CRAWL_RESULT_MARKER}\\n${json}\\n`, (error) =>\n error ? rejectWrite(error) : resolveWrite()\n );\n });\n }\n}\n\nmain().then(\n () => {\n // The booted app's plugins may hold handles (watchers, sockets) past\n // server.close(); the crawl is a read-only child, so exit explicitly.\n process.exit(process.exitCode ?? 0);\n },\n (error) => {\n process.stderr.write(`[timber] crawl failed: ${error?.stack ?? String(error)}\\n`);\n process.exit(1);\n }\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,sBAAsB;;;;;AAiEnC,IAAM,qBAAN,cAAiC,MAAM,CAAC;;AAGxC,SAAS,aAAgB,SAAqB,aAAqB,OAA2B;CAC5F,OAAO,IAAI,SAAY,gBAAgB,kBAAkB;EACvD,MA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CACrE,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;AC/dA,SAAS,SAAS,MAAgB,MAAkC;CAClE,MAAM,QAAQ,KAAK,QAAQ,IAAI;CAC/B,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,KAAA;AAC1C;AAEA,eAAe,OAAsB;CACnC,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;CACjC,MAAM,UAAU,SAAS,MAAM,QAAQ;CACvC,IAAI,CAAC,SAAS;EACZ,QAAQ,OAAO,MAAM,oEAAoE;EACzF,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,aAAa,SAAS,MAAM,WAAW;CAC7C,MAAM,SAAS,MAAM,aAAa;EAChC,MAAM,QAAQ,OAAO;EACrB,YAAY,SAAS,MAAM,UAAU;EACrC,WAAW,aAAa,OAAO,UAAU,IAAI,KAAA;CAC/C,CAAC;CAED,MAAM,OAAO,KAAK,UAAU,MAAM;CAClC,MAAM,UAAU,SAAS,MAAM,OAAO;CACtC,IAAI,SACF,MAAM,UAAU,QAAQ,OAAO,GAAG,IAAI;MAKtC,MAAM,IAAI,SAAe,cAAc,gBAAgB;EACrD,QAAQ,OAAO,MAAM,KAAK,oBAAoB,IAAI,KAAK,MAAM,UAC3D,QAAQ,YAAY,KAAK,IAAI,aAAa,CAC5C;CACF,CAAC;AAEL;AAEA,KAAK,CAAC,CAAC,WACC;CAGJ,QAAQ,KAAK,QAAQ,YAAY,CAAC;AACpC,IACC,UAAU;CACT,QAAQ,OAAO,MAAM,0BAA0B,OAAO,SAAS,OAAO,KAAK,EAAE,GAAG;CAChF,QAAQ,KAAK,CAAC;AAChB,CACF"}
|
|
1
|
+
{"version":3,"file":"crawl-entry.js","names":[],"sources":["../../src/analyze/crawl.ts","../../src/analyze/crawl-entry.ts"],"sourcesContent":["/**\n * crawl — programmatic middleware-mode crawl (the cold path).\n *\n * Boots `createServer({ middlewareMode: true })` — no HTTP port, no route\n * rendering — and BFS-walks `env.transformRequest(url)` → importedModules\n * edges from `virtual:timber-rsc-entry`, then from every discovered\n * `'use client'` boundary through the SSR environment. This reuses Vite's\n * actual resolution (aliases, tsconfig paths, react-server export\n * conditions, virtual modules), so it cannot drift from what dev or the\n * build does; hand-rolled resolution was evaluated and rejected\n * (design/47 §\"Verified Prototype Findings\").\n *\n * Cost model (design/47 §6): 2.5 s on small apps to ~10 s on dep-heavy\n * plugin stacks, with a transient ~1.3 GB RSS — callers MUST run this in\n * a short-lived child process (see crawl-entry.ts) and cache the\n * classification output, not the Vite transforms. The crawl always\n * covers the full project: one crawl per project state, never per\n * question — marginal per-file cost is ~zero once booted.\n *\n * `TIMBER_ANALYZE=1` is set before the server boots so platform dev\n * plugins (wrangler bindings — a measured ~6.8 s remote-bindings\n * handshake on website) skip work the crawl never needs: classification\n * wants import edges, not live Cloudflare connections.\n *\n * Design docs: 47-module-environment-tooling.md §6, §8.\n */\n\nimport { readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { normalizePath } from 'vite';\nimport {\n classifyModules,\n detectDirective,\n type Directive,\n type ModuleClassification,\n} from './classify.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, isScannableSourceFile } from './scan.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { isTimberPluginApi, resolveAppDir } from '../plugin-context.ts';\n\nconst RSC_ENTRY_URL = 'virtual:timber-rsc-entry';\n\n/**\n * Marker preceding the JSON report on crawl-entry's stdout. Lives here\n * (not in crawl-entry.ts) so consumers can import it without executing\n * the child entry's main().\n */\nexport const CRAWL_RESULT_MARKER = '__TIMBER_CRAWL_RESULT__';\n\nexport interface CrawlOptions {\n /** Project root (the app directory containing vite.config). */\n root: string;\n /** Explicit Vite config file; discovered from root when omitted. */\n configFile?: string;\n /** Overall crawl deadline. Default 120s. */\n timeoutMs?: number;\n}\n\nexport interface CrawlError {\n /** 'scan' covers disk-scan and directive-read failures. */\n environment: 'rsc' | 'ssr' | 'scan';\n id: string;\n message: string;\n}\n\n/**\n * One project file's full graph answer — the classification plus the\n * remaining JSON-contract fields (`boundary`, `chains`, `poisonings`)\n * that need the open graphs / original sources to compute. This is the\n * per-module unit `timber graph` caches and serves.\n */\nexport interface GraphModuleReport extends ModuleClassification {\n /** True when the file itself carries `'use client'`. */\n boundary: boolean;\n /** Boundary-aware import chains (design/47 §7); [] when in no graph. */\n chains: ImportChain[];\n /** Report-only poisoning conflicts (design/47 §3); [] when clean. */\n poisonings: Poisoning[];\n}\n\nexport interface CrawlReport {\n root: string;\n /**\n * True when the crawl deadline expired mid-walk — the report is\n * truncated, not wrong, and the condition is transient (a slow\n * machine, a cold dep-optimizer). Consumers must not cache an\n * incomplete report: with unchanged files it would be served forever,\n * never retrying after the transient cause cleared. Deterministic\n * per-module transform failures do NOT set this — they recur on\n * retry, so caching them is correct.\n */\n incomplete: boolean;\n /** Classification of every project file, sorted by path. */\n modules: GraphModuleReport[];\n /**\n * Transform failures encountered during the BFS. These are classified,\n * not swallowed — CSS/asset URLs and non-transformable modules land\n * here (44 on website in the §6 measurement) and the crawl continues.\n */\n errors: CrawlError[];\n stats: {\n rscGraphModules: number;\n ssrGraphModules: number;\n projectFiles: number;\n durationMs: number;\n };\n}\n\n/** Marker error for deadline expiry — structurally distinguishable\n * from a deterministic transform failure (consumers must not cache a\n * deadline-truncated report; a transform failure recurs on retry and\n * caches fine). */\nclass CrawlDeadlineError extends Error {}\n\n/** Race a promise against the crawl deadline. */\nfunction withDeadline<T>(promise: Promise<T>, remainingMs: number, label: string): Promise<T> {\n return new Promise<T>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(\n () =>\n rejectPromise(\n new CrawlDeadlineError(`crawl deadline exceeded while transforming ${label}`)\n ),\n Math.max(remainingMs, 1)\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (error) => {\n clearTimeout(timer);\n rejectPromise(error);\n }\n );\n });\n}\n\n/** Duck-typed view of the Vite dev environment surface the crawl uses. */\nexport interface CrawlEnvironment {\n transformRequest(url: string): Promise<unknown>;\n moduleGraph: {\n getModuleByUrl(url: string): Promise<CrawlModuleNode | undefined>;\n };\n}\n\ninterface CrawlModuleNode {\n id: string | null;\n url: string;\n file: string | null;\n importedModules: Set<CrawlModuleNode>;\n transformResult: unknown;\n}\n\ninterface EnvCrawlResult {\n /** Absolute paths of project files reached in this environment. */\n projectFiles: Set<string>;\n /** Project files whose own transform failed (membership unconfirmed subtree). */\n failedFiles: Set<string>;\n /** Total graph modules visited (project + deps + virtual). */\n visited: number;\n /** The deadline expired mid-walk — the result is truncated. */\n deadlineHit: boolean;\n}\n\n/**\n * Whether a graph node's file belongs in the report. `root` must be\n * slash-normalized; module-node paths already are (Vite normalizes\n * them, even on Windows — comparing against a backslashed root would\n * reject every physical module there and misreport the whole app as\n * pending). The rule set is the scan's own (isScannableSourceFile), so\n * report membership, disk-scan coverage, and the cache fingerprint are\n * one set — a graph-reachable file the fingerprint never tracked would\n * let its edits serve a stale cache (codex review, PR #1056).\n */\nfunction isProjectFile(file: string | null, root: string, extensions?: RegExp): file is string {\n if (!file) return false;\n return isScannableSourceFile(normalizePath(file), root, extensions);\n}\n\n/**\n * BFS one environment from the given seed URLs, transforming every\n * discovered module unconditionally. Transforming (rather than reading\n * live graphs) is what closes the §8 blind spot: modules behind\n * unexecuted dynamic imports are transformed here like any other edge.\n *\n * Exported for tests (deadline behavior is exercised with a fake env).\n */\nexport async function crawlEnvironment(\n env: CrawlEnvironment,\n envName: 'rsc' | 'ssr',\n seeds: string[],\n root: string,\n deadlineAt: number,\n errors: CrawlError[],\n extensions?: RegExp\n): Promise<EnvCrawlResult> {\n const queue = [...seeds];\n const enqueued = new Set(queue);\n const projectFiles = new Set<string>();\n const failedFiles = new Set<string>();\n let visited = 0;\n let deadlineHit = false;\n\n // Index-cursor BFS — the queue only grows, so this walks each entry once.\n for (let cursor = 0; cursor < queue.length; cursor++) {\n const url = queue[cursor];\n const remaining = deadlineAt - Date.now();\n if (remaining <= 0) {\n errors.push({ environment: envName, id: url, message: 'crawl deadline exceeded' });\n deadlineHit = true;\n break;\n }\n\n let node: CrawlModuleNode | undefined;\n try {\n await withDeadline(env.transformRequest(url), remaining, url);\n node = await env.moduleGraph.getModuleByUrl(url);\n } catch (error) {\n if (error instanceof CrawlDeadlineError) deadlineHit = true;\n errors.push({\n environment: envName,\n id: url,\n message: error instanceof Error ? error.message : String(error),\n });\n // The URL may still have a graph node with a file — it IS a graph\n // member (reachable), its transform just failed. Record membership\n // AND the failure so classification reports it as reachable with\n // subtreeUnknown, not as pending/unreferenced.\n node = await env.moduleGraph.getModuleByUrl(url).catch(() => undefined);\n if (node && isProjectFile(node.file, root, extensions)) {\n projectFiles.add(node.file);\n failedFiles.add(node.file);\n }\n continue;\n }\n\n if (!node) continue;\n visited++;\n if (isProjectFile(node.file, root, extensions)) projectFiles.add(node.file);\n\n for (const child of node.importedModules) {\n const childUrl = child.url ?? child.id;\n if (!childUrl || enqueued.has(childUrl)) continue;\n enqueued.add(childUrl);\n queue.push(childUrl);\n }\n }\n\n return { projectFiles, failedFiles, visited, deadlineHit };\n}\n\n/** Root-relative Vite URL for an absolute project file path.\n * Both arguments must be slash-normalized (the crawl normalizes at\n * the boundary, so callers always satisfy this). */\nfunction fileToUrl(file: string, root: string): string {\n return file.slice(root.length);\n}\n\n/** What one read of a module's original source yields. */\ninterface SourceFacts {\n directive: Directive;\n /** Import-specifier exclusivity signals (poison-scan). */\n signals: Poisoning[];\n}\n\n/**\n * Read a file's first directive and poison signals from its original\n * source on disk, in one read. A failure is recorded, not swallowed —\n * a lost 'use client' here would silently drop the whole client\n * subtree from the SSR crawl.\n */\nasync function sourceFactsOf(file: string, errors: CrawlError[]): Promise<SourceFacts> {\n try {\n const code = await readFile(file, 'utf8');\n return {\n directive: detectDirective(code, file),\n signals: importSignals(collectImportSpecifiers(code, file)),\n };\n } catch (error) {\n errors.push({\n environment: 'scan',\n id: file,\n message: `directive read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { directive: null, signals: [] };\n }\n}\n\n/**\n * Crawl a project cold and classify every project file.\n *\n * Boots a middleware-mode Vite server with the app's own config (all\n * timber plugins, real resolution), crawls the RSC graph from the entry,\n * detects directives from original sources, crawls the SSR graph from\n * every `'use client'` boundary, and intersects the memberships.\n */\nexport async function crawlProject(options: CrawlOptions): Promise<CrawlReport> {\n const startedAt = Date.now();\n const deadlineAt = startedAt + (options.timeoutMs ?? 120_000);\n // Signal platform dev plugins (wrangler bindings) to skip boot work the\n // crawl never uses. Must be set before createServer runs plugin hooks.\n process.env.TIMBER_ANALYZE = '1';\n\n const { createServer } = await import('vite');\n const server: ViteDevServer = await createServer({\n root: options.root,\n configFile: options.configFile,\n server: { middlewareMode: true, watch: null },\n logLevel: 'error',\n });\n\n try {\n // The root must live in the same path space as the graph nodes.\n // By default Vite resolves through symlinks, so nodes carry\n // realpaths and a symlinked root (pnpm workspaces, ~ links) would\n // string-mismatch every file and misclassify the whole project as\n // unreferenced (design/43 open question 3). Under\n // resolve.preserveSymlinks the graphs keep the SYMLINK paths, and\n // realpathing would create exactly the mismatch it normally\n // prevents — honor the resolved setting. Slash-normalize either\n // way: module-node paths are slash-normalized even on Windows.\n const root = normalizePath(\n server.config.resolve.preserveSymlinks\n ? server.config.root\n : await realpath(server.config.root)\n );\n // Structural assignment, no cast: CrawlEnvironment/CrawlModuleNode\n // are supertypes of Vite's DevEnvironment/EnvironmentModuleNode for\n // the members the BFS reads, so an upstream shape change fails here\n // at compile time instead of inside the walk.\n const rscEnv: CrawlEnvironment | undefined = server.environments.rsc;\n const ssrEnv: CrawlEnvironment | undefined = server.environments.ssr;\n if (!rscEnv?.transformRequest || !ssrEnv?.transformRequest) {\n throw new Error('[timber] crawl requires the rsc and ssr Vite environments');\n }\n\n const errors: CrawlError[] = [];\n\n // appDir and pageExtensions come from the booted server's own\n // resolved timber config (the root-sync plugin api — the single\n // supported way to read it; cf. cli-check.ts). Resolved before\n // Phase 1 so the scan extension set is available to isProjectFile\n // and scanProjectSourceFiles — custom pageExtensions must be\n // admitted throughout, or graph membership disagrees with the\n // disk scan and fingerprint (TIM-1392).\n const rootSyncPlugin = server.config.plugins.find((p) => p.name === 'timber-root-sync');\n let appDir: string;\n let pageExtensions: readonly string[] | undefined;\n if (rootSyncPlugin && isTimberPluginApi(rootSyncPlugin.api)) {\n const pluginCtx = rootSyncPlugin.api.getContext();\n appDir = pluginCtx.appDir;\n pageExtensions = pluginCtx.config.pageExtensions;\n } else {\n try {\n appDir = resolveAppDir(root);\n } catch {\n // No app directory at all — provisional convention hints just\n // never fire; graph-membership classification is unaffected.\n appDir = join(root, 'app');\n }\n }\n // Normalize once at the boundary: appDir comes from node:path\n // join() (backslashes on Windows) but all downstream comparisons\n // — classify, chains, isRouteRoot — expect slash-normalized paths.\n appDir = normalizePath(appDir);\n const extensions = buildSourceExtensions(pageExtensions);\n\n // Phase 1 — RSC graph from the entry.\n const rsc = await crawlEnvironment(\n rscEnv,\n 'rsc',\n [RSC_ENTRY_URL],\n root,\n deadlineAt,\n errors,\n extensions\n );\n\n // Phase 2 — directives + poison signals for everything discovered so\n // far plus files on disk that no graph reached (the provisional/\n // pending set). The disk walk is the same one the graph cache\n // fingerprints (scan.ts) so cache validity covers exactly this set.\n const diskFiles: string[] = [];\n await scanProjectSourceFiles(\n root,\n diskFiles,\n (failure) => errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n // One path space throughout: graph paths are already slash-\n // normalized, disk-walk paths are node-joined (backslashed on\n // Windows) — mixing them in one Set would duplicate every file.\n const allFiles = new Set([...rsc.projectFiles, ...diskFiles.map(normalizePath)]);\n const facts = new Map<string, SourceFacts>();\n for (const file of allFiles) {\n facts.set(file, await sourceFactsOf(file, errors));\n }\n\n // Phase 3 — SSR graph from every RSC-REACHABLE 'use client'\n // boundary. SSR renders exactly the tree the browser hydrates, so\n // this yields the client tree (boundaries plus everything they\n // transitively import). Disk-only boundaries are deliberately NOT\n // seeded: an unreferenced 'use client' file must keep its\n // provisional pending classification, not get promoted to a\n // confirmed boundary (and drag its imports in as client-internal)\n // by the act of analyzing it.\n const boundarySeeds = [...rsc.projectFiles]\n .filter((file) => facts.get(file)?.directive === 'use client')\n .map((file) => fileToUrl(file, root));\n const ssr = await crawlEnvironment(\n ssrEnv,\n 'ssr',\n boundarySeeds,\n root,\n deadlineAt,\n errors,\n extensions\n );\n\n // SSR-only discoveries (client-internal files) need facts too.\n for (const file of ssr.projectFiles) {\n if (!facts.has(file)) {\n facts.set(file, await sourceFactsOf(file, errors));\n allFiles.add(file);\n }\n }\n\n const classifications = classifyModules(\n [...allFiles].map((file) => ({\n file,\n inRsc: rsc.projectFiles.has(file),\n inSsr: ssr.projectFiles.has(file),\n // The crawl transforms unconditionally, so the untransformed\n // frontier only arises where the transform itself failed.\n ssrTransformed: ssr.projectFiles.has(file) ? !ssr.failedFiles.has(file) : undefined,\n directive: facts.get(file)?.directive ?? null,\n })),\n { appDir, pageExtensions }\n );\n\n // Phase 4 — chains, from the live graphs of the still-open server.\n // ChainGraph is a structural supertype of Vite's module graphs\n // (TIM-1382), so the assignment is cast-free and an upstream shape\n // change fails at compile time.\n const rscChainGraph: ChainGraph = server.environments.rsc.moduleGraph;\n const ssrChainGraph: ChainGraph = server.environments.ssr.moduleGraph;\n const chainCtx = {\n rsc: rscChainGraph,\n ssr: ssrChainGraph,\n appDir,\n pageExtensions,\n // facts keys are already slash-normalized (allFiles is built from\n // graph membership + diskFiles.map(normalizePath)), so no\n // per-lookup normalization is needed.\n getDirective: (file: string) => facts.get(file)?.directive ?? null,\n };\n\n const modules: GraphModuleReport[] = classifications.map((classification) => ({\n ...classification,\n boundary: facts.get(classification.file)?.directive === 'use client',\n chains: stitchImportChains(classification.file, chainCtx),\n poisonings: poisoningsFor(\n classification.kind,\n classification.pending,\n facts.get(classification.file)?.signals ?? []\n ),\n }));\n\n return {\n root,\n incomplete: rsc.deadlineHit || ssr.deadlineHit,\n modules,\n errors,\n stats: {\n rscGraphModules: rsc.visited,\n ssrGraphModules: ssr.visited,\n projectFiles: allFiles.size,\n durationMs: Date.now() - startedAt,\n },\n };\n } finally {\n // Bound the cleanup: after a deadline expiry the very transforms\n // that hung are what server.close() waits on — an unbounded await\n // here would hang the child past its own --timeout and the report\n // would never be emitted. The child's process.exit reaps whatever\n // close left behind.\n await Promise.race([\n server.close().catch(() => {}),\n new Promise<void>((resolveTimer) => setTimeout(resolveTimer, 5_000)),\n ]);\n }\n}\n","/**\n * crawl-entry — child-process entry point for the cold crawl.\n *\n * The crawl's memory footprint is transient but large (~1.3 GB RSS on\n * plugin-heavy apps — design/47 §6), so consumers spawn this module as a\n * short-lived child process instead of crawling in-process:\n *\n * node --import tsx/esm crawl-entry.ts --root <dir> [--config <file>]\n * [--out <file>] [--timeout <ms>]\n *\n * With `--out`, the JSON report is written to that file. Otherwise it is\n * printed to stdout after a marker line — plugins in the booted app may\n * write their own stdout noise, so consumers parse everything after the\n * marker, not the whole stream.\n */\n\nimport { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { crawlProject, CRAWL_RESULT_MARKER } from './crawl.ts';\n\nfunction readFlag(argv: string[], name: string): string | undefined {\n const index = argv.indexOf(name);\n return index !== -1 ? argv[index + 1] : undefined;\n}\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n const rootArg = readFlag(argv, '--root');\n if (!rootArg) {\n process.stderr.write('usage: crawl-entry --root <dir> [--config <file>] [--out <file>]\\n');\n process.exitCode = 2;\n return;\n }\n\n const timeoutArg = readFlag(argv, '--timeout');\n const report = await crawlProject({\n root: resolve(rootArg),\n configFile: readFlag(argv, '--config'),\n timeoutMs: timeoutArg ? Number(timeoutArg) : undefined,\n });\n\n const json = JSON.stringify(report);\n const outFile = readFlag(argv, '--out');\n if (outFile) {\n await writeFile(resolve(outFile), json);\n } else {\n // Await the flush: stdout to a pipe is async, and process.exit()\n // below does NOT flush pending pipe writes — a large report would\n // be truncated right after the marker.\n await new Promise<void>((resolveWrite, rejectWrite) => {\n process.stdout.write(`\\n${CRAWL_RESULT_MARKER}\\n${json}\\n`, (error) =>\n error ? rejectWrite(error) : resolveWrite()\n );\n });\n }\n}\n\nmain().then(\n () => {\n // The booted app's plugins may hold handles (watchers, sockets) past\n // server.close(); the crawl is a read-only child, so exit explicitly.\n process.exit(process.exitCode ?? 0);\n },\n (error) => {\n process.stderr.write(`[timber] crawl failed: ${error?.stack ?? String(error)}\\n`);\n process.exit(1);\n }\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,sBAAsB;;;;;AAiEnC,IAAM,qBAAN,cAAiC,MAAM,CAAC;;AAGxC,SAAS,aAAgB,SAAqB,aAAqB,OAA2B;CAC5F,OAAO,IAAI,SAAY,gBAAgB,kBAAkB;EACvD,MAAM,QAAQ,iBAEV,cACE,IAAI,mBAAmB,8CAA8C,OAAO,CAC9E,GACF,KAAK,IAAI,aAAa,CAAC,CACzB;EACA,QAAQ,MACL,UAAU;GACT,aAAa,KAAK;GAClB,eAAe,KAAK;EACtB,IACC,UAAU;GACT,aAAa,KAAK;GAClB,cAAc,KAAK;EACrB,CACF;CACF,CAAC;AACH;;;;;;;;;;;AAuCA,SAAS,cAAc,MAAqB,MAAc,YAAqC;CAC7F,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,sBAAsB,cAAc,IAAI,GAAG,MAAM,UAAU;AACpE;;;;;;;;;AAUA,eAAsB,iBACpB,KACA,SACA,OACA,MACA,YACA,QACA,YACyB;CACzB,MAAM,QAAQ,CAAC,GAAG,KAAK;CACvB,MAAM,WAAW,IAAI,IAAI,KAAK;CAC9B,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,8BAAc,IAAI,IAAY;CACpC,IAAI,UAAU;CACd,IAAI,cAAc;CAGlB,KAAK,I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ACF,MAAM,UAAU,QAAQ,OAAO,GAAG,IAAI;MAKtC,MAAM,IAAI,SAAe,cAAc,gBAAgB;EACrD,QAAQ,OAAO,MAAM,KAAK,oBAAoB,IAAI,KAAK,MAAM,UAC3D,QAAQ,YAAY,KAAK,IAAI,aAAa,CAC5C;CACF,CAAC;AAEL;AAEA,KAAK,CAAC,CAAC,WACC;CAGJ,QAAQ,KAAK,QAAQ,YAAY,CAAC;AACpC,IACC,UAAU;CACT,QAAQ,OAAO,MAAM,0BAA0B,OAAO,SAAS,OAAO,KAAK,EAAE,GAAG;CAChF,QAAQ,KAAK,CAAC;AAChB,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-command.d.ts","sourceRoot":"","sources":["../../src/analyze/graph-command.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;
|
|
1
|
+
{"version":3,"file":"graph-command.d.ts","sourceRoot":"","sources":["../../src/analyze/graph-command.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AA0BH,MAAM,MAAM,WAAW,GAAG,YAAY,GAAG,aAAa,CAAC;AAoBvD,MAAM,WAAW,YAAY;IAC3B,0CAA0C;IAC1C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,GAAG,EAAE,OAAO,CAAC;CACd;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAWpE;AAgbD;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CA6HnE"}
|