@timber-js/app 0.2.0-alpha.221 → 0.2.0-alpha.223
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent-skill.md +21 -5
- package/dist/_chunks/{actions-BDqn4Oxj.js → actions-7dTXYJfu.js} +53 -24
- package/dist/_chunks/actions-7dTXYJfu.js.map +1 -0
- package/dist/_chunks/{als-registry-BZqHCtq-.js → als-registry-DpygwCp0.js} +2 -3
- package/dist/_chunks/{als-registry-BZqHCtq-.js.map → als-registry-DpygwCp0.js.map} +1 -1
- package/dist/_chunks/{als-slots-BEEIPKYm.js → als-slots-kbQrHTzm.js} +2 -3
- package/dist/_chunks/{als-slots-BEEIPKYm.js.map → als-slots-kbQrHTzm.js.map} +1 -1
- package/dist/_chunks/{base-path-DaQrzbez.js → base-path-DDIx0FXe.js} +2 -3
- package/dist/_chunks/{base-path-DaQrzbez.js.map → base-path-DDIx0FXe.js.map} +1 -1
- package/dist/_chunks/{build-manifest-DWppEdLB.js → build-manifest-Y4jl7nwU.js} +2 -3
- package/dist/_chunks/{build-manifest-DWppEdLB.js.map → build-manifest-Y4jl7nwU.js.map} +1 -1
- package/dist/_chunks/{build-output-helper-RV_BRcF1.js → build-output-helper-B7wWGTfR.js} +14 -10
- package/dist/_chunks/build-output-helper-B7wWGTfR.js.map +1 -0
- package/dist/_chunks/{cache-api-GE4AOe2H.js → cache-api-TDZ4hlDc.js} +237 -37
- package/dist/_chunks/cache-api-TDZ4hlDc.js.map +1 -0
- package/dist/_chunks/{canonicalize-BAWkWiKK.js → canonicalize-CqK135BN.js} +29 -4
- package/dist/_chunks/{canonicalize-BAWkWiKK.js.map → canonicalize-CqK135BN.js.map} +1 -1
- package/dist/_chunks/chains-CwOr3Myj.js +1 -0
- package/dist/_chunks/{chains-e_Buf9vg.js → chains-Dgm3PrMe.js} +3 -4
- package/dist/_chunks/{chains-e_Buf9vg.js.map → chains-Dgm3PrMe.js.map} +1 -1
- package/dist/_chunks/{classify-2Yp3xJY1.js → classify--_kINHQV.js} +4 -5
- package/dist/_chunks/{classify-2Yp3xJY1.js.map → classify--_kINHQV.js.map} +1 -1
- package/dist/_chunks/{cli-check-DDwCkeDY.js → cli-check-Dv3f8d2j.js} +5 -6
- package/dist/_chunks/{cli-check-DDwCkeDY.js.map → cli-check-Dv3f8d2j.js.map} +1 -1
- package/dist/_chunks/{cli-context-_mPttGGY.js → cli-context-CbZp32SK.js} +3 -4
- package/dist/_chunks/{cli-context-_mPttGGY.js.map → cli-context-CbZp32SK.js.map} +1 -1
- package/dist/_chunks/cli-context-n5hmkdla.js +1 -0
- package/dist/_chunks/cli-dev-status-prPMLU8G.js +138 -0
- package/dist/_chunks/cli-dev-status-prPMLU8G.js.map +1 -0
- package/dist/_chunks/cli-init-BoXOYYil.js +196 -0
- package/dist/_chunks/cli-init-BoXOYYil.js.map +1 -0
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js → cli-schema-sync-DIPurq7X.js} +4 -5
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js.map → cli-schema-sync-DIPurq7X.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CLNfXQDK.js → cli-schema-sync-uq72EZmD.js} +1 -1
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js → client-dep-entries-CP7AkMCM.js} +4 -5
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js.map → client-dep-entries-CP7AkMCM.js.map} +1 -1
- package/dist/_chunks/{cloudflare-Byxl8FWP.js → cloudflare-B75X6u4O.js} +10 -13
- package/dist/_chunks/{cloudflare-Byxl8FWP.js.map → cloudflare-B75X6u4O.js.map} +1 -1
- package/dist/_chunks/{codec-registry-oOUxugz3.js → codec-registry-CPc6bjVl.js} +2 -3
- package/dist/_chunks/{codec-registry-oOUxugz3.js.map → codec-registry-CPc6bjVl.js.map} +1 -1
- package/dist/_chunks/{codegen-Bps1sLKJ.js → codegen-B9oWkWGf.js} +5 -8
- package/dist/_chunks/{codegen-Bps1sLKJ.js.map → codegen-B9oWkWGf.js.map} +1 -1
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js → convention-lint-hZwz5wd4.js} +8 -11
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js.map → convention-lint-hZwz5wd4.js.map} +1 -1
- package/dist/_chunks/dev-discovery-YnabkCKD.js +238 -0
- package/dist/_chunks/dev-discovery-YnabkCKD.js.map +1 -0
- package/dist/_chunks/{dev-server-DIy-SY-J.js → dev-server-C61GWpGg.js} +409 -51
- package/dist/_chunks/dev-server-C61GWpGg.js.map +1 -0
- package/dist/_chunks/dev-server-CBvvM7Lr.js +1 -0
- package/dist/_chunks/{dev-store-BOa304m_.js → dev-store-BvdqtHvK.js} +82 -38
- package/dist/_chunks/dev-store-BvdqtHvK.js.map +1 -0
- package/dist/_chunks/{dist-DtrJyBbw.js → dist-C1Rjlo6s.js} +3 -5
- package/dist/_chunks/{dist-DtrJyBbw.js.map → dist-C1Rjlo6s.js.map} +1 -1
- package/dist/_chunks/{error-boundary-Bc8QPZuq.js → error-boundary-DRQXGWCp.js} +20 -27
- package/dist/_chunks/{error-boundary-Bc8QPZuq.js.map → error-boundary-DRQXGWCp.js.map} +1 -1
- package/dist/_chunks/{fast-hash-C-tVYrLb.js → fast-hash-DddxkU5Y.js} +2 -3
- package/dist/_chunks/{fast-hash-C-tVYrLb.js.map → fast-hash-DddxkU5Y.js.map} +1 -1
- package/dist/_chunks/{flight-source-node-HptmGMT8.js → flight-source-node-0Tp6evlz.js} +6 -8
- package/dist/_chunks/flight-source-node-0Tp6evlz.js.map +1 -0
- package/dist/_chunks/{format-BKclgVbk.js → format-DuPOoXUP.js} +2 -3
- package/dist/_chunks/{format-BKclgVbk.js.map → format-DuPOoXUP.js.map} +1 -1
- package/dist/_chunks/{fs-identity-BRKuL215.js → fs-identity-BmQ_Agg-.js} +3 -5
- package/dist/_chunks/{fs-identity-BRKuL215.js.map → fs-identity-BmQ_Agg-.js.map} +1 -1
- package/dist/_chunks/global-context-DbxNWeBP.js +47 -0
- package/dist/_chunks/global-context-DbxNWeBP.js.map +1 -0
- package/dist/_chunks/{graph-cache-CYiUS2aS.js → graph-cache-B1LAg4t7.js} +5 -89
- package/dist/_chunks/graph-cache-B1LAg4t7.js.map +1 -0
- package/dist/_chunks/{href-validation-BIrxavIy.js → href-validation-CEZy1V-k.js} +4 -7
- package/dist/_chunks/{href-validation-BIrxavIy.js.map → href-validation-CEZy1V-k.js.map} +1 -1
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js → json-lossy-check-DVkLUlfC.js} +3 -4
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js.map → json-lossy-check-DVkLUlfC.js.map} +1 -1
- package/dist/_chunks/{live-graph-tSWrv8eH.js → live-graph-BcVjQ1Te.js} +6 -7
- package/dist/_chunks/{live-graph-tSWrv8eH.js.map → live-graph-BcVjQ1Te.js.map} +1 -1
- package/dist/_chunks/{logger-CbLdcy-W.js → logger-CWk44DLp.js} +97 -47
- package/dist/_chunks/logger-CWk44DLp.js.map +1 -0
- package/dist/_chunks/{metadata-routes-B3XJNyIH.js → metadata-routes-BL26HCDd.js} +2 -3
- package/dist/_chunks/{metadata-routes-B3XJNyIH.js.map → metadata-routes-BL26HCDd.js.map} +1 -1
- package/dist/_chunks/{navigation-root-BQfo1-kG.js → navigation-root-M3B2ZrdO.js} +6 -10
- package/dist/_chunks/{navigation-root-BQfo1-kG.js.map → navigation-root-M3B2ZrdO.js.map} +1 -1
- package/dist/_chunks/{node-response-rkQqcFGq.js → node-response-B9aviPDa.js} +43 -9
- package/dist/_chunks/node-response-B9aviPDa.js.map +1 -0
- package/dist/_chunks/{param-value-C8TNYchQ.js → param-value-DqlGfF57.js} +2 -3
- package/dist/_chunks/{param-value-C8TNYchQ.js.map → param-value-DqlGfF57.js.map} +1 -1
- package/dist/_chunks/{plugin-context-uDHFqHHJ.js → plugin-context-BfSRKJfz.js} +1 -1
- package/dist/_chunks/{plugin-context-DxMMvjUt.js → plugin-context-FCkaNLUB.js} +4 -6
- package/dist/_chunks/plugin-context-FCkaNLUB.js.map +1 -0
- package/dist/_chunks/{poison-rules-DoEhbqaY.js → poison-rules-Bmz-lCPi.js} +2 -3
- package/dist/_chunks/{poison-rules-DoEhbqaY.js.map → poison-rules-Bmz-lCPi.js.map} +1 -1
- package/dist/_chunks/{poison-scan-C4FgMxFl.js → poison-scan-DJYxZc_7.js} +4 -5
- package/dist/_chunks/{poison-scan-C4FgMxFl.js.map → poison-scan-DJYxZc_7.js.map} +1 -1
- package/dist/_chunks/{purge-store-WZaxu-3m.js → purge-store-8BqLAYZ1.js} +2 -3
- package/dist/_chunks/{purge-store-WZaxu-3m.js.map → purge-store-8BqLAYZ1.js.map} +1 -1
- package/dist/_chunks/{render-timeout-joFhz4KH.js → render-timeout-MrrqD1wd.js} +20 -4
- package/dist/_chunks/{render-timeout-joFhz4KH.js.map → render-timeout-MrrqD1wd.js.map} +1 -1
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js → resolve-schema-B-aCuTu3.js} +3 -4
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js.map → resolve-schema-B-aCuTu3.js.map} +1 -1
- package/dist/_chunks/{rsc-cache-key-ClUiXQnK.js → rsc-cache-key-D0cb0Gmc.js} +2 -3
- package/dist/_chunks/{rsc-cache-key-ClUiXQnK.js.map → rsc-cache-key-D0cb0Gmc.js.map} +1 -1
- package/dist/_chunks/{rsc-media-type-DDc7duTD.js → rsc-media-type-m8jz9u6_.js} +2 -3
- package/dist/_chunks/{rsc-media-type-DDc7duTD.js.map → rsc-media-type-m8jz9u6_.js.map} +1 -1
- package/dist/_chunks/{rsc-payload-path-dffcs4jp.js → rsc-payload-path-EphpDB-J.js} +2 -3
- package/dist/_chunks/{rsc-payload-path-dffcs4jp.js.map → rsc-payload-path-EphpDB-J.js.map} +1 -1
- package/dist/_chunks/{scan-BoP17W3w.js → scan-CyizcBiX.js} +2 -3
- package/dist/_chunks/{scan-BoP17W3w.js.map → scan-CyizcBiX.js.map} +1 -1
- package/dist/_chunks/{scanner-Cb3fSjAC.js → scanner-CJC-ScJU.js} +15 -23
- package/dist/_chunks/{scanner-Cb3fSjAC.js.map → scanner-CJC-ScJU.js.map} +1 -1
- package/dist/_chunks/{schema-bridge-C83xa9lT.js → schema-bridge-DyRs3cqy.js} +61 -25
- package/dist/_chunks/schema-bridge-DyRs3cqy.js.map +1 -0
- package/dist/_chunks/{segment-classify-C539Pa2O.js → segment-classify-Ho8jXWeC.js} +3 -5
- package/dist/_chunks/{segment-classify-C539Pa2O.js.map → segment-classify-Ho8jXWeC.js.map} +1 -1
- package/dist/_chunks/{segment-context-xtPUGfdq.js → segment-context-CYiGTi3K.js} +6 -12
- package/dist/_chunks/segment-context-CYiGTi3K.js.map +1 -0
- package/dist/_chunks/{segment-keys-D5hu1hz4.js → segment-keys-Y60KNc8C.js} +2 -3
- package/dist/_chunks/{segment-keys-D5hu1hz4.js.map → segment-keys-Y60KNc8C.js.map} +1 -1
- package/dist/_chunks/{singleflight-BeVMMKi0.js → singleflight-BChPMjwH.js} +2 -3
- package/dist/_chunks/{singleflight-BeVMMKi0.js.map → singleflight-BChPMjwH.js.map} +1 -1
- package/dist/_chunks/{sizeof-QPE5nd3u.js → sizeof-DG4W40lv.js} +3 -4
- package/dist/_chunks/{sizeof-QPE5nd3u.js.map → sizeof-DG4W40lv.js.map} +1 -1
- package/dist/_chunks/{ssr-data-nA3I70_n.js → ssr-data-9hPtcNOr.js} +3 -4
- package/dist/_chunks/{ssr-data-nA3I70_n.js.map → ssr-data-9hPtcNOr.js.map} +1 -1
- package/dist/_chunks/{state-BhNGPsdi.js → state-B-EBjeER.js} +2 -3
- package/dist/_chunks/{state-BhNGPsdi.js.map → state-B-EBjeER.js.map} +1 -1
- package/dist/_chunks/{status-page-marker-BRX9Ib-d.js → status-page-marker-XIQXlTOb.js} +8 -13
- package/dist/_chunks/{status-page-marker-BRX9Ib-d.js.map → status-page-marker-XIQXlTOb.js.map} +1 -1
- package/dist/_chunks/{tree-match-6yihorhk.js → tree-match-Bqdr9szG.js} +2 -3
- package/dist/_chunks/{tree-match-6yihorhk.js.map → tree-match-Bqdr9szG.js.map} +1 -1
- package/dist/_chunks/{use-query-states-I3JMng6J.js → use-query-states-pkDV-jSg.js} +4 -7
- package/dist/_chunks/{use-query-states-I3JMng6J.js.map → use-query-states-pkDV-jSg.js.map} +1 -1
- package/dist/_chunks/{walkers-qu8TpiLh.js → walkers-DIE203ir.js} +6 -8
- package/dist/_chunks/{walkers-qu8TpiLh.js.map → walkers-DIE203ir.js.map} +1 -1
- package/dist/_chunks/{write-file-atomic-D1qWqHb4.js → write-file-atomic-DW8m_Atv.js} +2 -3
- package/dist/_chunks/{write-file-atomic-D1qWqHb4.js.map → write-file-atomic-DW8m_Atv.js.map} +1 -1
- package/dist/adapters/build-output-helper.d.ts +10 -1
- package/dist/adapters/build-output-helper.d.ts.map +1 -1
- package/dist/adapters/cloudflare-dev.js +2 -3
- package/dist/adapters/cloudflare-kv-cache.js +3 -4
- package/dist/adapters/cloudflare.d.ts.map +1 -1
- package/dist/adapters/cloudflare.js +1 -1
- package/dist/adapters/nitro-presets.d.ts +6 -0
- package/dist/adapters/nitro-presets.d.ts.map +1 -1
- package/dist/adapters/nitro-preview.d.ts.map +1 -1
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +94 -57
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/crawl-entry.js +7 -9
- package/dist/analyze/crawl-entry.js.map +1 -1
- package/dist/analyze/graph-command.d.ts.map +1 -1
- package/dist/analyze/graph-command.js +19 -105
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/cache/guarded-read.d.ts +29 -0
- package/dist/cache/guarded-read.d.ts.map +1 -0
- package/dist/cache/index.js +3 -3
- package/dist/cache/key-discipline.d.ts +61 -0
- package/dist/cache/key-discipline.d.ts.map +1 -0
- package/dist/cache/stores/cloudflare-kv.js +1 -2
- package/dist/cache/stores/memory.js +2 -3
- package/dist/cache/stores/redis.js +1 -2
- package/dist/cache/stores/vercel.js +1 -2
- package/dist/cache/timber-cache.d.ts +5 -1
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/cdn/cloudflare-purge.js +1 -2
- package/dist/cdn/fastly-purge.js +1 -2
- package/dist/cdn/index.js +2 -3
- package/dist/cdn/workers-cache-purge.js +3 -5
- package/dist/cdn/workers-cache-purge.js.map +1 -1
- package/dist/cli-dev-status.d.ts +75 -0
- package/dist/cli-dev-status.d.ts.map +1 -0
- package/dist/cli-init.d.ts +72 -0
- package/dist/cli-init.d.ts.map +1 -0
- package/dist/cli.d.ts +4 -12
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +27 -54
- package/dist/cli.js.map +1 -1
- package/dist/client/error-boundary.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/global-context.d.ts +21 -1
- package/dist/client/global-context.d.ts.map +1 -1
- package/dist/client/index.js +23 -44
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +13 -18
- package/dist/client/internal.js.map +1 -1
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/params-context.d.ts.map +1 -1
- package/dist/client/slot-context.d.ts +2 -2
- package/dist/client/slot-context.d.ts.map +1 -1
- package/dist/client/use-cookie.d.ts +18 -5
- package/dist/client/use-cookie.d.ts.map +1 -1
- package/dist/codec.js +2 -3
- package/dist/config-types.d.ts +22 -5
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/cookies/define-cookie.d.ts.map +1 -1
- package/dist/cookies/index.js +40 -67
- package/dist/cookies/index.js.map +1 -1
- package/dist/cookies/json-cookie.d.ts +4 -4
- package/dist/index.js +266 -229
- package/dist/index.js.map +1 -1
- package/dist/params/index.js +3 -4
- package/dist/plugin-context.d.ts +7 -0
- package/dist/plugin-context.d.ts.map +1 -1
- package/dist/plugins/dev-discovery.d.ts +69 -5
- package/dist/plugins/dev-discovery.d.ts.map +1 -1
- package/dist/plugins/dev-hostname.d.ts +152 -0
- package/dist/plugins/dev-hostname.d.ts.map +1 -0
- package/dist/plugins/dev-server.d.ts +6 -2
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/dev-store-clear.d.ts +83 -0
- package/dist/plugins/dev-store-clear.d.ts.map +1 -0
- package/dist/plugins/graph-endpoint.d.ts +4 -2
- package/dist/plugins/graph-endpoint.d.ts.map +1 -1
- package/dist/plugins/prebuilt.d.ts.map +1 -1
- package/dist/routing/index.js +4 -4
- package/dist/rsc-runtime/rsc.d.ts +2 -1
- package/dist/rsc-runtime/rsc.d.ts.map +1 -1
- package/dist/rsc-runtime/server-references.d.ts +8 -0
- package/dist/rsc-runtime/server-references.d.ts.map +1 -0
- package/dist/schema-bridge.d.ts +28 -19
- package/dist/schema-bridge.d.ts.map +1 -1
- package/dist/search-params/define.d.ts +1 -1
- package/dist/search-params/define.d.ts.map +1 -1
- package/dist/search-params/index.js +11 -14
- package/dist/search-params/index.js.map +1 -1
- package/dist/search-params/wrappers.d.ts +3 -3
- package/dist/server/access-gate.d.ts +12 -0
- package/dist/server/access-gate.d.ts.map +1 -1
- package/dist/server/canonicalize.d.ts +21 -0
- package/dist/server/canonicalize.d.ts.map +1 -1
- package/dist/server/cookie-context.d.ts +8 -1
- package/dist/server/cookie-context.d.ts.map +1 -1
- package/dist/server/flight-source-node.d.ts.map +1 -1
- package/dist/server/flight-source.d.ts.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +8 -13
- package/dist/server/index.js.map +1 -1
- package/dist/server/interception-gates.d.ts +49 -0
- package/dist/server/interception-gates.d.ts.map +1 -0
- package/dist/server/internal.js +1080 -959
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +26 -0
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/param-coercion.d.ts +8 -0
- package/dist/server/param-coercion.d.ts.map +1 -1
- package/dist/server/pipeline-interception.d.ts +34 -4
- package/dist/server/pipeline-interception.d.ts.map +1 -1
- package/dist/server/pipeline-metadata-route.d.ts +24 -0
- package/dist/server/pipeline-metadata-route.d.ts.map +1 -0
- package/dist/server/pipeline-metadata.d.ts +3 -2
- package/dist/server/pipeline-metadata.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts +9 -3
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts +18 -0
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/prebuilt/dev-store.d.ts +68 -22
- package/dist/server/prebuilt/dev-store.d.ts.map +1 -1
- package/dist/server/prebuilt/overlay.d.ts +17 -3
- package/dist/server/prebuilt/overlay.d.ts.map +1 -1
- package/dist/server/prebuilt-runtime.d.ts.map +1 -1
- package/dist/server/primitives.d.ts +13 -0
- package/dist/server/primitives.d.ts.map +1 -1
- package/dist/server/render-utils.d.ts +21 -0
- package/dist/server/render-utils.d.ts.map +1 -1
- package/dist/server/request-context.d.ts +14 -0
- package/dist/server/request-context.d.ts.map +1 -1
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/route-handler.d.ts +7 -0
- package/dist/server/route-handler.d.ts.map +1 -1
- package/dist/server/route-matcher.d.ts +14 -3
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
- package/dist/server/signal-identity.d.ts +6 -0
- package/dist/server/signal-identity.d.ts.map +1 -1
- package/dist/server/traced-access.d.ts +18 -0
- package/dist/server/traced-access.d.ts.map +1 -0
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/server/types.d.ts +5 -4
- package/dist/server/types.d.ts.map +1 -1
- package/dist/shims/font-google.js +1 -2
- package/dist/shims/font-local.js +1 -2
- package/dist/shims/headers.d.ts +11 -4
- package/dist/shims/headers.d.ts.map +1 -1
- package/docs/api/30-api-server.mdx +3 -1
- package/docs/api/32-api-cache.mdx +1 -1
- package/docs/api/33-api-search-params.mdx +3 -1
- package/docs/api/34-api-config.mdx +22 -0
- package/docs/api/36-cli.mdx +72 -6
- package/docs/learn/01-quick-start.mdx +1 -1
- package/docs/learn/06-typed-params.mdx +4 -4
- package/docs/learn/10-caching.mdx +26 -5
- package/llms.txt +1 -1
- package/package.json +12 -12
- package/src/adapters/build-output-helper.ts +26 -4
- package/src/adapters/cloudflare.ts +1 -0
- package/src/adapters/nitro-presets.ts +15 -0
- package/src/adapters/nitro-preview.ts +66 -34
- package/src/adapters/nitro.ts +14 -6
- package/src/analyze/graph-command.ts +25 -133
- package/src/cache/guarded-read.ts +44 -0
- package/src/cache/key-discipline.ts +218 -0
- package/src/cache/timber-cache.ts +46 -7
- package/src/cli-dev-status.ts +196 -0
- package/src/cli-init.ts +278 -0
- package/src/cli.ts +33 -79
- package/src/client/error-boundary.tsx +19 -2
- package/src/client/global-context.ts +42 -14
- package/src/client/navigation-context.ts +4 -11
- package/src/client/params-context.ts +5 -17
- package/src/client/segment-update-context.ts +1 -1
- package/src/client/slot-content-cache-context.ts +1 -1
- package/src/client/slot-context.ts +6 -17
- package/src/client/use-cookie.ts +33 -21
- package/src/config-types.ts +22 -5
- package/src/config-validation.ts +17 -0
- package/src/cookies/define-cookie.ts +10 -46
- package/src/cookies/json-cookie.ts +4 -4
- package/src/plugin-context.ts +7 -0
- package/src/plugins/dev-discovery.ts +216 -6
- package/src/plugins/dev-hostname.ts +322 -0
- package/src/plugins/dev-server.ts +130 -37
- package/src/plugins/dev-store-clear.ts +145 -0
- package/src/plugins/graph-endpoint.ts +15 -3
- package/src/plugins/prebuilt.ts +9 -0
- package/src/rsc-runtime/rsc.ts +7 -3
- package/src/rsc-runtime/server-references.ts +73 -0
- package/src/rsc-runtime/vendor-types.d.ts +17 -0
- package/src/schema-bridge.ts +93 -38
- package/src/search-params/define.ts +5 -6
- package/src/search-params/wrappers.ts +3 -3
- package/src/server/access-gate.tsx +32 -20
- package/src/server/action-handler.ts +58 -36
- package/src/server/canonicalize.ts +27 -0
- package/src/server/cookie-context.ts +11 -3
- package/src/server/flight-source-node.ts +5 -2
- package/src/server/flight-source.ts +4 -3
- package/src/server/index.ts +6 -1
- package/src/server/interception-gates.ts +94 -0
- package/src/server/logger.ts +32 -0
- package/src/server/param-coercion.ts +22 -0
- package/src/server/pipeline-interception.ts +64 -4
- package/src/server/pipeline-metadata-route.ts +242 -0
- package/src/server/pipeline-metadata.ts +7 -5
- package/src/server/pipeline-phases.ts +71 -131
- package/src/server/pipeline.ts +20 -2
- package/src/server/prebuilt/dev-store.ts +113 -34
- package/src/server/prebuilt/overlay.ts +32 -4
- package/src/server/prebuilt-runtime.ts +63 -45
- package/src/server/primitives.ts +14 -0
- package/src/server/render-utils.ts +25 -0
- package/src/server/request-context.ts +27 -3
- package/src/server/route-element-builder.ts +15 -2
- package/src/server/route-handler.ts +3 -2
- package/src/server/route-matcher.ts +48 -33
- package/src/server/rsc-entry/api-handler.ts +2 -33
- package/src/server/rsc-entry/index.ts +8 -3
- package/src/server/rsc-entry/rsc-stream.ts +7 -1
- package/src/server/signal-identity.ts +30 -12
- package/src/server/traced-access.ts +50 -0
- package/src/server/tracing.ts +18 -1
- package/src/server/types.ts +5 -4
- package/src/shims/headers.ts +12 -4
- package/dist/_chunks/actions-BDqn4Oxj.js.map +0 -1
- package/dist/_chunks/build-output-helper-RV_BRcF1.js.map +0 -1
- package/dist/_chunks/cache-api-GE4AOe2H.js.map +0 -1
- package/dist/_chunks/chains-CDK1AWZQ.js +0 -1
- package/dist/_chunks/cli-context-BJQB6rtF.js +0 -1
- package/dist/_chunks/dev-server-BiWNMBVU.js +0 -1
- package/dist/_chunks/dev-server-DIy-SY-J.js.map +0 -1
- package/dist/_chunks/dev-store-BOa304m_.js.map +0 -1
- package/dist/_chunks/flight-source-node-HptmGMT8.js.map +0 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +0 -1
- package/dist/_chunks/logger-CbLdcy-W.js.map +0 -1
- package/dist/_chunks/node-response-rkQqcFGq.js.map +0 -1
- package/dist/_chunks/plugin-context-DxMMvjUt.js.map +0 -1
- package/dist/_chunks/schema-bridge-C83xa9lT.js.map +0 -1
- package/dist/_chunks/segment-context-xtPUGfdq.js.map +0 -1
- package/dist/server/prebuilt/key-discipline.d.ts +0 -52
- package/dist/server/prebuilt/key-discipline.d.ts.map +0 -1
- package/src/server/prebuilt/key-discipline.ts +0 -122
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-check-DDwCkeDY.js","names":[],"sources":["../../src/cli-check.ts"],"sourcesContent":["/**\n * `timber check` — the implementation behind the CLI command.\n *\n * Two passes, in order:\n *\n * 1. **Routes.** Resolve the project through Vite — so root, `appDir`, and\n * `pageExtensions` are the ones `timber build` uses, including config\n * passed inline to `timber()` — then scan, run the convention linter, and\n * write the route codegen (`.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts`, `timber-env.d.ts`).\n *\n * Codegen runs *before* the type pass on purpose: those\n * files are what give `<Link href>`, `useSegmentParams()` and\n * `MiddlewareContext` their per-route types (design/09-typescript.md\n * §\"Typed Routes\"), and they are build artifacts — a fresh clone that has\n * never run `timber dev` or `timber build` does not have them, so a type\n * pass on its own would report errors about correct code. A clone whose\n * routes changed since the last build has the same problem with stale ones.\n * 2. **Types.** `tsgo --noEmit` over the project.\n *\n * tsgo is spawned as `node <@typescript/native-preview>/lib/tsgo.js`, never as\n * a bare `tsgo` off PATH — the package is an *optional peer dependency*, so\n * there is no reason for its shim to be on a user's PATH, and the shim is a\n * `.cmd` on Windows which cannot be spawned without a shell. `shell: true`\n * would then concatenate the argv into an unescaped command string, so a\n * project path containing a space would break on exactly the platform the\n * shell was there to support. This mirrors `scripts/build-types.js`, whose\n * header comment is the specification for the pattern.\n *\n * Design docs: 11-platform.md §CLI, 09-typescript.md, 28-npm-packaging.md\n */\n\nimport { createRequire } from 'node:module';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport { lintConventions, formatConventionWarnings } from './routing/convention-lint.ts';\nimport { writeRouteCodegen, CODEGEN_OUTPUT, ENV_DTS_FILENAME } from './routing/codegen-write.ts';\nimport { resolveTimberContext, type ResolveViteConfig } from './cli-context.ts';\n\n/** The npm package that provides tsgo. Named in the missing-tool message. */\nconst TSGO_PACKAGE = '@typescript/native-preview';\n\n/**\n * The two generated declaration paths, relative to the project root, as they\n * appear in a resolved tsconfig file list. Derived from the writer's own\n * constants — a rename there cannot leave this check hunting for a file nothing\n * writes.\n */\nconst GENERATED_TYPE_PATHS = [ENV_DTS_FILENAME, CODEGEN_OUTPUT];\n\n/**\n * Run the compiler to completion.\n *\n * Resolves with its exit status (`null` when a signal killed it) and rejects\n * only when the process could not be started — the two outcomes `runTypeCheck`\n * has to keep apart. The seam is this narrow on purpose: a test double is a\n * plain async function, with no `ChildProcess` shape to imitate.\n */\nexport type RunTsgo = (command: string, args: string[], cwd: string) => Promise<number | null>;\n\n/**\n * Run the compiler and capture its stdout — used for `--showConfig`, whose\n * output is data we read rather than diagnostics the user reads.\n */\nexport type ReadTsgoConfig = (command: string, args: string[], cwd: string) => Promise<string>;\n\n/** @internal Dependency injection for testing. */\nexport interface CheckDeps {\n /**\n * Resolve tsgo's own JS entry point. Throws when the package is not\n * installed — the caller turns that into an install instruction.\n */\n resolveTsgoEntry?: () => string;\n runTsgo?: RunTsgo;\n readTsgoConfig?: ReadTsgoConfig;\n resolveViteConfig?: ResolveViteConfig;\n}\n\nexport interface CheckOptions {\n /** Project root, for resolving tsgo. Defaults to `process.cwd()`. */\n root?: string;\n /**\n * Path to a **tsconfig**, forwarded to tsgo as `--project` and sourced from\n * the CLI's own `--project`. The route pass takes no part in it: it resolves\n * the app's configuration through Vite, as `timber build` does.\n */\n config?: string;\n}\n\n/**\n * Locate `@typescript/native-preview`'s JS entry.\n *\n * Resolution is attempted from this package first (it is declared an optional\n * peer dependency, so a package manager links it here when the user installs\n * it) and then from the project root (covering a hoisted install, or a user who\n * added it without the peer link). Throws if neither finds it.\n */\nexport function resolveTsgoEntry(\n root: string,\n resolveFrom: (from: string, specifier: string) => string = (from, specifier) =>\n createRequire(from).resolve(specifier)\n): string {\n // `createRequire` takes a filename or a file URL; a plain absolute path is\n // the portable spelling for the project root (a `file://` prefix on a Windows\n // path is not a valid URL). Same form as `checkPeerDependencies`.\n const candidates = [import.meta.url, join(root, 'package.json')];\n let lastError: unknown;\n\n for (const from of candidates) {\n try {\n // The package exports no subpath for its entry, so resolve the manifest\n // and walk to the module its `bin/tsgo` shim imports.\n const manifest = resolveFrom(from, `${TSGO_PACKAGE}/package.json`);\n return join(dirname(manifest), 'lib', 'tsgo.js');\n } catch (err) {\n lastError = err;\n }\n }\n\n throw new Error(\n `[timber] Cannot find ${TSGO_PACKAGE}, which \\`timber check\\` uses to type-check.\\n\\n` +\n ` Install it as a dev dependency:\\n\\n` +\n ` pnpm add -D ${TSGO_PACKAGE}\\n\\n` +\n ` (resolution failed: ${lastError instanceof Error ? lastError.message : String(lastError)})`\n );\n}\n\n/** What the route pass needs from the command line. */\nexport interface RouteOptions {\n /**\n * Path to a **Vite** config file, from `--config`. Undefined means Vite's own\n * discovery, the same as `timber dev`/`build` without the flag. A project\n * that builds with a custom Vite config has to be checkable with it too, or\n * `check` resolves a different app than `build` does (TIM-1332, round 4).\n */\n viteConfigFile?: string;\n}\n\n/** Everything the route scan needs, as the build itself resolves it. */\nexport interface RouteInputs {\n root: string;\n appDir: string;\n pageExtensions: string[] | undefined;\n}\n\n/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them\n * — through Vite, never by re-reading `timber.config.ts` (see `cli-context.ts`).\n * Inline `timber({ pageExtensions: [...] })` is the case that bites: a scan\n * that re-read the file would silently use default page extensions and write a\n * route map missing the app's pages. `examples/next-playground-migration` is\n * exactly this shape.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const ctx = await resolveTimberContext('check', options.viteConfigFile, deps.resolveViteConfig);\n return { root: ctx.root, appDir: ctx.appDir, pageExtensions: ctx.config.pageExtensions };\n}\n\n/**\n * Resolve the app directory, scan it, fail on proven-fatal route\n * misconfigurations, print warnings, and write the route codegen the type pass\n * depends on.\n *\n * Error-level lint findings throw rather than print, matching what\n * `plugins/routing.ts` does at build time: the tree is not fit to publish, so\n * it must not reach codegen either. Warnings are printed and do not fail the\n * command — same severity contract as dev and build, so `timber check` cannot\n * disagree with them about what a valid app is.\n */\nexport async function checkRoutes(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const inputs = await resolveRouteInputs(options, deps);\n const { root, appDir, pageExtensions } = inputs;\n\n const tree = scanRoutes(appDir, { pageExtensions });\n\n const warnings = lintConventions(tree, appDir);\n const fatal = warnings.filter((w) => w.level === 'error');\n if (fatal.length > 0) {\n throw new Error(formatConventionWarnings(fatal, { color: false }));\n }\n if (warnings.length > 0) {\n process.stderr.write(`${formatConventionWarnings(warnings)}\\n`);\n }\n\n // Awaited, unlike the dev/build path: the type pass reads these files, so a\n // failed write would be reported as type errors in the user's own code.\n // Reported as a codegen failure rather than surfaced as a bare `EROFS`/\n // `EACCES` from somewhere unnamed — the raw error says which path could not\n // be written but not which pass wanted it.\n try {\n await writeRouteCodegen(tree, appDir, root);\n } catch (err) {\n throw new Error(\n `[timber] Failed to write the generated route types, which the type check reads: ` +\n `${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n verifyCodegenImports(root);\n\n // Returned so the type pass runs against the same root these files landed in.\n return inputs;\n}\n\n/**\n * Verify that the import specifiers in the generated route types resolve on the\n * filesystem. A `.d.ts` whose import fails does NOT produce a TypeScript error —\n * every type that depends on it silently becomes `any`. The generated file\n * contains type-level `_AssertSchemaNotAny` / `_AssertCodecTypeNotAny` guards\n * that catch this at typecheck time, but a diagnostic here fires earlier and\n * names the exact import that is broken rather than leaving the user to decode\n * a constraint error.\n */\nexport function verifyCodegenImports(root: string): void {\n const dtsPath = join(root, CODEGEN_OUTPUT);\n let content: string;\n try {\n content = readFileSync(dtsPath, 'utf-8');\n } catch {\n return;\n }\n\n const dtsDir = dirname(dtsPath);\n\n // Check relative imports (default imports only — the generated codegen uses\n // `import type schema from '...'` for relative paths). Named imports from\n // relative paths are not emitted today; if codegen adds them, extend this.\n const RELATIVE_IMPORT_RE = /^import\\s+type\\s+\\w+\\s+from\\s+'(\\.\\.?\\/[^']+)'/gm;\n const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx'];\n let match;\n while ((match = RELATIVE_IMPORT_RE.exec(content)) !== null) {\n const specifier = match[1];\n const base = join(dtsDir, specifier);\n const resolves = existsSync(base) || EXTENSIONS.some((ext) => existsSync(base + ext));\n if (!resolves) {\n process.stderr.write(\n `[timber] WARNING: the generated ${CODEGEN_OUTPUT} imports '${specifier}',\\n` +\n ` but no file resolves at ${base}{${EXTENSIONS.join(',')}}.\\n` +\n ` Every type that depends on this import will silently become \\`any\\`.\\n\\n` +\n ` Check that your app/ directory is where timber expects it.\\n\\n`\n );\n }\n }\n\n // Bare-specifier imports (`@timber-js/app/params`) are NOT checked here.\n // They are all dependencies of @timber-js/app itself — if timber is installed,\n // they resolve. And createRequire uses CJS resolution which cannot follow\n // ESM-only subpath exports, producing false warnings (TIM-1348 review).\n}\n\n/**\n * The production `RunTsgo`: spawn the compiler with its stdio inherited, so its\n * diagnostics stream to the terminal as they are produced (and are not capped\n * by a buffer, as `execFile` output would be).\n */\nconst spawnTsgo: RunTsgo = async (command, args, cwd) => {\n const { spawn } = await import('node:child_process');\n return new Promise<number | null>((resolve, reject) => {\n // No `shell: true`: Node would concatenate the argv into an unescaped\n // command string, so a project path containing a space would break.\n const child = spawn(command, args, { stdio: 'inherit', cwd });\n child.on('error', reject);\n child.on('close', (code) => resolve(code));\n });\n};\n\n/**\n * The production `ReadTsgoConfig`: `--showConfig`, with stdout captured.\n *\n * `maxBuffer` is raised well past `execFile`'s 1 MB default because the output\n * is one line per file in the program — a large app can exceed that, and\n * overflowing it would make this advisory go quiet on exactly the projects\n * where a misconfigured `include` costs the most. A size-dependent silence is\n * indistinguishable from \"everything is fine\".\n */\nconst execTsgoConfig: ReadTsgoConfig = async (command, args, cwd) => {\n const { execFile } = await import('node:child_process');\n return new Promise<string>((resolve, reject) => {\n execFile(command, args, { cwd, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) =>\n err ? reject(err) : resolve(stdout)\n );\n });\n};\n\n/**\n * Warn when the generated route declarations will not reach the type checker.\n *\n * Writing `.timber/timber-routes.d.ts` and `timber-env.d.ts` is only half the\n * job: TypeScript loads them only if the project's `include`/`files` actually\n * pull `timber-env.d.ts` in (it is what `/// <reference>`s the route map). A\n * tsconfig with an explicit `include` that lists only source directories —\n * `[\"app\", \"*.config.ts\"]`, which is what `create-timber-app` shipped before\n * TIM-1332 — silently omits it, and every `<Link href>` then type-checks\n * against the empty placeholder instead of the generated route union. The\n * check would pass while answering the wrong question.\n *\n * The resolved file list comes from `tsgo --showConfig` rather than from our\n * own reading of the tsconfig: `include`, `exclude`, `files`, and `extends`\n * compose in ways that are the compiler's to decide, and a second\n * implementation of them would be a duplicate that drifts. `--showConfig` only\n * resolves globs, so it costs no type checking.\n *\n * This warns rather than fails. An app that never uses typed routes is\n * correct without those declarations, and a hard error would refuse it — the\n * one outcome a check must not produce for a working project. When the answer\n * cannot be determined (tsgo errored, output was not the expected JSON), the\n * warning is skipped: an advisory that fires on an unknown is noise.\n */\nasync function warnIfRouteTypesUnreachable(\n tsgoEntry: string,\n configArgs: string[],\n cwd: string,\n readConfig: ReadTsgoConfig\n): Promise<void> {\n let files: unknown;\n try {\n const raw = await readConfig(process.execPath, [tsgoEntry, '--showConfig', ...configArgs], cwd);\n files = (JSON.parse(raw) as { files?: unknown }).files;\n } catch {\n return;\n }\n if (!Array.isArray(files)) return;\n\n // Suffix match, not path resolution: `--showConfig` prints paths relative to\n // whichever tsconfig the compiler *found*, which for a bare `timber check`\n // is a directory we never learn. Over-matching only suppresses an advisory.\n //\n // The bare form is matched as well as the `/`-prefixed one. tsgo emits\n // `./timber-env.d.ts` today, but a leading `./` is cosmetic and an emitter\n // that dropped it would turn this into a warning printed at every correctly\n // configured project — the failure direction that trains people to ignore it.\n const reaches = files.some((file) => {\n if (typeof file !== 'string') return false;\n const normalized = file.replace(/\\\\/g, '/');\n return GENERATED_TYPE_PATHS.some(\n (path) => normalized === path || normalized.endsWith(`/${path}`)\n );\n });\n if (reaches) return;\n\n process.stderr.write(\n `[timber] The generated route types are not part of this TypeScript project, so\\n` +\n ` \\`<Link href>\\` and \\`useSegmentParams()\\` are being checked against empty\\n` +\n ` placeholders. Your tsconfig's \"include\" does not pull in timber-env.d.ts.\\n\\n` +\n ` To fix: add it to \"include\":\\n\\n` +\n ` \"include\": [\"app\", \"*.config.ts\", \"timber-env.d.ts\"]\\n\\n`\n );\n}\n\n/**\n * Run `tsgo --noEmit`, streaming its output.\n *\n * Rejects with the real numeric exit status on type errors. A failure to *start*\n * the compiler is reported separately — the historical bug this replaces\n * surfaced ENOENT as \"Type check failed with exit code undefined\", which read\n * as a type error and sent users looking at their own code.\n */\nexport async function runTypeCheck(\n options: CheckOptions = {},\n deps: CheckDeps = {}\n): Promise<void> {\n // The *resolved* root, handed over by the route pass — not `process.cwd()`.\n // The two differ whenever `--config` names a Vite config elsewhere, and the\n // route pass wrote `.timber/*` and `timber-env.d.ts` under the resolved one.\n // Running tsgo from cwd would then discover a different tsconfig entirely and\n // type-check a different project than the one just validated (TIM-1332, round\n // 5) — routes checked for the app, types checked for the monorepo around it.\n const root = options.root ?? process.cwd();\n const tsgoEntry = (deps.resolveTsgoEntry ?? (() => resolveTsgoEntry(root)))();\n const runTsgo = deps.runTsgo ?? spawnTsgo;\n\n // An explicit `--project` is a path the user typed at their own prompt, so it\n // is resolved against *their* cwd before the compiler is moved to the project\n // root. Without `--project`, tsgo discovers `tsconfig.json` from `root`,\n // which is where the declarations it needs were just written.\n const configArgs = options.config ? ['--project', resolve(process.cwd(), options.config)] : [];\n\n // Before checking: say so if the declarations the route pass just wrote will\n // not be part of the program. Otherwise the check passes while `<Link href>`\n // is measured against a placeholder. Same root and same argv as the check\n // itself, or it would inspect a different program than the one tsgo reads.\n await warnIfRouteTypesUnreachable(\n tsgoEntry,\n configArgs,\n root,\n deps.readTsgoConfig ?? execTsgoConfig\n );\n\n let code: number | null;\n try {\n code = await runTsgo(process.execPath, [tsgoEntry, '--noEmit', ...configArgs], root);\n } catch (err) {\n // Could not start the compiler at all. Kept distinct from a nonzero exit:\n // the version this replaced reported ENOENT as \"Type check failed with\n // exit code undefined\", which reads as a verdict on the user's types.\n throw new Error(\n `[timber] Failed to start the type checker: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (code === 0) return;\n\n // A null code means a signal killed the process rather than it exiting.\n // Say so instead of printing \"exit code null\".\n throw new Error(\n code === null\n ? 'Type check terminated before it finished'\n : `Type check failed with exit code ${code}`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAiD9D,SAAgB,iBACd,MACA,eAA4D,MAAM,cAChE,cAAc,IAAI,CAAC,CAAC,QAAQ,SAAS,GAC/B;CAIR,MAAM,aAAa,CAAC,YAAY,KAAK,KAAK,MAAM,cAAc,CAAC;CAC/D,IAAI;CAEJ,KAAK,MAAM,QAAQ,YACjB,IAAI;EAGF,MAAM,WAAW,YAAY,MAAM,GAAG,aAAa,cAAc;EACjE,OAAO,KAAK,QAAQ,QAAQ,GAAG,OAAO,SAAS;CACjD,SAAS,KAAK;EACZ,YAAY;CACd;CAGF,MAAM,IAAI,MACR,wBAAwB,aAAa,uGAEhB,aAAa,4BACP,qBAAqB,QAAQ,UAAU,UAAU,OAAO,SAAS,E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AqB,MACzB,SAAS,eAAe,QAAQ,WAAW,SAAS,IAAI,MAAM,CACjE;CACF,CACI,GAAS;CAEb,QAAQ,OAAO,MACb,qVAKF;AACF;;;;;;;;;AAUA,eAAsB,aACpB,UAAwB,CAAC,GACzB,OAAkB,CAAC,GACJ;CAOf,MAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI;CACzC,MAAM,aAAa,KAAK,2BAA2B,iBAAiB,IAAI,GAAA,CAAI;CAC5E,MAAM,UAAU,KAAK,WAAW;CAMhC,MAAM,aAAa,QAAQ,SAAS,CAAC,aAAa,QAAQ,QAAQ,IAAI,GAAG,QAAQ,MAAM,CAAC,IAAI,CAAC;CAM7F,MAAM,4BACJ,WACA,YACA,MACA,KAAK,kBAAkB,cACzB;CAEA,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,QAAQ,UAAU;GAAC;GAAW;GAAY,GAAG;EAAU,GAAG,IAAI;CACrF,SAAS,KAAK;EAIZ,MAAM,IAAI,MACR,8CAA8C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAC/F;CACF;CAEA,IAAI,SAAS,GAAG;CAIhB,MAAM,IAAI,MACR,SAAS,OACL,6CACA,oCAAoC,MAC1C;AACF"}
|
|
1
|
+
{"version":3,"file":"cli-check-Dv3f8d2j.js","names":[],"sources":["../../src/cli-check.ts"],"sourcesContent":["/**\n * `timber check` — the implementation behind the CLI command.\n *\n * Two passes, in order:\n *\n * 1. **Routes.** Resolve the project through Vite — so root, `appDir`, and\n * `pageExtensions` are the ones `timber build` uses, including config\n * passed inline to `timber()` — then scan, run the convention linter, and\n * write the route codegen (`.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts`, `timber-env.d.ts`).\n *\n * Codegen runs *before* the type pass on purpose: those\n * files are what give `<Link href>`, `useSegmentParams()` and\n * `MiddlewareContext` their per-route types (design/09-typescript.md\n * §\"Typed Routes\"), and they are build artifacts — a fresh clone that has\n * never run `timber dev` or `timber build` does not have them, so a type\n * pass on its own would report errors about correct code. A clone whose\n * routes changed since the last build has the same problem with stale ones.\n * 2. **Types.** `tsgo --noEmit` over the project.\n *\n * tsgo is spawned as `node <@typescript/native-preview>/lib/tsgo.js`, never as\n * a bare `tsgo` off PATH — the package is an *optional peer dependency*, so\n * there is no reason for its shim to be on a user's PATH, and the shim is a\n * `.cmd` on Windows which cannot be spawned without a shell. `shell: true`\n * would then concatenate the argv into an unescaped command string, so a\n * project path containing a space would break on exactly the platform the\n * shell was there to support. This mirrors `scripts/build-types.js`, whose\n * header comment is the specification for the pattern.\n *\n * Design docs: 11-platform.md §CLI, 09-typescript.md, 28-npm-packaging.md\n */\n\nimport { createRequire } from 'node:module';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport { lintConventions, formatConventionWarnings } from './routing/convention-lint.ts';\nimport { writeRouteCodegen, CODEGEN_OUTPUT, ENV_DTS_FILENAME } from './routing/codegen-write.ts';\nimport { resolveTimberContext, type ResolveViteConfig } from './cli-context.ts';\n\n/** The npm package that provides tsgo. Named in the missing-tool message. */\nconst TSGO_PACKAGE = '@typescript/native-preview';\n\n/**\n * The two generated declaration paths, relative to the project root, as they\n * appear in a resolved tsconfig file list. Derived from the writer's own\n * constants — a rename there cannot leave this check hunting for a file nothing\n * writes.\n */\nconst GENERATED_TYPE_PATHS = [ENV_DTS_FILENAME, CODEGEN_OUTPUT];\n\n/**\n * Run the compiler to completion.\n *\n * Resolves with its exit status (`null` when a signal killed it) and rejects\n * only when the process could not be started — the two outcomes `runTypeCheck`\n * has to keep apart. The seam is this narrow on purpose: a test double is a\n * plain async function, with no `ChildProcess` shape to imitate.\n */\nexport type RunTsgo = (command: string, args: string[], cwd: string) => Promise<number | null>;\n\n/**\n * Run the compiler and capture its stdout — used for `--showConfig`, whose\n * output is data we read rather than diagnostics the user reads.\n */\nexport type ReadTsgoConfig = (command: string, args: string[], cwd: string) => Promise<string>;\n\n/** @internal Dependency injection for testing. */\nexport interface CheckDeps {\n /**\n * Resolve tsgo's own JS entry point. Throws when the package is not\n * installed — the caller turns that into an install instruction.\n */\n resolveTsgoEntry?: () => string;\n runTsgo?: RunTsgo;\n readTsgoConfig?: ReadTsgoConfig;\n resolveViteConfig?: ResolveViteConfig;\n}\n\nexport interface CheckOptions {\n /** Project root, for resolving tsgo. Defaults to `process.cwd()`. */\n root?: string;\n /**\n * Path to a **tsconfig**, forwarded to tsgo as `--project` and sourced from\n * the CLI's own `--project`. The route pass takes no part in it: it resolves\n * the app's configuration through Vite, as `timber build` does.\n */\n config?: string;\n}\n\n/**\n * Locate `@typescript/native-preview`'s JS entry.\n *\n * Resolution is attempted from this package first (it is declared an optional\n * peer dependency, so a package manager links it here when the user installs\n * it) and then from the project root (covering a hoisted install, or a user who\n * added it without the peer link). Throws if neither finds it.\n */\nexport function resolveTsgoEntry(\n root: string,\n resolveFrom: (from: string, specifier: string) => string = (from, specifier) =>\n createRequire(from).resolve(specifier)\n): string {\n // `createRequire` takes a filename or a file URL; a plain absolute path is\n // the portable spelling for the project root (a `file://` prefix on a Windows\n // path is not a valid URL). Same form as `checkPeerDependencies`.\n const candidates = [import.meta.url, join(root, 'package.json')];\n let lastError: unknown;\n\n for (const from of candidates) {\n try {\n // The package exports no subpath for its entry, so resolve the manifest\n // and walk to the module its `bin/tsgo` shim imports.\n const manifest = resolveFrom(from, `${TSGO_PACKAGE}/package.json`);\n return join(dirname(manifest), 'lib', 'tsgo.js');\n } catch (err) {\n lastError = err;\n }\n }\n\n throw new Error(\n `[timber] Cannot find ${TSGO_PACKAGE}, which \\`timber check\\` uses to type-check.\\n\\n` +\n ` Install it as a dev dependency:\\n\\n` +\n ` pnpm add -D ${TSGO_PACKAGE}\\n\\n` +\n ` (resolution failed: ${lastError instanceof Error ? lastError.message : String(lastError)})`\n );\n}\n\n/** What the route pass needs from the command line. */\nexport interface RouteOptions {\n /**\n * Path to a **Vite** config file, from `--config`. Undefined means Vite's own\n * discovery, the same as `timber dev`/`build` without the flag. A project\n * that builds with a custom Vite config has to be checkable with it too, or\n * `check` resolves a different app than `build` does (TIM-1332, round 4).\n */\n viteConfigFile?: string;\n}\n\n/** Everything the route scan needs, as the build itself resolves it. */\nexport interface RouteInputs {\n root: string;\n appDir: string;\n pageExtensions: string[] | undefined;\n}\n\n/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them\n * — through Vite, never by re-reading `timber.config.ts` (see `cli-context.ts`).\n * Inline `timber({ pageExtensions: [...] })` is the case that bites: a scan\n * that re-read the file would silently use default page extensions and write a\n * route map missing the app's pages. `examples/next-playground-migration` is\n * exactly this shape.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const ctx = await resolveTimberContext('check', options.viteConfigFile, deps.resolveViteConfig);\n return { root: ctx.root, appDir: ctx.appDir, pageExtensions: ctx.config.pageExtensions };\n}\n\n/**\n * Resolve the app directory, scan it, fail on proven-fatal route\n * misconfigurations, print warnings, and write the route codegen the type pass\n * depends on.\n *\n * Error-level lint findings throw rather than print, matching what\n * `plugins/routing.ts` does at build time: the tree is not fit to publish, so\n * it must not reach codegen either. Warnings are printed and do not fail the\n * command — same severity contract as dev and build, so `timber check` cannot\n * disagree with them about what a valid app is.\n */\nexport async function checkRoutes(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const inputs = await resolveRouteInputs(options, deps);\n const { root, appDir, pageExtensions } = inputs;\n\n const tree = scanRoutes(appDir, { pageExtensions });\n\n const warnings = lintConventions(tree, appDir);\n const fatal = warnings.filter((w) => w.level === 'error');\n if (fatal.length > 0) {\n throw new Error(formatConventionWarnings(fatal, { color: false }));\n }\n if (warnings.length > 0) {\n process.stderr.write(`${formatConventionWarnings(warnings)}\\n`);\n }\n\n // Awaited, unlike the dev/build path: the type pass reads these files, so a\n // failed write would be reported as type errors in the user's own code.\n // Reported as a codegen failure rather than surfaced as a bare `EROFS`/\n // `EACCES` from somewhere unnamed — the raw error says which path could not\n // be written but not which pass wanted it.\n try {\n await writeRouteCodegen(tree, appDir, root);\n } catch (err) {\n throw new Error(\n `[timber] Failed to write the generated route types, which the type check reads: ` +\n `${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n verifyCodegenImports(root);\n\n // Returned so the type pass runs against the same root these files landed in.\n return inputs;\n}\n\n/**\n * Verify that the import specifiers in the generated route types resolve on the\n * filesystem. A `.d.ts` whose import fails does NOT produce a TypeScript error —\n * every type that depends on it silently becomes `any`. The generated file\n * contains type-level `_AssertSchemaNotAny` / `_AssertCodecTypeNotAny` guards\n * that catch this at typecheck time, but a diagnostic here fires earlier and\n * names the exact import that is broken rather than leaving the user to decode\n * a constraint error.\n */\nexport function verifyCodegenImports(root: string): void {\n const dtsPath = join(root, CODEGEN_OUTPUT);\n let content: string;\n try {\n content = readFileSync(dtsPath, 'utf-8');\n } catch {\n return;\n }\n\n const dtsDir = dirname(dtsPath);\n\n // Check relative imports (default imports only — the generated codegen uses\n // `import type schema from '...'` for relative paths). Named imports from\n // relative paths are not emitted today; if codegen adds them, extend this.\n const RELATIVE_IMPORT_RE = /^import\\s+type\\s+\\w+\\s+from\\s+'(\\.\\.?\\/[^']+)'/gm;\n const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx'];\n let match;\n while ((match = RELATIVE_IMPORT_RE.exec(content)) !== null) {\n const specifier = match[1];\n const base = join(dtsDir, specifier);\n const resolves = existsSync(base) || EXTENSIONS.some((ext) => existsSync(base + ext));\n if (!resolves) {\n process.stderr.write(\n `[timber] WARNING: the generated ${CODEGEN_OUTPUT} imports '${specifier}',\\n` +\n ` but no file resolves at ${base}{${EXTENSIONS.join(',')}}.\\n` +\n ` Every type that depends on this import will silently become \\`any\\`.\\n\\n` +\n ` Check that your app/ directory is where timber expects it.\\n\\n`\n );\n }\n }\n\n // Bare-specifier imports (`@timber-js/app/params`) are NOT checked here.\n // They are all dependencies of @timber-js/app itself — if timber is installed,\n // they resolve. And createRequire uses CJS resolution which cannot follow\n // ESM-only subpath exports, producing false warnings (TIM-1348 review).\n}\n\n/**\n * The production `RunTsgo`: spawn the compiler with its stdio inherited, so its\n * diagnostics stream to the terminal as they are produced (and are not capped\n * by a buffer, as `execFile` output would be).\n */\nconst spawnTsgo: RunTsgo = async (command, args, cwd) => {\n const { spawn } = await import('node:child_process');\n return new Promise<number | null>((resolve, reject) => {\n // No `shell: true`: Node would concatenate the argv into an unescaped\n // command string, so a project path containing a space would break.\n const child = spawn(command, args, { stdio: 'inherit', cwd });\n child.on('error', reject);\n child.on('close', (code) => resolve(code));\n });\n};\n\n/**\n * The production `ReadTsgoConfig`: `--showConfig`, with stdout captured.\n *\n * `maxBuffer` is raised well past `execFile`'s 1 MB default because the output\n * is one line per file in the program — a large app can exceed that, and\n * overflowing it would make this advisory go quiet on exactly the projects\n * where a misconfigured `include` costs the most. A size-dependent silence is\n * indistinguishable from \"everything is fine\".\n */\nconst execTsgoConfig: ReadTsgoConfig = async (command, args, cwd) => {\n const { execFile } = await import('node:child_process');\n return new Promise<string>((resolve, reject) => {\n execFile(command, args, { cwd, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) =>\n err ? reject(err) : resolve(stdout)\n );\n });\n};\n\n/**\n * Warn when the generated route declarations will not reach the type checker.\n *\n * Writing `.timber/timber-routes.d.ts` and `timber-env.d.ts` is only half the\n * job: TypeScript loads them only if the project's `include`/`files` actually\n * pull `timber-env.d.ts` in (it is what `/// <reference>`s the route map). A\n * tsconfig with an explicit `include` that lists only source directories —\n * `[\"app\", \"*.config.ts\"]`, which is what `create-timber-app` shipped before\n * TIM-1332 — silently omits it, and every `<Link href>` then type-checks\n * against the empty placeholder instead of the generated route union. The\n * check would pass while answering the wrong question.\n *\n * The resolved file list comes from `tsgo --showConfig` rather than from our\n * own reading of the tsconfig: `include`, `exclude`, `files`, and `extends`\n * compose in ways that are the compiler's to decide, and a second\n * implementation of them would be a duplicate that drifts. `--showConfig` only\n * resolves globs, so it costs no type checking.\n *\n * This warns rather than fails. An app that never uses typed routes is\n * correct without those declarations, and a hard error would refuse it — the\n * one outcome a check must not produce for a working project. When the answer\n * cannot be determined (tsgo errored, output was not the expected JSON), the\n * warning is skipped: an advisory that fires on an unknown is noise.\n */\nasync function warnIfRouteTypesUnreachable(\n tsgoEntry: string,\n configArgs: string[],\n cwd: string,\n readConfig: ReadTsgoConfig\n): Promise<void> {\n let files: unknown;\n try {\n const raw = await readConfig(process.execPath, [tsgoEntry, '--showConfig', ...configArgs], cwd);\n files = (JSON.parse(raw) as { files?: unknown }).files;\n } catch {\n return;\n }\n if (!Array.isArray(files)) return;\n\n // Suffix match, not path resolution: `--showConfig` prints paths relative to\n // whichever tsconfig the compiler *found*, which for a bare `timber check`\n // is a directory we never learn. Over-matching only suppresses an advisory.\n //\n // The bare form is matched as well as the `/`-prefixed one. tsgo emits\n // `./timber-env.d.ts` today, but a leading `./` is cosmetic and an emitter\n // that dropped it would turn this into a warning printed at every correctly\n // configured project — the failure direction that trains people to ignore it.\n const reaches = files.some((file) => {\n if (typeof file !== 'string') return false;\n const normalized = file.replace(/\\\\/g, '/');\n return GENERATED_TYPE_PATHS.some(\n (path) => normalized === path || normalized.endsWith(`/${path}`)\n );\n });\n if (reaches) return;\n\n process.stderr.write(\n `[timber] The generated route types are not part of this TypeScript project, so\\n` +\n ` \\`<Link href>\\` and \\`useSegmentParams()\\` are being checked against empty\\n` +\n ` placeholders. Your tsconfig's \"include\" does not pull in timber-env.d.ts.\\n\\n` +\n ` To fix: add it to \"include\":\\n\\n` +\n ` \"include\": [\"app\", \"*.config.ts\", \"timber-env.d.ts\"]\\n\\n`\n );\n}\n\n/**\n * Run `tsgo --noEmit`, streaming its output.\n *\n * Rejects with the real numeric exit status on type errors. A failure to *start*\n * the compiler is reported separately — the historical bug this replaces\n * surfaced ENOENT as \"Type check failed with exit code undefined\", which read\n * as a type error and sent users looking at their own code.\n */\nexport async function runTypeCheck(\n options: CheckOptions = {},\n deps: CheckDeps = {}\n): Promise<void> {\n // The *resolved* root, handed over by the route pass — not `process.cwd()`.\n // The two differ whenever `--config` names a Vite config elsewhere, and the\n // route pass wrote `.timber/*` and `timber-env.d.ts` under the resolved one.\n // Running tsgo from cwd would then discover a different tsconfig entirely and\n // type-check a different project than the one just validated (TIM-1332, round\n // 5) — routes checked for the app, types checked for the monorepo around it.\n const root = options.root ?? process.cwd();\n const tsgoEntry = (deps.resolveTsgoEntry ?? (() => resolveTsgoEntry(root)))();\n const runTsgo = deps.runTsgo ?? spawnTsgo;\n\n // An explicit `--project` is a path the user typed at their own prompt, so it\n // is resolved against *their* cwd before the compiler is moved to the project\n // root. Without `--project`, tsgo discovers `tsconfig.json` from `root`,\n // which is where the declarations it needs were just written.\n const configArgs = options.config ? ['--project', resolve(process.cwd(), options.config)] : [];\n\n // Before checking: say so if the declarations the route pass just wrote will\n // not be part of the program. Otherwise the check passes while `<Link href>`\n // is measured against a placeholder. Same root and same argv as the check\n // itself, or it would inspect a different program than the one tsgo reads.\n await warnIfRouteTypesUnreachable(\n tsgoEntry,\n configArgs,\n root,\n deps.readTsgoConfig ?? execTsgoConfig\n );\n\n let code: number | null;\n try {\n code = await runTsgo(process.execPath, [tsgoEntry, '--noEmit', ...configArgs], root);\n } catch (err) {\n // Could not start the compiler at all. Kept distinct from a nonzero exit:\n // the version this replaced reported ENOENT as \"Type check failed with\n // exit code undefined\", which reads as a verdict on the user's types.\n throw new Error(\n `[timber] Failed to start the type checker: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (code === 0) return;\n\n // A null code means a signal killed the process rather than it exiting.\n // Say so instead of printing \"exit code null\".\n throw new Error(\n code === null\n ? 'Type check terminated before it finished'\n : `Type check failed with exit code ${code}`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAi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
import { s as isTimberPluginApi } from "./plugin-context-
|
|
2
|
-
|
|
1
|
+
import { s as isTimberPluginApi } from "./plugin-context-FCkaNLUB.js";
|
|
2
|
+
// src/cli-context.ts
|
|
3
3
|
/**
|
|
4
4
|
* Resolve timber's configuration the way `timber build` resolves it, for CLI
|
|
5
5
|
* commands that run outside the build: `timber check` and `timber preview`.
|
|
@@ -64,7 +64,6 @@ async function resolveTimberContext(command, viteConfigFile, resolveViteConfig =
|
|
|
64
64
|
if (!rootSync || !isTimberPluginApi(rootSync.api)) throw new Error(`[timber] Could not read the resolved timber configuration from your Vite config.\n\n \`timber ${command}\` resolves your project through Vite so it sees the same\n configuration \`timber build\` uses — including config passed inline to timber().\n\n Check that vite.config.ts exists and lists the timber plugin:\n\n import { timber } from '@timber-js/app';\n export default { plugins: [timber()] };\n`);
|
|
65
65
|
return rootSync.api.getContext();
|
|
66
66
|
}
|
|
67
|
-
//#endregion
|
|
68
67
|
export { resolveTimberContext as t };
|
|
69
68
|
|
|
70
|
-
//# sourceMappingURL=cli-context-
|
|
69
|
+
//# sourceMappingURL=cli-context-CbZp32SK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-context-
|
|
1
|
+
{"version":3,"file":"cli-context-CbZp32SK.js","names":[],"sources":["../../src/cli-context.ts"],"sourcesContent":["/**\n * Resolve timber's configuration the way `timber build` resolves it, for CLI\n * commands that run outside the build: `timber check` and `timber preview`.\n *\n * Reading `timber.config.ts` directly is **not** equivalent, which is the whole\n * reason this goes through Vite (TIM-1332, review round 3; TIM-1531):\n *\n * - Config passed inline — `timber({ pageExtensions, adapter, output })` in\n * `vite.config.ts` — lives only in the plugin's closure. Nothing that\n * re-reads the config file can see it.\n * - `root` is Vite's resolved root, not the caller's cwd, and the two differ in\n * the monorepo layouts TIM-498 describes.\n * - The build directory can come from Vite's `build.outDir`, which only a\n * resolved Vite config knows.\n * - `--config` names a Vite config file; only Vite can load it.\n *\n * There is no fallback to a second, hand-rolled resolution. A project whose\n * Vite config does not produce the timber plugin cannot be built either, so a\n * command that quietly proceeded on a guess would act on an app that does not\n * exist.\n *\n * Design docs: 11-platform.md §CLI\n */\n\nimport { isTimberPluginApi, type PluginContext } from './plugin-context.ts';\n\n/** The plugin that publishes timber's resolved context on its Vite `api`. */\nconst TIMBER_ROOT_SYNC_PLUGIN = 'timber-root-sync';\n\n/** The subset of a resolved Vite plugin this module reads. */\nexport interface PluginWithApi {\n name: string;\n api?: unknown;\n}\n\n/**\n * Vite's own `resolveConfig`, narrowed to what this module passes and reads.\n *\n * The seam sits at `resolveConfig` rather than at \"give me the plugins\" so the\n * *arguments* are the thing under test: which config file, which command, and\n * which mode defaults. Those arguments have been wrong three separate times\n * (TIM-1332 rounds 4-6), and a double that answered \"here are the plugins\"\n * could not see any of it. The double returns what Vite returns — plugins with\n * an opaque `api` — so the lookup and narrowing under test stay the real ones.\n */\nexport type ResolveViteConfig = (\n inlineConfig: { configFile: string | undefined },\n command: 'build',\n defaultMode: string,\n defaultNodeEnv: string\n) => Promise<{ plugins: readonly PluginWithApi[] }>;\n\n/**\n * Ask Vite for the resolved config, which is what carries timber's context.\n *\n * `resolveConfig` runs the whole config pipeline — config file discovery,\n * `config` and `configResolved` hooks — so the context it produces is the one\n * `timber build` would use. Measured at ~300-400ms on a real app.\n */\nconst defaultResolveViteConfig: ResolveViteConfig = async (\n inlineConfig,\n command,\n defaultMode,\n defaultNodeEnv\n) => {\n const { resolveConfig } = await import('vite');\n return resolveConfig(inlineConfig, command, defaultMode, defaultNodeEnv);\n};\n\n/**\n * The mode defaults `timber build` resolves under.\n *\n * `resolveConfig`'s own defaults are `'development'` for both, but nothing\n * reaches it with those on a build: `createBuilder` goes through Vite's\n * internal `resolveConfigToBuild`, which calls\n * `resolveConfig(inlineConfig, 'build', 'production', 'production')`. A config\n * written as `defineConfig(({ mode }) => …)`, or one that loads `.env.production`,\n * therefore resolves to a *different* app under the two. Passing the defaults\n * explicitly is what makes \"check validates what build builds\" — and \"preview\n * serves what build wrote\" — true rather than true-by-coincidence for configs\n * that ignore mode (TIM-1332, round 6).\n */\nconst BUILD_MODE_DEFAULTS = ['production', 'production'] as const;\n\n/**\n * Resolve the project through Vite and return timber's context as\n * `timber build` would see it.\n *\n * @param command The CLI command asking, named in the error message.\n * @param viteConfigFile `--config`. Undefined means Vite's own discovery, the\n * same as `timber build` without the flag.\n */\nexport async function resolveTimberContext(\n command: string,\n viteConfigFile: string | undefined,\n resolveViteConfig: ResolveViteConfig = defaultResolveViteConfig\n): Promise<PluginContext> {\n // `configFile: undefined` is Vite's own \"discover it\" value, so the default\n // path stays exactly what Vite does for `timber build` without `--config`.\n const { plugins } = await resolveViteConfig(\n { configFile: viteConfigFile },\n 'build',\n ...BUILD_MODE_DEFAULTS\n );\n\n const rootSync = plugins.find((plugin) => plugin.name === TIMBER_ROOT_SYNC_PLUGIN);\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] Could not read the resolved timber configuration from your Vite config.\\n\\n` +\n ` \\`timber ${command}\\` resolves your project through Vite so it sees the same\\n` +\n ` configuration \\`timber build\\` uses — including config passed inline to timber().\\n\\n` +\n ` Check that vite.config.ts exists and lists the timber plugin:\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n\n return rootSync.api.getContext();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,0BAA0B;;;;;;;;AAgChC,IAAM,2BAA8C,OAClD,cACA,SACA,aACA,mBACG;CACH,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,OAAO,cAAc,cAAc,SAAS,aAAa,cAAc;AACzE;;;;;;;;;;;;;;AAeA,IAAM,sBAAsB,CAAC,cAAc,YAAY;;;;;;;;;AAUvD,eAAsB,qBACpB,SACA,gBACA,oBAAuC,0BACf;CAGxB,MAAM,EAAE,YAAY,MAAM,kBACxB,EAAE,YAAY,eAAe,GAC7B,SACA,GAAG,mBACL;CAEA,MAAM,WAAW,QAAQ,MAAM,WAAW,OAAO,SAAS,uBAAuB;CACjF,IAAI,CAAC,YAAY,CAAC,kBAAkB,SAAS,GAAG,GAC9C,MAAM,IAAI,MACR,kGACgB,QAAQ,iTAK1B;CAGF,OAAO,SAAS,IAAI,WAAW;AACjC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as resolveTimberContext } from "./cli-context-CbZp32SK.js";
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { o as readLiveDevRecords } from "./dev-discovery-YnabkCKD.js";
|
|
2
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { realpath } from "node:fs/promises";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
// src/cli-dev-status.ts
|
|
7
|
+
/**
|
|
8
|
+
* `timber dev status [--json]` — which dev servers are running for this app.
|
|
9
|
+
*
|
|
10
|
+
* The agent-facing answer to "is a dev server already up?" Agents that
|
|
11
|
+
* skip the question start a second server, Vite bumps it to the next
|
|
12
|
+
* port, and the agent then tests a different server than the one the user
|
|
13
|
+
* is watching.
|
|
14
|
+
*
|
|
15
|
+
* Servers are found through their discovery records (plugins/dev-discovery.ts)
|
|
16
|
+
* and listed only after the full validation: pid alive AND the server
|
|
17
|
+
* answers the status probe with that pid. The record format stays private;
|
|
18
|
+
* this command is the public contract.
|
|
19
|
+
*
|
|
20
|
+
* Worktree-aware: `.timber/` is gitignored, so each git worktree has its own
|
|
21
|
+
* records. A server in another worktree serves that worktree's code — never
|
|
22
|
+
* reuse it — but it may be holding the port this checkout would have taken,
|
|
23
|
+
* so it is reported separately.
|
|
24
|
+
*
|
|
25
|
+
* See design/21-dev-server.md §"`timber dev status`".
|
|
26
|
+
*/
|
|
27
|
+
var execFileAsync = promisify(execFile);
|
|
28
|
+
/** `git` must answer fast or not at all — not being a repo is normal. */
|
|
29
|
+
var GIT_TIMEOUT_MS = 2e3;
|
|
30
|
+
function toServer(record) {
|
|
31
|
+
return {
|
|
32
|
+
url: record.url,
|
|
33
|
+
loopbackUrl: record.loopbackUrl,
|
|
34
|
+
port: record.port,
|
|
35
|
+
pid: record.pid
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
async function liveServers(appRoot) {
|
|
39
|
+
return (await readLiveDevRecords(appRoot)).map(toServer).sort((a, b) => a.port - b.port);
|
|
40
|
+
}
|
|
41
|
+
/** Parse `git worktree list --porcelain`, skipping bare entries. */
|
|
42
|
+
function parseWorktreeList(porcelain) {
|
|
43
|
+
const worktrees = [];
|
|
44
|
+
for (const stanza of porcelain.split(/\n\s*\n/)) {
|
|
45
|
+
let path = null;
|
|
46
|
+
let branch = null;
|
|
47
|
+
let bare = false;
|
|
48
|
+
for (const line of stanza.split("\n")) if (line.startsWith("worktree ")) path = line.slice(9);
|
|
49
|
+
else if (line.startsWith("branch ")) branch = line.slice(7);
|
|
50
|
+
else if (line === "bare") bare = true;
|
|
51
|
+
if (path && !bare) worktrees.push({
|
|
52
|
+
path,
|
|
53
|
+
branch: branch?.replace(/^refs\/heads\//, "") ?? null
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return worktrees;
|
|
57
|
+
}
|
|
58
|
+
async function git(cwd, args) {
|
|
59
|
+
const { stdout } = await execFileAsync("git", args, {
|
|
60
|
+
cwd,
|
|
61
|
+
timeout: GIT_TIMEOUT_MS
|
|
62
|
+
});
|
|
63
|
+
return stdout;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Live servers for this app in every other worktree of its repository.
|
|
67
|
+
* Any git failure (not a repo, no git binary, timeout) means "no other
|
|
68
|
+
* worktrees", silently.
|
|
69
|
+
*/
|
|
70
|
+
async function otherWorktreeServers(appRoot) {
|
|
71
|
+
let toplevel;
|
|
72
|
+
let porcelain;
|
|
73
|
+
try {
|
|
74
|
+
toplevel = (await git(appRoot, ["rev-parse", "--show-toplevel"])).trim();
|
|
75
|
+
porcelain = await git(appRoot, [
|
|
76
|
+
"worktree",
|
|
77
|
+
"list",
|
|
78
|
+
"--porcelain"
|
|
79
|
+
]);
|
|
80
|
+
} catch {
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
const appPath = relative(await realpath(toplevel), await realpath(appRoot));
|
|
84
|
+
const self = resolve(toplevel);
|
|
85
|
+
return (await Promise.all(parseWorktreeList(porcelain).filter((worktree) => resolve(worktree.path) !== self).map(async (worktree) => {
|
|
86
|
+
const otherApp = join(worktree.path, appPath);
|
|
87
|
+
return {
|
|
88
|
+
...worktree,
|
|
89
|
+
appRoot: otherApp,
|
|
90
|
+
servers: await liveServers(otherApp)
|
|
91
|
+
};
|
|
92
|
+
}))).filter((worktree) => worktree.servers.length > 0);
|
|
93
|
+
}
|
|
94
|
+
async function collectDevStatus(appRoot) {
|
|
95
|
+
const [servers, otherWorktrees] = await Promise.all([liveServers(appRoot), otherWorktreeServers(appRoot)]);
|
|
96
|
+
return {
|
|
97
|
+
version: 1,
|
|
98
|
+
appRoot,
|
|
99
|
+
servers,
|
|
100
|
+
otherWorktrees
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** `(pid N)`, plus the plain-localhost URL when it differs from the printed one. */
|
|
104
|
+
function serverNote(server) {
|
|
105
|
+
return server.loopbackUrl === server.url ? `(pid ${server.pid})` : `(pid ${server.pid}; non-browser clients: ${server.loopbackUrl})`;
|
|
106
|
+
}
|
|
107
|
+
function formatDevStatus(report) {
|
|
108
|
+
const lines = [];
|
|
109
|
+
if (report.servers.length === 0) lines.push(`[timber] No dev server is running for this checkout (${report.appRoot}).`);
|
|
110
|
+
else {
|
|
111
|
+
lines.push(`[timber] Dev server running for this checkout (${report.appRoot}):`);
|
|
112
|
+
for (const server of report.servers) lines.push(` ${server.url} ${serverNote(server)}`);
|
|
113
|
+
}
|
|
114
|
+
if (report.otherWorktrees.length > 0) {
|
|
115
|
+
lines.push("[timber] In other git worktrees (different code — do not test against these):");
|
|
116
|
+
for (const worktree of report.otherWorktrees) {
|
|
117
|
+
const branch = worktree.branch ?? "detached HEAD";
|
|
118
|
+
for (const server of worktree.servers) lines.push(` ${server.url} ${serverNote(server)} ${worktree.path} [${branch}]`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return lines.join("\n");
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Resolve the app root the way `timber graph` does — the directory of the
|
|
125
|
+
* Vite config, found by walking up from the cwd unless `--config` names it —
|
|
126
|
+
* then print the report. Exits 0 whether or not servers are found ("no server"
|
|
127
|
+
* is an answer); throws only when there is no config to anchor on.
|
|
128
|
+
*/
|
|
129
|
+
async function runDevStatus(options) {
|
|
130
|
+
const { findViteConfigUpward } = await import("../analyze/graph-command.js");
|
|
131
|
+
const configFile = options.config ? resolve(options.config) : findViteConfigUpward(process.cwd());
|
|
132
|
+
if (!configFile) throw new Error("[timber] No Vite config found in this directory or any parent — run `timber dev status` from inside a timber app, or pass --config <path>.");
|
|
133
|
+
const report = await collectDevStatus(dirname(configFile));
|
|
134
|
+
console.log(options.json ? JSON.stringify(report) : formatDevStatus(report));
|
|
135
|
+
}
|
|
136
|
+
export { runDevStatus };
|
|
137
|
+
|
|
138
|
+
//# sourceMappingURL=cli-dev-status-prPMLU8G.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-dev-status-prPMLU8G.js","names":[],"sources":["../../src/cli-dev-status.ts"],"sourcesContent":["/**\n * `timber dev status [--json]` — which dev servers are running for this app.\n *\n * The agent-facing answer to \"is a dev server already up?\" Agents that\n * skip the question start a second server, Vite bumps it to the next\n * port, and the agent then tests a different server than the one the user\n * is watching.\n *\n * Servers are found through their discovery records (plugins/dev-discovery.ts)\n * and listed only after the full validation: pid alive AND the server\n * answers the status probe with that pid. The record format stays private;\n * this command is the public contract.\n *\n * Worktree-aware: `.timber/` is gitignored, so each git worktree has its own\n * records. A server in another worktree serves that worktree's code — never\n * reuse it — but it may be holding the port this checkout would have taken,\n * so it is reported separately.\n *\n * See design/21-dev-server.md §\"`timber dev status`\".\n */\n\nimport { execFile } from 'node:child_process';\nimport { realpath } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { readLiveDevRecords, type DevRecord } from './plugins/dev-discovery.ts';\n\nconst execFileAsync = promisify(execFile);\n\n/** `git` must answer fast or not at all — not being a repo is normal. */\nconst GIT_TIMEOUT_MS = 2_000;\n\n/** Bumped only on a breaking change to the `--json` shape. */\nexport const DEV_STATUS_JSON_VERSION = 1;\n\nexport interface DevStatusServer {\n /** The URL the server printed — open this in a browser (`http://blog.localhost:3000/`). */\n url: string;\n /**\n * The same server through plain `localhost` (`http://localhost:3000/`), for\n * HTTP clients that resolve through the OS, which may not map `*.localhost`.\n * Equal to `url` when the server has no dev hostname, or when its https\n * certificate does not cover `localhost` (the named URL is then the only\n * one that verifies).\n */\n loopbackUrl: string;\n port: number;\n pid: number;\n}\n\nexport interface DevStatusWorktree {\n /** The other worktree's root directory. */\n path: string;\n /** Short branch name, or null for a detached HEAD. */\n branch: string | null;\n /** The same app, inside that worktree. */\n appRoot: string;\n servers: DevStatusServer[];\n}\n\n/** The `timber dev status --json` contract. */\nexport interface DevStatusReport {\n version: typeof DEV_STATUS_JSON_VERSION;\n /** The app this checkout's servers were looked up for. */\n appRoot: string;\n /** Live servers serving this checkout. Reuse one of these. */\n servers: DevStatusServer[];\n /** Live servers in other git worktrees of the same app — different code. */\n otherWorktrees: DevStatusWorktree[];\n}\n\nfunction toServer(record: DevRecord): DevStatusServer {\n return {\n url: record.url,\n loopbackUrl: record.loopbackUrl,\n port: record.port,\n pid: record.pid,\n };\n}\n\nasync function liveServers(appRoot: string): Promise<DevStatusServer[]> {\n return (await readLiveDevRecords(appRoot)).map(toServer).sort((a, b) => a.port - b.port);\n}\n\ninterface Worktree {\n path: string;\n branch: string | null;\n}\n\n/** Parse `git worktree list --porcelain`, skipping bare entries. */\nexport function parseWorktreeList(porcelain: string): Worktree[] {\n const worktrees: Worktree[] = [];\n for (const stanza of porcelain.split(/\\n\\s*\\n/)) {\n let path: string | null = null;\n let branch: string | null = null;\n let bare = false;\n for (const line of stanza.split('\\n')) {\n if (line.startsWith('worktree ')) path = line.slice('worktree '.length);\n else if (line.startsWith('branch ')) branch = line.slice('branch '.length);\n else if (line === 'bare') bare = true;\n }\n if (path && !bare) {\n worktrees.push({ path, branch: branch?.replace(/^refs\\/heads\\//, '') ?? null });\n }\n }\n return worktrees;\n}\n\nasync function git(cwd: string, args: string[]): Promise<string> {\n const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT_MS });\n return stdout;\n}\n\n/**\n * Live servers for this app in every other worktree of its repository.\n * Any git failure (not a repo, no git binary, timeout) means \"no other\n * worktrees\", silently.\n */\nasync function otherWorktreeServers(appRoot: string): Promise<DevStatusWorktree[]> {\n let toplevel: string;\n let porcelain: string;\n try {\n toplevel = (await git(appRoot, ['rev-parse', '--show-toplevel'])).trim();\n porcelain = await git(appRoot, ['worktree', 'list', '--porcelain']);\n } catch {\n return [];\n }\n // git prints resolved paths; resolve the app root too (macOS /tmp is a\n // symlink) so the relative app path is computed in one path space.\n const appPath = relative(await realpath(toplevel), await realpath(appRoot));\n const self = resolve(toplevel);\n\n const results = await Promise.all(\n parseWorktreeList(porcelain)\n .filter((worktree) => resolve(worktree.path) !== self)\n .map(async (worktree): Promise<DevStatusWorktree> => {\n const otherApp = join(worktree.path, appPath);\n return { ...worktree, appRoot: otherApp, servers: await liveServers(otherApp) };\n })\n );\n return results.filter((worktree) => worktree.servers.length > 0);\n}\n\nexport async function collectDevStatus(appRoot: string): Promise<DevStatusReport> {\n const [servers, otherWorktrees] = await Promise.all([\n liveServers(appRoot),\n otherWorktreeServers(appRoot),\n ]);\n return { version: DEV_STATUS_JSON_VERSION, appRoot, servers, otherWorktrees };\n}\n\n/** `(pid N)`, plus the plain-localhost URL when it differs from the printed one. */\nfunction serverNote(server: DevStatusServer): string {\n return server.loopbackUrl === server.url\n ? `(pid ${server.pid})`\n : `(pid ${server.pid}; non-browser clients: ${server.loopbackUrl})`;\n}\n\nexport function formatDevStatus(report: DevStatusReport): string {\n const lines: string[] = [];\n if (report.servers.length === 0) {\n lines.push(`[timber] No dev server is running for this checkout (${report.appRoot}).`);\n } else {\n lines.push(`[timber] Dev server running for this checkout (${report.appRoot}):`);\n for (const server of report.servers) lines.push(` ${server.url} ${serverNote(server)}`);\n }\n if (report.otherWorktrees.length > 0) {\n lines.push('[timber] In other git worktrees (different code — do not test against these):');\n for (const worktree of report.otherWorktrees) {\n const branch = worktree.branch ?? 'detached HEAD';\n for (const server of worktree.servers) {\n lines.push(` ${server.url} ${serverNote(server)} ${worktree.path} [${branch}]`);\n }\n }\n }\n return lines.join('\\n');\n}\n\n/**\n * Resolve the app root the way `timber graph` does — the directory of the\n * Vite config, found by walking up from the cwd unless `--config` names it —\n * then print the report. Exits 0 whether or not servers are found (\"no server\"\n * is an answer); throws only when there is no config to anchor on.\n */\nexport async function runDevStatus(options: { config?: string; json: boolean }): Promise<void> {\n const { findViteConfigUpward } = await import('./analyze/graph-command.ts');\n const configFile = options.config ? resolve(options.config) : findViteConfigUpward(process.cwd());\n if (!configFile) {\n throw new Error(\n '[timber] No Vite config found in this directory or any parent — ' +\n 'run `timber dev status` from inside a timber app, or pass --config <path>.'\n );\n }\n const report = await collectDevStatus(dirname(configFile));\n console.log(options.json ? JSON.stringify(report) : formatDevStatus(report));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,gBAAgB,UAAU,QAAQ;;AAGxC,IAAM,iBAAiB;AAyCvB,SAAS,SAAS,QAAoC;CACpD,OAAO;EACL,KAAK,OAAO;EACZ,aAAa,OAAO;EACpB,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,eAAe,YAAY,SAA6C;CACtE,QAAQ,MAAM,mBAAmB,OAAO,EAAA,CAAG,IAAI,QAAQ,CAAC,CAAC,MAA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M,SAAS,MAAM,iBAAiB,QAAQ,UAAU,CAAC;CACzD,QAAQ,IAAI,QAAQ,OAAO,KAAK,UAAU,MAAM,IAAI,gBAAgB,MAAM,CAAC;AAC7E"}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
// src/cli-init.ts
|
|
4
|
+
/**
|
|
5
|
+
* `timber init` — point a project's agent instruction files at the guide
|
|
6
|
+
* that ships inside the installed `@timber-js/app` package.
|
|
7
|
+
*
|
|
8
|
+
* The guide (`node_modules/@timber-js/app/agent-skill.md`) is never copied.
|
|
9
|
+
* A copy freezes at the version `init` ran with; a pointer always reads the
|
|
10
|
+
* installed version. Each of `AGENTS.md` and `CLAUDE.md` gets one
|
|
11
|
+
* marker-delimited block that timber owns; everything outside the markers
|
|
12
|
+
* belongs to the user and is never touched.
|
|
13
|
+
*
|
|
14
|
+
* This module is also the single source of the block text: the
|
|
15
|
+
* create-timber-app templates are generated from `agentsFileContent()` /
|
|
16
|
+
* `claudeFileContent()` and a test fails if they drift.
|
|
17
|
+
*
|
|
18
|
+
* See design/11-platform.md §"`timber init` — agent guide pointer blocks".
|
|
19
|
+
*/
|
|
20
|
+
var BLOCK_START = "<!-- timber:start -->";
|
|
21
|
+
var BLOCK_END = "<!-- timber:end -->";
|
|
22
|
+
/** Where the guide lives, relative to the project root, in a non-hoisted install. */
|
|
23
|
+
var AGENT_GUIDE_PATH = "node_modules/@timber-js/app/agent-skill.md";
|
|
24
|
+
/** The AGENTS.md block: a plain pointer, for every AGENTS.md-reading tool. */
|
|
25
|
+
function agentsBlock(guide = AGENT_GUIDE_PATH) {
|
|
26
|
+
return [
|
|
27
|
+
BLOCK_START,
|
|
28
|
+
`This is a timber.js app. Before working, read \`${guide}\`.`,
|
|
29
|
+
"It matches the installed timber version and updates when timber is upgraded.",
|
|
30
|
+
BLOCK_END
|
|
31
|
+
].join("\n");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The CLAUDE.md block: Claude Code's `@path` imports, so the guide is
|
|
35
|
+
* loaded into every session instead of relying on the agent following a
|
|
36
|
+
* pointer. `@AGENTS.md` carries the user's own AGENTS.md content to Claude.
|
|
37
|
+
* A missing import target is skipped silently, so the block is harmless
|
|
38
|
+
* before `node_modules` exists.
|
|
39
|
+
*/
|
|
40
|
+
function claudeBlock(guide = AGENT_GUIDE_PATH) {
|
|
41
|
+
return [
|
|
42
|
+
BLOCK_START,
|
|
43
|
+
`@${guide}`,
|
|
44
|
+
"@AGENTS.md",
|
|
45
|
+
BLOCK_END
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Files timber wrote before the pointer model. A file matching one of
|
|
50
|
+
* these is timber's, not the user's, and is replaced (after a backup)
|
|
51
|
+
* rather than appended to. Anything else is user-authored.
|
|
52
|
+
*/
|
|
53
|
+
function isLegacyCopy(content) {
|
|
54
|
+
const trimmed = content.replace(/^\uFEFF/, "").trim();
|
|
55
|
+
const firstLine = trimmed.split(/\r?\n/, 1)[0].trim();
|
|
56
|
+
return firstLine === "# timber.js — AI Agent Skill" || firstLine === "# timber.js Project" || trimmed === "Read AGENTS.md for project context and conventions." || trimmed === "AGENTS.md";
|
|
57
|
+
}
|
|
58
|
+
/** Indices of lines that are exactly `marker` (surrounding whitespace allowed). */
|
|
59
|
+
function markerLines(lines, marker) {
|
|
60
|
+
return lines.flatMap((line, i) => line.trim() === marker ? [i] : []);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Replace the contents of an existing block, or return null when the file
|
|
64
|
+
* has none. A marker counts only on a line of its own, so prose or a code
|
|
65
|
+
* sample that mentions one is ordinary content. A start without an end (or
|
|
66
|
+
* the reverse, or two blocks) is a hand-edit we cannot interpret: fail
|
|
67
|
+
* loudly rather than append a second block or guess where the user's
|
|
68
|
+
* content ends. `eol` keeps a CRLF file CRLF.
|
|
69
|
+
*/
|
|
70
|
+
function replaceBlock(content, block, file, eol) {
|
|
71
|
+
const lines = content.split("\n");
|
|
72
|
+
const starts = markerLines(lines, BLOCK_START);
|
|
73
|
+
const ends = markerLines(lines, BLOCK_END);
|
|
74
|
+
if (starts.length === 0 && ends.length === 0) return null;
|
|
75
|
+
if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) throw new Error(`[timber] ${file} has malformed timber markers — expected exactly one ${BLOCK_START} line followed by one ${BLOCK_END} line. Fix or remove them, then re-run \`timber init\`. Nothing was written.`);
|
|
76
|
+
const blockLines = block.split("\n").map((line) => eol === "\r\n" ? line + "\r" : line);
|
|
77
|
+
return [
|
|
78
|
+
...lines.slice(0, starts[0]),
|
|
79
|
+
...blockLines,
|
|
80
|
+
...lines.slice(ends[0] + 1)
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
/** `<file>.bak`, or `.bak.1`, `.bak.2`, … — never overwrites a backup. */
|
|
84
|
+
function freeBackupPath(path) {
|
|
85
|
+
if (!existsSync(`${path}.bak`)) return `${path}.bak`;
|
|
86
|
+
for (let i = 1;; i++) {
|
|
87
|
+
const candidate = `${path}.bak.${i}`;
|
|
88
|
+
if (!existsSync(candidate)) return candidate;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Both paths name the same file (case-insensitive filesystems included). */
|
|
92
|
+
function sameFile(a, b) {
|
|
93
|
+
try {
|
|
94
|
+
return realpathSync.native(a) === realpathSync.native(b);
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Decide what to do with one file. Pure: reads, never writes. `runInit`
|
|
101
|
+
* plans both files before applying either, so an error in one (malformed
|
|
102
|
+
* markers) leaves both untouched.
|
|
103
|
+
*/
|
|
104
|
+
function planBlock(root, name, block) {
|
|
105
|
+
const path = join(root, name);
|
|
106
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
107
|
+
const write = (content) => () => writeFileSync(path, content);
|
|
108
|
+
if (stat?.isSymbolicLink()) {
|
|
109
|
+
const agentsPath = join(root, "AGENTS.md");
|
|
110
|
+
const target = resolve(root, readlinkSync(path));
|
|
111
|
+
if (name === "CLAUDE.md" && (target === agentsPath || sameFile(path, agentsPath))) return {
|
|
112
|
+
outcome: { kind: "replaced-symlink" },
|
|
113
|
+
apply: () => {
|
|
114
|
+
rmSync(path);
|
|
115
|
+
writeFileSync(path, block + "\n");
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
outcome: {
|
|
120
|
+
kind: "skipped-symlink",
|
|
121
|
+
target
|
|
122
|
+
},
|
|
123
|
+
apply: () => {}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (!stat) return {
|
|
127
|
+
outcome: { kind: "created" },
|
|
128
|
+
apply: write(block + "\n")
|
|
129
|
+
};
|
|
130
|
+
const content = readFileSync(path, "utf8");
|
|
131
|
+
const eol = content.includes("\r\n") ? "\r\n" : "\n";
|
|
132
|
+
const replaced = replaceBlock(content, block, name, eol);
|
|
133
|
+
if (replaced !== null) return replaced === content ? {
|
|
134
|
+
outcome: { kind: "unchanged" },
|
|
135
|
+
apply: () => {}
|
|
136
|
+
} : {
|
|
137
|
+
outcome: { kind: "updated" },
|
|
138
|
+
apply: write(replaced)
|
|
139
|
+
};
|
|
140
|
+
if (isLegacyCopy(content)) {
|
|
141
|
+
const backup = freeBackupPath(path);
|
|
142
|
+
return {
|
|
143
|
+
outcome: {
|
|
144
|
+
kind: "replaced-legacy",
|
|
145
|
+
backup
|
|
146
|
+
},
|
|
147
|
+
apply: () => {
|
|
148
|
+
renameSync(path, backup);
|
|
149
|
+
writeFileSync(path, block + "\n");
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
outcome: { kind: "appended" },
|
|
155
|
+
apply: write(content + (content.length === 0 ? "" : content.endsWith("\n") ? eol : eol + eol) + block.split("\n").join(eol) + eol)
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function outcomeLine(name, outcome, root) {
|
|
159
|
+
const rel = (path) => relative(root, path) || ".";
|
|
160
|
+
switch (outcome.kind) {
|
|
161
|
+
case "created": return `${name}: created`;
|
|
162
|
+
case "updated": return `${name}: updated timber block`;
|
|
163
|
+
case "appended": return `${name}: appended timber block`;
|
|
164
|
+
case "unchanged": return `${name}: unchanged`;
|
|
165
|
+
case "replaced-symlink": return `${name}: replaced symlink to AGENTS.md with a regular file`;
|
|
166
|
+
case "replaced-legacy": return `${name}: replaced old timber-generated copy (backup: ${rel(outcome.backup)})`;
|
|
167
|
+
case "skipped-symlink": return `${name}: skipped — it is a symlink to ${rel(outcome.target)}, and timber does not write through links. Add the block to the file you want it in, or replace the link.`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Where the installed guide is, relative to `root`: `node_modules` in the
|
|
172
|
+
* project, or one a package manager hoisted to an ancestor (npm/yarn/bun
|
|
173
|
+
* workspaces). Null when no install is found (not installed yet, or Yarn PnP).
|
|
174
|
+
*/
|
|
175
|
+
function findAgentGuide(root) {
|
|
176
|
+
for (let dir = root;; dir = dirname(dir)) {
|
|
177
|
+
if (existsSync(join(dir, "node_modules/@timber-js/app/agent-skill.md"))) return relative(root, join(dir, AGENT_GUIDE_PATH)).split(sep).join("/");
|
|
178
|
+
if (dirname(dir) === dir) return null;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Run `timber init` in `root`: plan both files, then write them. */
|
|
182
|
+
function runInit(root) {
|
|
183
|
+
const found = findAgentGuide(root);
|
|
184
|
+
const guide = found ?? "node_modules/@timber-js/app/agent-skill.md";
|
|
185
|
+
const plans = [["AGENTS.md", planBlock(root, "AGENTS.md", agentsBlock(guide))], ["CLAUDE.md", planBlock(root, "CLAUDE.md", claudeBlock(guide))]];
|
|
186
|
+
for (const [name, plan] of plans) {
|
|
187
|
+
plan.apply();
|
|
188
|
+
console.log(`[timber] ${outcomeLine(name, plan.outcome, root)}`);
|
|
189
|
+
}
|
|
190
|
+
console.log(`[timber] Agent guide: ${guide}`);
|
|
191
|
+
if (found === null) console.log(`[timber] Note: ${AGENT_GUIDE_PATH} does not exist yet. Install @timber-js/app (Yarn PnP has no node_modules, so the pointer cannot resolve there).`);
|
|
192
|
+
else if (found.startsWith("../")) console.log("[timber] Note: the guide is hoisted above this project. Claude Code may not load an @import from outside the project directory without approval; AGENTS.md still points at it.");
|
|
193
|
+
}
|
|
194
|
+
export { runInit };
|
|
195
|
+
|
|
196
|
+
//# sourceMappingURL=cli-init-BoXOYYil.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-init-BoXOYYil.js","names":[],"sources":["../../src/cli-init.ts"],"sourcesContent":["/**\n * `timber init` — point a project's agent instruction files at the guide\n * that ships inside the installed `@timber-js/app` package.\n *\n * The guide (`node_modules/@timber-js/app/agent-skill.md`) is never copied.\n * A copy freezes at the version `init` ran with; a pointer always reads the\n * installed version. Each of `AGENTS.md` and `CLAUDE.md` gets one\n * marker-delimited block that timber owns; everything outside the markers\n * belongs to the user and is never touched.\n *\n * This module is also the single source of the block text: the\n * create-timber-app templates are generated from `agentsFileContent()` /\n * `claudeFileContent()` and a test fails if they drift.\n *\n * See design/11-platform.md §\"`timber init` — agent guide pointer blocks\".\n */\n\nimport {\n existsSync,\n lstatSync,\n readFileSync,\n readlinkSync,\n realpathSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\n\nexport const BLOCK_START = '<!-- timber:start -->';\nexport const BLOCK_END = '<!-- timber:end -->';\n\n/** Where the guide lives, relative to the project root, in a non-hoisted install. */\nexport const AGENT_GUIDE_PATH = 'node_modules/@timber-js/app/agent-skill.md';\n\n/** The AGENTS.md block: a plain pointer, for every AGENTS.md-reading tool. */\nexport function agentsBlock(guide: string = AGENT_GUIDE_PATH): string {\n return [\n BLOCK_START,\n `This is a timber.js app. Before working, read \\`${guide}\\`.`,\n 'It matches the installed timber version and updates when timber is upgraded.',\n BLOCK_END,\n ].join('\\n');\n}\n\n/**\n * The CLAUDE.md block: Claude Code's `@path` imports, so the guide is\n * loaded into every session instead of relying on the agent following a\n * pointer. `@AGENTS.md` carries the user's own AGENTS.md content to Claude.\n * A missing import target is skipped silently, so the block is harmless\n * before `node_modules` exists.\n */\nexport function claudeBlock(guide: string = AGENT_GUIDE_PATH): string {\n return [BLOCK_START, `@${guide}`, '@AGENTS.md', BLOCK_END].join('\\n');\n}\n\n/** A freshly created AGENTS.md: just the block. */\nexport function agentsFileContent(): string {\n return agentsBlock() + '\\n';\n}\n\n/** A freshly created CLAUDE.md: just the block. */\nexport function claudeFileContent(): string {\n return claudeBlock() + '\\n';\n}\n\n/**\n * Files timber wrote before the pointer model. A file matching one of\n * these is timber's, not the user's, and is replaced (after a backup)\n * rather than appended to. Anything else is user-authored.\n */\nfunction isLegacyCopy(content: string): boolean {\n const trimmed = content.replace(/^\\uFEFF/, '').trim();\n const firstLine = trimmed.split(/\\r?\\n/, 1)[0].trim();\n return (\n // Old `timber init`: the full agent-skill.md copied into AGENTS.md.\n firstLine === '# timber.js — AI Agent Skill' ||\n // Old create-timber-app AGENTS.md.\n firstLine === '# timber.js Project' ||\n // Old create-timber-app CLAUDE.md, and old `init`'s Windows fallback.\n trimmed === 'Read AGENTS.md for project context and conventions.' ||\n // Old `init`'s CLAUDE.md symlink, checked out with core.symlinks=false:\n // a regular file whose whole content is the link target.\n trimmed === 'AGENTS.md'\n );\n}\n\nexport type InitOutcome =\n | { kind: 'created' }\n | { kind: 'updated' }\n | { kind: 'appended' }\n | { kind: 'unchanged' }\n | { kind: 'replaced-legacy'; backup: string }\n | { kind: 'replaced-symlink' }\n | { kind: 'skipped-symlink'; target: string };\n\n/** What `init` will do to one file, decided before anything is written. */\ninterface Plan {\n outcome: InitOutcome;\n apply(): void;\n}\n\n/** Indices of lines that are exactly `marker` (surrounding whitespace allowed). */\nfunction markerLines(lines: string[], marker: string): number[] {\n return lines.flatMap((line, i) => (line.trim() === marker ? [i] : []));\n}\n\n/**\n * Replace the contents of an existing block, or return null when the file\n * has none. A marker counts only on a line of its own, so prose or a code\n * sample that mentions one is ordinary content. A start without an end (or\n * the reverse, or two blocks) is a hand-edit we cannot interpret: fail\n * loudly rather than append a second block or guess where the user's\n * content ends. `eol` keeps a CRLF file CRLF.\n */\nfunction replaceBlock(content: string, block: string, file: string, eol: string): string | null {\n // Split on \\n only: a CRLF file's lines keep their \\r, so every line\n // outside the block is reassembled byte-for-byte.\n const lines = content.split('\\n');\n const starts = markerLines(lines, BLOCK_START);\n const ends = markerLines(lines, BLOCK_END);\n if (starts.length === 0 && ends.length === 0) return null;\n if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) {\n throw new Error(\n `[timber] ${file} has malformed timber markers — expected exactly one ` +\n `${BLOCK_START} line followed by one ${BLOCK_END} line. ` +\n `Fix or remove them, then re-run \\`timber init\\`. Nothing was written.`\n );\n }\n const blockLines = block.split('\\n').map((line) => (eol === '\\r\\n' ? line + '\\r' : line));\n // The end-marker line carried its own \\r; the block's last line now does.\n return [...lines.slice(0, starts[0]), ...blockLines, ...lines.slice(ends[0] + 1)].join('\\n');\n}\n\n/** `<file>.bak`, or `.bak.1`, `.bak.2`, … — never overwrites a backup. */\nfunction freeBackupPath(path: string): string {\n if (!existsSync(`${path}.bak`)) return `${path}.bak`;\n for (let i = 1; ; i++) {\n const candidate = `${path}.bak.${i}`;\n if (!existsSync(candidate)) return candidate;\n }\n}\n\n/** Both paths name the same file (case-insensitive filesystems included). */\nfunction sameFile(a: string, b: string): boolean {\n try {\n return realpathSync.native(a) === realpathSync.native(b);\n } catch {\n return false;\n }\n}\n\n/**\n * Decide what to do with one file. Pure: reads, never writes. `runInit`\n * plans both files before applying either, so an error in one (malformed\n * markers) leaves both untouched.\n */\nexport function planBlock(root: string, name: string, block: string): Plan {\n const path = join(root, name);\n const stat = lstatSync(path, { throwIfNoEntry: false });\n const write = (content: string) => () => writeFileSync(path, content);\n\n // timber never writes through a symlink: the target may be the sibling\n // agent file (the CLAUDE block would land in AGENTS.md) or a file shared\n // outside the project.\n if (stat?.isSymbolicLink()) {\n const agentsPath = join(root, 'AGENTS.md');\n const target = resolve(root, readlinkSync(path));\n // Old `init` made CLAUDE.md a symlink to AGENTS.md: that one is timber's,\n // so it becomes a regular file (which also sidesteps Windows symlink\n // EPERM). Its content still reaches Claude through the block's\n // @AGENTS.md. Matched by real path too, for case-insensitive filesystems.\n if (name === 'CLAUDE.md' && (target === agentsPath || sameFile(path, agentsPath))) {\n return {\n outcome: { kind: 'replaced-symlink' },\n apply: () => {\n rmSync(path);\n writeFileSync(path, block + '\\n');\n },\n };\n }\n // Any other link (a user's own, or dangling) is left alone.\n return { outcome: { kind: 'skipped-symlink', target }, apply: () => {} };\n }\n\n if (!stat) return { outcome: { kind: 'created' }, apply: write(block + '\\n') };\n\n const content = readFileSync(path, 'utf8');\n const eol = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const replaced = replaceBlock(content, block, name, eol);\n if (replaced !== null) {\n return replaced === content\n ? { outcome: { kind: 'unchanged' }, apply: () => {} }\n : { outcome: { kind: 'updated' }, apply: write(replaced) };\n }\n\n if (isLegacyCopy(content)) {\n const backup = freeBackupPath(path);\n return {\n outcome: { kind: 'replaced-legacy', backup },\n apply: () => {\n // Back up first, then replace: the copy may carry the user's edits.\n // rename keeps the original bytes and fails before anything is lost.\n renameSync(path, backup);\n writeFileSync(path, block + '\\n');\n },\n };\n }\n\n const separator = content.length === 0 ? '' : content.endsWith('\\n') ? eol : eol + eol;\n const appended = content + separator + block.split('\\n').join(eol) + eol;\n return { outcome: { kind: 'appended' }, apply: write(appended) };\n}\n\nfunction outcomeLine(name: string, outcome: InitOutcome, root: string): string {\n const rel = (path: string) => relative(root, path) || '.';\n switch (outcome.kind) {\n case 'created':\n return `${name}: created`;\n case 'updated':\n return `${name}: updated timber block`;\n case 'appended':\n return `${name}: appended timber block`;\n case 'unchanged':\n return `${name}: unchanged`;\n case 'replaced-symlink':\n return `${name}: replaced symlink to AGENTS.md with a regular file`;\n case 'replaced-legacy':\n return `${name}: replaced old timber-generated copy (backup: ${rel(outcome.backup)})`;\n case 'skipped-symlink':\n return (\n `${name}: skipped — it is a symlink to ${rel(outcome.target)}, and timber does not ` +\n `write through links. Add the block to the file you want it in, or replace the link.`\n );\n }\n}\n\n/**\n * Where the installed guide is, relative to `root`: `node_modules` in the\n * project, or one a package manager hoisted to an ancestor (npm/yarn/bun\n * workspaces). Null when no install is found (not installed yet, or Yarn PnP).\n */\nexport function findAgentGuide(root: string): string | null {\n for (let dir = root; ; dir = dirname(dir)) {\n if (existsSync(join(dir, AGENT_GUIDE_PATH))) {\n return relative(root, join(dir, AGENT_GUIDE_PATH)).split(sep).join('/');\n }\n if (dirname(dir) === dir) return null;\n }\n}\n\n/** Run `timber init` in `root`: plan both files, then write them. */\nexport function runInit(root: string): void {\n const found = findAgentGuide(root);\n const guide = found ?? AGENT_GUIDE_PATH;\n const plans: Array<[string, Plan]> = [\n ['AGENTS.md', planBlock(root, 'AGENTS.md', agentsBlock(guide))],\n ['CLAUDE.md', planBlock(root, 'CLAUDE.md', claudeBlock(guide))],\n ];\n // AGENTS.md first: a legacy CLAUDE.md link to it is replaced only after\n // AGENTS.md is in its final state.\n for (const [name, plan] of plans) {\n plan.apply();\n console.log(`[timber] ${outcomeLine(name, plan.outcome, root)}`);\n }\n console.log(`[timber] Agent guide: ${guide}`);\n if (found === null) {\n console.log(\n `[timber] Note: ${AGENT_GUIDE_PATH} does not exist yet. Install @timber-js/app ` +\n `(Yarn PnP has no node_modules, so the pointer cannot resolve there).`\n );\n } else if (found.startsWith('../')) {\n console.log(\n '[timber] Note: the guide is hoisted above this project. Claude Code may not load an ' +\n '@import from outside the project directory without approval; AGENTS.md still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AAQ,GAAG,MAAM,KAAK,OAAO;CACnC;AACF;;AAGA,SAAgB,QAAQ,MAAoB;CAC1C,MAAM,QAAQ,eAAe,IAAI;CACjC,MAAM,QAAQ,SAAA;CACd,MAAM,QAA+B,CACnC,CAAC,aAAa,UAAU,MAAM,aAAa,YAAY,KAAK,CAAC,CAAC,GAC9D,CAAC,aAAa,UAAU,MAAM,aAAa,YAAY,KAAK,CAAC,CAAC,CAChE;CAGA,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO;EAChC,KAAK,MAAM;EACX,QAAQ,IAAI,YAAY,YAAY,MAAM,KAAK,SAAS,IAAI,GAAG;CACjE;CACA,QAAQ,IAAI,yBAAyB,OAAO;CAC5C,IAAI,UAAU,MACZ,QAAQ,IACN,kBAAkB,iBAAiB,iHAErC;MACK,IAAI,MAAM,WAAW,KAAK,GAC/B,QAAQ,IACN,gLAEF;AAEJ"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as scanRoutes } from "./scanner-
|
|
2
|
-
import { u as resolveAppDir } from "./plugin-context-
|
|
1
|
+
import { n as scanRoutes } from "./scanner-CJC-ScJU.js";
|
|
2
|
+
import { u as resolveAppDir } from "./plugin-context-FCkaNLUB.js";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
-
|
|
5
|
+
// src/cli-schema-sync.ts
|
|
6
6
|
/**
|
|
7
7
|
* `timber schema sync` — scan filesystem for dynamic segments, append
|
|
8
8
|
* missing entries with `codec.string` defaults, and remove stale entries
|
|
@@ -284,7 +284,6 @@ function runSchemaSync(projectRoot) {
|
|
|
284
284
|
created: false
|
|
285
285
|
};
|
|
286
286
|
}
|
|
287
|
-
//#endregion
|
|
288
287
|
export { parseExistingSchemaKeys as a, findSegmentParamsBlock as i, defaultCodecForSegment as n, runSchemaSync as o, findSchemaFile as r, collectDynamicSegments as t };
|
|
289
288
|
|
|
290
|
-
//# sourceMappingURL=cli-schema-sync-
|
|
289
|
+
//# sourceMappingURL=cli-schema-sync-DIPurq7X.js.map
|