@timber-js/app 0.2.0-alpha.196 → 0.2.0-alpha.198
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/dist/_chunks/{actions-CWYtq6ii.js → actions-BS-m5SLv.js} +3 -3
- package/dist/_chunks/{actions-CWYtq6ii.js.map → actions-BS-m5SLv.js.map} +1 -1
- package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -1
- package/dist/_chunks/{build-manifest-DWppEdLB.js → build-manifest-DTmSGLRz.js} +51 -2
- package/dist/_chunks/build-manifest-DTmSGLRz.js.map +1 -0
- package/dist/_chunks/{cache-api-CQeYzA5g.js → cache-api-DqzgTEqk.js} +4 -49
- package/dist/_chunks/cache-api-DqzgTEqk.js.map +1 -0
- package/dist/_chunks/{chains-h7EO-u3n.js → chains-CZG7E5zg.js} +2 -2
- package/dist/_chunks/{chains-h7EO-u3n.js.map → chains-CZG7E5zg.js.map} +1 -1
- package/dist/_chunks/{cli-check-BVthpfLS.js → cli-check-dVDi1GQz.js} +3 -3
- package/dist/_chunks/{cli-check-BVthpfLS.js.map → cli-check-dVDi1GQz.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js → cli-schema-sync-DTy_-Msq.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js.map → cli-schema-sync-DTy_-Msq.js.map} +1 -1
- package/dist/_chunks/{cloudflare-BKJC3SC_.js → cloudflare-BFb__LYG.js} +2 -2
- package/dist/_chunks/{cloudflare-BKJC3SC_.js.map → cloudflare-BFb__LYG.js.map} +1 -1
- package/dist/_chunks/{convention-lint-DO10_pVl.js → convention-lint-Ph6luW4c.js} +4 -2
- package/dist/_chunks/convention-lint-Ph6luW4c.js.map +1 -0
- package/dist/_chunks/{error-boundary-D-lkwyaD.js → error-boundary-BvRCCmbN.js} +3 -3
- package/dist/_chunks/{error-boundary-D-lkwyaD.js.map → error-boundary-BvRCCmbN.js.map} +1 -1
- package/dist/_chunks/{href-validation-CMc5JRls.js → href-validation-BIrxavIy.js} +74 -2
- package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
- package/dist/_chunks/{live-graph-Bx4HodF1.js → live-graph-BXDsdzBv.js} +3 -3
- package/dist/_chunks/{live-graph-Bx4HodF1.js.map → live-graph-BXDsdzBv.js.map} +1 -1
- package/dist/_chunks/{logger-pumCm3Il.js → logger-DDirEsn7.js} +3 -4
- package/dist/_chunks/{logger-pumCm3Il.js.map → logger-DDirEsn7.js.map} +1 -1
- package/dist/_chunks/navigation-root-B00jjGd5.js +233 -0
- package/dist/_chunks/navigation-root-B00jjGd5.js.map +1 -0
- package/dist/_chunks/{segment-context-CjOlyB8Y.js → param-value-C8TNYchQ.js} +2 -33
- package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
- package/dist/_chunks/{poison-scan-BAxfTT5L.js → poison-scan-BoDLgbix.js} +2 -2
- package/dist/_chunks/{poison-scan-BAxfTT5L.js.map → poison-scan-BoDLgbix.js.map} +1 -1
- package/dist/_chunks/{router-ref-BzqbPwYC.js → router-ref-8gr8qsxN.js} +2 -2
- package/dist/_chunks/{router-ref-BzqbPwYC.js.map → router-ref-8gr8qsxN.js.map} +1 -1
- package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js → rsc-cache-key-ClUiXQnK.js} +2 -2
- package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js.map → rsc-cache-key-ClUiXQnK.js.map} +1 -1
- package/dist/_chunks/{scanner-BRIOmHE2.js → scanner-tdFPvDYi.js} +174 -7
- package/dist/_chunks/scanner-tdFPvDYi.js.map +1 -0
- package/dist/_chunks/segment-context-D9_89u34.js +34 -0
- package/dist/_chunks/segment-context-D9_89u34.js.map +1 -0
- package/dist/_chunks/singleflight-2lUWfcAk.js +54 -0
- package/dist/_chunks/singleflight-2lUWfcAk.js.map +1 -0
- package/dist/_chunks/{ssr-data-Ya2HJPFp.js → ssr-data-BQGhTPAK.js} +2 -17
- package/dist/_chunks/ssr-data-BQGhTPAK.js.map +1 -0
- package/dist/_chunks/{walkers-BU6z9xRV.js → walkers-DNX05dC0.js} +2 -2
- package/dist/_chunks/{walkers-BU6z9xRV.js.map → walkers-DNX05dC0.js.map} +1 -1
- package/dist/adapters/cloudflare-dev.js +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/adapters/cloudflare.js +1 -1
- package/dist/adapters/nitro.d.ts +1 -1
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/crawl-entry.js +2 -2
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/index.js +1 -1
- package/dist/cache/singleflight.d.ts +2 -0
- package/dist/cache/singleflight.d.ts.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/client/browser-entry/hydrate.d.ts +21 -15
- package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
- package/dist/client/browser-entry/index.d.ts +4 -3
- package/dist/client/browser-entry/index.d.ts.map +1 -1
- package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
- package/dist/client/browser-entry/router-init.d.ts +17 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/global-context.d.ts +15 -0
- package/dist/client/global-context.d.ts.map +1 -0
- package/dist/client/index.js +138 -35
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.d.ts +0 -1
- package/dist/client/internal.d.ts.map +1 -1
- package/dist/client/internal.js +206 -55
- package/dist/client/internal.js.map +1 -1
- package/dist/client/link.d.ts.map +1 -1
- package/dist/client/location-search.d.ts +12 -0
- package/dist/client/location-search.d.ts.map +1 -0
- package/dist/client/navigation-api.d.ts.map +1 -1
- package/dist/client/navigation-commit.d.ts +18 -0
- package/dist/client/navigation-commit.d.ts.map +1 -1
- package/dist/client/navigation-context.d.ts +13 -11
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/navigation-root.d.ts +47 -108
- package/dist/client/navigation-root.d.ts.map +1 -1
- package/dist/client/navigation-transition.d.ts +136 -0
- package/dist/client/navigation-transition.d.ts.map +1 -0
- package/dist/client/nuqs-adapter.d.ts.map +1 -1
- package/dist/client/params-context.d.ts +4 -5
- package/dist/client/params-context.d.ts.map +1 -1
- package/dist/client/react-root.d.ts +44 -0
- package/dist/client/react-root.d.ts.map +1 -0
- package/dist/client/router-pipeline.d.ts +2 -2
- package/dist/client/router-pipeline.d.ts.map +1 -1
- package/dist/client/router-types.d.ts +12 -2
- package/dist/client/router-types.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/segment-cache.d.ts +39 -0
- package/dist/client/segment-cache.d.ts.map +1 -1
- package/dist/client/segment-context.d.ts.map +1 -1
- package/dist/client/segment-outlet.d.ts +25 -14
- package/dist/client/segment-outlet.d.ts.map +1 -1
- package/dist/client/segment-update-context.d.ts +3 -9
- package/dist/client/segment-update-context.d.ts.map +1 -1
- package/dist/client/slot-content-cache-context.d.ts +35 -0
- package/dist/client/slot-content-cache-context.d.ts.map +1 -0
- package/dist/client/ssr-data.d.ts +8 -2
- package/dist/client/ssr-data.d.ts.map +1 -1
- package/dist/client/state.d.ts +0 -15
- package/dist/client/state.d.ts.map +1 -1
- package/dist/client/use-pathname.d.ts +13 -11
- package/dist/client/use-pathname.d.ts.map +1 -1
- package/dist/client/use-search-params.d.ts +13 -13
- package/dist/client/use-search-params.d.ts.map +1 -1
- package/dist/client/use-segment-params.d.ts +18 -68
- package/dist/client/use-segment-params.d.ts.map +1 -1
- package/dist/config-types.d.ts +17 -0
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/cookies/index.js +1 -1
- package/dist/dev-tools/holding-server.d.ts +15 -10
- package/dist/dev-tools/holding-server.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -43
- package/dist/index.js.map +1 -1
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/plugins/static-build.d.ts +2 -2
- package/dist/plugins/static-build.d.ts.map +1 -1
- package/dist/routing/codegen-write.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/routing/interception-overlap.d.ts +35 -0
- package/dist/routing/interception-overlap.d.ts.map +1 -0
- package/dist/routing/interception.d.ts.map +1 -1
- package/dist/rsc-runtime/ssr.d.ts +3 -1
- package/dist/rsc-runtime/ssr.d.ts.map +1 -1
- package/dist/server/als-registry.d.ts +6 -0
- package/dist/server/als-registry.d.ts.map +1 -1
- package/dist/server/csp-nonce.d.ts +45 -0
- package/dist/server/csp-nonce.d.ts.map +1 -0
- package/dist/server/default-status-page.d.ts.map +1 -1
- package/dist/server/deny-renderer.d.ts.map +1 -1
- package/dist/server/flight-scripts.d.ts +5 -2
- package/dist/server/flight-scripts.d.ts.map +1 -1
- package/dist/server/html-injector-core.d.ts +17 -2
- package/dist/server/html-injector-core.d.ts.map +1 -1
- package/dist/server/html-injectors.d.ts +3 -2
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +86 -37
- package/dist/server/internal.js.map +1 -1
- package/dist/server/metadata-render.d.ts.map +1 -1
- package/dist/server/node-stream-transforms.d.ts +3 -17
- package/dist/server/node-stream-transforms.d.ts.map +1 -1
- package/dist/server/nuqs-ssr-provider.d.ts +7 -3
- package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/prebuilt/key-discipline.d.ts +32 -3
- package/dist/server/prebuilt/key-discipline.d.ts.map +1 -1
- package/dist/server/primitives.d.ts.map +1 -1
- package/dist/server/render-utils.d.ts +4 -3
- package/dist/server/render-utils.d.ts.map +1 -1
- package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -1
- package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
- package/dist/server/ssr-bridge-types.d.ts +22 -2
- package/dist/server/ssr-bridge-types.d.ts.map +1 -1
- package/dist/server/ssr-entry.d.ts.map +1 -1
- package/dist/server/ssr-render.d.ts +5 -1
- package/dist/server/ssr-render.d.ts.map +1 -1
- package/dist/server/ssr-wrappers.d.ts +59 -27
- package/dist/server/ssr-wrappers.d.ts.map +1 -1
- package/dist/server/types.d.ts +10 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/shims/navigation-rsc.d.ts +21 -0
- package/dist/shims/navigation-rsc.d.ts.map +1 -0
- package/docs/api/30-api-server.mdx +1 -0
- package/docs/api/35-api-typescript.mdx +4 -83
- package/docs/learn/03-fetching-data.mdx +1 -1
- package/docs/learn/{03b-access-control.mdx → 04-access-control.mdx} +2 -17
- package/docs/learn/05-the-flush-point.mdx +175 -0
- package/docs/learn/{05-typed-params.mdx → 06-typed-params.mdx} +1 -1
- package/docs/learn/07-typed-routes.mdx +25 -49
- package/docs/learn/{08-streaming.mdx → 09-streaming.mdx} +1 -7
- package/docs/learn/{10-middleware.mdx → 11-middleware.mdx} +1 -0
- package/package.json +3 -3
- package/src/adapters/nitro.ts +7 -7
- package/src/cache/singleflight.ts +5 -0
- package/src/client/browser-entry/hydrate.ts +54 -104
- package/src/client/browser-entry/index.ts +16 -6
- package/src/client/browser-entry/post-hydration.ts +3 -2
- package/src/client/browser-entry/router-init.ts +84 -33
- package/src/client/global-context.ts +31 -0
- package/src/client/internal.ts +1 -2
- package/src/client/link.tsx +18 -18
- package/src/client/location-search.ts +15 -0
- package/src/client/navigation-api.ts +4 -2
- package/src/client/navigation-commit.ts +48 -2
- package/src/client/navigation-context.ts +25 -37
- package/src/client/navigation-root.tsx +55 -411
- package/src/client/navigation-transition.ts +278 -0
- package/src/client/nuqs-adapter.tsx +4 -5
- package/src/client/params-context.ts +13 -18
- package/src/client/react-root.ts +72 -0
- package/src/client/router-lifecycle.ts +1 -1
- package/src/client/router-pipeline.ts +96 -22
- package/src/client/router-types.ts +12 -2
- package/src/client/router.ts +48 -36
- package/src/client/segment-cache.ts +70 -2
- package/src/client/segment-context.ts +7 -4
- package/src/client/segment-outlet.tsx +41 -86
- package/src/client/segment-update-context.ts +7 -26
- package/src/client/slot-content-cache-context.ts +43 -0
- package/src/client/ssr-data.ts +8 -2
- package/src/client/state.ts +0 -26
- package/src/client/use-pathname.ts +21 -31
- package/src/client/use-search-params.ts +31 -29
- package/src/client/use-segment-params.ts +27 -126
- package/src/config-types.ts +17 -0
- package/src/config-validation.ts +17 -0
- package/src/dev-tools/holding-server.ts +23 -12
- package/src/index.ts +26 -11
- package/src/plugins/dev-server.ts +9 -12
- package/src/plugins/entries.ts +3 -0
- package/src/plugins/shims.ts +8 -7
- package/src/plugins/static-build.ts +9 -5
- package/src/react-canary.d.ts +2 -0
- package/src/routing/codegen-write.ts +2 -0
- package/src/routing/interception-overlap.ts +141 -0
- package/src/routing/interception.ts +118 -5
- package/src/rsc-runtime/ssr.ts +3 -2
- package/src/server/als-registry.ts +6 -0
- package/src/server/csp-nonce.ts +70 -0
- package/src/server/default-status-page.ts +1 -0
- package/src/server/deny-renderer.ts +7 -3
- package/src/server/flight-scripts.ts +9 -4
- package/src/server/html-injector-core.ts +26 -9
- package/src/server/html-injectors.ts +8 -8
- package/src/server/metadata-render.ts +26 -4
- package/src/server/node-stream-transforms.ts +7 -20
- package/src/server/nuqs-ssr-provider.tsx +8 -7
- package/src/server/pipeline-phases.ts +5 -0
- package/src/server/prebuilt/key-discipline.ts +82 -13
- package/src/server/prebuilt-runtime.ts +2 -2
- package/src/server/primitives.ts +4 -4
- package/src/server/render-utils.ts +8 -4
- package/src/server/rsc-entry/action-middleware-runner.ts +7 -0
- package/src/server/rsc-entry/error-renderer.ts +5 -2
- package/src/server/rsc-entry/index.ts +8 -0
- package/src/server/rsc-entry/ssr-renderer.ts +11 -4
- package/src/server/ssr-bridge-types.ts +22 -2
- package/src/server/ssr-entry.ts +35 -28
- package/src/server/ssr-render.ts +13 -4
- package/src/server/ssr-wrappers.tsx +81 -61
- package/src/server/types.ts +10 -0
- package/src/shared/slot-params.ts +3 -4
- package/src/shims/navigation-rsc.ts +47 -0
- package/dist/_chunks/build-manifest-DWppEdLB.js.map +0 -1
- package/dist/_chunks/cache-api-CQeYzA5g.js.map +0 -1
- package/dist/_chunks/convention-lint-DO10_pVl.js.map +0 -1
- package/dist/_chunks/href-validation-CMc5JRls.js.map +0 -1
- package/dist/_chunks/scanner-BRIOmHE2.js.map +0 -1
- package/dist/_chunks/segment-context-CjOlyB8Y.js.map +0 -1
- package/dist/_chunks/slot-params-BCTmZkQB.js +0 -76
- package/dist/_chunks/slot-params-BCTmZkQB.js.map +0 -1
- package/dist/_chunks/ssr-data-Ya2HJPFp.js.map +0 -1
- package/dist/_chunks/use-segment-params-DzTBpkvj.js +0 -398
- package/dist/_chunks/use-segment-params-DzTBpkvj.js.map +0 -1
- package/docs/learn/04-loading-states.mdx +0 -67
- package/docs/learn/04b-the-flush-point.mdx +0 -115
- package/docs/learn/12-client-navigation.mdx +0 -176
- package/docs/learn/13-configuration.mdx +0 -166
- package/docs/more/01-advanced-routing.mdx +0 -344
- package/docs/more/02-advanced-forms.mdx +0 -137
- package/docs/more/03-coming-from-nextjs.mdx +0 -186
- package/docs/more/04-metadata-and-fonts.mdx +0 -193
- package/docs/more/04b-mdx.mdx +0 -229
- package/docs/more/05-content-collections.mdx +0 -90
- package/docs/more/06-instrumentation.mdx +0 -214
- package/docs/more/07-security.mdx +0 -129
- package/docs/more/08-developer-experience.mdx +0 -134
- package/docs/more/40-why-timber.mdx +0 -50
- package/docs/more/41-timber-vs-nextjs.mdx +0 -81
- package/docs/more/42-timber-vs-others.mdx +0 -68
- package/docs/more/50-ai-agent-instructions.mdx +0 -171
- /package/docs/learn/{06-forms-and-actions.mdx → 08-forms-and-actions.mdx} +0 -0
- /package/docs/learn/{09-caching.mdx → 10-caching.mdx} +0 -0
- /package/docs/learn/{11-error-handling.mdx → 12-error-handling.mdx} +0 -0
- /package/docs/learn/{14-deploying.mdx → 13-deploying.mdx} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"convention-lint-DO10_pVl.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/routing/export-detect.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFile(segmentFile, content, 'utf-8'))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n Promise.all([\n writeFile(routesPath, content, 'utf-8'),\n writeFile(envPath, TIMBER_ENV_DTS, 'utf-8'),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * AST-based export detection for route files.\n *\n * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and\n * default exports, replacing the regex-based approach that was fragile\n * with TypeScript syntax (type exports, `as` aliases, comments, etc.).\n */\n\nimport { existsSync } from 'node:fs';\nimport { parseAst } from 'vite';\nimport { readFileCached } from './file-cache.ts';\n\ninterface AstNode {\n type: string;\n exportKind?: string;\n declaration?: AstNode;\n specifiers?: Array<{\n exported?: { name: string };\n local?: { name: string };\n exportKind?: string;\n }>;\n id?: { name: string };\n declarations?: Array<{ id?: { name: string }; init?: AstNode }>;\n /** Set on re-exports: `export { X } from './y'`. Absent on local exports. */\n source?: { value?: string } | null;\n /** Set on runtime-transparent wrappers: `X as T`, `X satisfies T`, `(X)`, `X!`. */\n expression?: AstNode;\n /** Set on `Identifier` nodes. */\n name?: string;\n}\n\ninterface ProgramNode {\n body: AstNode[];\n}\n\nfunction tryParse(source: string): ProgramNode | null {\n try {\n return parseAst(source, { lang: 'tsx' }) as unknown as ProgramNode;\n } catch {\n return null;\n }\n}\n\n/**\n * Collect all named export identifiers from a parsed program.\n * Handles: `export function X`, `export const X`, `export { X }`,\n * `export { X } from '...'`, `export { Y as X }`.\n */\nfunction collectNamedExports(program: ProgramNode): Set<string> {\n const names = new Set<string>();\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n // Skip `export type ...` declarations — they're erased at runtime\n if (stmt.exportKind === 'type') continue;\n\n if (stmt.declaration) {\n if (stmt.declaration.id?.name) {\n names.add(stmt.declaration.id.name);\n }\n if (stmt.declaration.declarations) {\n for (const decl of stmt.declaration.declarations) {\n if (decl.id?.name) names.add(decl.id.name);\n }\n }\n }\n\n if (stmt.specifiers) {\n for (const spec of stmt.specifiers) {\n // Skip `export { type X }` — per-specifier type exports\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name && spec.exported.name !== 'default') {\n names.add(spec.exported.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * The specifier exporting a *runtime* default from this statement, if any.\n *\n * Type-only exports erase, so they are not default exports at runtime — and\n * TypeScript spells that two ways, on two different nodes: `export type { X as\n * default }` marks the **statement**, `export { type X as default }` marks the\n * **specifier**. Both have to be checked, or a type alias reads as a component:\n * a status file whose only default is a type has nothing for the error boundary\n * to receive (the renderer's `mod?.default` skips it), so treating it as one\n * would fail a build over a file that cannot break anything.\n *\n * One implementation because two callers must agree on what \"has a default\n * export\" means: `hasDefaultExport` decides whether to warn that a page has\n * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.\n */\nfunction defaultSpecifier(stmt: AstNode): NonNullable<AstNode['specifiers']>[number] | null {\n if (stmt.type !== 'ExportNamedDeclaration' || !stmt.specifiers) return null;\n if (stmt.exportKind === 'type') return null;\n for (const spec of stmt.specifiers) {\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name === 'default') return spec;\n }\n return null;\n}\n\n/**\n * Check whether a program has a default export.\n * Handles: `export default ...`, `export { X as default }`,\n * `export { default } from '...'`. Type-only defaults do not count —\n * see `defaultSpecifier`.\n */\nfunction hasDefaultExport(program: ProgramNode): boolean {\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') return true;\n if (defaultSpecifier(stmt)) return true;\n }\n return false;\n}\n\n/**\n * Check whether a program has any bare `export * from '...'` declarations.\n * Excludes `export * as X from '...'` (namespace re-exports) since those\n * create a namespace object, not individual top-level exports.\n */\nfunction hasStarExport(program: ProgramNode): boolean {\n return program.body.some(\n (stmt) =>\n stmt.type === 'ExportAllDeclaration' && !(stmt as any).exported && stmt.exportKind !== 'type'\n );\n}\n\n/**\n * Check if a file exports a specific named export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return collectNamedExports(program).has(exportName);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any of the given named exports.\n * Returns the set of matching export names.\n */\nexport function fileHasAnyExport(filePath: string, exportNames: readonly string[]): Set<string> {\n const matches = new Set<string>();\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return matches;\n const exports = collectNamedExports(program);\n for (const name of exportNames) {\n if (exports.has(name)) matches.add(name);\n }\n } catch {\n // Graceful fallback: return empty set\n }\n return matches;\n}\n\n/**\n * Check if a file has a default export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasDefaultExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasDefaultExport(program);\n } catch {\n return false;\n }\n}\n\n/** Node types whose value is unambiguously constructed by this module. */\nconst FUNCTION_LIKE = new Set([\n 'FunctionDeclaration',\n 'FunctionExpression',\n 'ArrowFunctionExpression',\n 'ClassDeclaration',\n 'ClassExpression',\n]);\n\n/**\n * Expression wrappers that erase at runtime and so cannot change where a value\n * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.\n */\nconst TRANSPARENT_WRAPPERS = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n 'TSInstantiationExpression',\n 'ParenthesizedExpression',\n]);\n\n/**\n * Strip runtime-transparent wrappers so the node underneath can be classified.\n *\n * Without this, `(() => <h1 />) satisfies React.FC` reads as a\n * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a\n * provably-local component is misread as one whose origin cannot be\n * determined — turning a build error into a warning.\n */\nfunction unwrapTransparent(node: AstNode): AstNode {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) {\n current = current.expression;\n }\n return current;\n}\n\n/**\n * Whether `name` is bound at module top level to a function or class written\n * in this file. An imported binding can never match: imports are\n * `ImportDeclaration` specifiers, not function/class/variable declarations,\n * and a module-level name cannot be both.\n */\nfunction bindsLocalFunction(program: ProgramNode, name: string): boolean {\n for (const stmt of program.body) {\n // `export function X() {}` binds X locally too — unwrap the export.\n const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;\n if (!decl) continue;\n if (\n (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') &&\n decl.id?.name === name\n ) {\n return true;\n }\n if (decl.type === 'VariableDeclaration') {\n for (const d of decl.declarations ?? []) {\n if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the default export is *provably* a value constructed by this module:\n * `export default function/class/() => {}`, or a name bound to a function or\n * class declared here — whether it leaves via `export default Name` or\n * `export { Name as default }`. Both spellings are the same fact about where\n * the value was built, so both must answer the same way.\n *\n * This is the sound half of \"is this a server component?\". A file with no\n * `'use client'` directive whose default export is built here is a server\n * component, full stop. Everything else — `export { default } from\n * './client-thing'`, `export default Imported`, `export default memo(X)`,\n * an unparseable file — returns false, because the exported value may have\n * been minted in a module that *does* carry the directive. Callers must not\n * infer \"server component\" from a missing directive alone.\n */\nexport function fileDefaultExportIsLocalValue(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') {\n const decl = stmt.declaration && unwrapTransparent(stmt.declaration);\n if (!decl) return false;\n if (FUNCTION_LIKE.has(decl.type)) return true;\n if (decl.type === 'Identifier' && decl.name) {\n return bindsLocalFunction(program, decl.name);\n }\n return false;\n }\n\n // `export { Name as default }` — the same default export by another\n // spelling. `hasDefaultExport` already counts it, so an analysis that\n // skipped it here would let the exact defect this powers slip through\n // as a warning.\n const spec = defaultSpecifier(stmt);\n if (spec) {\n // `export { X as default } from './client-thing'` re-exports another\n // module's value — the directive governing it lives over there.\n if (stmt.source) return false;\n return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any `export * from '...'` declarations.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasStarExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasStarExport(program);\n } catch {\n return false;\n }\n}\n\n/**\n * Parsed value of `export const prerender` from a route file.\n *\n * - `true` / `false` — literal boolean\n * - `{ ttl?, tags? }` — ISR options object (prerender: true is implied)\n * - `undefined` — no `export const prerender` found\n *\n * See design/45-cache-lifetimes.md §\"Route-Level Static\".\n */\nexport type PrerenderExportValue = boolean | { ttl?: number; tags?: string[] };\n\nfunction extractLiteralValue(node: AstNode): unknown {\n if (!node) return undefined;\n const n = node as any;\n if (n.type === 'Literal') return n.value;\n if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument?.type === 'Literal') {\n return -(n.argument.value as number);\n }\n if (n.type === 'ArrayExpression') {\n const elements = n.elements as AstNode[] | undefined;\n if (!elements) return undefined;\n const result: unknown[] = [];\n for (const el of elements) {\n const v = extractLiteralValue(el);\n if (v === undefined) return undefined;\n result.push(v);\n }\n return result;\n }\n return undefined;\n}\n\nfunction extractObjectLiteral(node: AstNode): Record<string, unknown> | undefined {\n if ((node as any).type !== 'ObjectExpression') return undefined;\n const props = (node as any).properties as AstNode[] | undefined;\n if (!props) return undefined;\n const result: Record<string, unknown> = {};\n for (const prop of props) {\n const p = prop as any;\n if (p.type === 'SpreadElement') return undefined;\n if (p.type !== 'Property' || p.computed) return undefined;\n const key =\n p.key?.type === 'Identifier'\n ? p.key.name\n : p.key?.type === 'Literal'\n ? String(p.key.value)\n : undefined;\n if (!key) return undefined;\n const value = extractLiteralValue(p.value);\n if (value === undefined) return undefined;\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Extract the value of `export const prerender` from a file.\n * Returns undefined if the file doesn't export `prerender` or can't be parsed.\n *\n * Supports:\n * export const prerender = true;\n * export const prerender = false;\n * export const prerender = { ttl: 3600, tags: ['docs'] };\n */\nexport function getPrerenderExport(filePath: string): PrerenderExportValue | undefined {\n if (!existsSync(filePath)) return undefined;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return undefined;\n\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n if (stmt.exportKind === 'type') continue;\n if (!stmt.declaration) continue;\n const decl = stmt.declaration;\n if (decl.type !== 'VariableDeclaration') continue;\n const declarations = decl.declarations as\n | Array<{\n id?: { name?: string };\n init?: AstNode;\n }>\n | undefined;\n if (!declarations) continue;\n for (const d of declarations) {\n if (d.id?.name !== 'prerender' || !d.init) continue;\n const init = d.init as any;\n if (init.type === 'Literal' && typeof init.value === 'boolean') {\n return init.value;\n }\n if (init.type === 'ObjectExpression') {\n const obj = extractObjectLiteral(init);\n if (!obj) return undefined;\n const result: { ttl?: number; tags?: string[] } = {};\n if ('ttl' in obj && typeof obj.ttl === 'number') result.ttl = obj.ttl;\n if (\n 'tags' in obj &&\n Array.isArray(obj.tags) &&\n obj.tags.every((t: unknown) => typeof t === 'string')\n ) {\n result.tags = obj.tags as string[];\n }\n return result;\n }\n return undefined;\n }\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Check if a file starts with a specific directive (e.g. \"use client\").\n * Directives are string literal expression statements at the top of the file.\n */\nexport function fileHasDirective(filePath: string, directive: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type !== 'ExpressionStatement') break;\n const expr = (stmt as any).expression;\n if (expr?.type !== 'Literal' || typeof expr.value !== 'string') break;\n if (expr.value === directive) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and fatal\n * to rendering. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport { isMdxFilePath } from '../server/utils/mdx-file.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n} from './export-detect.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(tree: RouteTree, appDir: string): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n // Check 8: Wildcard MDX status files (4xx.mdx, 5xx.mdx, error.mdx) that\n // reference `props` — props resolve on deny and throw paths but are empty\n // on the boundary path. See design/10-error-handling.md §\"MDX Props by Path\".\n checkWildcardMdxProps(tree.root, warnings);\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/** HTTP methods that route.ts can export. */\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * MDX status files are exempt: they are server components by design and the\n * renderer pre-renders them into `fallbackElement` instead. See TIM-503 and\n * `server/error-boundary-wrapper.ts`.\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // MDX/markdown status and error files are server components by design — the\n // renderer pre-renders them into `fallbackElement`, so they never cross the\n // boundary as a function.\n //\n // The exemption is the *complement* of the renderer's own test, using the\n // renderer's own helper: everything `error-boundary-wrapper.ts` and\n // `error-renderer.ts` do not treat as MDX, they pass as a component. An\n // independent \"is this a script extension?\" list here would be a second\n // expression of that fact, free to drift into a gap where a file is a\n // component to the renderer and exempt to the linter.\n if (isMdxFilePath(file.filePath)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: Wildcard MDX Props ──────────────────────────────────────────────\n\n/**\n * Wildcard status file keys in `statusFiles` whose props differ by path.\n * `error` is not here — the scanner stores it in `node.error`, not\n * `node.statusFiles`, and the check handles it separately below.\n */\nconst WILDCARD_MDX_STATUS_KEYS = new Set(['4xx', '5xx']);\n\n/**\n * Warn when a wildcard MDX status file (`4xx.mdx`, `5xx.mdx`, `error.mdx`)\n * appears to reference `props` in its source.\n *\n * These files are pre-rendered into `fallbackElement` on the error-boundary\n * path, before the error happens, so they receive empty or partial props.\n * On the deny and error-renderer paths they receive the real props. An author\n * writing `{props.status}` gets the number on some paths and `undefined` on\n * others — same source, different output.\n *\n * A text scan for `props` is acceptable here because the check is `level:\n * 'warn'` — a false positive costs a printed line, not a refused build. A\n * sound check would need the MDX compiler, which is optional, async, and\n * scoped to the RSC environment. See TIM-1333.\n *\n * Exact-code MDX files (e.g. `503.mdx`) are unaffected — all four paths\n * agree on their status.\n */\nfunction checkWildcardMdxProps(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.statusFiles) {\n for (const [key, file] of Object.entries(node.statusFiles)) {\n if (WILDCARD_MDX_STATUS_KEYS.has(key) && isMdxFilePath(file.filePath)) {\n checkMdxFileForProps(file.filePath, key, warnings);\n }\n }\n }\n if (node.error && isMdxFilePath(node.error.filePath)) {\n checkMdxFileForProps(node.error.filePath, 'error', warnings);\n }\n\n for (const child of node.children) {\n checkWildcardMdxProps(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkWildcardMdxProps(slot, warnings);\n }\n}\n\n/**\n * Check if an MDX file's source appears to reference `props`.\n *\n * MDX passes a `props` object to the default export function. A reference to\n * `props.status` or `props.dangerouslyPassData` in a wildcard file works on\n * the deny/throw paths but renders `undefined` on the boundary path.\n */\nfunction checkMdxFileForProps(\n filePath: string,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n let source: string;\n try {\n source = readFileSync(filePath, 'utf-8');\n } catch {\n return;\n }\n\n // MDX exposes props via the default export: export default function(props) { ... }\n // and via JSX expressions: {props.status}. A text scan is intentionally\n // broad — false positives are cheap at warn level.\n if (!/\\bprops\\b/.test(source)) return;\n\n const label = `${convention}.${filePath.endsWith('.md') ? 'md' : 'mdx'}`;\n warnings.push({\n id: `MDX_WILDCARD_PROPS:${filePath}`,\n summary: `${label} references props, which are empty on the error boundary path: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` Wildcard MDX status files (${convention}.mdx) are pre-rendered into\\n` +\n ' fallbackElement before the error occurs. On that path, props are\\n' +\n ` empty${convention === 'error' ? '' : ' (no status, no dangerouslyPassData)'}. On the deny() and error-renderer\\n` +\n ' paths, props.status resolves correctly.\\n\\n' +\n ' If this file uses only static content and \"props\" appears in prose,\\n' +\n ' this warning is a false positive — ignore it.\\n\\n' +\n ' To fix: Use only static content in wildcard MDX status files, or\\n' +\n ' use an exact-code file (e.g. 404.mdx) where all paths agree.\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push(style('dim', w.details));\n }\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,mBAAmB,MAAiB,QAA0C;CAC5F,MAAM,sBAAM,IAAI,IAAyB;CAEzC,SAAS,KAAK,MAAmB,QAAgB,UAAwB;EACvE,IAAI,IAAI,QAAQ;GACd,OAAO,KAAK,WAAW;GACvB,aAAa,YAAY;EAC3B,CAAC;EAED,KAAK,MAAM,SAAS,KAAK,UAGvB,KAAK,OAFY,KAAK,QAAQ,MAAM,WAExB,GAAU,GADG,SAAS,GAAG,MAAM,aACR;EAErC,KAAK,MAAM,CAAC,UAAU,aAAa,OAAO,QAAQ,KAAK,KAAK,GAG1D,KAAK,UAFW,KAAK,QAAQ,IAAI,UAElB,GAAS,GADA,SAAS,IAAI,UACD;CAExC;CAEA,KAAK,KAAK,MAAM,QAAQ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src/shared/href-validation.ts"],"sourcesContent":["/**\n * Shared utility for merging preserved search params into a target URL.\n *\n * Used by both <Link> (client) and redirect() (server). Extracted to a shared\n * module to avoid importing client code ('use client') from server modules.\n */\n\n/**\n * Merge preserved search params from the current URL into a target href.\n *\n * When `preserve` is `true`, all current search params are merged.\n * When `preserve` is a `string[]`, only the named params are merged.\n *\n * The target href's own search params take precedence — preserved params\n * are only added if the target doesn't already define them.\n *\n * @param targetHref - The resolved target href (may already contain query string)\n * @param currentSearch - The current URL's search string (e.g. \"?private=access&page=2\")\n * @param preserve - `true` to preserve all, or `string[]` to preserve specific params\n * @returns The target href with preserved search params merged in\n */\nexport function mergePreservedSearchParams(\n targetHref: string,\n currentSearch: string,\n preserve: true | string[]\n): string {\n const currentParams = new URLSearchParams(currentSearch);\n if (currentParams.size === 0) return targetHref;\n\n // Split hash fragment from target before processing query params.\n // Hash must come after query string: /path?query=value#hash\n const hashIdx = targetHref.indexOf('#');\n const hrefWithoutHash = hashIdx >= 0 ? targetHref.slice(0, hashIdx) : targetHref;\n const hash = hashIdx >= 0 ? targetHref.slice(hashIdx) : '';\n\n // Split target into path and existing query\n const qIdx = hrefWithoutHash.indexOf('?');\n const targetPath = qIdx >= 0 ? hrefWithoutHash.slice(0, qIdx) : hrefWithoutHash;\n const targetParams = new URLSearchParams(qIdx >= 0 ? hrefWithoutHash.slice(qIdx + 1) : '');\n\n // Collect params to preserve (that aren't already in the target)\n const merged = new URLSearchParams(targetParams);\n for (const [key, value] of currentParams) {\n // Only preserve if: (a) not already in target, and (b) included in preserve list\n if (!targetParams.has(key)) {\n if (preserve === true || preserve.includes(key)) {\n merged.append(key, value);\n }\n }\n }\n\n const qs = merged.toString();\n const pathWithQuery = qs ? `${targetPath}?${qs}` : targetPath;\n return pathWithQuery + hash;\n}\n","/**\n * Shared href/URL validation for all navigation sinks.\n *\n * Used by <Link>, useRouter().push/replace, and redirectExternal().\n * Single source of truth for dangerous-scheme detection — prevents\n * control-character smuggling that bypasses naive regex checks.\n *\n * See design/13-security.md §\"Link scheme injection\" (test #9)\n * and design/07-routing.md §\"<Link> Scheme Validation\".\n */\n\n/**\n * All C0 control characters (U+0000–U+001F) that browsers strip during\n * URL preprocessing. Browsers and `new URL()` strip the full C0 range,\n * not just tab/LF/CR — so we must match that behavior to prevent\n * bypass vectors like `\\x00javascript:alert(1)`.\n */\n// eslint-disable-next-line no-control-regex -- intentional: must match all C0 controls to prevent bypass\nconst CONTROL_CHARS_RE = /[\\x00-\\x1f]/g;\n\nconst DANGEROUS_SCHEMES = new Set(['javascript:', 'data:', 'vbscript:']);\n\n/**\n * Strip C0 control chars and leading whitespace, then extract the scheme.\n * Returns the lowercase scheme (e.g. \"javascript:\") or null if no scheme.\n */\nfunction extractScheme(href: string): string | null {\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart();\n const match = /^([a-z][a-z0-9+.-]*:)/i.exec(cleaned);\n return match ? match[1].toLowerCase() : null;\n}\n\n/**\n * Validate an href for navigation sinks (<Link>, useRouter, etc.).\n *\n * Rejects dangerous schemes (javascript:, data:, vbscript:) even when\n * control characters are embedded to bypass naive regex checks.\n * Also rejects protocol-relative URLs (//evil.com).\n *\n * Throws on rejection. Safe hrefs pass through silently.\n */\nexport function validateNavigationHref(href: string): void {\n // Normalize for validation: strip C0 controls, trim, then replace backslashes\n // with forward slashes. Browsers normalize \\ → / during URL resolution, so\n // \"/\\evil.com\" becomes \"//evil.com\" (protocol-relative open redirect).\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n // Protocol-relative URLs can redirect to attacker-controlled origins\n if (cleaned.startsWith('//')) {\n throw new Error(\n `Navigation received a protocol-relative or backslash-prefixed URL: \"${href}\". ` +\n 'Use an absolute URL with an explicit scheme or a relative path.'\n );\n }\n\n const scheme = extractScheme(href);\n if (scheme && DANGEROUS_SCHEMES.has(scheme)) {\n throw new Error(\n `Navigation received a dangerous href: \"${href}\". ` +\n 'javascript:, data:, and vbscript: URLs are not allowed.'\n );\n }\n}\n\n/**\n * Check if an href is internal (same-origin navigation) or external.\n *\n * Strips control characters before checking so that \"java\\tscript:\" is\n * correctly identified as having a scheme (and thus not internal).\n */\nexport function isInternalHref(href: string): boolean {\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n if (cleaned.startsWith('//')) return false;\n if (cleaned.startsWith('/') || cleaned.startsWith('#') || cleaned.startsWith('?')) return true;\n\n const scheme = extractScheme(href);\n if (scheme) return false;\n\n return true;\n}\n\n/** Pattern matching absolute URLs: any scheme (http:, javascript:, …) or protocol-relative // */\nconst ABSOLUTE_URL_RE = /^(?:[a-zA-Z][a-zA-Z\\d+\\-.]*:|\\/\\/)/;\n\n/**\n * Assert that a redirect target is a relative path — rejects absolute and\n * protocol-relative URLs. Used by both the server `redirect()` primitive and\n * the client next/navigation shim so they enforce identical semantics.\n *\n * Normalizes for validation only: strips C0 controls, trims, then replaces\n * backslashes with forward slashes. Browsers normalize \\ → / during URL\n * resolution, so \"/\\evil.com\" becomes \"//evil.com\" (protocol-relative open\n * redirect). See design/13-security.md tests #8, #8a–#8c.\n */\nexport function assertRelativeRedirectPath(path: string): void {\n const cleaned = path.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n if (ABSOLUTE_URL_RE.test(cleaned)) {\n throw new Error(\n `redirect() only accepts relative URLs. Got absolute URL: \"${path}\". ` +\n 'Use redirectExternal(url, allowList) for external redirects.'\n );\n }\n\n // eslint-disable-next-line no-control-regex -- intentional: must match C0 controls\n if (/[\\x00-\\x1f]/.test(path)) {\n throw new Error(\n `redirect() received a path containing control characters (U+0000–U+001F). ` +\n 'Sanitize user input before passing it to redirect().'\n );\n }\n}\n\nconst SAFE_REDIRECT_SCHEMES = new Set(['http:', 'https:']);\n\n/**\n * Validate and canonicalize an external redirect URL.\n *\n * Requires http: or https: scheme and checks origin against an allow-list.\n * Returns the parsed canonical URL string (from URL.href) to prevent\n * raw user input from reaching the Location header.\n *\n * @throws On invalid URL, dangerous scheme, or origin not in allow-list.\n */\nexport function validateExternalRedirectUrl(url: string, allowList: string[]): string {\n // Strip control chars before parsing to prevent scheme smuggling\n const cleaned = url.replace(CONTROL_CHARS_RE, '').trimStart();\n\n if (cleaned.startsWith('//')) {\n throw new Error(\n `redirectExternal() received a protocol-relative URL: \"${url}\". ` +\n 'Use an absolute URL with http: or https: scheme.'\n );\n }\n\n let parsed: URL;\n try {\n parsed = new URL(cleaned);\n } catch {\n throw new Error(`redirectExternal() received an invalid URL: \"${url}\"`);\n }\n\n if (!SAFE_REDIRECT_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `redirectExternal() received a non-http(s) URL: \"${url}\". ` +\n 'Only http: and https: schemes are allowed for external redirects.'\n );\n }\n\n if (!allowList.includes(parsed.origin)) {\n throw new Error(\n `redirectExternal() target \"${parsed.origin}\" is not in the allow-list. ` +\n `Allowed: [${allowList.join(', ')}]`\n );\n }\n\n return parsed.href;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,2BACd,YACA,eACA,UACQ;CACR,MAAM,gBAAgB,IAAI,gBAAgB,aAAa;CACvD,IAAI,cAAc,SAAS,GAAG,OAAO;CAIrC,MAAM,UAAU,WAAW,QAAQ,GAAG;CACtC,MAAM,kBAAkB,WAAW,IAAI,WAAW,MAAM,GAAG,OAAO,IAAI;CACtE,MAAM,OAAO,WAAW,IAAI,WAAW,MAAM,OAAO,IAAI;CAGxD,MAAM,OAAO,gBAAgB,QAAQ,GAAG;CACxC,MAAM,aAAa,QAAQ,IAAI,gBAAgB,MAAM,GAAG,IAAI,IAAI;CAChE,MAAM,eAAe,IAAI,gBAAgB,QAAQ,IAAI,gBAAgB,MAAM,OAAO,CAAC,IAAI,EAAE;CAGzF,MAAM,SAAS,IAAI,gBAAgB,YAAY;CAC/C,KAAK,MAAM,CAAC,KAAK,UAAU,eAEzB,IAAI,CAAC,aAAa,IAAI,GAAG,GACnB;MA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,CAAC,CAAC,WAAW,MAAM,GAAG;CAEnF,IAAI,gBAAgB,KAAK,OAAO,GAC9B,MAAM,IAAI,MACR,6DAA6D,KAAK,gEAEpE;CAIF,IAAI,cAAc,KAAK,IAAI,GACzB,MAAM,IAAI,MACR,gIAEF;AAEJ;AAEA,IAAM,wCAAwB,IAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;;;;;;;;;;AAWzD,SAAgB,4BAA4B,KAAa,WAA6B;CAEpF,MAAM,UAAU,IAAI,QAAQ,kBAAkB,EAAE,CAAC,CAAC,UAAU;CAE5D,IAAI,QAAQ,WAAW,IAAI,GACzB,MAAM,IAAI,MACR,yDAAyD,IAAI,oDAE/D;CAGF,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,OAAO;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,gDAAgD,IAAI,EAAE;CACxE;CAEA,IAAI,CAAC,sBAAsB,IAAI,OAAO,QAAQ,GAC5C,MAAM,IAAI,MACR,mDAAmD,IAAI,qEAEzD;CAGF,IAAI,CAAC,UAAU,SAAS,OAAO,MAAM,GACnC,MAAM,IAAI,MACR,8BAA8B,OAAO,OAAO,wCAC7B,UAAU,KAAK,IAAI,EAAE,EACtC;CAGF,OAAO,OAAO;AAChB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scanner-BRIOmHE2.js","names":[],"sources":["../../src/server/tree-match.ts","../../src/routing/collision-probe.ts","../../src/routing/interception.ts","../../src/routing/collision-spaces.ts","../../src/routing/slot-placement.ts","../../src/routing/scanner.ts"],"sourcesContent":["/**\n * Shared URL-matching tree walker for segment trees.\n *\n * Both the main route matcher (`route-matcher.ts`) and slot resolver\n * (`slot-resolver.ts`) need to walk a SegmentNode tree, matching URL\n * parts against children with the same priority semantics:\n *\n * static > dynamic > catch-all > optional-catch-all\n *\n * Before this module, each had its own walker with subtle divergences\n * (different group handling, missing backtracking, incomplete\n * optional-catch-all support). This shared walker is the single\n * source of truth for URL-to-segment matching.\n *\n * See design/07-routing.md §\"Request Lifecycle\" and TIM-940.\n */\n\nimport type { SegmentNode } from '../routing/types.ts';\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/** Result of matching URL parts against a segment tree. */\nexport interface TreeMatchResult<TFile> {\n /** Matched segment chain from root to leaf, inclusive. */\n chain: SegmentNode<TFile>[];\n /** Collected params, keyed by param name. Catch-all params are string[]. */\n params: Record<string, string | string[]>;\n}\n\nexport interface TreeMatchOptions {\n /**\n * When true (default), only match if the leaf node has a page or route\n * handler. Set to false for metadata route matching, where we just need\n * to find the owning segment regardless of whether it has a page.\n */\n requireTerminal?: boolean;\n}\n\n/**\n * Match URL path parts against a segment tree.\n *\n * Walks the tree depth-first with backtracking, applying priority\n * ordering globally across group boundaries. Returns the matched\n * segment chain and collected params, or null if no route matches.\n *\n * By default, a match requires a terminal node (one with `page` or\n * `route`) at the leaf. Pass `{ requireTerminal: false }` to match\n * any segment (used by metadata route matching).\n *\n * @param root The root segment node to start matching from.\n * @param parts URL path parts (e.g. ['blog', 'hello-world']).\n * Empty array matches the root itself (if terminal).\n */\nexport function matchUrlParts<TFile>(\n root: SegmentNode<TFile>,\n parts: string[],\n options?: TreeMatchOptions\n): TreeMatchResult<TFile> | null {\n const chain: SegmentNode<TFile>[] = [];\n const params: Record<string, string | string[]> = {};\n const requireTerminal = options?.requireTerminal ?? true;\n\n if (matchNode(root, parts, 0, chain, params, requireTerminal)) {\n return { chain, params };\n }\n return null;\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────\n\n/**\n * A child node flattened through group segments, along with the\n * chain of group nodes that must appear in the segment chain\n * before the child to preserve the tree path.\n */\ninterface EffectiveChild<TFile> {\n child: SegmentNode<TFile>;\n groupChain: SegmentNode<TFile>[];\n}\n\n/**\n * Flatten children through group segments.\n *\n * Groups are transparent for URL matching — their non-group descendants\n * are returned with the chain of group nodes leading to them. This lets\n * the caller apply priority ordering (static > dynamic > catch-all >\n * optional-catch-all) across all groups uniformly instead of per-group.\n */\nfunction collectEffectiveChildren<TFile>(\n node: SegmentNode<TFile>,\n groupChain: SegmentNode<TFile>[] = []\n): EffectiveChild<TFile>[] {\n const result: EffectiveChild<TFile>[] = [];\n for (const child of node.children) {\n if (child.segmentType === 'group') {\n const nested = collectEffectiveChildren(child, [...groupChain, child]);\n result.push(...nested);\n } else {\n result.push({ child, groupChain });\n }\n }\n return result;\n}\n\n/** A node is terminal if it can serve a response (has a page or route handler). */\nfunction isTerminal<TFile>(node: SegmentNode<TFile>): boolean {\n return !!(node.page || node.route);\n}\n\n/** Combined affix length for specificity ordering. */\nfunction affixLength<TFile>(node: SegmentNode<TFile>): number {\n return (node.paramPrefix?.length ?? 0) + (node.paramSuffix?.length ?? 0);\n}\n\n/**\n * Recursive depth-first matcher with backtracking.\n *\n * Mutates `chain` and `params` in place for performance; backtracks\n * (restores previous state) when a candidate doesn't lead to a match.\n */\nfunction matchNode<TFile>(\n node: SegmentNode<TFile>,\n parts: string[],\n index: number,\n chain: SegmentNode<TFile>[],\n params: Record<string, string | string[]>,\n requireTerminal: boolean\n): boolean {\n chain.push(node);\n\n // All parts consumed — check if this node is terminal (or any node if !requireTerminal)\n if (index >= parts.length) {\n if (!requireTerminal || isTerminal(node)) return true;\n\n // Groups don't consume URL segments, so a group child's page can\n // match at the same URL depth. Recurse into groups transparently.\n for (const child of node.children) {\n if (child.segmentType === 'group') {\n if (matchNode(child, parts, index, chain, params, requireTerminal)) {\n return true;\n }\n }\n }\n\n // Optional catch-all with zero segments (direct and through groups).\n // The param is NOT set — matching Next.js semantics for [[...slug]]\n // with no path segments.\n const effective = collectEffectiveChildren(node);\n for (const { child, groupChain } of effective) {\n if (child.segmentType === 'optional-catch-all' && (!requireTerminal || isTerminal(child))) {\n chain.push(...groupChain, child);\n return true;\n }\n }\n\n chain.pop();\n return false;\n }\n\n const part = parts[index];\n\n // Flatten children through groups so priority ordering applies globally.\n const effective = collectEffectiveChildren(node);\n\n // 1. Static segments (exact name match)\n for (const { child, groupChain } of effective) {\n if (child.segmentType === 'static' && child.segmentName === part) {\n chain.push(...groupChain);\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n chain.length -= groupChain.length;\n }\n }\n\n // 2. Affixed dynamic segments (e.g. img-[id].png) — more specific than bare dynamic.\n // Sorted by specificity: longer combined prefix+suffix wins.\n const affixed = effective.filter(\n ({ child }) =>\n child.segmentType === 'dynamic' && child.paramName && (child.paramPrefix || child.paramSuffix)\n );\n affixed.sort((a, b) => affixLength(b.child) - affixLength(a.child));\n for (const { child, groupChain } of affixed) {\n const prefix = child.paramPrefix ?? '';\n const suffix = child.paramSuffix ?? '';\n if (\n part.length > prefix.length + suffix.length &&\n (!prefix || part.startsWith(prefix)) &&\n (!suffix || part.endsWith(suffix))\n ) {\n const value = part.slice(prefix.length, part.length - (suffix.length || 0));\n chain.push(...groupChain);\n const prev = params[child.paramName!];\n params[child.paramName!] = value;\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n // Backtrack\n chain.length -= groupChain.length;\n if (prev !== undefined) {\n params[child.paramName!] = prev;\n } else {\n delete params[child.paramName!];\n }\n }\n }\n\n // 3. Bare dynamic segments ([param])\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'dynamic' &&\n child.paramName &&\n !child.paramPrefix &&\n !child.paramSuffix\n ) {\n chain.push(...groupChain);\n const prev = params[child.paramName];\n params[child.paramName] = part;\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n // Backtrack\n chain.length -= groupChain.length;\n if (prev !== undefined) {\n params[child.paramName] = prev;\n } else {\n delete params[child.paramName];\n }\n }\n }\n\n // 4. Catch-all segments ([...param]) — must be terminal unless the\n // caller passed requireTerminal:false (metadata route matching needs to\n // find the owning segment even when it has no page).\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'catch-all' &&\n child.paramName &&\n (!requireTerminal || isTerminal(child))\n ) {\n chain.push(...groupChain, child);\n params[child.paramName] = parts.slice(index);\n return true;\n }\n }\n\n // 5. Optional catch-all segments ([[...param]]) — same terminal rule\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'optional-catch-all' &&\n child.paramName &&\n (!requireTerminal || isTerminal(child))\n ) {\n chain.push(...groupChain, child);\n params[child.paramName] = parts.slice(index);\n return true;\n }\n }\n\n chain.pop();\n return false;\n}\n","/**\n * The order-dependence oracle shared by every route collision validator.\n *\n * A \"collision space\" is a set of pages that compete for URLs with each other:\n * the main tree, each parallel slot, each intercepting subtree. Two pages in\n * one space that answer the same URL are ambiguous — `matchNode` resolves the\n * tie by whichever `children` array lists first, so which page renders is\n * decided by filesystem enumeration order and renaming a route group can flip\n * it. Every space rejects that shape, and they all reject it the same way,\n * through this module.\n *\n * **The check asks the real matcher rather than modelling it.** For each leaf\n * we build a URL it matches, then run `matchUrlParts` twice — once on the\n * space, once on a clone with every `children` array reversed — and compare the\n * winners. A URL answered by two or more candidates in the same priority tier\n * resolves to whichever comes first in `children`, so reversing the arrays\n * flips it; a URL with a single winner, or one settled by a higher tier, is\n * unaffected. Order-dependence is therefore detected exactly, with no second\n * copy of the precedence rules to drift.\n *\n * That drift is why this is written as an oracle. The interception validator's\n * first version normalized each pattern into a \"match shape\" and compared\n * shapes, which meant reimplementing `matchNode`'s tiers, its group flattening,\n * and its zero-length optional-catch-all handling. Five review rounds found\n * five divergences between the two — param spelling, a zero-length catch-all,\n * the bracket tokens colliding with legal static directory names, a page\n * settling a grouped catch-all, and a page settling a *direct* one (which the\n * model could not express at all, because `matchNode` checks every route-group\n * page before any direct optional catch-all). Each fix was locally right and\n * the next divergence surfaced anyway. The model was the defect.\n *\n * **Every claim made here is existential** — \"here is a URL these two contend\n * for\" — which is what a finite set of probes can actually establish. The\n * reverse, \"this page can never win any URL\", is universal, and a probe's\n * silence is not evidence for it: a leaf that loses every probe may still own\n * URLs no probe visited. An earlier revision reported that as an\n * unreachable-page error and produced two false build errors in one review\n * round. Probe inadequacy must only ever cost a missed collision, never a\n * rejected app — so nothing here may report a leaf as unreachable.\n *\n * See design/07-routing.md §\"Comparing Routes by the URLs They Match\".\n */\n\nimport type { SegmentNode } from './types.ts';\nimport { effectiveUrlSegment } from './segment-classify.ts';\n// The validators ask the real matcher which page answers a URL rather than\n// modelling its precedence rules a second time. `tree-match.ts` is a pure\n// walker over `SegmentNode` with no request-time state, and\n// `server/chain-url-parts.ts` already imports the other direction.\nimport { matchUrlParts } from '../server/tree-match.ts';\n\n/** One page-or-route-bearing node in a collision space. */\nexport interface ProbeLeaf {\n /** The file that serves it — what the error message names. */\n filePath: string;\n /**\n * The nodes from the space root down to this leaf that contribute URL parts\n * — route groups excluded, since they are transparent for matching. Empty\n * for the space root's own page: `matchUrlParts` matches parts against the\n * root's *children*, so the root itself consumes nothing.\n */\n chain: SegmentNode[];\n}\n\n/** Two files in one space that a single URL resolves to order-dependently. */\nexport interface ProbedCollision {\n /** The contended URL, written for a human (see `describeProbeUrl`). */\n url: string;\n /** The file that wins in filesystem order. */\n first: string;\n /** The file that wins when every `children` array is reversed. */\n second: string;\n}\n\n/**\n * Find a URL in this collision space whose winner depends on `children` order,\n * or null if every probed URL resolves the same way in both orderings.\n *\n * `spaceRoot` is the node `matchUrlParts` starts from — the app root, a slot\n * node, or an intercepting directory. `base` is the URL that root sits at, used\n * only to render the reported URL.\n */\nexport function findOrderDependentCollision(\n spaceRoot: SegmentNode,\n leaves: Iterable<ProbeLeaf>,\n base: string\n): ProbedCollision | null {\n const reversed = withReversedChildren(spaceRoot);\n const longTail = longTailLength(spaceRoot) + 1;\n // Computed once for the space, not per leaf: it bounds the second candidate\n // wave, which only runs for a leaf the first wave never reached.\n const minLength = longestStaticName(spaceRoot);\n\n // Each probe is checked as it is generated, and the first flipped winner\n // returns immediately. Accumulating every probe first and scanning afterwards\n // reports the same collision — this walks the same probes in the same order —\n // but it pays for the whole space before saying anything, and the leaves that\n // cost the most are exactly the ones a found collision makes irrelevant.\n //\n // In a space of N equivalent dynamic siblings, only the first and last can\n // win a probe (one per ordering), so every middle leaf is unreachable and\n // exhausts the entire candidate alphabet looking for a value that reaches it\n // — 300 such siblings took ~2.5s to produce a build error the very first\n // probe already proved (codex, on PR #1002). A valid space of the same size\n // scans in ~35ms, so the cost was confined to the error path, but a slow\n // error is still a bad error.\n //\n // Deduped so a space with many leaves does not re-probe one URL, and so the\n // collision reported does not depend on which leaf generated a shared probe.\n const seen = new Set<string>();\n for (const leaf of leaves) {\n for (const { parts, display } of probeUrlsForLeaf(\n spaceRoot,\n reversed,\n leaf,\n longTail,\n minLength\n )) {\n const key = parts.join('/');\n if (seen.has(key)) continue;\n seen.add(key);\n\n const first = matchedLeafFile(spaceRoot, parts);\n const second = matchedLeafFile(reversed, parts);\n if (!first || !second || first === second) continue;\n return { url: describeProbeUrl(base, display), first, second };\n }\n }\n\n return null;\n}\n\n/** Join a probe's display parts onto its space's base. */\nfunction describeProbeUrl(base: string, display: string[]): string {\n if (display.length === 0) return base || '/';\n return `${base === '/' ? '' : base}/${display.join('/')}`;\n}\n\n/**\n * The file `matchUrlParts` resolves for a URL, or null if nothing does.\n *\n * A `route.ts` counts: `isTerminal` accepts either, so a route handler is a\n * legitimate winner of the walk and an ambiguity between a page and a route\n * handler is as real as one between two pages.\n */\nfunction matchedLeafFile(node: SegmentNode, parts: string[]): string | null {\n const match = matchUrlParts(node, parts);\n if (!match) return null;\n const leaf = match.chain[match.chain.length - 1];\n return leaf.page?.filePath ?? leaf.route?.filePath ?? null;\n}\n\n/**\n * A generated URL, and how to show it to a human.\n *\n * `display` is built alongside `parts` rather than derived from it by\n * substitution: a *static* segment can legitimately be named the same as the\n * probe value, and replacing every occurrence of that string rewrote the\n * literal directory to `<any>` — reporting `/<any>/<any>` for a collision under\n * a static `atimber-probea`, which claims a URL position is dynamic when the\n * author wrote it out (codex, on PR #1002). Only the segment that generated a\n * value knows whether it stood for one.\n */\ninterface ProbeUrl {\n parts: string[];\n display: string[];\n /**\n * Whether any part of this URL stood in for a value. When nothing did, every\n * candidate generates the identical URL and the search can stop after one.\n */\n dynamic: boolean;\n}\n\n/**\n * The values a probe's dynamic parts are tried with, in order.\n *\n * A probe stands in for \"any value\" at a dynamic position, so it is only useful\n * if it reaches the leaf it was built for. A *static* sibling's literal name or\n * a more specific *affixed* sibling's pattern can claim it instead, and that\n * higher-priority segment then wins in both orderings — a genuine tie\n * underneath goes unreported, which is safe but is the whole thing these\n * validators are for.\n *\n * Which values are claimable is a question about `matchNode`'s precedence, so\n * `probeUrlsForLeaf` asks `matchUrlParts` rather than deciding it here. This\n * only has to offer enough shapes for the search to find one that works: an\n * affixed sibling constrains the head of the value, its tail, or both, so head\n * and tail are varied over an alphanumeric alphabet. The head varies fastest\n * because a prefix is the more common affix. Exhausting the list is a missed\n * collision like any other inadequate probe, so this is a search and not a\n * proof — nothing downstream may treat it as one.\n *\n * Exported so a test that has to *name* a capturing static sibling can derive\n * the name from this list rather than restate it — a fixture spelling the value\n * out by hand stops being a capture the moment the list changes, and passes.\n *\n * Three revisions of a hand-built value each dodged one more capture and were\n * each followed by another (avoid static names; avoid affix boundary\n * characters; avoid re-affixed forms of static names — then a strictly more\n * specific affixed sibling, TIM-1313). Each rule was modelling affix precedence\n * by hand, which is what the match-shape model was deleted for.\n */\nexport function* probeCandidates(minLength = 0): Generator<string> {\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n const base = 'timber-probe';\n\n function* wave(core: string): Generator<string> {\n for (const tail of alphabet) {\n for (const head of alphabet) yield `${head}${core}${tail}`;\n }\n }\n\n yield* wave(base);\n\n // A second wave, longer than every static segment name in the space.\n //\n // A static sibling claims a probe only by **string equality**, so a value\n // longer than every static name in the space cannot be claimed by one — that\n // is a fact about lengths, not a model of `matchNode`'s precedence, which is\n // what makes it safe to state as an invariant where \"pick an unclaimable\n // value\" was not. An app holding a static directory for all 1296 first-wave\n // candidates claimed every probe and hid a real collision (codex, on\n // PR #1002); it cannot do the same here, because the length is derived from\n // its own longest static and adding a longer one only pushes this further out.\n //\n // Affix capture is not addressed by length and is not addressable this way:\n // an affixed pattern matches infinitely many values, so escaping one is still\n // the head/tail search below. The first wave is byte-identical to what it was\n // before this existed, so nothing that already found a value changes.\n const padded = base.padEnd(Math.max(base.length, minLength), 'x');\n if (padded !== base) yield* wave(padded);\n}\n\n/**\n * The longest static segment name anywhere in the space.\n *\n * Read through `effectiveUrlSegment` so an intercepting directory counts as the\n * segment it intercepts, and only static kinds count: a dynamic sibling claims\n * a probe by pattern rather than by equality, which no length can escape.\n */\nfunction longestStaticName(node: SegmentNode): number {\n let longest = 0;\n for (const child of node.children) {\n const seg = effectiveUrlSegment(child);\n if (seg.segmentType === 'static') longest = Math.max(longest, seg.segmentName.length);\n longest = Math.max(longest, longestStaticName(child));\n }\n return longest;\n}\n\n/**\n * The probe URLs for one leaf, built from the first candidate value that\n * actually reaches it.\n *\n * \"Reaches it\" is `matchUrlParts` resolving one of the leaf's own URLs to the\n * leaf's file, in either ordering — either is enough, because a leaf that wins\n * only in the reversed ordering is precisely the contention being looked for.\n * A catch-all leaf may be reached by its long probe and not its short one (at\n * one part it loses to a bare dynamic sibling deterministically), so any one of\n * the generated URLs landing is enough to accept the value.\n *\n * A leaf that no candidate reaches is shadowed at its position for every value\n * tried — most often because it sits below a catch-all, which `matchNode`\n * accepts only as a terminal and never descends past. Its probes are still\n * emitted, from the first candidate: a probe that misses its own leaf is never\n * *wrong* — it is a real URL, and a winner that differs between the two\n * orderings is a real ambiguity whichever leaf it belongs to. Nothing here may\n * report the leaf as unreachable; that is the universal claim these validators\n * do not make.\n */\nfunction probeUrlsForLeaf(\n root: SegmentNode,\n reversed: SegmentNode,\n leaf: ProbeLeaf,\n longTail: number,\n minLength: number\n): ProbeUrl[] {\n let fallback: ProbeUrl[] | null = null;\n\n for (const value of probeCandidates(minLength)) {\n const urls = probeUrlsFor(leaf.chain, value, longTail);\n const reaches = urls.some(\n ({ parts }) =>\n matchedLeafFile(root, parts) === leaf.filePath ||\n matchedLeafFile(reversed, parts) === leaf.filePath\n );\n if (reaches) return urls;\n fallback ??= urls;\n\n // A leaf with no dynamic part in its chain matches exactly one URL, so the\n // candidate value never appears in it and every further candidate would\n // generate the identical probe. Searching on would cost the whole alphabet\n // per statically-shadowed leaf — and in the main tree those are ordinary\n // (anything below a catch-all) rather than the pathology they are inside an\n // intercepting subtree. Stopping is not a weaker check: the URLs are the\n // same ones, and they are still probed via `fallback`.\n if (!urls.some(({ dynamic }) => dynamic)) break;\n }\n\n // `probeCandidates` is non-empty, so this is only reached with a fallback.\n return fallback ?? [];\n}\n\n/**\n * The URL part one segment contributes to a probe.\n *\n * A dynamic segment stands for any single value, so it contributes the\n * candidate value — re-affixed, since an affixed segment only matches parts\n * that carry its prefix and suffix, so a probe without them could not reach it.\n * A catch-all stands for one or more parts, and one is enough to reach the leaf.\n *\n * The re-affixed part is the reason a value cannot be checked once for the\n * whole space: it exposes the value to every affixed sibling that *extends*\n * this segment's affixes, which differs per position. `probeUrlsForLeaf` asks\n * the matcher whether the assembled URL reaches its leaf, and moves to the next\n * candidate when it does not.\n *\n * Segments are read through `effectiveUrlSegment` so an intercepting directory\n * contributes the part the segment it intercepts would.\n */\nfunction probePartFor(node: SegmentNode, value: string): ProbePart {\n const seg = effectiveUrlSegment(node);\n switch (seg.segmentType) {\n case 'dynamic': {\n const prefix = seg.paramPrefix ?? '';\n const suffix = seg.paramSuffix ?? '';\n // The affixes are kept in the shown form too: `x-<any>` says which URLs\n // are contended for, where a bare `<any>` would claim every value at that\n // position.\n return {\n part: `${prefix}${value}${suffix}`,\n shown: `${prefix}<any>${suffix}`,\n dynamic: true,\n };\n }\n case 'catch-all':\n case 'optional-catch-all':\n return { part: value, shown: '<any>', dynamic: true };\n default:\n return { part: seg.segmentName, shown: seg.segmentName, dynamic: false };\n }\n}\n\n/** One URL part of a probe: what to send, what to show, and whether it stands for a value. */\ninterface ProbePart {\n part: string;\n shown: string;\n dynamic: boolean;\n}\n\n/**\n * The URLs that reach a leaf.\n *\n * An **optional catch-all also matches zero parts**, so it answers the URL its\n * parent sits at as well as longer ones. Both are probed: whether the shorter\n * one is actually *its* to answer is `matchUrlParts`' business, not something\n * to decide here — a page above it, or in a route group beside it, may take\n * that URL deterministically, and the probe will simply report the same winner\n * in both orderings.\n */\nfunction probeUrlsFor(chain: SegmentNode[], value: string, longTail: number): ProbeUrl[] {\n const probeParts = chain.map((node) => probePartFor(node, value));\n const url = (ps: ProbePart[]): ProbeUrl => ({\n parts: ps.map((p) => p.part),\n display: ps.map((p) => p.shown),\n dynamic: ps.some((p) => p.dynamic),\n });\n\n // The kind that decides the probe lengths is the last part-CONTRIBUTING\n // segment's, which is why it is read off the chain rather than off the leaf\n // node. An empty chain is the space root's own page: the walk matches parts\n // against that node's children, so the node's own segment consumes nothing\n // and the only URL that reaches the page is the empty one — even when the\n // root is itself a catch-all (`(.)[...rest]`).\n const leaf = chain[chain.length - 1];\n const kind = leaf && effectiveUrlSegment(leaf).segmentType;\n const isCatchAll = kind === 'catch-all' || kind === 'optional-catch-all';\n if (!isCatchAll) return [url(probeParts)];\n\n // `matchNode` accepts a catch-all only as a terminal, so a catch-all that\n // *is* the leaf owns the whole tail of the probe and it can be re-sized\n // freely. (A catch-all higher in the chain has descendants nothing can\n // reach; those leaves are the statically-shadowed case above.)\n const head = probeParts.slice(0, -1);\n const urls = [url(probeParts)];\n\n // A LONG tail as well as a short one. At one part a catch-all loses to any\n // bare dynamic sibling, deterministically — so a one-part probe reports that\n // sibling in both orderings and two catch-alls competing at every longer URL\n // go unnoticed. `longTail` is past every finite branch in the space, where\n // no fixed-length competitor can still be matching.\n if (longTail > 1) {\n // Every part is the candidate value verbatim. Decorating them to differ\n // (`${value}-0`) puts them back inside patterns like `[value]-0/[...rest]`,\n // which outranks a catch-all — the trailing counter reintroduced exactly\n // the affix capture the value is being searched for (codex, on PR #1000).\n // The parts need not differ from each other; a catch-all consumes them all.\n const tail: ProbePart[] = Array.from({ length: longTail }, () => ({\n part: value,\n shown: '<any>',\n dynamic: true,\n }));\n urls.push(url([...head, ...tail]));\n }\n\n // An optional catch-all also matches zero parts.\n if (kind === 'optional-catch-all') urls.push(url(head));\n\n return urls;\n}\n\n/**\n * One more than the longest fixed-length path in the space.\n *\n * A probe of this length cannot be claimed by any branch that consumes a fixed\n * number of URL parts, so whatever matches it is a catch-all — which is\n * exactly the competition a short probe hides.\n */\nfunction longTailLength(node: SegmentNode): number {\n let deepest = 0;\n for (const child of node.children) {\n const own = child.segmentType === 'group' ? 0 : 1;\n deepest = Math.max(deepest, own + longTailLength(child));\n }\n return deepest;\n}\n\n/**\n * The subtree with every `children` array reversed, top to bottom.\n *\n * Nodes are shallow-copied, so files and slots are shared with the original —\n * only the ordering `matchNode` reads is different. Slots are not reversed\n * because `matchNode` never walks them; each slot is validated as its own\n * collision space, with its own reversed clone.\n */\nfunction withReversedChildren(node: SegmentNode): SegmentNode {\n return { ...node, children: [...node.children].reverse().map(withReversedChildren) };\n}\n","/**\n * Intercepting route utilities.\n *\n * Computes rewrite rules from the route tree that enable intercepting routes\n * to conditionally render when navigating via client-side (soft) navigation.\n *\n * The mechanism: at build time, each intercepting route directory generates a\n * conditional rewrite. On soft navigation, the client sends an `X-Timber-URL`\n * header with the current pathname. The server checks if any rewrite's source\n * (the intercepted URL) matches the target pathname AND the header matches\n * the intercepting route's parent URL. If both match, the intercepting route\n * renders instead of the normal route.\n *\n * On hard navigation (no header), no rewrite matches, and the normal route\n * renders.\n *\n * See design/07-routing.md §\"Intercepting Routes\"\n */\n\nimport type { SegmentNode, InterceptionMarker, RouteFile } from './types.ts';\nimport { computeSegmentTreePaths, treePathDepth } from './segment-keys.ts';\nimport { classifyUrlSegment, effectiveUrlSegment } from './segment-classify.ts';\n// Every collision space — the main tree, each slot, each intercepting subtree\n// — decides order-dependence with the same oracle, so the spaces cannot drift\n// on what counts as two pages answering one URL. See TIM-1308.\nimport { findOrderDependentCollision, type ProbeLeaf } from './collision-probe.ts';\n\n/** Fields shared by both interception shapes. */\ninterface InterceptionRewriteBase {\n /**\n * The URL pattern that this rewrite intercepts (the target of navigation).\n * E.g., \"/photo/[id]\" for a (.)photo/[id] interception.\n */\n interceptedPattern: string;\n /**\n * The tree path of the segment that OWNS the slot holding this\n * intercepting route (`computeSegmentTreePaths`, e.g. \"/feed\",\n * \"/(browse)\", \"/(browse)/feed\", or \"/\" at the app root).\n *\n * The rewrite only applies when the source route — the page the user is\n * navigating FROM — passes through that directory, because only then\n * does the slot holding the intercepting page exist in the rendered\n * tree. The server checks this by matching X-Timber-URL and testing its\n * segment chain's tree paths for this value.\n *\n * Neither of the identities already in the codebase works here:\n *\n * - A **URL prefix** cannot express it. Route groups contribute nothing\n * to `urlPath`, so `(browse)/@detail/(...)x` and a genuinely\n * root-level `@modal/(...)x` both have prefix \"/\" while meaning very\n * different things.\n * - A **state-tree key** (`computeSegmentKeys`) cannot either. It\n * qualifies a group with its ancestry but resets to `urlPath` at the\n * next URL-visible segment, so `(browse)/feed` and `(landing)/feed`\n * both key as \"/feed\" — and a navigation inside `(landing)/feed/…`\n * would reach `(browse)/feed`'s slot.\n *\n * Tree paths never reset, so two directories that render different\n * layouts never share one. \"/\" as a scope means the app root, which\n * every route passes through — preserving the intentional\n * match-from-anywhere behavior of a root-level `(...)` interception\n * (TIM-1006) without an exemption. See TIM-1279.\n */\n interceptingScope: string;\n}\n\n/**\n * A conditional rewrite rule generated from an intercepting route.\n *\n * `mode` records which of the two shapes the directory expresses, because the\n * two render through entirely different mechanisms and the fields they need\n * are not the same. It is a union rather than a flag so a reader cannot\n * re-match `interceptingPrefix` on the shape that has no such pathname.\n *\n * See design/07-routing.md §\"Intercepting Routes\".\n */\nexport type InterceptionRewrite = SlotInterceptionRewrite | ChildrenInterceptionRewrite;\n\n/**\n * A **modal overlay** interception — the intercepting directory is a direct\n * child of a parallel slot (`feed/@modal/(.)photo/[id]`).\n *\n * The server re-matches the *source* route and the slot resolver finds the\n * intercepting child inside the slot, so the intercepting page layers over\n * the page the user was already on.\n */\nexport interface SlotInterceptionRewrite extends InterceptionRewriteBase {\n mode: 'slot';\n /**\n * The pathname the server re-matches when this rewrite applies — the\n * intercepting slot owner's URL path. E.g., \"/feed\" for a (.)photo/[id]\n * inside /feed/@modal/.\n *\n * This is a build-time constant, never a client-supplied value: the\n * X-Timber-URL header selects a rewrite but never becomes the rendered\n * pathname.\n */\n interceptingPrefix: string;\n}\n\n/**\n * A **sibling layout swap** interception — the intercepting directory is a\n * direct child of an ordinary segment or route group\n * (`(browse)/(...)[artistSlug]/…`).\n *\n * There is no overlay, no slot and no `default.tsx`: the intercepting page\n * *replaces* `children` for the owner's layout chain. Nothing is re-matched\n * either. The server resolves the owner by `interceptingScope` — a tree path,\n * which identifies exactly one directory — and builds the rendered chain as\n * `[…owner ancestors, interceptingNode, …its matched descendants]`. That is an\n * ordinary segment chain, so `tree-builder.ts` renders it with no knowledge\n * that interception happened.\n *\n * Resolving the owner from the tree rather than from a URL is what makes this\n * shape work where the modal shape cannot: `interceptingPrefix` is\n * URL-derived, and a route group contributes nothing to `urlPath`, so an owner\n * like `app/(browse)/` serializes to \"/\" and re-matching it lands in whichever\n * group owns the canonical page. A tree path never collapses (TIM-1280).\n */\nexport interface ChildrenInterceptionRewrite extends InterceptionRewriteBase {\n mode: 'children';\n}\n\n/**\n * A set of sibling interceptors that compete for one URL position.\n *\n * `base` is the intercepted base they share — the URL their own segments sit\n * directly under — and `anchorIndex` is how many URL parts that base spans,\n * which is the index in a target pathname their segments are matched at.\n * Deeper anchors are more local and are tried first.\n */\nexport interface InterceptorAnchorGroup<TFile> {\n base: string;\n anchorIndex: number;\n interceptors: SegmentNode<TFile>[];\n}\n\n/**\n * Group an owner's intercepting children by the URL position they contend for.\n *\n * This is the definition of *which interceptors compete*, and it has exactly\n * one caller shape on each side of the build: `findInterceptingMatch` resolves\n * a group with one `matchUrlParts` walk, and\n * `assertNoInterceptedPatternCollisions` validates the same group as one\n * collision space. Written twice, the two would be free to disagree about what\n * competes — and a resolver that walks a wider set than the validator checked\n * is precisely the order-dependence the validator exists to reject (TIM-1310).\n *\n * Contention is keyed by the computed intercepted **base**, not by the marker:\n * under an owner at `/feed`, `(..)` and `(...)` both base at `/` and are both\n * matched at index 0, so they are one group. Different bases are different\n * positions — a `(.)` interceptor can never claim a target that belongs to a\n * `(..)` one beside it, because the base must also match the target's leading\n * parts.\n *\n * The base is a URL *pattern*, so its length is its part count only because\n * every pattern part stands for exactly one URL part. A catch-all in the base\n * breaks that, and `assertInterceptedBaseIsCountable` rejects the shape at\n * build time.\n *\n * A node missing either marker field is skipped, which `classifySegment` never\n * produces — it sets both whenever it reports `'intercepting'`. Stating the\n * filter here rather than defaulting the marker is what makes the validator and\n * the resolver see the same set: such a node renders nothing either way, and a\n * validator more permissive than the resolver would be checking a candidate\n * that never competes while the resolver walks one nobody checked.\n *\n * `children` is read directly rather than flattened through route groups,\n * matching both resolvers: the slot resolver reads `slotNode.children`, and an\n * interceptor deeper inside a slot subtree is rejected by\n * `validateInterceptionPlacement`. On the children path an interceptor under a\n * route group is legal and the *group* is its owner, so it is grouped with that\n * group's other interceptors — which is again exactly what the resolver walks,\n * since it resolves the owner by tree path.\n */\nexport function groupByInterceptedAnchor<TFile>(\n ownerUrlPath: string,\n children: readonly SegmentNode<TFile>[]\n): InterceptorAnchorGroup<TFile>[] {\n const byBase = new Map<string, InterceptorAnchorGroup<TFile>>();\n\n for (const child of children) {\n if (child.segmentType !== 'intercepting') continue;\n if (!child.interceptionMarker || !child.interceptedSegmentName) continue;\n\n const base = computeInterceptedBase(ownerUrlPath, child.interceptionMarker);\n const group = byBase.get(base);\n if (group) {\n group.interceptors.push(child);\n } else {\n byBase.set(base, {\n base,\n anchorIndex: base === '/' ? 0 : base.slice(1).split('/').length,\n interceptors: [child],\n });\n }\n }\n\n // Deepest anchor first: a `(.)` interception is the most local one and wins\n // over a `(...)` that reaches the same page from the root.\n return [...byBase.values()].sort((a, b) => b.anchorIndex - a.anchorIndex);\n}\n\n/**\n * Collect all interception rewrite rules from the route tree.\n *\n * Walks the tree recursively. For each intercepting segment, computes the\n * intercepted URL based on the marker and the segment's position.\n *\n * The list is returned **deepest scope first**, which is what makes\n * `findInterceptionMatch`'s first-match rule deterministic; see\n * `sortByScopeDepth`.\n */\nexport function collectInterceptionRewrites(root: SegmentNode): InterceptionRewrite[] {\n const rewrites: InterceptionRewrite[] = [];\n walkForInterceptions(root, [root], false, rewrites);\n return sortByScopeDepth(rewrites);\n}\n\n/**\n * Order the rewrites deepest scope first, so the request-time first-match rule\n * resolves two applicable rewrites by *nesting* rather than by tree-walk order.\n *\n * `findInterceptionMatch` returns the first rewrite whose pattern matches the\n * target and whose scope the source route reports. More than one can satisfy\n * both, and the case is not exotic — an owner and a directory *beneath* it may\n * each hold an interceptor for one URL:\n *\n * ```\n * app/feed/(.)photo/page.tsx scope /feed\n * app/feed/(a)/(.)photo/page.tsx scope /feed/(a)\n * ```\n *\n * A page inside `(a)` renders both owners' layouts, so the client reports both\n * tree paths and both scopes pass. Unsorted, the winner is whichever the\n * filesystem enumerated first — renaming the group flips which page a click\n * opens, the defect class TIM-1305/TIM-1308/TIM-1310 each rejected in a\n * different space. Here it is an ambiguity between *rewrites* rather than\n * between pages inside one walk, so no collision space sees it.\n *\n * **Deepest wins, and it is specified rather than rejected** because the shape\n * is one a correct app writes on purpose: a nested layout refining the\n * interception its parent declares, exactly as `groupByInterceptedAnchor`\n * already prefers the deepest *anchor* within one owner. The two rules are the\n * same preference — the more local interception is the author's more specific\n * statement — applied at the two levels the mechanism has.\n *\n * Depth is counted on the **tree path**, the identity that never collapses\n * (TIM-1279/TIM-1280); a `urlPath` prefix test would relate `(browse)` and\n * `(landing)`, which render different layouts and share no chain. Two scopes on\n * one rendered chain are strictly nested, so depth orders them totally, and two\n * scopes that are *not* on one chain — sibling groups, `feed/(a)` beside\n * `feed/(b)` — never both pass the scope check, so their relative order is not\n * observable. That is why this sorts on depth alone rather than testing\n * ancestry: it is a total order over the pairs that can compete, and it costs\n * nothing per request.\n *\n * Sorting is stable, so rewrites sharing one scope keep tree-walk order. Equal\n * scopes mean one owner, and of the three pairings that produces only one is an\n * ambiguity — a children-path interceptor beside a slot one, tracked as\n * TIM-1319. The enumeration is in design/07-routing.md §\"Selection Between\n * Owners\" rather than repeated here, so there is one place to correct if a\n * rewrite ever grows a field that makes two of them distinguishable.\n */\nfunction sortByScopeDepth(rewrites: InterceptionRewrite[]): InterceptionRewrite[] {\n return rewrites.sort(\n (a, b) => treePathDepth(b.interceptingScope) - treePathDepth(a.interceptingScope)\n );\n}\n\n/**\n * Validate that every intercepting segment sits where it can actually render.\n *\n * There are exactly two positions a renderer exists for, and they are the two\n * shapes interception has:\n *\n * 1. **Direct child of a parallel slot** — the modal overlay. The slot\n * resolver scans a slot node's *direct children* for an intercepting\n * segment (`server/slot-interception.ts`). Nothing between the slot and\n * the intercepting directory is allowed, because nothing walks it.\n * 2. **Direct child of an ordinary segment or route group** — the sibling\n * layout swap (TIM-1280). The pipeline resolves the owner by tree path and\n * builds the rendered chain through the intercepting node itself\n * (`server/children-interception.ts`).\n *\n * Everywhere else, rewrite generation still emits a rewrite and nothing\n * renders it: the rewrite matches the soft navigation, and the user is served\n * the page they were already on under a changed URL (TIM-1278). The rejected\n * positions are:\n *\n * - **Inside a slot subtree but not directly under the slot**\n * (`@modal/(inner)/(.)photo`). Neither renderer applies: the slot resolver\n * only reads direct children, and the children-path resolver builds a\n * *chain*, which cannot express a descent through a slot.\n * - **Inside another intercepting subtree** (`(.)a/(.)b`). Left unvalidated\n * `collectLeavesWithRewrites` walks the inner one as an ordinary URL\n * segment and emits a pattern containing a literal \"(.)b\".\n *\n * Two further shapes are rejected here (TIM-1288). Both are about a catch-all,\n * and both are specific to interception: elsewhere in the tree the same\n * shapes are inert or fail safely, and the general \"nothing below a catch-all\n * is reachable\" rule is tracked as TIM-1286.\n *\n * And one is specific to the children path: an owner chain that binds params\n * (see `assertOwnerChainBindsNoParams`).\n */\nexport function validateInterceptionPlacement(root: SegmentNode): void {\n walkForPlacement(root, '', {\n parentIsSlot: false,\n inSlotSubtree: false,\n inInterceptingSubtree: false,\n ancestorsBindParams: false,\n });\n}\n\n/**\n * Reject a children-path interception whose owner chain binds params.\n *\n * The rendered chain is `[…owner ancestors, interceptingNode, …descendants]`,\n * and the only pathname available to bind params from is the **target** — the\n * URL being navigated to. The intercepting subtree's own params come from it\n * by construction. The owner chain's do not, in general:\n *\n * - With a climbing marker the owner's URL segments are not in the target at\n * all. `app/[team]/(..)photo/[id]` bases at \"/\", so the target is\n * `/photo/9` — there is no team value anywhere in it, and `[team]`'s layout\n * would render with the param it declares missing.\n * - With `(.)` the base *is* the owner's `urlPath`, so the target's leading\n * parts would bind it. Supporting only that half means one marker behaves\n * differently from its siblings for reasons the author cannot see from the\n * directory names, so the rule is stated once, on the owner chain.\n *\n * A layout that silently renders without the param it declares is the failure\n * this prevents; it is rejected where it can be explained rather than left to\n * surface as `undefined` deep inside user code. Route groups and static\n * segments bind nothing and are unrestricted, which is the whole motivating\n * shape (`app/(browse)/(...)[artistSlug]/…`).\n *\n * The rule stops at a slot boundary: a slot-mode interception re-matches the\n * *source* route, which supplies the owner's params, so a dynamic owner is\n * fine there and always has been.\n */\n/**\n * Require a children-path interception's owner to have a `layout.tsx`.\n *\n * The scope is the owner's tree path, and the client reports which tree paths\n * it has mounted from `X-Timber-Segments` — which carries **one entry per\n * layout-bearing segment**, because those are the segments the client needs an\n * outlet and a cache node for. `buildSegmentInfo` skips the rest.\n *\n * For the modal shape that set is exactly the set of possible scope owners, by\n * construction: a slot is only resolved inside a rendering layout\n * (`route-element-builder.ts`), so a layoutless segment can never own one. A\n * children-path interception broke that equivalence — its owner is an ordinary\n * directory and needs no layout.\n *\n * Left unchecked the result is a swap that works exactly once: the first soft\n * navigation renders, then the client reports no such tree path, and the next\n * navigation fails the scope check and falls back to the canonical page. That\n * is fail-safe but silent, and the address-bar channel cannot recover it —\n * once the swap is on screen the address holds the *intercepted* URL, which\n * re-matches the canonical chain (the TIM-1282 problem, in the one shape the\n * rendered-scope fix does not reach).\n *\n * Requiring the layout restores the invariant the state tree is built on\n * rather than widening the wire format to carry segments that own no outlet\n * and no payload. It also costs the author nothing they were not already\n * doing: the point of this shape is to render inside the owner's own layout,\n * so an owner with no layout has no chrome to preserve.\n */\nfunction assertOwnerHasLayout(ownerPath: string, childPath: string): void {\n const owner = ownerPath || '(app root)';\n throw new Error(\n `Build error: intercepting route whose owner has no layout.\\n` +\n ` Directory: app/${childPath}\\n` +\n ` Owner: app/${owner}\\n` +\n `An intercepting directory outside a parallel slot renders inside its owner's ` +\n `layout chain, and the owner must have a layout.tsx: the client reports which ` +\n `directories it has mounted from its layout segments, and a scope it cannot ` +\n `report would let the interception fire once and then silently stop.\\n` +\n `Add app/${owner}/layout.tsx (a pass-through returning {children} is enough), or ` +\n `move the interception under a directory that has one.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n}\n\nfunction assertOwnerChainBindsNoParams(childPath: string, marker: InterceptionMarker): void {\n throw new Error(\n `Build error: intercepting route under a dynamic segment.\\n` +\n ` Directory: app/${childPath}\\n` +\n `An intercepting directory outside a parallel slot renders inside its own ` +\n `layout chain, and the only pathname available to bind params from is the ` +\n `intercepted URL — which does not carry the values of the segments above ` +\n `\"${marker}\".\\n` +\n `Move the interception so every directory above it is a static segment or a ` +\n `route group, or place it inside a parallel slot (@modal/) to render it as an ` +\n `overlay over the source route instead.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n}\n\n/**\n * Reject an intercepting route whose intercepted level is not well-defined.\n *\n * \"One level up\" is counted in URL segments, which works because every\n * pattern part stands for exactly one URL part — except a catch-all, which\n * stands for a number that varies per request. `anchorIndex` fixes the anchor\n * at the base's pattern length, so with an owner at `/docs/[...path]` the\n * interception resolves when the catch-all consumed exactly one segment\n * (`/docs/a/photo/5`) and is dropped when it consumed more\n * (`/docs/a/b/photo/5`), because the base no longer matches the target's\n * leading parts.\n *\n * Dropping is fail-safe — the canonical route renders, as on hard navigation\n * — so this is never a wrong page. But it is a modal that opens at one depth\n * and silently does not at another, with nothing to tell the author why, and\n * no request-time input can fix it: the only available source depth is\n * `X-Timber-URL`, which is the browser's address bar, and once a modal is\n * open that holds the *intercepted* URL rather than the source.\n *\n * So the shape is rejected where it can be explained. A marker that climbs\n * *past* the catch-all is fine — `(..)` from `/docs/[...path]` bases at\n * `/docs` — and so is `(...)`, which always bases at the root. The rule is on\n * the *computed* base, not on having a catch-all anywhere above.\n */\nfunction assertInterceptedBaseIsCountable(\n child: SegmentNode,\n ownerUrlPath: string,\n childPath: string\n): void {\n const marker = child.interceptionMarker ?? '(.)';\n const base = computeInterceptedBase(ownerUrlPath, marker);\n const baseParts = base === '/' ? [] : base.slice(1).split('/');\n const ambiguous = baseParts.find((part) => {\n const kind = classifyUrlSegment(part).kind;\n return kind === 'catch-all' || kind === 'optional-catch-all';\n });\n if (!ambiguous) return;\n\n throw new Error(\n `Build error: intercepting route below a catch-all segment.\\n` +\n ` Directory: app/${childPath}\\n` +\n ` Intercepted base: ${base}\\n` +\n `A catch-all (${ambiguous}) matches a number of URL segments that varies per ` +\n `request, so \"${marker}\" cannot identify which segment of a target pathname the ` +\n `interception starts at — the modal would open at one depth and silently not at ` +\n `another.\\n` +\n `Move the interception above the catch-all, or use a marker that climbs past it ` +\n `((..) or (...)).\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n}\n\n/**\n * Reject a catch-all inside an intercepting subtree that has directories\n * below it.\n *\n * A catch-all consumes the whole remaining path, so nothing under it is\n * reachable — `matchUrlParts` only accepts a catch-all as a terminal leaf and\n * never descends past one. Rewrite generation is not so strict: it walks the\n * subtree and emits `/feed/[...rest]/child`, and `pathnameMatchesPattern`\n * returns as soon as it reaches the catch-all without ever looking at\n * `child`. So the rewrite matches the navigation and then no renderer exists\n * — the TIM-1278 failure mode reached by a different route, with the user\n * served the page they were already on under a changed URL.\n *\n * The check covers the whole intercepting subtree, not just the intercepted\n * segment: `(.)photo/[...rest]/child` emits `/feed/photo/[...rest]/child` and\n * hijacks `/feed/photo/a/b` by exactly the same mechanism. And it does not\n * exempt a catch-all that carries its own page — that one does render, but\n * the rewrite generated for the unreachable descendant is broader than any\n * route in the tree, so the tail modal fires on navigations no directory\n * describes.\n *\n * Outside a slot the same shape merely 404s, which is why the general rule is\n * tracked separately (TIM-1286); here it is unsafe, and it only became\n * reachable when catch-all intercepted segments started matching at all\n * (TIM-1281).\n *\n * The walk descends `children` and not `slots`, mirroring\n * `collectLeavesWithRewrites` exactly: what this rejects is precisely the set\n * of paths rewrite generation emits, so the two cannot disagree about which\n * shapes exist. A slot nested inside an intercepting subtree produces no\n * rewrite and so cannot hijack anything.\n */\nfunction assertInterceptedCatchAllsAreTerminal(node: SegmentNode, nodePath: string): void {\n const { segmentType, segmentName } = effectiveUrlSegment(node);\n const isCatchAll = segmentType === 'catch-all' || segmentType === 'optional-catch-all';\n\n if (isCatchAll && node.children.length > 0) {\n throw new Error(\n `Build error: catch-all with nested segments inside an intercepting route.\\n` +\n ` Directory: app/${nodePath}\\n` +\n ` Nested: ${node.children.map((c) => c.segmentName).join(', ')}\\n` +\n `A catch-all (${segmentName}) consumes every remaining URL segment, so nothing ` +\n `below it can ever match — but the interception rewrite would still be generated ` +\n `and would hijack the navigation with no page to render.\\n` +\n `Move the nested routes above the catch-all, or intercept a named segment instead.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n }\n\n for (const child of node.children) {\n assertInterceptedCatchAllsAreTerminal(child, `${nodePath}/${child.segmentName}`);\n }\n}\n\n/**\n * Reject a `route.ts` anywhere inside an intercepting subtree.\n *\n * An interception is a soft-navigation variant of a page — it swaps which\n * page component renders. A route handler returns a `Response` and cannot\n * be an interception target: `walkInterceptedLeaves` visits `node.page`\n * only, so no rewrite is emitted for it, but `isTerminal` in\n * `tree-match.ts` counts both `page` and `route`, so `matchUrlParts` can\n * resolve to the route handler. `slot-interception.ts` then drops the\n * match (`if (!leaf.page) continue`), silently disabling the page's\n * interception. Fail-safe (the canonical route renders) but silent.\n *\n * The walk mirrors `assertInterceptedCatchAllsAreTerminal`: it descends\n * `children` (not `slots`), matching `collectLeavesWithRewrites` exactly.\n */\nfunction assertNoRouteHandlersInSubtree(node: SegmentNode, nodePath: string): void {\n if (node.route) {\n throw new Error(\n `Build error: route handler inside an intercepting route.\\n` +\n ` File: ${node.route.filePath}\\n` +\n ` Directory: app/${nodePath}\\n` +\n `An intercepting subtree renders a page component on soft navigation — a ` +\n `route handler returns a Response and cannot be an interception target. ` +\n `The route handler would silently shadow the interception: the resolver ` +\n `would match it and then discard it because it has no page, so the modal ` +\n `would stop opening with no diagnostic.\\n` +\n `Remove the route.ts, or move it outside the intercepting subtree.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n }\n\n for (const child of node.children) {\n assertNoRouteHandlersInSubtree(child, `${nodePath}/${child.segmentName}`);\n }\n}\n\n/**\n * Reject two pages that answer one URL among the interceptors an owner\n * resolves in a single walk.\n *\n * `validateRouteGroupCollisions` in the scanner returns early on an\n * intercepting node, so nothing else validates in here. That exemption exists\n * for a real reason — an interception's computed URL legitimately mirrors the\n * canonical route it replaces, and interceptors at *different* anchors\n * deliberately target one URL, which the resolver then orders (deepest anchor\n * first). But the exemption was broader than its reason. Two shapes slip\n * through it, and they are the same shape seen from two levels:\n *\n * feed/(.)photo/(a)/page.tsx feed/@modal/(.)[a]/page.tsx\n * feed/(.)photo/(b)/page.tsx feed/@modal/(.)[b]/page.tsx\n *\n * Both pairs answer one URL, and in both `matchUrlParts` resolves the tie by\n * whichever `children` array lists first — so the winner is whichever the\n * filesystem enumerated first, and renaming a directory flips it. That is\n * exactly what `validateRouteGroupCollisions` and\n * `validateAffixedSiblingConflicts` exist to reject for ordinary siblings.\n *\n * **The collision space is the anchor group, not the directory.** An earlier\n * revision ran once per intercepting directory, which sees the left-hand pair\n * and not the right-hand one: those leaves live in two different directories.\n * The space is `groupByInterceptedAnchor`'s output — the same grouping\n * `findInterceptingMatch` hands to one `matchUrlParts` call — so what is\n * validated together is exactly what is resolved together. Interceptors at\n * different anchors stay independent, which is the documented case, and two\n * slots on one owner are two owners and so two spaces.\n *\n * **Two checks, and the difference between them matters.** A duplicate\n * intercepted *pattern* is decided by string equality, which is exact: two\n * leaves with one pattern claim one set of URLs, whatever the precedence rules\n * are. Everything else is decided by asking the matcher — `collision-probe.ts`,\n * the same oracle the main tree and every slot use, so the spaces cannot\n * disagree about whether a pair of pages collides.\n *\n * Not covered: two affixed dynamics that tie on specificity (`(x)/a-[id]` vs\n * `(y)/[slug]-b`, ambiguous only for a part shaped `a-…-b`). No single probe\n * URL exercises both, and `validateAffixedSiblingConflicts` already rejects\n * that pair by affix length — including through groups, inside intercepting\n * subtrees, and between two interceptors sharing an anchor.\n *\n * The shape applies to both interception mechanisms — a slot interceptor and a\n * children-path one produce their leaves through the same walk, and both are\n * resolved by `findInterceptingMatch` — so this is called from the one place in\n * `walkForPlacement` that sees every owner regardless of position.\n */\nfunction assertNoInterceptedPatternCollisions(owner: SegmentNode, ownerPath: string): void {\n for (const group of groupByInterceptedAnchor(owner.urlPath, owner.children)) {\n assertAnchorGroupHasNoCollisions(group, ownerPath);\n }\n}\n\n/**\n * The URL-matching identity of an intercepting node, as a node.\n *\n * `matchUrlParts` reads `segmentType` directly and knows nothing about\n * interception, so a marker'd directory has to be handed to it under the\n * identity of the segment it intercepts — `(.)[id]` as `[id]`. Priority\n * ordering, affix stripping and catch-all handling then come from the shared\n * walker rather than from a second classifier here.\n *\n * Shared with `findInterceptingMatch` for the same reason the grouping is: the\n * collision space is the resolver's synthetic anchor parent, so its children\n * have to carry the identity the resolver gives them or the validator would be\n * probing a tree that does not match the one served. The caller keeps its own\n * map back to the real node — the proxy is a matching identity, not a\n * replacement (tree paths still need the directory name).\n */\nexport function interceptorProxy<TFile>(node: SegmentNode<TFile>): SegmentNode<TFile> {\n return { ...node, ...effectiveUrlSegment(node) };\n}\n\nfunction assertAnchorGroupHasNoCollisions(\n group: InterceptorAnchorGroup<RouteFile>,\n ownerPath: string\n): void {\n const { base } = group;\n const owner = ownerPath || '(app root)';\n\n // The space the resolver walks: a synthetic parent sitting at the anchor\n // base, holding every interceptor of this group under its matching identity.\n // `matchUrlParts` starts below this node, so the interceptors' own segments\n // are matched parts here — which is what lets a probe reach across two\n // directories and find the pair that competes.\n const proxies = group.interceptors.map(interceptorProxy);\n const anchorNode: SegmentNode = {\n segmentName: '',\n segmentType: 'static',\n urlPath: base,\n children: proxies,\n slots: {},\n };\n\n const patterns = new Map<string, string>();\n const probeLeaves: ProbeLeaf[] = [];\n\n for (const proxy of proxies) {\n // The proxy's name, not the directory's `interceptedSegmentName`: they are\n // the same string, and this is the one `matchUrlParts` matches on, so the\n // reported pattern and the probed URL cannot describe different segments.\n const pattern = joinInterceptedBase(base, proxy.segmentName);\n walkInterceptedLeaves(proxy, pattern, [proxy], (page, leaf) => {\n // Two leaves whose intercepted pattern is the *same string* claim exactly\n // the same set of URLs — one is ambiguous with the other, or dead. This\n // needs no probe and no reasoning about precedence: identical patterns are\n // identical URL sets by definition. It is the case route groups make easy\n // to write, `(a)/page.tsx` beside `(b)/page.tsx`, and the one the main\n // tree already rejects by comparing urlPath. Across two interceptors it\n // is `(..)photo` beside `(...)photo` under `/feed`, which both base at\n // `/` and both intercept the literal `photo`.\n const duplicate = patterns.get(leaf.interceptedPattern);\n if (duplicate) {\n throw new Error(\n `Build error: route collision between intercepting routes — two pages intercept the same URL.\\n` +\n ` Owner: app/${owner}\\n` +\n ` Intercepted base: ${base}\\n` +\n ` URL: ${leaf.interceptedPattern}\\n` +\n ` File 1: ${duplicate}\\n` +\n ` File 2: ${page.filePath}\\n` +\n `A route group is transparent for matching, so moving a page into one does not ` +\n `give it a URL of its own — these two claim the same one. Rename or move one of ` +\n `them.\\n` +\n `See design/07-routing.md §\"Collisions Among Intercepting Routes\".`\n );\n }\n patterns.set(leaf.interceptedPattern, page.filePath);\n probeLeaves.push({ filePath: page.filePath, chain: leaf.chain });\n });\n }\n\n // Differently-spelled patterns that nonetheless compete: ask the matcher.\n const collision = findOrderDependentCollision(anchorNode, probeLeaves, base);\n if (collision) {\n throw new Error(\n `Build error: route collision between intercepting routes — two pages answer the same URL.\\n` +\n ` Owner: app/${owner}\\n` +\n ` Intercepted base: ${base}\\n` +\n ` URL: ${collision.url}\\n` +\n ` File 1: ${collision.first}\\n` +\n ` File 2: ${collision.second}\\n` +\n `Both match it, so which one renders would be decided by filesystem enumeration ` +\n `order — renaming a route group can flip it. Rename or move one of them.\\n` +\n `Pages are compared by the URLs they match, not by how they are spelled: [id] and ` +\n `[slug] match the same URLs, and an optional catch-all also matches with zero ` +\n `segments.\\n` +\n `Intercepting directories based at *different* URLs may target one page — the ` +\n `resolver tries the deepest first — so this rejects only an ambiguity among the ` +\n `ones based at ${base}.\\n` +\n `See design/07-routing.md §\"Collisions Among Intercepting Routes\".`\n );\n }\n}\n\n/** What the walk knows about the position it is currently standing in. */\ninterface PlacementContext {\n /** `node` is itself a slot node, so its children are direct slot children. */\n parentIsSlot: boolean;\n /** `node` is at or below a slot node. */\n inSlotSubtree: boolean;\n /** `node` is inside an intercepting subtree. */\n inInterceptingSubtree: boolean;\n /** Some segment from the root down to `node`, inclusive, binds a param. */\n ancestorsBindParams: boolean;\n}\n\nfunction walkForPlacement(node: SegmentNode, path: string, ctx: PlacementContext): void {\n for (const child of node.children) {\n const childPath = path ? `${path}/${child.segmentName}` : child.segmentName;\n\n if (child.segmentType === 'intercepting') {\n const marker = child.interceptionMarker ?? '(.)';\n\n if (ctx.inInterceptingSubtree) {\n throw new Error(\n `Build error: intercepting route nested inside another intercepting route.\\n` +\n ` Directory: app/${childPath}\\n` +\n `An intercepting directory (${marker}) resolves against the URL its own parent ` +\n `renders at, and an intercepting subtree has no such URL — nothing walks it, so ` +\n `the rewrite would match the navigation and then have nothing to render.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n }\n\n // Inside a slot, only a *direct* slot child is reachable: the slot\n // resolver reads `slotNode.children` and stops. The children-path\n // renderer cannot pick it up either — it builds a segment chain, which\n // has no way to express a descent through a slot.\n if (ctx.inSlotSubtree && !ctx.parentIsSlot) {\n throw new Error(\n `Build error: intercepting route inside a parallel slot but not directly under it.\\n` +\n ` Directory: app/${childPath}\\n` +\n `An intercepting directory (${marker}) inside an @slot must be a *direct* child of ` +\n `that slot, e.g. app/feed/@modal/${child.segmentName}/page.tsx. The slot resolver ` +\n `scans the slot's direct children only; elsewhere the rewrite would match the ` +\n `navigation and then have nothing to render.\\n` +\n `See design/07-routing.md §\"Intercepting Routes\".`\n );\n }\n\n // Outside a slot the intercepting page replaces `children` for the\n // owner's own layout chain, so those layouts render against the\n // intercepted URL — which carries no values for params declared above\n // the interception.\n if (!ctx.parentIsSlot && ctx.ancestorsBindParams) {\n assertOwnerChainBindsNoParams(childPath, marker);\n }\n\n if (!ctx.parentIsSlot && !node.layout) {\n assertOwnerHasLayout(path, childPath);\n }\n\n // `node` is the owner — the slot (whose urlPath is the owning segment's,\n // since slots add no URL depth) or the ordinary segment holding the\n // interception. The same input rewrite generation bases from.\n assertInterceptedBaseIsCountable(child, node.urlPath, childPath);\n assertInterceptedCatchAllsAreTerminal(child, childPath);\n assertNoRouteHandlersInSubtree(child, childPath);\n }\n\n walkForPlacement(child, childPath, {\n parentIsSlot: false,\n // A slot subtree stays a slot subtree all the way down: the deeper\n // positions are exactly the ones neither renderer reaches.\n inSlotSubtree: ctx.inSlotSubtree,\n inInterceptingSubtree: ctx.inInterceptingSubtree || child.segmentType === 'intercepting',\n ancestorsBindParams: ctx.ancestorsBindParams || !!child.paramName,\n });\n }\n\n // After every child has been recursed into, so a placement error inside any\n // intercepting subtree is reported in preference to what it causes here — a\n // nested interception leaves a node `matchUrlParts` cannot match at all, and\n // the resulting nonsense below it is not what the author needs to be told\n // about. This is per *owner* rather than per intercepting directory because\n // the collision space is the anchor group; see\n // `assertNoInterceptedPatternCollisions`.\n assertNoInterceptedPatternCollisions(node, path);\n\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n walkForPlacement(slotNode, path ? `${path}/@${slotName}` : `@${slotName}`, {\n parentIsSlot: true,\n inSlotSubtree: true,\n inInterceptingSubtree: ctx.inInterceptingSubtree,\n // A slot-mode interception never binds owner params from the target —\n // the pipeline re-matches the source route, which supplies them — so the\n // rule stops at the slot boundary.\n ancestorsBindParams: false,\n });\n }\n}\n\n/**\n * Recursively walk the segment tree to find intercepting routes.\n *\n * `ancestors` deliberately excludes slot nodes: a slot doesn't appear in a\n * matched route chain, so the last entry is always the nearest chain-visible\n * ancestor — the segment that owns the slot, and therefore the segment whose\n * presence in the source route gates the interception.\n *\n * Intercepting nodes only ever appear as a direct child of a slot or of an\n * ordinary chain segment in a valid tree; `validateInterceptionPlacement`\n * rejects every other placement at scan time, so this walk never has to\n * decide what an unrenderable intercepting node should generate.\n *\n * `parentIsSlot` is what distinguishes the two shapes, and it is the only\n * input that does: the owner, the scope and the intercepted pattern are all\n * computed identically either way.\n */\nfunction walkForInterceptions(\n node: SegmentNode,\n ancestors: SegmentNode[],\n parentIsSlot: boolean,\n rewrites: InterceptionRewrite[]\n): void {\n // Check children\n for (const child of node.children) {\n if (child.segmentType === 'intercepting' && child.interceptionMarker) {\n // Found an intercepting route — collect rewrites from its sub-tree\n collectFromInterceptingNode(child, ancestors, parentIsSlot, rewrites);\n } else {\n walkForInterceptions(child, [...ancestors, child], false, rewrites);\n }\n }\n\n // Check slots (intercepting routes are typically inside slots like @modal)\n for (const slot of Object.values(node.slots)) {\n walkForInterceptions(slot, ancestors, true, rewrites);\n }\n}\n\n/**\n * For an intercepting segment, find all leaf pages in its sub-tree and\n * generate rewrite rules for each.\n */\nfunction collectFromInterceptingNode(\n interceptingNode: SegmentNode,\n ancestors: SegmentNode[],\n parentIsSlot: boolean,\n rewrites: InterceptionRewrite[]\n): void {\n const marker = interceptingNode.interceptionMarker!;\n const segmentName = interceptingNode.interceptedSegmentName!;\n\n // Compute the intercepted URL base based on the marker\n const parentUrlPath = ancestors[ancestors.length - 1].urlPath;\n const interceptedUrlBase = computeInterceptedUrlBase(parentUrlPath, marker, segmentName);\n\n // The scope key and the re-match prefix both describe the same node — the\n // interception's owner — so they are derived here together from one\n // ancestor chain.\n const ancestorPaths = computeSegmentTreePaths(ancestors);\n const interceptingScope = ancestorPaths[ancestorPaths.length - 1];\n\n // Find all leaf pages in the intercepting sub-tree\n const shape: InterceptionShape = parentIsSlot\n ? { mode: 'slot', interceptingPrefix: parentUrlPath, interceptingScope }\n : { mode: 'children', interceptingScope };\n collectLeavesWithRewrites(interceptingNode, interceptedUrlBase, shape, rewrites);\n}\n\n/**\n * Everything about a rewrite except which URL it intercepts — one intercepting\n * directory produces one of these and one rewrite per leaf page beneath it.\n *\n * Written as a union of `Omit`s rather than `Omit` of the union: `Omit` is not\n * distributive, so the latter would silently collapse to the shapes' common\n * fields and drop `interceptingPrefix`.\n */\ntype InterceptionShape =\n | Omit<SlotInterceptionRewrite, 'interceptedPattern'>\n | Omit<ChildrenInterceptionRewrite, 'interceptedPattern'>;\n\n/**\n * Walk an intercepting sub-tree and visit every page-bearing node with the URL\n * pattern it is intercepted at, and URLs that reach it.\n *\n * Route groups are transparent, exactly as they are in the main tree — which\n * is what makes two groups under one interceptor able to claim one URL, and is\n * why the collision validator has to walk the same shape this does.\n *\n * Rewrite generation and that validator are the two callers. They share this\n * walk rather than each having their own so they cannot disagree about which\n * URLs an interceptor claims: a leaf the validator did not see is a rewrite\n * nobody checked, and a leaf only the validator sees is a build error for a\n * route that does not exist. Slots are not descended, here or in either caller\n * — a slot nested inside an intercepting subtree produces no rewrite.\n *\n * That answers the rewrite question only, and the resolution question is\n * answered elsewhere: `validateSlotsInsideInterceptingSubtree`\n * (`collision-spaces.ts`) gives each such slot its own collision space, and\n * `validateSlotPlacement` (`slot-placement.ts`) rejects the ones no renderer\n * reaches. Between them the slots this walk skips are covered; do not conclude\n * from the skip here that they are unvalidated (TIM-1308, TIM-1311).\n *\n * The walk reports the chain of URL-contributing nodes rather than building\n * probe URLs itself: choosing a probe value means running the matcher over the\n * whole subtree, which is the validator's business and not something rewrite\n * generation should be paying for or passing dummy arguments around.\n */\nfunction walkInterceptedLeaves(\n node: SegmentNode,\n interceptedUrlPath: string,\n chain: SegmentNode[],\n visit: (page: NonNullable<SegmentNode['page']>, leaf: InterceptedLeaf) => void\n): void {\n if (node.page) {\n // The page is handed over rather than the node so callers reading it do\n // not need a non-null assertion to say what this branch already proved.\n visit(node.page, { interceptedPattern: interceptedUrlPath, chain });\n }\n\n for (const child of node.children) {\n const isGroup = child.segmentType === 'group';\n walkInterceptedLeaves(\n child,\n isGroup ? interceptedUrlPath : `${interceptedUrlPath}/${child.segmentName}`,\n isGroup ? chain : [...chain, child],\n visit\n );\n }\n}\n\n/** What one page-bearing node in an intercepting subtree claims. */\ninterface InterceptedLeaf {\n /** The URL pattern the rewrite carries — the author's own spelling. */\n interceptedPattern: string;\n /**\n * The nodes from the intercepting directory down to this page that contribute\n * URL parts — route groups excluded, since they are transparent for matching.\n * Empty for the intercepting directory's own page.\n */\n chain: SegmentNode[];\n}\n\n/**\n * Recursively find leaf pages in an intercepting sub-tree and generate\n * rewrite rules for each.\n */\nfunction collectLeavesWithRewrites(\n node: SegmentNode,\n interceptedUrlPath: string,\n shape: InterceptionShape,\n rewrites: InterceptionRewrite[]\n): void {\n walkInterceptedLeaves(node, interceptedUrlPath, [], (_page, leaf) => {\n rewrites.push({ ...shape, interceptedPattern: leaf.interceptedPattern });\n });\n}\n\n/**\n * How many URL levels a marker climbs from the slot owner to reach the\n * intercepted segment, or `'root'` for a marker that climbs all the way.\n *\n * Level counting operates on URL path segments, NOT filesystem directories.\n * Route groups and parallel slots are already excluded from urlPath (they\n * don't add URL depth), so (..) correctly climbs visible segments. This\n * avoids the Vinext bug where path.dirname() on filesystem paths would\n * waste climbs on invisible route groups.\n *\n * Used only by `computeInterceptedBase` below — both rewrite generation and\n * the slot resolver go through that, so the arithmetic exists once.\n */\nfunction interceptionClimb(marker: InterceptionMarker): number | 'root' {\n switch (marker) {\n case '(.)':\n return 0;\n case '(..)':\n return 1;\n case '(..)(..)':\n return 2;\n case '(...)':\n return 'root';\n }\n}\n\n/**\n * Compute the base URL that an intercepting route intercepts, given the\n * parent's URL path and the interception marker.\n *\n * - (.) — same level: parent's URL path\n * - (..) — one level up: parent's parent URL path\n * - (...) — root level: /\n * - (..)(..) — two levels up: parent's grandparent URL path\n *\n * The result is a URL **pattern**, not a URL — `parentUrlPath` carries the\n * directory names, so a dynamic ancestor appears as `/docs/[...path]`.\n * Rewrite generation wants exactly that. The slot resolver imports this to\n * locate the intercepted segment in a concrete target pathname, and must\n * therefore account for a bracket part standing for a different number of\n * URL parts than itself (TIM-1281).\n *\n * Climbing past the root clamps to `/` rather than erroring, so generation\n * and resolution never disagree about what an over-reaching marker\n * intercepts.\n */\n/**\n * The URL pattern an intercepting directory's own page sits at — its\n * `computeInterceptedBase` joined with the segment it intercepts.\n *\n * The root case is why this is a function rather than a template literal at\n * each caller: a base of `/` must not produce `//photo`. Rewrite generation\n * and the collision validator both start their walk from this value, so the\n * two describe the same URLs by construction.\n */\nexport function computeInterceptedUrlBase(\n parentUrlPath: string,\n marker: InterceptionMarker,\n interceptedSegmentName: string\n): string {\n return joinInterceptedBase(computeInterceptedBase(parentUrlPath, marker), interceptedSegmentName);\n}\n\n/**\n * An intercepted base joined with one segment beneath it.\n *\n * The whole content of the \"function rather than a template literal\" rule\n * above: a base of `/` must not produce `//photo`. The collision validator has\n * the base in hand already (it groups by it) and joins through this rather than\n * re-deriving it from an owner path, so both callers spell the root case once.\n */\nexport function joinInterceptedBase(base: string, segmentName: string): string {\n return base === '/' ? `/${segmentName}` : `${base}/${segmentName}`;\n}\n\nexport function computeInterceptedBase(parentUrlPath: string, marker: InterceptionMarker): string {\n const climb = interceptionClimb(marker);\n if (climb === 'root') return '/';\n\n const parts = parentUrlPath.split('/').filter(Boolean);\n for (let i = 0; i < climb; i++) parts.pop();\n return parts.length === 0 ? '/' : `/${parts.join('/')}`;\n}\n","/**\n * Route collision spaces.\n *\n * A collision space is a set of routes that compete for URLs with each other,\n * and there are three: the main tree, each parallel slot, and each intercepting\n * subtree. This module owns the first two; `interception.ts` owns the third.\n * All of them decide order-dependence with the one oracle in\n * `collision-probe.ts`, so they cannot drift on what counts as two routes\n * answering a single URL.\n *\n * See design/07-routing.md §\"Route Collisions\".\n */\n\nimport type { SegmentNode } from './types.ts';\nimport { computeInterceptedUrlBase } from './interception.ts';\nimport { findOrderDependentCollision, type ProbeLeaf } from './collision-probe.ts';\n\n/**\n * Validate that no two pages/routes in one collision space answer the same URL.\n *\n * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim\n * /login — the scanner must detect and reject this at build time.\n *\n * Each parallel slot is validated as its OWN collision space: a slot's pages\n * intentionally share URL paths with the parent tree (that's the point of\n * parallel routes), but two route groups INSIDE one slot claiming the same\n * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.\n */\nexport function validateRouteGroupCollisions(root: SegmentNode): void {\n validateCollisionSpace(root, '', root.urlPath);\n}\n\n/**\n * Validate one collision space — the main tree, or one parallel slot.\n *\n * **Two checks, and the difference between them matters.** Two leaves at the\n * same `urlPath` are decided by string equality, which is exact and needs no\n * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs\n * whatever the precedence rules are, and naming the shared path is the clearest\n * thing to tell the author.\n *\n * Everything else is decided by asking the matcher, through the shared oracle\n * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses\n * every pair that matches the same URLs while being *spelled* differently:\n * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority\n * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`\n * because an optional catch-all also matches zero parts. Both built before\n * TIM-1308 with filesystem enumeration order deciding which page renders,\n * which is precisely what this validator and `validateAffixedSiblingConflicts`\n * exist to reject.\n *\n * Segment *kinds* stay distinct without any special-casing here, because the\n * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside\n * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is\n * not reported. So does an affixed sibling against a bare one; the\n * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and\n * duplicating it here would double-report.\n */\nfunction validateCollisionSpace(spaceRoot: SegmentNode, segmentPath: string, base: string): void {\n const leaves: ProbeLeaf[] = [];\n collectRoutableLeaves(spaceRoot, new Map(), segmentPath, [], leaves, base);\n\n const collision = findOrderDependentCollision(spaceRoot, leaves, base);\n if (!collision) return;\n\n throw new Error(\n `Build error: route collision — two pages/routes answer the same URL.\\n` +\n ` URL: ${collision.url}\\n` +\n ` File 1: ${collision.first}\\n` +\n ` File 2: ${collision.second}\\n` +\n `Both match it, so which one renders would be decided by filesystem enumeration ` +\n `order — renaming a route group can flip it. Rename or move one of them.\\n` +\n `Routes are compared by the URLs they match, not by how they are spelled: [id] and ` +\n `[slug] match the same URLs, and an optional catch-all also matches with zero ` +\n `segments.`\n );\n}\n\n/**\n * Walk one collision space and collect its routable leaves (page or route\n * files), throwing on an exact `urlPath` collision. Each slot recurses as its\n * OWN space — slots are parallel routes that intentionally share URL paths with\n * their parent tree, but collisions within a single slot are real errors.\n *\n * The early return at an intercepting node drops that subtree's own pages from\n * this space, but not its slots: a slot is its own collision space wherever it\n * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before\n * returning.\n *\n * `chain` accumulates the URL-contributing nodes from the space root down, for\n * the probe oracle. Route groups are excluded because they are transparent for\n * matching, and the space root itself is excluded because `matchUrlParts`\n * matches parts against its *children* — the root consumes nothing.\n */\nfunction collectRoutableLeaves(\n node: SegmentNode,\n seen: Map<string, { filePath: string; segmentPath: string }>,\n segmentPath: string,\n chain: SegmentNode[],\n leaves: ProbeLeaf[],\n base: string\n): void {\n // Intercepting routes are resolved by the interception resolvers, not URL\n // matching, and their computed urlPaths are not addresses — an interception\n // mirrors the canonical route it replaces, so comparing those paths here\n // would reject every correct interception. Skipping is not \"unvalidated\":\n // `assertNoInterceptedPatternCollisions` gives each intercepting subtree its\n // own collision space, keyed by the intercepted pattern rather than by these\n // paths (TIM-1305). See design/07-routing.md §\"Collisions Inside an\n // Intercepting Subtree\" and §\"Why urlPath Stays Parent-Relative Inside an\n // Intercepting Subtree\".\n const currentPath = segmentPath\n ? `${segmentPath}/${node.segmentName}`\n : node.segmentName || '(root)';\n\n // The intercepting subtree's own pages leave this space — but its SLOTS do\n // not leave every space, so they are picked up before returning. See\n // `validateSlotsInsideInterceptingSubtree`.\n if (node.segmentType === 'intercepting') {\n // `node.urlPath` on an intercepting node is its OWNER's path — the input\n // `computeInterceptedUrlBase` wants — because an intercepting segment adds\n // no URL depth.\n validateSlotsInsideInterceptingSubtree(\n node,\n currentPath,\n interceptedBaseOf(node, node.urlPath)\n );\n return;\n }\n\n const routableFile = node.page ?? node.route;\n if (routableFile) {\n const existing = seen.get(node.urlPath);\n if (existing) {\n throw new Error(\n `Build error: route collision — multiple route groups produce a page/route at the same URL path.\\n` +\n ` URL path: ${urlFromChain(base, chain)}\\n` +\n ` File 1: ${existing.filePath} (via ${existing.segmentPath})\\n` +\n ` File 2: ${routableFile.filePath} (via ${currentPath})\\n` +\n `Each URL path must map to exactly one page or route handler. ` +\n `Rename or move one of the conflicting files.`\n );\n }\n seen.set(node.urlPath, { filePath: routableFile.filePath, segmentPath: currentPath });\n leaves.push({ filePath: routableFile.filePath, chain });\n }\n\n // Recurse into children. A route group contributes no URL part, so it is\n // absent from the chain — exactly as `collectEffectiveChildren` flattens it\n // away in the matcher.\n for (const child of node.children) {\n const isGroup = child.segmentType === 'group';\n collectRoutableLeaves(\n child,\n seen,\n currentPath,\n isGroup ? chain : [...chain, child],\n leaves,\n base\n );\n }\n\n // Recurse into slots — each slot is its own collision space, with its own\n // seen map, its own leaf set and its own probe run.\n //\n // The base is accumulated from this space's own base rather than read off\n // `slotNode.urlPath`, because this walk also runs on slot spaces nested inside\n // an intercepting subtree, where `urlPath` is parent-relative and not an\n // address. Outside one the two are identical by construction.\n for (const slotNode of Object.values(node.slots)) {\n validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));\n }\n}\n\n/**\n * Validate every parallel slot nested anywhere inside an intercepting subtree.\n *\n * Two walks each skip these slots for their own good reason, and together they\n * left them checked by nothing: `collectRoutableLeaves` returns at the\n * intercepting node before it reaches them, and `walkInterceptedLeaves`\n * deliberately does not descend slots — correct for rewrite generation, since a\n * slot inside an intercepting subtree produces no rewrite. But \"produces no\n * rewrite\" answers the rewrite question and not the resolution one, so\n * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor\n * built with filesystem order picking the page — the ordinary per-slot\n * collision that fails the build anywhere else in the tree (codex, on PR #1002).\n *\n * A slot is its own collision space wherever it sits, so each one is validated\n * as one.\n *\n * **Which interception shape this still applies to.** TIM-1311 answered the\n * question this was written under — whether such a slot renders at all — and\n * the answer is per-shape:\n *\n * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node\n * joins the main route chain, so `route-element-builder.ts` resolves slots on\n * it and below it like any other chain segment. They render, and this is the\n * space where the check is load-bearing.\n * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another\n * slot's subtree, which no renderer descends for slots — so it never renders,\n * and `validateSlotPlacement` now rejects the placement before this runs.\n * That rule subsumes this one for the modal shape rather than conflicting\n * with it, exactly as anticipated.\n *\n * So this walk is reached only for children-path interceptors in a valid tree.\n * It is not narrowed to them: the rule it states — a slot is its own collision\n * space wherever it sits — is shape-independent, and making it conditional on a\n * property the placement validator already guarantees would just be a second\n * place for the two to disagree.\n *\n * The walk covers the whole subtree, not just the interceptor's direct slot\n * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the\n * same reason as `(...)photo/@side`.\n */\nfunction validateSlotsInsideInterceptingSubtree(\n node: SegmentNode,\n segmentPath: string,\n base: string\n): void {\n for (const slotNode of Object.values(node.slots)) {\n // A slot adds no URL depth, so it answers its owner's base.\n validateCollisionSpace(slotNode, segmentPath, base);\n }\n for (const child of node.children) {\n validateSlotsInsideInterceptingSubtree(\n child,\n `${segmentPath}/${child.segmentName}`,\n childInterceptedBase(child, base)\n );\n }\n}\n\n/**\n * The URL a leaf answers, built from its space's base and its own chain.\n *\n * Read instead of `node.urlPath` because `urlPath` inside an intercepting\n * subtree is parent-relative and is not an address — the collision URL has to\n * be one the author can actually find. Outside an intercepting subtree the two\n * are identical by construction: the base is the space root's `urlPath` and the\n * chain is every URL-contributing segment below it.\n */\nfunction urlFromChain(base: string, chain: SegmentNode[]): string {\n if (chain.length === 0) return base || '/';\n const tail = chain.map((n) => n.segmentName).join('/');\n return `${base === '/' ? '' : base}/${tail}`;\n}\n\n/**\n * The intercepted URL an intercepting directory's own page sits at.\n *\n * `urlPath` inside an intercepting subtree is deliberately parent-relative and\n * is **not** an address (see design/07-routing.md §\"Why urlPath Stays\n * Parent-Relative Inside an Intercepting Subtree\"), so a collision reported\n * from one names a URL the author cannot find. The intercepted base is the real\n * address, and it is what rewrite generation and the interception collision\n * validator both already use.\n */\nfunction interceptedBaseOf(node: SegmentNode, ownerUrlPath: string): string {\n return computeInterceptedUrlBase(\n ownerUrlPath,\n node.interceptionMarker ?? '(.)',\n node.interceptedSegmentName ?? node.segmentName\n );\n}\n\n/**\n * Extend an intercepted base by one child segment.\n *\n * Route groups are transparent and contribute nothing. A nested intercepting\n * node re-bases from its own marker rather than appending — that tree is\n * rejected by `validateInterceptionPlacement`, but collision validation runs\n * first, so it still has to produce a sensible URL rather than one containing a\n * literal \"(.)b\".\n */\nfunction childInterceptedBase(child: SegmentNode, base: string): string {\n // Slots are not in `children` — `scanChildren` files them under `slots` — so\n // only groups are transparent here.\n if (child.segmentType === 'group') return base;\n if (child.segmentType === 'intercepting') return interceptedBaseOf(child, base);\n return base === '/' ? `/${child.segmentName}` : `${base}/${child.segmentName}`;\n}\n","/**\n * Parallel slot placement.\n *\n * One rule: a slot is resolved only for a segment on the **matched route\n * chain**, and a slot's own subtree is never on that chain. So a slot declared\n * anywhere inside another slot's subtree can never render, and is rejected at\n * build time rather than left as a directory the author will keep editing.\n *\n * See design/07-routing.md §\"Parallel Routes\".\n */\n\nimport type { SegmentNode } from './types.ts';\n\n/**\n * Reject every parallel slot that no renderer reaches.\n *\n * **Where slots are resolved.** Two places read `segment.slots`, and both walk\n * the main route chain: `route-element-builder.ts` (the RSC render) and\n * `tree-builder.ts`. Neither is reachable from inside a slot. The slot's own\n * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched\n * chain to apply that chain's layouts, error boundaries and access gates\n * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`\n * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and\n * everything below it is dead: the file is scanned, typed, code-split and\n * shipped, and no request can render it.\n *\n * That is the TIM-1278 failure — a directory that silently never renders —\n * and the reason it is a build error rather than a documented limit is that\n * nothing at request time can report it. A slot that does not match renders\n * `default.tsx` or `null`, which is exactly what a slot the resolver never\n * looked at also produces, so the author sees the *designed* behaviour of a\n * non-matching slot and has no signal to distinguish it from a slot that\n * cannot match at all.\n *\n * **Interception is incidental.** TIM-1311 arrived as\n * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the\n * identical `feed/@modal/photo/@side` never renders either, for the same\n * reason and with no marker anywhere. Rejecting only the intercepting spelling\n * would have drawn a line the author cannot see from the directory names.\n *\n * The children-path interception shape is **not** affected and must not be:\n * its intercepting node joins the main chain (`server/children-interception.ts`\n * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary\n * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below\n * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`\n * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot\n * boundary, which is what this walk tracks — not the marker.\n */\nexport function validateSlotPlacement(root: SegmentNode): void {\n walkForSlotPlacement(root, '', null);\n}\n\n/**\n * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or\n * above `node`, or null on the main chain. It is carried rather than recomputed\n * so the error can name the slot that swallows the offender — \"this is inside\n * @modal\" is the part of the diagnosis the author cannot see from the offending\n * path alone.\n */\nfunction walkForSlotPlacement(\n node: SegmentNode,\n path: string,\n enclosingSlotPath: string | null\n): void {\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;\n if (enclosingSlotPath !== null) {\n throwNestedSlot(slotPath, enclosingSlotPath);\n }\n walkForSlotPlacement(slotNode, slotPath, slotPath);\n }\n\n for (const child of node.children) {\n walkForSlotPlacement(\n child,\n path ? `${path}/${child.segmentName}` : child.segmentName,\n enclosingSlotPath\n );\n }\n}\n\nfunction throwNestedSlot(slotPath: string, enclosingSlotPath: string): never {\n throw new Error(\n `Build error: parallel slot nested inside another parallel slot.\\n` +\n ` Directory: app/${slotPath}\\n` +\n ` Inside: app/${enclosingSlotPath}\\n` +\n `A parallel slot is resolved only for a segment on the matched route chain, and a ` +\n `slot's own subtree is never on that chain — the slot resolver walks the slot's ` +\n `matched chain to apply its layouts, error boundaries and access gates, and never ` +\n `looks at slots declared inside it. So app/${slotPath} and everything below it can ` +\n `never render, and no request-time signal can tell you: an unreachable slot ` +\n `produces exactly what a slot that simply did not match produces.\\n` +\n `Declare the slot on a segment of the main route chain instead, or move its pages ` +\n `into app/${enclosingSlotPath}'s own subtree.\\n` +\n `See design/07-routing.md §\"Parallel Routes\".`\n );\n}\n","/**\n * Route discovery scanner.\n *\n * Pure function: (appDir, config) → RouteTree\n *\n * Scans the app/ directory and builds a segment tree recognizing all\n * timber.js file conventions. Does NOT handle request matching — this\n * is discovery only.\n */\n\nimport { readdirSync, statSync } from 'node:fs';\nimport { join, extname, basename } from 'node:path';\nimport type {\n RouteTree,\n SegmentNode,\n SegmentType,\n RouteFile,\n ScannerConfig,\n InterceptionMarker,\n} from './types.ts';\nimport { classifySegment, effectiveUrlSegment } from './segment-classify.ts';\nimport { validateInterceptionPlacement, computeInterceptedBase } from './interception.ts';\nimport { validateRouteGroupCollisions } from './collision-spaces.ts';\nimport { validateSlotPlacement } from './slot-placement.ts';\nimport { DEFAULT_PAGE_EXTENSIONS } from './types.ts';\nimport { classifyMetadataRoute, isDynamicMetadataExtension } from '../server/metadata-routes.ts';\nimport { swallow } from '../server/logger.ts';\nimport { ENCODED_SEPARATOR_RE, NULL_BYTE_RE } from '../server/canonicalize.ts';\n\n/**\n * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)\n */\nconst PAGE_EXT_CONVENTIONS = new Set(['page', 'layout', 'error', 'default', 'denied']);\n\n/**\n * File convention names that are always .ts/.tsx (never .mdx etc.)\n */\nconst FIXED_CONVENTIONS = new Set(['middleware', 'access', 'route']);\n\n/**\n * Status-code file patterns:\n * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx\n * - Category catch-alls: 4xx.tsx, 5xx.tsx\n */\nconst STATUS_CODE_PATTERN = /^(\\d{3}|[45]xx)$/;\n\n/**\n * Whether a basename + extension pair is a route-convention file the\n * framework itself imports: page/layout/error/default/denied and\n * global-error on pageExtensions, middleware/access/route/proxy on\n * .ts/.tsx/.js/.jsx only, and status-code files (404, 4xx, …) on\n * pageExtensions or .json — mirroring this scanner's own recognition\n * rules per family.\n *\n * Exported for the analyze classifier so its provisional classification\n * (design/47 §2) derives from the scanner's real conventions instead of\n * a duplicate list that can drift.\n */\nexport function isRouteConventionFile(\n base: string,\n ext: string,\n pageExtensions: readonly string[] = DEFAULT_PAGE_EXTENSIONS\n): boolean {\n const isPageExt = pageExtensions.includes(ext);\n if ((PAGE_EXT_CONVENTIONS.has(base) || base === 'global-error') && isPageExt) return true;\n if ((FIXED_CONVENTIONS.has(base) || base === 'proxy') && /^[jt]sx?$/.test(ext)) return true;\n if (STATUS_CODE_PATTERN.test(base) && (isPageExt || ext === 'json')) return true;\n return false;\n}\n\n/**\n * Scan the app/ directory and build the route tree.\n *\n * @param appDir - Absolute path to the app/ directory\n * @param config - Scanner configuration\n * @returns The complete route tree\n */\nexport function scanRoutes(appDir: string, config: ScannerConfig = {}): RouteTree {\n const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;\n const extSet = new Set(pageExtensions);\n\n const tree: RouteTree = {\n root: createSegmentNode('', 'static', '/'),\n };\n\n // Check for proxy.ts at app root\n const proxyFile = findFixedFile(appDir, 'proxy');\n if (proxyFile) {\n tree.proxy = proxyFile;\n }\n\n // Check for global-error.{tsx,ts,jsx,js} at app root.\n // Tier 2 error page — renders standalone (no layouts) when no segment-level\n // error file is found. See design/10-error-handling.md §\"Tier 2\".\n const globalErrorFile = findPageExtFile(appDir, 'global-error', extSet);\n if (globalErrorFile) {\n tree.globalError = globalErrorFile;\n }\n\n // Scan the root directory's files\n scanSegmentFiles(appDir, tree.root, extSet);\n\n // Scan children recursively\n scanChildren(appDir, tree.root, extSet);\n\n // Validate: every parallel slot sits where a renderer reaches it. First,\n // because a slot nested inside another slot never renders, and a collision\n // reported from inside one would send the author to fix an ambiguity between\n // two pages that were both already dead.\n validateSlotPlacement(tree.root);\n\n // Validate: detect route group collisions (different groups producing pages at the same URL)\n validateRouteGroupCollisions(tree.root);\n\n // Validate: detect duplicate param names in nested dynamic segments\n // e.g., /[id]/items/[id] — same param name in ancestor and descendant\n validateDuplicateParamNames(tree.root);\n\n // Validate: detect same param name used with different bracket forms\n // e.g., [id] in one route and [...id] in another\n validateUniqueBracketForms(tree.root);\n\n // Validate: detect affixed dynamic siblings with equal specificity\n // e.g., a-[id] and [slug]-b both have prefix+suffix length = 2\n validateAffixedSiblingConflicts(tree.root);\n\n // Validate: intercepting routes must be direct children of a parallel slot —\n // the slot resolver is the only thing that can render one.\n validateInterceptionPlacement(tree.root);\n\n return tree;\n}\n\n/**\n * Create an empty segment node.\n */\nfunction createSegmentNode(\n segmentName: string,\n segmentType: SegmentType,\n urlPath: string,\n paramName?: string,\n interceptionMarker?: InterceptionMarker,\n interceptedSegmentName?: string,\n paramPrefix?: string,\n paramSuffix?: string\n): SegmentNode {\n return {\n segmentName,\n segmentType,\n urlPath,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n children: [],\n slots: {},\n };\n}\n\n/**\n * Compute the URL path for a child segment given its parent's URL path.\n * Route groups, slots, and intercepting routes do NOT add URL depth.\n */\nfunction computeUrlPath(parentUrlPath: string, dirName: string, segmentType: SegmentType): string {\n // Groups, slots, and intercepting routes don't add to URL path\n if (segmentType === 'group' || segmentType === 'slot' || segmentType === 'intercepting') {\n return parentUrlPath;\n }\n\n const parentPath = parentUrlPath === '/' ? '' : parentUrlPath;\n return `${parentPath}/${dirName}`;\n}\n\n/**\n * Scan a directory for file conventions and populate the segment node.\n */\nfunction scanSegmentFiles(dirPath: string, node: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n // Skip directories — handled by scanChildren\n try {\n if (statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n const ext = extname(entry).slice(1); // remove leading dot\n const name = basename(entry, `.${ext}`);\n\n // Page-extension conventions (page, layout, error, default, denied)\n if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {\n const key = name as 'page' | 'layout' | 'error' | 'default' | 'denied';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Fixed conventions (middleware, access, route) — only\n // .ts/.tsx/.js/.jsx, never pageExtensions like .mdx. The regex is\n // anchored: mts/cts/mjs/cjs (and stray tail matches like `.foots`)\n // are NOT recognized. See design/07-routing.md §\"Page Extensions\".\n if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {\n const key = name as 'middleware' | 'access' | 'route';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // JSON status-code files (401.json, 4xx.json, 503.json, 5xx.json)\n // Recognized regardless of pageExtensions — .json is a data format, not a page extension.\n if (STATUS_CODE_PATTERN.test(name) && ext === 'json') {\n if (!node.jsonStatusFiles) {\n node.jsonStatusFiles = {};\n }\n node.jsonStatusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Status-code files (401.tsx, 4xx.tsx, 503.tsx, 5xx.tsx)\n if (STATUS_CODE_PATTERN.test(name) && extSet.has(ext)) {\n if (!node.statusFiles) {\n node.statusFiles = {};\n }\n const existing = node.statusFiles[name];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node.statusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Metadata route files (sitemap.ts, robots.ts, icon.tsx, opengraph-image.tsx, etc.)\n // Both static (.xml, .txt, .png, .ico, etc.) and dynamic (.ts, .tsx) files are recognized.\n // When both exist for the same base name, dynamic takes precedence.\n // Two files of the SAME kind (static+static or dynamic+dynamic) are a\n // build error — picking one by readdir order is platform-dependent.\n // See design/16-metadata.md §\"Metadata Routes\"\n const metaInfo = classifyMetadataRoute(entry);\n if (metaInfo) {\n if (!metaInfo.nestable && node.segmentName !== '') {\n throw new Error(\n `Build error: '${name}' is a root-only metadata convention and must be in the app root directory.\\n` +\n ` File: ${fullPath}\\n` +\n ` Move this file to the app root (not a route group or nested segment).`\n );\n }\n if (!node.metadataRoutes) {\n node.metadataRoutes = {};\n }\n const existing = node.metadataRoutes[name];\n if (existing) {\n const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);\n const newIsDynamic = isDynamicMetadataExtension(name, ext);\n if (existingIsDynamic === newIsDynamic) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n // Dynamic > static precedence: overwrite only when the new file is dynamic.\n if (newIsDynamic) {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n } else {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n }\n }\n\n // Validate: route.ts + page.* is a hard build error\n if (node.route && node.page) {\n throw new Error(\n `Build error: route.ts and page.* cannot coexist in the same segment.\\n` +\n ` route.ts: ${node.route.filePath}\\n` +\n ` page: ${node.page.filePath}\\n` +\n `A URL is either an API endpoint or a rendered page, not both.`\n );\n }\n}\n\n/**\n * Throw a build error for two files claiming the same convention slot in\n * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first\n * is platform-dependent (APFS sorts entries, ext4 does not) — silently\n * picking one would let macOS dev and Linux CI serve different\n * implementations of the same route.\n */\nfunction throwDuplicateConvention(\n convention: string,\n firstPath: string,\n secondPath: string\n): never {\n throw new Error(\n `Build error: duplicate '${convention}' files in the same route segment.\\n` +\n ` File 1: ${firstPath}\\n` +\n ` File 2: ${secondPath}\\n` +\n `Each segment may define '${convention}' at most once. Remove one of the files.`\n );\n}\n\n/**\n * Recursively scan child directories and build the segment tree.\n */\nfunction scanChildren(dirPath: string, parentNode: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n try {\n if (!statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n // Reject directories with encoded path delimiters or null bytes.\n // These can cause route collisions when decoded at the URL boundary.\n // See design/13-security.md §\"Encoded separators rejected\" and §\"Null bytes rejected\".\n if (ENCODED_SEPARATOR_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded path delimiter (%2F or %5C).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded separators in directory names cause route collisions when decoded. ` +\n `Rename the directory to remove the encoded delimiter.`\n );\n }\n if (NULL_BYTE_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded null byte (%00).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded null bytes in directory names are not allowed. ` +\n `Rename the directory to remove the null byte encoding.`\n );\n }\n\n const {\n type,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n } = classifySegment(entry);\n\n // Skip private folders — underscore-prefixed dirs are excluded from routing\n if (type === 'private') continue;\n\n const urlPath = computeUrlPath(parentNode.urlPath, entry, type);\n const childNode = createSegmentNode(\n entry,\n type,\n urlPath,\n paramName,\n interceptionMarker,\n interceptedSegmentName,\n paramPrefix,\n paramSuffix\n );\n\n // Scan this segment's files\n scanSegmentFiles(fullPath, childNode, extSet);\n\n // Recurse into subdirectories\n scanChildren(fullPath, childNode, extSet);\n\n // Attach to parent: slots go into slots record, everything else is a child\n if (type === 'slot') {\n const slotName = entry.slice(1); // remove @\n parentNode.slots[slotName] = childNode;\n } else {\n parentNode.children.push(childNode);\n }\n }\n}\n\n/**\n * Validate that no route chain contains duplicate dynamic param names.\n *\n * Example violation:\n * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.\n *\n * Route groups are transparent — params accumulate through them.\n * Slots are independent — duplicate detection does NOT cross slot boundaries.\n *\n * See design/07-routing.md §\"Duplicate Param Name Detection\"\n */\nfunction validateDuplicateParamNames(root: SegmentNode): void {\n walkForDuplicateParams(root, new Map());\n}\n\n/**\n * Recursively walk the segment tree, tracking seen param names → segment paths.\n * Throws on the first duplicate found.\n */\nfunction walkForDuplicateParams(node: SegmentNode, seen: Map<string, string>): void {\n // Read through the effective identity so an intercepting directory is seen\n // as the segment it intercepts: the scanner leaves `paramName` unset on\n // `(.)[id]`, so a validator reading the node directly is blind to a param\n // the resolver goes on to bind — `@modal/(.)[id]/[id]` would pass here and\n // then silently overwrite the outer `id` at match time, where the ordinary\n // `/[id]/[id]` is rejected. See TIM-1288.\n const { paramName } = effectiveUrlSegment(node);\n\n // If this node introduces a param name, check for duplicates\n if (paramName) {\n const existing = seen.get(paramName);\n if (existing) {\n throw new Error(\n `[timber] Duplicate param name '${paramName}' in route chain.\\n` +\n ` First defined at: ${existing}\\n` +\n ` Duplicate at: ${node.urlPath || '/'}\\n` +\n ` Rename one of the segments to avoid ambiguity.`\n );\n }\n // Add to seen for descendants (use a new Map to avoid polluting siblings)\n seen = new Map(seen);\n seen.set(paramName, node.urlPath || '/');\n }\n\n // Recurse into children (they inherit the accumulated params)\n for (const child of node.children) {\n walkForDuplicateParams(child, seen);\n }\n\n // A slot INHERITS the ancestor params rather than starting fresh: a slot\n // child may not reuse a name its owner already bound\n // (`app/gallery/[id]/@modal/[id]` is rejected). The copy is so sibling\n // slots don't see each other's names, not so the chain is reset.\n //\n // Whether that rule is right is a separate question — slot params are\n // merged over the main route's at read time, so a collision is defined\n // rather than ambiguous — but changing it would change every slot.\n // Tracked as TIM-1287; do not \"fix\" this by making the map fresh without\n // deciding that.\n for (const slotNode of Object.values(node.slots)) {\n walkForDuplicateParams(slotNode, new Map(seen));\n }\n}\n\n/**\n * Validate that each param name uses a single bracket form across the entire route tree.\n *\n * Different bracket forms produce different types:\n * [id] → string\n * [...id] → string[]\n * [[...id]] → string[] | undefined\n *\n * If the same param name appears with multiple forms, the no-argument\n * getSegmentParams() / useSegmentParams() return type becomes ambiguous.\n *\n * Same name + same form across different routes is fine and expected.\n */\nfunction validateUniqueBracketForms(root: SegmentNode): void {\n const forms = new Map<string, { segmentType: SegmentType; urlPath: string }>();\n collectBracketForms(root, forms);\n}\n\nfunction collectBracketForms(\n node: SegmentNode,\n forms: Map<string, { segmentType: SegmentType; urlPath: string }>\n): void {\n // Effective identity, so `(.)[...rest]` is compared as the catch-all it\n // intercepts rather than skipped as an 'intercepting' node (TIM-1288).\n const { paramName, segmentType } = effectiveUrlSegment(node);\n\n if (paramName && segmentType !== 'static' && segmentType !== 'group') {\n const existing = forms.get(paramName);\n if (existing && existing.segmentType !== segmentType) {\n const bracketExamples: Record<string, string> = {\n 'dynamic': `[${paramName}]`,\n 'catch-all': `[...${paramName}]`,\n 'optional-catch-all': `[[...${paramName}]]`,\n };\n throw new Error(\n `[timber] Param name '${paramName}' uses multiple bracket forms.\\n` +\n ` ${bracketExamples[existing.segmentType] ?? existing.segmentType} at: ${existing.urlPath}\\n` +\n ` ${bracketExamples[segmentType] ?? segmentType} at: ${node.urlPath || '/'}\\n` +\n ` Each param name must use a single bracket form across all routes.\\n` +\n ` Rename one of the segments to fix this (e.g., [${paramName}] → [${paramName}Id]).`\n );\n }\n if (!existing) {\n forms.set(paramName, {\n segmentType,\n urlPath: node.urlPath || '/',\n });\n }\n }\n\n for (const child of node.children) {\n collectBracketForms(child, forms);\n }\n for (const slotNode of Object.values(node.slots)) {\n collectBracketForms(slotNode, forms);\n }\n}\n\n/**\n * Validate that no sibling affixed dynamic segments have equal specificity.\n *\n * Among affixed siblings, longer combined prefix+suffix length wins. When two\n * siblings tie (same total affix length), the router would fall back to\n * filesystem scan order — which is platform-dependent. This is a build error.\n *\n * Route groups are URL-transparent, so affixed segments inside different groups\n * at the same level still conflict with each other.\n *\n * Ambiguity requires the two segments to be candidates for the *same* URL\n * part, which is narrower than \"same parent\" once interception is involved:\n *\n * - Plain children and intercepting children never compete. They are resolved\n * by different walks — `findSlotMatch` matches the slot subtree (where\n * `tree-match.ts` ignores intercepting nodes outright) and\n * `findInterceptingMatch` builds a synthetic parent holding only\n * interceptors.\n * - Two interceptors compete only at the same anchor. `(.)a-[id]` and\n * `(..)[slug]-b` in one slot are based at different URL depths, so no\n * pathname reaches both, and `anchorIndex` rejects the one whose base does\n * not match the target. Grouping them together would fail the build for a\n * pair that can never be ambiguous.\n *\n * So candidates are keyed by the position they contend for, then by affix\n * length. See design/07-routing.md §\"Priority\" and §\"Intercepting Routes\".\n */\nfunction validateAffixedSiblingConflicts(node: SegmentNode): void {\n const affixed = collectEffectiveAffixed(node);\n\n if (affixed.length >= 2) {\n const byLength = new Map<string, SegmentNode[]>();\n for (const child of affixed) {\n // `\\0` as the separator, written as the escape rather than a literal\n // byte: a raw NUL in the source makes git and grep treat this file as\n // binary. A contention key is a URL path, which cannot contain one, so\n // the two halves of the key can never run together.\n const key = `${contentionKey(node, child)}\\0${affixLengthOf(child)}`;\n const group = byLength.get(key);\n if (group) {\n group.push(child);\n } else {\n byLength.set(key, [child]);\n }\n }\n\n for (const [, group] of byLength) {\n if (group.length >= 2) {\n throw new Error(\n `Build error: ambiguous affixed dynamic siblings with equal specificity.\\n` +\n ` Parent: ${node.urlPath || '/'}\\n` +\n ` Segments: ${group.map((s) => s.segmentName).join(', ')}\\n` +\n ` Combined prefix+suffix length: ${affixLengthOf(group[0]!)}\\n` +\n `The router cannot deterministically choose between these — filesystem scan order is platform-dependent.\\n` +\n `Rename one segment to give it a longer or shorter combined affix.`\n );\n }\n }\n }\n\n for (const child of node.children) {\n validateAffixedSiblingConflicts(child);\n }\n for (const slotNode of Object.values(node.slots)) {\n validateAffixedSiblingConflicts(slotNode);\n }\n}\n\n/**\n * The URL position a child contends for, as a comparable key.\n *\n * Plain children contend for the parent's next part. An intercepting child\n * contends for a part determined by its marker's intercepted base, so two\n * markers of different depth are simply different positions — and two markers\n * that compute the *same* base do contend, which is why the key is the base\n * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).\n *\n * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical\n * statement of that grouping — it is what the resolver walks and what the\n * collision validator checks. This computes the same key from the same\n * `computeInterceptedBase` rather than calling it, because affix ambiguity is\n * decided per *child* and `collectEffectiveAffixed` looks through route groups,\n * so the two do not partition the same set of nodes.\n */\nfunction contentionKey(parent: SegmentNode, child: SegmentNode): string {\n if (child.segmentType !== 'intercepting') return 'child';\n return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? '(.)')}`;\n}\n\n/** Combined affix length of a node, read through its effective identity. */\nfunction affixLengthOf(node: SegmentNode): number {\n const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);\n return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);\n}\n\n/**\n * Collect affixed dynamic segments that are effective children of a node.\n * Route groups are URL-transparent, so we look through them recursively.\n *\n * Segments are read through `effectiveUrlSegment`, so an intercepting\n * directory counts as the affixed segment it intercepts: `(.)a-[id]` is\n * `a-[id]`. The proxy the slot resolver builds hands those affixes to\n * `matchUrlParts`, whose equal-length sort is not stable across equal\n * specificity — so two intercepting siblings with the same combined affix\n * length would resolve by filesystem enumeration order, which is precisely\n * what this validator exists to prevent for ordinary siblings (TIM-1288).\n */\nfunction collectEffectiveAffixed(node: SegmentNode): SegmentNode[] {\n const result: SegmentNode[] = [];\n for (const child of node.children) {\n const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);\n if (segmentType === 'dynamic' && (paramPrefix || paramSuffix)) {\n result.push(child);\n } else if (segmentType === 'group') {\n result.push(...collectEffectiveAffixed(child));\n }\n }\n return result;\n}\n\n/**\n * Find a fixed-extension file (proxy.ts) in a directory.\n */\nfunction findFixedFile(dirPath: string, name: string): RouteFile | undefined {\n for (const ext of ['ts', 'tsx']) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n\n/**\n * Find a file using the configured page extensions (tsx, ts, jsx, js, mdx, etc.).\n * Used for app-root conventions like global-error that aren't per-segment.\n */\nfunction findPageExtFile(\n dirPath: string,\n name: string,\n extSet: Set<string>\n): RouteFile | undefined {\n for (const ext of extSet) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,cACd,MACA,OACA,SAC+B;CAC/B,MAAM,QAA8B,CAAC;CACrC,MAAM,SAA4C,CAAC;CAGnD,IAAI,UAAU,MAAM,OAAO,GAAG,OAAO,QAFb,SAAS,mBAAmB,IAEQ,GAC1D,OAAO;EAAE;EAAO;CAAO;CAEzB,OAAO;AACT;;;;;;;;;AAsBA,SAAS,yBACP,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],"sources":["../../src/shared/param-value.ts","../../src/client/segment-context.ts"],"sourcesContent":["/**\n * The canonical form of a segment param value.\n *\n * `getSegmentParams()` on the server and `useSegmentParams()` on the client\n * must return the same value — same prototype, same own properties. This\n * module is how that is guaranteed, and the mechanism matters:\n *\n * **Both sides are images of one normalizer.** A codec's output is deep-cloned\n * into a closed canonical domain at coercion time, and *that clone* is what the\n * server returns and what goes on the wire. Server and client agree by\n * construction, because neither holds the codec's original.\n *\n * That replaces predicting what React Flight would do to an arbitrary value.\n * Prediction is what the previous design attempted and it cannot be finished:\n * the question \"will Flight's decode output be observably identical to this\n * input?\" ranges over every way a JS object can carry state that is not in its\n * serialization — own keys, enumerability, symbols, holes, accessors,\n * subclassing, exotic objects — and a `Proxy` defeats it outright, since a\n * lying `getPrototypeOf` trap makes any static check unsound. Twelve review\n * findings on PR #992 were each one more case of that set, and the set does\n * not close.\n *\n * Normalizing closes it. The only remaining question is whether Flight\n * round-trips the normalizer's *output range* — a finite domain we defined,\n * covered by `tests/e2e/segment-params.test.ts` against the real serializer.\n *\n * ## The domain\n *\n * - `undefined`, `null`, `string`, `number`, `boolean`, `bigint`\n * - null-prototype objects, own enumerable string keys only\n * - dense arrays\n * - `Date`, `Map`, `Set` — rebuilt, never the codec's instance\n *\n * ...and it is a **tree**: no value appears twice, and nothing is cyclic.\n * That is not a simplification, it is the last prediction being removed.\n * Flight encodes a `Date` by value at each occurrence but tracks plain objects\n * for reference dedup, so preserving aliasing would carry it across for some\n * types and drop it for others — and knowing which is exactly the kind of\n * guess this design exists to stop making (codex, PR #992). A tree has no\n * sharing to preserve or lose, so what Flight does about it is unobservable.\n *\n * Anything else throws, naming the param and what it was. Note what is *not*\n * a rejection: a `Date` subclass normalizes to a `Date`, a decorated array to\n * a plain one, a sparse array to a dense one, a getter to the value it\n * returned. Those used to be twelve separate checks. They are not divergences\n * any more, because the normalization happens once and both sides see its\n * result — so they need no checks at all.\n *\n * Own properties that Flight would drop (non-enumerable, symbol-keyed) are\n * dropped here instead, symmetrically. Prototype pollution is handled by the\n * same pass: `__proto__` is never copied, and every object is\n * `Object.create(null)` (design/13-security.md #36b/#36c, TIM-873).\n *\n * ## The prototype flip\n *\n * Flight refuses to serialize a null-prototype object, so the canonical form\n * cannot go on the wire as-is. `toPlainRecord` and `toNullProtoRecord` flip\n * the prototype on the way out and back. They are exact inverses and both\n * total, because they only ever see canonical values — there is nothing to\n * validate and no shape to special-case.\n *\n * See design/41-global-params.md §\"Transport\".\n */\n\n// ─── Post-coercion param types ──────────────────────────────────────────\n\n/**\n * A single segment param value after codec coercion and normalization.\n *\n * Before coercion, every param is `string | string[]` (the raw URL part).\n * After `app/schema.ts` codecs run, a param can be any value in the\n * `normalizeParamValue` domain below. This type replaces the previous\n * `string | string[]` declaration, which was a lie whenever a codec\n * produced a non-string value (TIM-1347).\n *\n * The typed accessor `getSegmentParams(SEGMENT_PATH)` resolves through\n * the schema and returns the exact type the codec declares. This type\n * covers the untyped/no-argument form and internal plumbing.\n */\nexport type CoercedParamValue =\n | string\n | number\n | boolean\n | bigint\n | null\n | undefined\n | Date\n | Map<CoercedParamValue, CoercedParamValue>\n | Set<CoercedParamValue>\n | CoercedParamValue[]\n | { [key: string]: CoercedParamValue };\n\n/**\n * A record of coerced segment params, keyed by param name.\n *\n * This is the post-coercion type for `segmentParams` throughout the\n * framework. Before coercion (route matcher output, `rawSegmentParams`),\n * the type is `Record<string, string | string[]>`.\n */\nexport type CoercedParams = Record<string, CoercedParamValue>;\n\n/** Types the canonical form rebuilds rather than rejects. */\nconst REBUILT = ['Date', 'Map', 'Set'] as const;\n\n/** The domain, for error messages. Derived, never a second hand-written list. */\nconst DOMAIN = `a string, number, boolean, bigint, null, undefined, a plain object, an array, or ${REBUILT.join('/')}`;\n\nfunction reject(path: string, was: string, hint: string): never {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" was coerced to ${was}, which cannot ` +\n `cross to the client. A param value may be ${DOMAIN}.\\n` +\n ` ${hint}\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n}\n\nfunction describe(value: object): string {\n return (value as { constructor?: { name?: string } }).constructor?.name ?? 'an object';\n}\n\n/**\n * Deep-clone a codec's output into the canonical form, or throw.\n *\n * `seen` accumulates every object the walk has entered, and a second encounter\n * is rejected. That is one rule for two things — a shared reference and a cycle\n * are both \"this object again\" — and it is what keeps the result a tree.\n */\nexport function normalizeParamValue(value: unknown, path = ''): CoercedParamValue {\n return normalize(value, path, new Set());\n}\n\nfunction normalize(value: unknown, path: string, seen: Set<object>): CoercedParamValue {\n if (value === null) return null;\n\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean' || kind === 'bigint') {\n return value as string | number | boolean | bigint;\n }\n if (kind === 'undefined') return undefined;\n if (kind === 'function') {\n reject(path, 'a function', 'Return the data it would produce, not the function.');\n }\n if (kind === 'symbol') {\n reject(path, 'a symbol', 'Return a string instead — a symbol has no wire representation.');\n }\n\n const object = value as object;\n if (seen.has(object)) {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" is a value that already appears ` +\n `elsewhere in the same param — a shared reference or a cycle. A param value is a ` +\n `tree: React Flight carries a repeated \\`Date\\` by value and a repeated object by ` +\n `reference, so sharing would survive for some types and not others.\\n` +\n ` Return separate values, or move the shared part outside the params.\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n }\n seen.add(object);\n\n if (Array.isArray(object)) {\n // Read by index, so holes become `undefined` — on both sides, which is\n // the point. A subclass and any own properties are left behind for the\n // same reason: the clone is a plain, dense array either way.\n const out: CoercedParamValue[] = [];\n for (let index = 0; index < object.length; index++) {\n out.push(normalize((object as unknown[])[index], `${path}[${index}]`, seen));\n }\n return out;\n }\n\n if (object instanceof Date) {\n // A fresh Date, so a subclass or an attached property cannot travel half\n // way and be dropped by the wire.\n return new Date(object.getTime());\n }\n\n if (object instanceof Map) {\n const out = new Map<CoercedParamValue, CoercedParamValue>();\n for (const [key, entry] of object) {\n out.set(\n normalize(key, `${path}<key>`, seen),\n normalize(entry, `${path}.get(${keyLabel(key)})`, seen)\n );\n }\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<CoercedParamValue>();\n let index = 0;\n for (const entry of object) out.add(normalize(entry, `${path}[${index++}]`, seen));\n return out;\n }\n\n // Everything else is judged by its prototype. A `Proxy` can lie here, and\n // that is fine: whatever it answers, the clone below reads through it once\n // and both sides see the same snapshot.\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== null && prototype !== Object.prototype) {\n reject(\n path,\n `a ${describe(object)} instance`,\n 'Return a plain object with the fields you need.'\n );\n }\n\n // Own *enumerable string* keys only — the rest is what Flight would drop,\n // so dropping it here keeps the two sides identical. `__proto__` is skipped\n // rather than copied: it has a language-level setter that would change the\n // prototype chain of the copy (TIM-655, TIM-855, TIM-873).\n const out: Record<string, CoercedParamValue> = Object.create(null);\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = normalize(\n (object as Record<string, unknown>)[key],\n path ? `${path}.${key}` : key,\n seen\n );\n }\n return out;\n}\n\nfunction keyLabel(key: unknown): string {\n return typeof key === 'string' ? JSON.stringify(key) : String(key);\n}\n\n// ─── Prototype flip ──────────────────────────────────────────────\n\n/**\n * Canonical form → wire form. React Flight rejects a null prototype\n * (\"Classes or null prototypes are not supported\"), so objects cross as plain\n * ones and are restored on arrival.\n */\nexport function toPlainRecord<T>(value: T): T {\n return reproto(value, {}) as T;\n}\n\n/** Wire form → canonical form. The exact inverse of `toPlainRecord`. */\nexport function toNullProtoRecord<T>(value: T): T {\n return reproto(value, null) as T;\n}\n\n/**\n * Rebuild a canonical value with objects on `proto`.\n *\n * Total by construction: its input is always canonical, so the cases are the\n * domain and nothing else. No validation, no shape it might not have seen, and\n * no cycle to guard — a canonical value is a tree. That is what moving the\n * checking to `normalizeParamValue` bought.\n */\nfunction reproto(value: unknown, proto: object | null): unknown {\n if (value === null || typeof value !== 'object') return value;\n\n const object = value as object;\n\n // A Date carries no nested values, so it crosses as itself.\n if (object instanceof Date) return object;\n\n if (Array.isArray(object)) {\n return (object as unknown[]).map((item) => reproto(item, proto));\n }\n\n if (object instanceof Map) {\n const out = new Map<unknown, unknown>();\n for (const [key, entry] of object) out.set(reproto(key, proto), reproto(entry, proto));\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<unknown>();\n for (const entry of object) out.add(reproto(entry, proto));\n return out;\n }\n\n const out: Record<string, unknown> = proto === null ? Object.create(null) : {};\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = reproto((object as Record<string, unknown>)[key], proto);\n }\n return out;\n}\n","/**\n * Segment Context — provides layout segment position for useSelectedLayoutSegment hooks.\n *\n * Each layout in the segment tree is wrapped with a SegmentProvider that stores\n * the URL segments from root to the current layout level. The hooks read this\n * context to determine which child segments are active below the calling layout.\n *\n * The context value is intentionally minimal: just the segment path array and\n * parallel route keys. No internal cache details are exposed.\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { createContext, useContext, createElement, useMemo } from 'react';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface SegmentContextValue {\n /** URL segments from root to this layout (e.g. ['', 'dashboard', 'settings']) */\n segments: string[];\n /** Parallel route slot keys available at this layout level (e.g. ['sidebar', 'modal']) */\n parallelRouteKeys: string[];\n}\n\n// ─── Context ─────────────────────────────────────────────────────\n\nconst SegmentContext = createContext<SegmentContextValue | null>(null);\n\n/** Read the segment context. Returns null if no provider is above this component. */\nexport function useSegmentContext(): SegmentContextValue | null {\n return useContext(SegmentContext);\n}\n\n// ─── Provider ────────────────────────────────────────────────────\n\ninterface SegmentProviderProps {\n segments: string[];\n /**\n * Unique identifier for this segment, used by the client-side segment\n * merger for element caching. For route groups this includes the group\n * name (e.g., \"/(marketing)\") since groups share their parent's urlPath.\n * Falls back to the reconstructed path from `segments` if not provided.\n */\n segmentId?: string;\n parallelRouteKeys: string[];\n children: React.ReactNode;\n}\n\n/**\n * Wraps each layout to provide segment position context.\n * Injected by rsc-entry.ts during element tree construction.\n */\nexport function SegmentProvider({\n segments,\n segmentId: _segmentId,\n parallelRouteKeys,\n children,\n}: SegmentProviderProps) {\n const value = useMemo(\n () => ({ segments, parallelRouteKeys }),\n // segments and parallelRouteKeys are static per layout — they don't change\n // across navigations. The layout's position in the tree is fixed.\n // Intentionally using derived keys — segments/parallelRouteKeys are static per layout\n [segments.join('/'), parallelRouteKeys.join(',')]\n );\n return createElement(SegmentContext.Provider, { value }, children);\n}\n"],"mappings":";;;AAyGA,IAAM,SAAS,oFAAoF;CAHlF;CAAQ;CAAO;AAGmE,CAAA,CAAQ,KAAK,GAAG;AAEnH,SAAS,OAAO,MAAc,KAAa,MAAqB;CAC9D,MAAM,IAAI,MACR,2BAA2B,QAAQ,SAAS,mBAAmB,IAAI,2DACpB,OAAO,OAC/C,KAAK,iDAEd;AACF;AAEA,SAAS,SAAS,OAAuB;CACvC,OAAQ,MAA8C,aAAa,QAAQ;AAC7E;;;;;;;;AASA,SAAgB,oBAAoB,OAAgB,OAAO,IAAuB;CAChF,OAAO,UAAU,OAAO,sBAAM,IAAI,IAAI,CAAC;AACzC;AAEA,SAAS,UAAU,OAAgB,MAAc,MAAsC;CACrF,IAAI,UAAU,MAAM,OAAO;CAE3B,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,aAAa,SAAS,UAC3E,OAAO;CAET,IAAI,SAAS,aAAa,OAAO,KAAA;CACjC,IAAI,SAAS,YACX,OAAO,MAAM,cAAc,qDAAqD;CAElF,IAAI,SAAS,UACX,OAAO,MAAM,YAAY,gEAAgE;CAG3F,MAAM,SAAS;CACf,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MACR,2BAA2B,QAAQ,SAAS,6XAM9C;CAEF,KAAK,IAAI,MAAM;CAEf,IAAI,MAAM,QAAQ,MAAM,GAAG;EAIzB,MAAM,MAA2B,CAAC;EAClC,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ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