@timber-js/app 0.2.0-alpha.237 → 0.2.0-alpha.239

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.
Files changed (97) hide show
  1. package/dist/_chunks/chains-CmzbpG-6.js +1 -0
  2. package/dist/_chunks/{chains-BsGKkMTK.js → chains-DMoHX4yH.js} +2 -2
  3. package/dist/_chunks/{chains-BsGKkMTK.js.map → chains-DMoHX4yH.js.map} +1 -1
  4. package/dist/_chunks/{classify-cmE0Gins.js → classify-BwyAd-dZ.js} +3 -3
  5. package/dist/_chunks/{classify-cmE0Gins.js.map → classify-BwyAd-dZ.js.map} +1 -1
  6. package/dist/_chunks/{cli-check-BwiahbTC.js → cli-check-DQAD9MLo.js} +3 -3
  7. package/dist/_chunks/{cli-check-BwiahbTC.js.map → cli-check-DQAD9MLo.js.map} +1 -1
  8. package/dist/_chunks/{cli-schema-sync-Brw7kTmm.js → cli-schema-sync-C_xNLqBj.js} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js → cli-schema-sync-CmGls3dc.js} +2 -2
  10. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js.map → cli-schema-sync-CmGls3dc.js.map} +1 -1
  11. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js → client-dep-entries-C5BTQtFS.js} +2 -2
  12. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js.map → client-dep-entries-C5BTQtFS.js.map} +1 -1
  13. package/dist/_chunks/{convention-lint-CLpuzY5h.js → convention-lint-GQA6WTRo.js} +2 -2
  14. package/dist/_chunks/{convention-lint-CLpuzY5h.js.map → convention-lint-GQA6WTRo.js.map} +1 -1
  15. package/dist/_chunks/dev-server--4_Ogy_6.js +1 -0
  16. package/dist/_chunks/{dev-server-lrdpD7Ws.js → dev-server-Cr3_Fu5A.js} +244 -26
  17. package/dist/_chunks/dev-server-Cr3_Fu5A.js.map +1 -0
  18. package/dist/_chunks/dev-span-RsVeYYc_.js.map +1 -1
  19. package/dist/_chunks/{scanner-CrB_h6FA.js → interception-CtNt9jPt.js} +169 -1043
  20. package/dist/_chunks/interception-CtNt9jPt.js.map +1 -0
  21. package/dist/_chunks/{live-graph-ChuFfmLi.js → live-graph-HcLScfiV.js} +4 -4
  22. package/dist/_chunks/{live-graph-ChuFfmLi.js.map → live-graph-HcLScfiV.js.map} +1 -1
  23. package/dist/_chunks/{metadata-routes-BL26HCDd.js → metadata-routes-MXNjWOt5.js} +60 -2
  24. package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -0
  25. package/dist/_chunks/{poison-scan-CJ9QfJWb.js → poison-scan-DONdiCGX.js} +2 -2
  26. package/dist/_chunks/{poison-scan-CJ9QfJWb.js.map → poison-scan-DONdiCGX.js.map} +1 -1
  27. package/dist/_chunks/scanner-DSAJjH0x.js +1043 -0
  28. package/dist/_chunks/scanner-DSAJjH0x.js.map +1 -0
  29. package/dist/_chunks/{walkers-BUvpsb2Q.js → walkers-96YopJds.js} +3 -3
  30. package/dist/_chunks/{walkers-BUvpsb2Q.js.map → walkers-96YopJds.js.map} +1 -1
  31. package/dist/analyze/crawl-entry.js +3 -3
  32. package/dist/analyze/graph-command.js +2 -2
  33. package/dist/cli.js +3 -3
  34. package/dist/config-types.d.ts +11 -0
  35. package/dist/config-types.d.ts.map +1 -1
  36. package/dist/config-validation.d.ts.map +1 -1
  37. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  38. package/dist/dev-tools/log-columns.d.ts +50 -0
  39. package/dist/dev-tools/log-columns.d.ts.map +1 -0
  40. package/dist/dev-tools/logger.d.ts +5 -0
  41. package/dist/dev-tools/logger.d.ts.map +1 -1
  42. package/dist/index.js +6 -155
  43. package/dist/index.js.map +1 -1
  44. package/dist/native/rsc/dev-tools/instrumentation.js +5 -1
  45. package/dist/native/rsc/dev-tools/instrumentation.js.map +1 -1
  46. package/dist/native/rsc/dev-tools/log-columns.js +69 -0
  47. package/dist/native/rsc/dev-tools/log-columns.js.map +1 -0
  48. package/dist/native/rsc/dev-tools/logger.js +60 -33
  49. package/dist/native/rsc/dev-tools/logger.js.map +1 -1
  50. package/dist/native/rsc/manifest.json +1 -0
  51. package/dist/native/rsc/shared/dev-span.js +5 -2
  52. package/dist/native/rsc/shared/dev-span.js.map +1 -1
  53. package/dist/native/rsc/shared/span-waterfall.js +13 -2
  54. package/dist/native/rsc/shared/span-waterfall.js.map +1 -1
  55. package/dist/native/ssr/dev-tools/instrumentation.js +5 -1
  56. package/dist/native/ssr/dev-tools/instrumentation.js.map +1 -1
  57. package/dist/native/ssr/dev-tools/log-columns.js +69 -0
  58. package/dist/native/ssr/dev-tools/log-columns.js.map +1 -0
  59. package/dist/native/ssr/dev-tools/logger.js +60 -33
  60. package/dist/native/ssr/dev-tools/logger.js.map +1 -1
  61. package/dist/native/ssr/manifest.json +1 -0
  62. package/dist/native/ssr/shared/dev-span.js +5 -2
  63. package/dist/native/ssr/shared/dev-span.js.map +1 -1
  64. package/dist/native/ssr/shared/span-waterfall.js +13 -2
  65. package/dist/native/ssr/shared/span-waterfall.js.map +1 -1
  66. package/dist/plugins/dev-precompile.d.ts +42 -14
  67. package/dist/plugins/dev-precompile.d.ts.map +1 -1
  68. package/dist/plugins/dev-server.d.ts.map +1 -1
  69. package/dist/routing/index.js +3 -2
  70. package/dist/routing/manifest-codegen.d.ts +2 -0
  71. package/dist/routing/manifest-codegen.d.ts.map +1 -1
  72. package/dist/server/internal.js +1 -2
  73. package/dist/server/internal.js.map +1 -1
  74. package/dist/shared/dev-span.d.ts +6 -0
  75. package/dist/shared/dev-span.d.ts.map +1 -1
  76. package/dist/shared/span-waterfall.d.ts.map +1 -1
  77. package/docs/api/34-api-config.mdx +18 -0
  78. package/package.json +1 -1
  79. package/src/config-types.ts +11 -0
  80. package/src/config-validation.ts +15 -8
  81. package/src/dev-tools/instrumentation.ts +4 -1
  82. package/src/dev-tools/log-columns.ts +156 -0
  83. package/src/dev-tools/logger.ts +107 -63
  84. package/src/plugins/dev-precompile.ts +108 -20
  85. package/src/plugins/dev-server.ts +12 -11
  86. package/src/routing/manifest-codegen.ts +2 -2
  87. package/src/shared/dev-span.ts +13 -1
  88. package/src/shared/span-waterfall.ts +36 -4
  89. package/dist/_chunks/chains-DHmoKxkO.js +0 -1
  90. package/dist/_chunks/dev-server-BGGGhHXx.js +0 -1
  91. package/dist/_chunks/dev-server-lrdpD7Ws.js.map +0 -1
  92. package/dist/_chunks/metadata-routes-BL26HCDd.js.map +0 -1
  93. package/dist/_chunks/scanner-CrB_h6FA.js.map +0 -1
  94. package/dist/_chunks/segment-keys-Y60KNc8C.js +0 -61
  95. package/dist/_chunks/segment-keys-Y60KNc8C.js.map +0 -1
  96. package/dist/_chunks/tree-match-Bqdr9szG.js +0 -168
  97. package/dist/_chunks/tree-match-Bqdr9szG.js.map +0 -1
@@ -0,0 +1,1043 @@
1
+ import { i as DEFAULT_PAGE_EXTENSIONS, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
2
+ import { a as findOrderDependentCollision, i as validateInterceptionPlacement, n as computeInterceptedBase, r as computeInterceptedUrlBase } from "./interception-CtNt9jPt.js";
3
+ import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-MXNjWOt5.js";
4
+ import { b as swallow } from "./logger-DDLtp5e-.js";
5
+ import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
6
+ import { parseAst } from "vite";
7
+ import { basename, extname, join } from "node:path";
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
9
+ // src/routing/collision-spaces.ts
10
+ /**
11
+ * Validate that no two pages/routes in one collision space answer the same URL.
12
+ *
13
+ * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim
14
+ * /login — the scanner must detect and reject this at build time.
15
+ *
16
+ * Each parallel slot is validated as its OWN collision space: a slot's pages
17
+ * intentionally share URL paths with the parent tree (that's the point of
18
+ * parallel routes), but two route groups INSIDE one slot claiming the same
19
+ * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.
20
+ */
21
+ function validateRouteGroupCollisions(root) {
22
+ validateCollisionSpace(root, "", root.urlPath);
23
+ }
24
+ /**
25
+ * Validate one collision space — the main tree, or one parallel slot.
26
+ *
27
+ * **Two checks, and the difference between them matters.** Two leaves at the
28
+ * same `urlPath` are decided by string equality, which is exact and needs no
29
+ * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs
30
+ * whatever the precedence rules are, and naming the shared path is the clearest
31
+ * thing to tell the author.
32
+ *
33
+ * Everything else is decided by asking the matcher, through the shared oracle
34
+ * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses
35
+ * every pair that matches the same URLs while being *spelled* differently:
36
+ * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority
37
+ * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`
38
+ * because an optional catch-all also matches zero parts. Both built before
39
+ * TIM-1308 with filesystem enumeration order deciding which page renders,
40
+ * which is precisely what this validator and `validateAffixedSiblingConflicts`
41
+ * exist to reject.
42
+ *
43
+ * Segment *kinds* stay distinct without any special-casing here, because the
44
+ * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside
45
+ * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is
46
+ * not reported. So does an affixed sibling against a bare one; the
47
+ * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and
48
+ * duplicating it here would double-report.
49
+ */
50
+ function validateCollisionSpace(spaceRoot, segmentPath, base) {
51
+ const leaves = [];
52
+ collectRoutableLeaves(spaceRoot, /* @__PURE__ */ new Map(), segmentPath, [], leaves, base);
53
+ const collision = findOrderDependentCollision(spaceRoot, leaves, base);
54
+ if (!collision) return;
55
+ throw new Error(`Build error: route collision — two pages/routes answer the same URL.\n URL: ${collision.url}\n File 1: ${collision.first}\n File 2: ${collision.second}\nBoth match it, so which one renders would be decided by filesystem enumeration order — renaming a route group can flip it. Rename or move one of them.\nRoutes are compared by the URLs they match, not by how they are spelled: [id] and [slug] match the same URLs, and an optional catch-all also matches with zero segments.`);
56
+ }
57
+ /**
58
+ * Walk one collision space and collect its routable leaves (page or route
59
+ * files), throwing on an exact `urlPath` collision. Each slot recurses as its
60
+ * OWN space — slots are parallel routes that intentionally share URL paths with
61
+ * their parent tree, but collisions within a single slot are real errors.
62
+ *
63
+ * The early return at an intercepting node drops that subtree's own pages from
64
+ * this space, but not its slots: a slot is its own collision space wherever it
65
+ * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before
66
+ * returning.
67
+ *
68
+ * `chain` accumulates the URL-contributing nodes from the space root down, for
69
+ * the probe oracle. Route groups are excluded because they are transparent for
70
+ * matching, and the space root itself is excluded because `matchUrlParts`
71
+ * matches parts against its *children* — the root consumes nothing.
72
+ */
73
+ function collectRoutableLeaves(node, seen, segmentPath, chain, leaves, base) {
74
+ const currentPath = segmentPath ? `${segmentPath}/${node.segmentName}` : node.segmentName || "(root)";
75
+ if (node.segmentType === "intercepting") {
76
+ validateSlotsInsideInterceptingSubtree(node, currentPath, interceptedBaseOf(node, node.urlPath));
77
+ return;
78
+ }
79
+ const routableFile = node.page ?? node.route;
80
+ if (routableFile) {
81
+ const existing = seen.get(node.urlPath);
82
+ if (existing) throw new Error(`Build error: route collision — multiple route groups produce a page/route at the same URL path.\n URL path: ${urlFromChain(base, chain)}\n File 1: ${existing.filePath} (via ${existing.segmentPath})\n File 2: ${routableFile.filePath} (via ${currentPath})\nEach URL path must map to exactly one page or route handler. Rename or move one of the conflicting files.`);
83
+ seen.set(node.urlPath, {
84
+ filePath: routableFile.filePath,
85
+ segmentPath: currentPath
86
+ });
87
+ leaves.push({
88
+ filePath: routableFile.filePath,
89
+ chain
90
+ });
91
+ }
92
+ for (const child of node.children) collectRoutableLeaves(child, seen, currentPath, child.segmentType === "group" ? chain : [...chain, child], leaves, base);
93
+ for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));
94
+ }
95
+ /**
96
+ * Validate every parallel slot nested anywhere inside an intercepting subtree.
97
+ *
98
+ * Two walks each skip these slots for their own good reason, and together they
99
+ * left them checked by nothing: `collectRoutableLeaves` returns at the
100
+ * intercepting node before it reaches them, and `walkInterceptedLeaves`
101
+ * deliberately does not descend slots — correct for rewrite generation, since a
102
+ * slot inside an intercepting subtree produces no rewrite. But "produces no
103
+ * rewrite" answers the rewrite question and not the resolution one, so
104
+ * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor
105
+ * built with filesystem order picking the page — the ordinary per-slot
106
+ * collision that fails the build anywhere else in the tree (codex, on PR #1002).
107
+ *
108
+ * A slot is its own collision space wherever it sits, so each one is validated
109
+ * as one.
110
+ *
111
+ * **Which interception shape this still applies to.** TIM-1311 answered the
112
+ * question this was written under — whether such a slot renders at all — and
113
+ * the answer is per-shape:
114
+ *
115
+ * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node
116
+ * joins the main route chain, so `route-element-builder.ts` resolves slots on
117
+ * it and below it like any other chain segment. They render, and this is the
118
+ * space where the check is load-bearing.
119
+ * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another
120
+ * slot's subtree, which no renderer descends for slots — so it never renders,
121
+ * and `validateSlotPlacement` now rejects the placement before this runs.
122
+ * That rule subsumes this one for the modal shape rather than conflicting
123
+ * with it, exactly as anticipated.
124
+ *
125
+ * So this walk is reached only for children-path interceptors in a valid tree.
126
+ * It is not narrowed to them: the rule it states — a slot is its own collision
127
+ * space wherever it sits — is shape-independent, and making it conditional on a
128
+ * property the placement validator already guarantees would just be a second
129
+ * place for the two to disagree.
130
+ *
131
+ * The walk covers the whole subtree, not just the interceptor's direct slot
132
+ * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the
133
+ * same reason as `(...)photo/@side`.
134
+ */
135
+ function validateSlotsInsideInterceptingSubtree(node, segmentPath, base) {
136
+ for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, segmentPath, base);
137
+ for (const child of node.children) validateSlotsInsideInterceptingSubtree(child, `${segmentPath}/${child.segmentName}`, childInterceptedBase(child, base));
138
+ }
139
+ /**
140
+ * The URL a leaf answers, built from its space's base and its own chain.
141
+ *
142
+ * Read instead of `node.urlPath` because `urlPath` inside an intercepting
143
+ * subtree is parent-relative and is not an address — the collision URL has to
144
+ * be one the author can actually find. Outside an intercepting subtree the two
145
+ * are identical by construction: the base is the space root's `urlPath` and the
146
+ * chain is every URL-contributing segment below it.
147
+ */
148
+ function urlFromChain(base, chain) {
149
+ if (chain.length === 0) return base || "/";
150
+ const tail = chain.map((n) => n.segmentName).join("/");
151
+ return `${base === "/" ? "" : base}/${tail}`;
152
+ }
153
+ /**
154
+ * The intercepted URL an intercepting directory's own page sits at.
155
+ *
156
+ * `urlPath` inside an intercepting subtree is deliberately parent-relative and
157
+ * is **not** an address (see design/07-routing.md §"Why urlPath Stays
158
+ * Parent-Relative Inside an Intercepting Subtree"), so a collision reported
159
+ * from one names a URL the author cannot find. The intercepted base is the real
160
+ * address, and it is what rewrite generation and the interception collision
161
+ * validator both already use.
162
+ */
163
+ function interceptedBaseOf(node, ownerUrlPath) {
164
+ return computeInterceptedUrlBase(ownerUrlPath, node.interceptionMarker ?? "(.)", node.interceptedSegmentName ?? node.segmentName);
165
+ }
166
+ /**
167
+ * Extend an intercepted base by one child segment.
168
+ *
169
+ * Route groups are transparent and contribute nothing. A nested intercepting
170
+ * node re-bases from its own marker rather than appending — that tree is
171
+ * rejected by `validateInterceptionPlacement`, but collision validation runs
172
+ * first, so it still has to produce a sensible URL rather than one containing a
173
+ * literal "(.)b".
174
+ */
175
+ function childInterceptedBase(child, base) {
176
+ if (child.segmentType === "group") return base;
177
+ if (child.segmentType === "intercepting") return interceptedBaseOf(child, base);
178
+ return base === "/" ? `/${child.segmentName}` : `${base}/${child.segmentName}`;
179
+ }
180
+ // src/routing/slot-placement.ts
181
+ /**
182
+ * Reject every parallel slot that no renderer reaches.
183
+ *
184
+ * **Where slots are resolved.** Two places read `segment.slots`, and both walk
185
+ * the main route chain: `route-element-builder.ts` (the RSC render).
186
+ * It is not reachable from inside a slot. The slot's own
187
+ * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched
188
+ * chain to apply that chain's layouts, error boundaries and access gates
189
+ * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`
190
+ * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and
191
+ * everything below it is dead: the file is scanned, typed, code-split and
192
+ * shipped, and no request can render it.
193
+ *
194
+ * That is the TIM-1278 failure — a directory that silently never renders —
195
+ * and the reason it is a build error rather than a documented limit is that
196
+ * nothing at request time can report it. A slot that does not match renders
197
+ * `default.tsx` or `null`, which is exactly what a slot the resolver never
198
+ * looked at also produces, so the author sees the *designed* behaviour of a
199
+ * non-matching slot and has no signal to distinguish it from a slot that
200
+ * cannot match at all.
201
+ *
202
+ * **Interception is incidental.** TIM-1311 arrived as
203
+ * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the
204
+ * identical `feed/@modal/photo/@side` never renders either, for the same
205
+ * reason and with no marker anywhere. Rejecting only the intercepting spelling
206
+ * would have drawn a line the author cannot see from the directory names.
207
+ *
208
+ * The children-path interception shape is **not** affected and must not be:
209
+ * its intercepting node joins the main chain (`server/children-interception.ts`
210
+ * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary
211
+ * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below
212
+ * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`
213
+ * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot
214
+ * boundary, which is what this walk tracks — not the marker.
215
+ */
216
+ function validateSlotPlacement(root) {
217
+ walkForSlotPlacement(root, "", null);
218
+ }
219
+ /**
220
+ * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or
221
+ * above `node`, or null on the main chain. It is carried rather than recomputed
222
+ * so the error can name the slot that swallows the offender — "this is inside
223
+ * @modal" is the part of the diagnosis the author cannot see from the offending
224
+ * path alone.
225
+ */
226
+ function walkForSlotPlacement(node, path, enclosingSlotPath) {
227
+ for (const [slotName, slotNode] of Object.entries(node.slots)) {
228
+ const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;
229
+ if (enclosingSlotPath !== null) throwNestedSlot(slotPath, enclosingSlotPath);
230
+ walkForSlotPlacement(slotNode, slotPath, slotPath);
231
+ }
232
+ for (const child of node.children) walkForSlotPlacement(child, path ? `${path}/${child.segmentName}` : child.segmentName, enclosingSlotPath);
233
+ }
234
+ function throwNestedSlot(slotPath, enclosingSlotPath) {
235
+ throw new Error(`Build error: parallel slot nested inside another parallel slot.\n Directory: app/${slotPath}\n Inside: app/${enclosingSlotPath}\nA parallel slot is resolved only for a segment on the matched route chain, and a slot's own subtree is never on that chain — the slot resolver walks the slot's matched chain to apply its layouts, error boundaries and access gates, and never looks at slots declared inside it. So app/${slotPath} and everything below it can never render, and no request-time signal can tell you: an unreachable slot produces exactly what a slot that simply did not match produces.\nDeclare the slot on a segment of the main route chain instead, or move its pages into app/${enclosingSlotPath}'s own subtree.\nSee design/07-routing.md §"Parallel Routes".`);
236
+ }
237
+ // src/routing/file-cache.ts
238
+ var cache = /* @__PURE__ */ new Map();
239
+ /**
240
+ * Read a file's text content, returning a cached copy when the file
241
+ * hasn't been modified since the last read (checked via mtime + size).
242
+ *
243
+ * Falls back to a fresh read on any stat/read error.
244
+ */
245
+ function readFileCached(filePath) {
246
+ try {
247
+ const stat = statSync(filePath);
248
+ const entry = cache.get(filePath);
249
+ if (entry && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) return entry.content;
250
+ const content = readFileSync(filePath, "utf-8");
251
+ cache.set(filePath, {
252
+ mtimeMs: stat.mtimeMs,
253
+ size: stat.size,
254
+ content
255
+ });
256
+ return content;
257
+ } catch {
258
+ cache.delete(filePath);
259
+ return readFileSync(filePath, "utf-8");
260
+ }
261
+ }
262
+ // src/routing/export-detect.ts
263
+ /**
264
+ * AST-based export detection for route files.
265
+ *
266
+ * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and
267
+ * default exports, replacing the regex-based approach that was fragile
268
+ * with TypeScript syntax (type exports, `as` aliases, comments, etc.).
269
+ */
270
+ function tryParse(source) {
271
+ try {
272
+ return parseAst(source, { lang: "tsx" });
273
+ } catch {
274
+ return null;
275
+ }
276
+ }
277
+ /**
278
+ * Collect all named export identifiers from a parsed program.
279
+ * Handles: `export function X`, `export const X`, `export { X }`,
280
+ * `export { X } from '...'`, `export { Y as X }`.
281
+ */
282
+ function collectNamedExports(program) {
283
+ const names = /* @__PURE__ */ new Set();
284
+ for (const stmt of program.body) {
285
+ if (stmt.type !== "ExportNamedDeclaration") continue;
286
+ if (stmt.exportKind === "type") continue;
287
+ if (stmt.declaration) {
288
+ if (stmt.declaration.id?.name) names.add(stmt.declaration.id.name);
289
+ if (stmt.declaration.declarations) {
290
+ for (const decl of stmt.declaration.declarations) if (decl.id?.name) names.add(decl.id.name);
291
+ }
292
+ }
293
+ if (stmt.specifiers) for (const spec of stmt.specifiers) {
294
+ if (spec.exportKind === "type") continue;
295
+ if (spec.exported?.name && spec.exported.name !== "default") names.add(spec.exported.name);
296
+ }
297
+ }
298
+ return names;
299
+ }
300
+ /**
301
+ * The specifier exporting a *runtime* default from this statement, if any.
302
+ *
303
+ * Type-only exports erase, so they are not default exports at runtime — and
304
+ * TypeScript spells that two ways, on two different nodes: `export type { X as
305
+ * default }` marks the **statement**, `export { type X as default }` marks the
306
+ * **specifier**. Both have to be checked, or a type alias reads as a component:
307
+ * a status file whose only default is a type has nothing for the error boundary
308
+ * to receive (the renderer's `mod?.default` skips it), so treating it as one
309
+ * would fail a build over a file that cannot break anything.
310
+ *
311
+ * One implementation because two callers must agree on what "has a default
312
+ * export" means: `hasDefaultExport` decides whether to warn that a page has
313
+ * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.
314
+ */
315
+ function defaultSpecifier(stmt) {
316
+ if (stmt.type !== "ExportNamedDeclaration" || !stmt.specifiers) return null;
317
+ if (stmt.exportKind === "type") return null;
318
+ for (const spec of stmt.specifiers) {
319
+ if (spec.exportKind === "type") continue;
320
+ if (spec.exported?.name === "default") return spec;
321
+ }
322
+ return null;
323
+ }
324
+ /**
325
+ * Check whether a program has a default export.
326
+ * Handles: `export default ...`, `export { X as default }`,
327
+ * `export { default } from '...'`. Type-only defaults do not count —
328
+ * see `defaultSpecifier`.
329
+ */
330
+ function hasDefaultExport(program) {
331
+ for (const stmt of program.body) {
332
+ if (stmt.type === "ExportDefaultDeclaration") return true;
333
+ if (defaultSpecifier(stmt)) return true;
334
+ }
335
+ return false;
336
+ }
337
+ /**
338
+ * Check whether a program has any bare `export * from '...'` declarations.
339
+ * Excludes `export * as X from '...'` (namespace re-exports) since those
340
+ * create a namespace object, not individual top-level exports.
341
+ */
342
+ function hasStarExport(program) {
343
+ return program.body.some((stmt) => stmt.type === "ExportAllDeclaration" && !stmt.exported && stmt.exportKind !== "type");
344
+ }
345
+ /**
346
+ * Check if a file has any of the given named exports.
347
+ * Returns the set of matching export names.
348
+ */
349
+ function fileHasAnyExport(filePath, exportNames) {
350
+ const matches = /* @__PURE__ */ new Set();
351
+ try {
352
+ const program = tryParse(readFileCached(filePath));
353
+ if (!program) return matches;
354
+ const exports = collectNamedExports(program);
355
+ for (const name of exportNames) if (exports.has(name)) matches.add(name);
356
+ } catch {}
357
+ return matches;
358
+ }
359
+ /**
360
+ * Check if a file has a default export.
361
+ * Returns false if the file doesn't exist or can't be parsed.
362
+ */
363
+ function fileHasDefaultExport(filePath) {
364
+ if (!existsSync(filePath)) return false;
365
+ try {
366
+ const program = tryParse(readFileCached(filePath));
367
+ if (!program) return false;
368
+ return hasDefaultExport(program);
369
+ } catch {
370
+ return false;
371
+ }
372
+ }
373
+ /** Node types whose value is unambiguously constructed by this module. */
374
+ var FUNCTION_LIKE = /* @__PURE__ */ new Set([
375
+ "FunctionDeclaration",
376
+ "FunctionExpression",
377
+ "ArrowFunctionExpression",
378
+ "ClassDeclaration",
379
+ "ClassExpression"
380
+ ]);
381
+ /**
382
+ * Expression wrappers that erase at runtime and so cannot change where a value
383
+ * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.
384
+ */
385
+ var TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
386
+ "TSAsExpression",
387
+ "TSSatisfiesExpression",
388
+ "TSTypeAssertion",
389
+ "TSNonNullExpression",
390
+ "TSInstantiationExpression",
391
+ "ParenthesizedExpression"
392
+ ]);
393
+ /**
394
+ * Strip runtime-transparent wrappers so the node underneath can be classified.
395
+ *
396
+ * Without this, `(() => <h1 />) satisfies React.FC` reads as a
397
+ * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a
398
+ * provably-local component is misread as one whose origin cannot be
399
+ * determined — turning a build error into a warning.
400
+ */
401
+ function unwrapTransparent(node) {
402
+ let current = node;
403
+ while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) current = current.expression;
404
+ return current;
405
+ }
406
+ /**
407
+ * Whether `name` is bound at module top level to a function or class written
408
+ * in this file. An imported binding can never match: imports are
409
+ * `ImportDeclaration` specifiers, not function/class/variable declarations,
410
+ * and a module-level name cannot be both.
411
+ */
412
+ function bindsLocalFunction(program, name) {
413
+ for (const stmt of program.body) {
414
+ const decl = stmt.type === "ExportNamedDeclaration" ? stmt.declaration : stmt;
415
+ if (!decl) continue;
416
+ if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id?.name === name) return true;
417
+ if (decl.type === "VariableDeclaration") {
418
+ for (const d of decl.declarations ?? []) if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) return true;
419
+ }
420
+ }
421
+ return false;
422
+ }
423
+ /**
424
+ * Whether the default export is *provably* a value constructed by this module:
425
+ * `export default function/class/() => {}`, or a name bound to a function or
426
+ * class declared here — whether it leaves via `export default Name` or
427
+ * `export { Name as default }`. Both spellings are the same fact about where
428
+ * the value was built, so both must answer the same way.
429
+ *
430
+ * This is the sound half of "is this a server component?". A file with no
431
+ * `'use client'` directive whose default export is built here is a server
432
+ * component, full stop. Everything else — `export { default } from
433
+ * './client-thing'`, `export default Imported`, `export default memo(X)`,
434
+ * an unparseable file — returns false, because the exported value may have
435
+ * been minted in a module that *does* carry the directive. Callers must not
436
+ * infer "server component" from a missing directive alone.
437
+ */
438
+ function fileDefaultExportIsLocalValue(filePath) {
439
+ if (!existsSync(filePath)) return false;
440
+ try {
441
+ const program = tryParse(readFileCached(filePath));
442
+ if (!program) return false;
443
+ for (const stmt of program.body) {
444
+ if (stmt.type === "ExportDefaultDeclaration") {
445
+ const decl = stmt.declaration && unwrapTransparent(stmt.declaration);
446
+ if (!decl) return false;
447
+ if (FUNCTION_LIKE.has(decl.type)) return true;
448
+ if (decl.type === "Identifier" && decl.name) return bindsLocalFunction(program, decl.name);
449
+ return false;
450
+ }
451
+ const spec = defaultSpecifier(stmt);
452
+ if (spec) {
453
+ if (stmt.source) return false;
454
+ return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;
455
+ }
456
+ }
457
+ return false;
458
+ } catch {
459
+ return false;
460
+ }
461
+ }
462
+ /**
463
+ * Check if a file has any `export * from '...'` declarations.
464
+ * Returns false if the file doesn't exist or can't be parsed.
465
+ */
466
+ function fileHasStarExport(filePath) {
467
+ if (!existsSync(filePath)) return false;
468
+ try {
469
+ const program = tryParse(readFileCached(filePath));
470
+ if (!program) return false;
471
+ return hasStarExport(program);
472
+ } catch {
473
+ return false;
474
+ }
475
+ }
476
+ function extractLiteralValue(node) {
477
+ if (!node) return void 0;
478
+ const n = node;
479
+ if (n.type === "Literal") return n.value;
480
+ if (n.type === "UnaryExpression" && n.operator === "-" && n.argument?.type === "Literal") return -n.argument.value;
481
+ if (n.type === "ArrayExpression") {
482
+ const elements = n.elements;
483
+ if (!elements) return void 0;
484
+ const result = [];
485
+ for (const el of elements) {
486
+ const v = extractLiteralValue(el);
487
+ if (v === void 0) return void 0;
488
+ result.push(v);
489
+ }
490
+ return result;
491
+ }
492
+ }
493
+ function extractObjectLiteral(node) {
494
+ if (node.type !== "ObjectExpression") return void 0;
495
+ const props = node.properties;
496
+ if (!props) return void 0;
497
+ const result = {};
498
+ for (const prop of props) {
499
+ const p = prop;
500
+ if (p.type === "SpreadElement") return void 0;
501
+ if (p.type !== "Property" || p.computed) return void 0;
502
+ const key = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : void 0;
503
+ if (!key) return void 0;
504
+ const value = extractLiteralValue(p.value);
505
+ if (value === void 0) return void 0;
506
+ result[key] = value;
507
+ }
508
+ return result;
509
+ }
510
+ /**
511
+ * Extract the value of `export const prerender` from a file.
512
+ * Returns undefined if the file doesn't export `prerender` or can't be parsed.
513
+ *
514
+ * Supports:
515
+ * export const prerender = true;
516
+ * export const prerender = false;
517
+ * export const prerender = { ttl: 3600, tags: ['docs'] };
518
+ */
519
+ function getPrerenderExport(filePath) {
520
+ if (!existsSync(filePath)) return void 0;
521
+ try {
522
+ const program = tryParse(readFileCached(filePath));
523
+ if (!program) return void 0;
524
+ for (const stmt of program.body) {
525
+ if (stmt.type !== "ExportNamedDeclaration") continue;
526
+ if (stmt.exportKind === "type") continue;
527
+ if (!stmt.declaration) continue;
528
+ const decl = stmt.declaration;
529
+ if (decl.type !== "VariableDeclaration") continue;
530
+ const declarations = decl.declarations;
531
+ if (!declarations) continue;
532
+ for (const d of declarations) {
533
+ if (d.id?.name !== "prerender" || !d.init) continue;
534
+ const init = d.init;
535
+ if (init.type === "Literal" && typeof init.value === "boolean") return init.value;
536
+ if (init.type === "ObjectExpression") {
537
+ const obj = extractObjectLiteral(init);
538
+ if (!obj) return void 0;
539
+ const result = {};
540
+ if ("ttl" in obj && typeof obj.ttl === "number") result.ttl = obj.ttl;
541
+ if ("tags" in obj && Array.isArray(obj.tags) && obj.tags.every((t) => typeof t === "string")) result.tags = obj.tags;
542
+ return result;
543
+ }
544
+ return;
545
+ }
546
+ }
547
+ return;
548
+ } catch {
549
+ return;
550
+ }
551
+ }
552
+ function getCsrfExport(filePath) {
553
+ if (!existsSync(filePath)) return "absent";
554
+ const program = tryParse(readFileCached(filePath));
555
+ if (!program) return "absent";
556
+ let found = "absent";
557
+ for (const stmt of program.body) {
558
+ if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type") continue;
559
+ for (const spec of stmt.specifiers ?? []) if (spec.exportKind !== "type" && specifierName(spec.exported) === "csrf") return "invalid";
560
+ const decl = stmt.declaration;
561
+ if (!decl) continue;
562
+ if (decl.id?.name === "csrf") return "invalid";
563
+ if (decl.type !== "VariableDeclaration") continue;
564
+ for (const d of decl.declarations ?? []) {
565
+ const id = d.id;
566
+ if (id?.type === "Identifier") {
567
+ if (id.name !== "csrf") continue;
568
+ const init = d.init && unwrapTransparent(d.init);
569
+ const literalFalse = init?.type === "Literal" && init.value === false;
570
+ if (decl.kind !== "const" || !literalFalse) return "invalid";
571
+ found = "exempt";
572
+ } else if (id && patternBinds(id, "csrf")) return "invalid";
573
+ }
574
+ }
575
+ return found;
576
+ }
577
+ /** An export specifier's name: `csrf` or the string literal `"csrf"`. */
578
+ function specifierName(node) {
579
+ if (!node) return void 0;
580
+ return typeof node.value === "string" ? node.value : node.name;
581
+ }
582
+ /** Whether a destructuring pattern binds `name` anywhere inside it. */
583
+ function patternBinds(node, name) {
584
+ if (!node || typeof node !== "object") return false;
585
+ const n = node;
586
+ switch (n.type) {
587
+ case "Identifier": return n.name === name;
588
+ case "ObjectPattern": return (n.properties ?? []).some((prop) => {
589
+ const p = prop;
590
+ return patternBinds(p.type === "RestElement" ? p.argument : p.value, name);
591
+ });
592
+ case "ArrayPattern": return (n.elements ?? []).some((el) => patternBinds(el, name));
593
+ case "RestElement": return patternBinds(n.argument, name);
594
+ case "AssignmentPattern": return patternBinds(n.left, name);
595
+ default: return false;
596
+ }
597
+ }
598
+ /**
599
+ * Check if a file starts with a specific directive (e.g. "use client").
600
+ * Directives are string literal expression statements at the top of the file.
601
+ */
602
+ function fileHasDirective(filePath, directive) {
603
+ if (!existsSync(filePath)) return false;
604
+ try {
605
+ const program = tryParse(readFileCached(filePath));
606
+ if (!program) return false;
607
+ for (const stmt of program.body) {
608
+ if (stmt.type !== "ExpressionStatement") break;
609
+ const expr = stmt.expression;
610
+ if (expr?.type !== "Literal" || typeof expr.value !== "string") break;
611
+ if (expr.value === directive) return true;
612
+ }
613
+ return false;
614
+ } catch {
615
+ return false;
616
+ }
617
+ }
618
+ // src/routing/scanner.ts
619
+ /**
620
+ * Route discovery scanner.
621
+ *
622
+ * Pure function: (appDir, config) → RouteTree
623
+ *
624
+ * Scans the app/ directory and builds a segment tree recognizing all
625
+ * timber.js file conventions. Does NOT handle request matching — this
626
+ * is discovery only.
627
+ */
628
+ /**
629
+ * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)
630
+ * `error` is excluded — it only accepts script extensions (TIM-1505).
631
+ */
632
+ var PAGE_EXT_CONVENTIONS = /* @__PURE__ */ new Set([
633
+ "page",
634
+ "layout",
635
+ "default",
636
+ "denied"
637
+ ]);
638
+ /**
639
+ * File convention names that are always .ts/.tsx (never .mdx etc.)
640
+ */
641
+ var FIXED_CONVENTIONS = /* @__PURE__ */ new Set([
642
+ "middleware",
643
+ "access",
644
+ "route"
645
+ ]);
646
+ /**
647
+ * Status-code file patterns:
648
+ * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx
649
+ * - Category catch-alls: 4xx.tsx, 5xx.tsx
650
+ */
651
+ var STATUS_CODE_PATTERN = /^(\d{3}|[45]xx)$/;
652
+ /**
653
+ * Whether a basename + extension pair is a route-convention file the
654
+ * framework itself imports: page/layout/default/denied on pageExtensions,
655
+ * error/global-error and status-code files on script extensions only,
656
+ * middleware/access/route/proxy on .ts/.tsx/.js/.jsx only, and
657
+ * status-code .json files — mirroring this scanner's own recognition
658
+ * rules per family.
659
+ *
660
+ * Exported for the analyze classifier so its provisional classification
661
+ * (design/47 §2) derives from the scanner's real conventions instead of
662
+ * a duplicate list that can drift.
663
+ */
664
+ function isRouteConventionFile(base, ext, pageExtensions = DEFAULT_PAGE_EXTENSIONS) {
665
+ const isPageExt = pageExtensions.includes(ext);
666
+ const isScriptExt = /^[jt]sx?$/.test(ext);
667
+ if (PAGE_EXT_CONVENTIONS.has(base) && isPageExt) return true;
668
+ if ((base === "error" || base === "global-error") && isScriptExt) return true;
669
+ if ((FIXED_CONVENTIONS.has(base) || base === "proxy") && isScriptExt) return true;
670
+ if (STATUS_CODE_PATTERN.test(base) && (isScriptExt || ext === "json")) return true;
671
+ return false;
672
+ }
673
+ /**
674
+ * Scan the app/ directory and build the route tree.
675
+ *
676
+ * @param appDir - Absolute path to the app/ directory
677
+ * @param config - Scanner configuration
678
+ * @returns The complete route tree
679
+ */
680
+ function scanRoutes(appDir, config = {}) {
681
+ const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;
682
+ const extSet = new Set(pageExtensions);
683
+ const tree = { root: createSegmentNode("", "static", "/") };
684
+ const proxyFile = findFixedFile(appDir, "proxy");
685
+ if (proxyFile) tree.proxy = proxyFile;
686
+ const globalErrorFile = findScriptExtFile(appDir, "global-error");
687
+ if (globalErrorFile) tree.globalError = globalErrorFile;
688
+ scanSegmentFiles(appDir, tree.root, extSet);
689
+ scanChildren(appDir, tree.root, extSet);
690
+ validateSlotPlacement(tree.root);
691
+ validateRouteGroupCollisions(tree.root);
692
+ validateDuplicateParamNames(tree.root);
693
+ validateUniqueBracketForms(tree.root);
694
+ validateAffixedSiblingConflicts(tree.root);
695
+ validateInterceptionPlacement(tree.root);
696
+ return tree;
697
+ }
698
+ /**
699
+ * Create an empty segment node.
700
+ */
701
+ function createSegmentNode(segmentName, segmentType, urlPath, paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix) {
702
+ return {
703
+ segmentName,
704
+ segmentType,
705
+ urlPath,
706
+ paramName,
707
+ paramPrefix,
708
+ paramSuffix,
709
+ interceptionMarker,
710
+ interceptedSegmentName,
711
+ children: [],
712
+ slots: {}
713
+ };
714
+ }
715
+ /**
716
+ * Compute the URL path for a child segment given its parent's URL path.
717
+ * Route groups, slots, and intercepting routes do NOT add URL depth.
718
+ */
719
+ function computeUrlPath(parentUrlPath, dirName, segmentType) {
720
+ if (segmentType === "group" || segmentType === "slot" || segmentType === "intercepting") return parentUrlPath;
721
+ return `${parentUrlPath === "/" ? "" : parentUrlPath}/${dirName}`;
722
+ }
723
+ /**
724
+ * Scan a directory for file conventions and populate the segment node.
725
+ */
726
+ function scanSegmentFiles(dirPath, node, extSet) {
727
+ let entries;
728
+ try {
729
+ entries = readdirSync(dirPath);
730
+ } catch (err) {
731
+ swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: "warn" });
732
+ return;
733
+ }
734
+ for (const entry of entries) {
735
+ const fullPath = join(dirPath, entry);
736
+ try {
737
+ if (statSync(fullPath).isDirectory()) continue;
738
+ } catch {
739
+ continue;
740
+ }
741
+ const ext = extname(entry).slice(1);
742
+ const name = basename(entry, `.${ext}`);
743
+ if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {
744
+ const key = name;
745
+ const existing = node[key];
746
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
747
+ node[key] = {
748
+ filePath: fullPath,
749
+ extension: ext
750
+ };
751
+ continue;
752
+ }
753
+ if (name === "error" && /^[jt]sx?$/.test(ext)) {
754
+ const existing = node.error;
755
+ if (existing) throwDuplicateConvention("error", existing.filePath, fullPath);
756
+ node.error = {
757
+ filePath: fullPath,
758
+ extension: ext
759
+ };
760
+ continue;
761
+ }
762
+ if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {
763
+ const key = name;
764
+ const existing = node[key];
765
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
766
+ node[key] = {
767
+ filePath: fullPath,
768
+ extension: ext
769
+ };
770
+ continue;
771
+ }
772
+ if (STATUS_CODE_PATTERN.test(name) && ext === "json") {
773
+ if (!node.jsonStatusFiles) node.jsonStatusFiles = {};
774
+ node.jsonStatusFiles[name] = {
775
+ filePath: fullPath,
776
+ extension: ext
777
+ };
778
+ continue;
779
+ }
780
+ if (STATUS_CODE_PATTERN.test(name) && /^[jt]sx?$/.test(ext)) {
781
+ if (!node.statusFiles) node.statusFiles = {};
782
+ const existing = node.statusFiles[name];
783
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
784
+ node.statusFiles[name] = {
785
+ filePath: fullPath,
786
+ extension: ext
787
+ };
788
+ continue;
789
+ }
790
+ const metaInfo = classifyMetadataRoute(entry);
791
+ if (metaInfo) {
792
+ if (!metaInfo.nestable && node.segmentName !== "") throw new Error(`Build error: '${name}' is a root-only metadata convention and must be in the app root directory.\n File: ${fullPath}\n Move this file to the app root (not a route group or nested segment).`);
793
+ if (!node.metadataRoutes) node.metadataRoutes = {};
794
+ const existing = node.metadataRoutes[name];
795
+ if (existing) {
796
+ const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);
797
+ const newIsDynamic = isDynamicMetadataExtension(name, ext);
798
+ if (existingIsDynamic === newIsDynamic) throwDuplicateConvention(name, existing.filePath, fullPath);
799
+ if (newIsDynamic) node.metadataRoutes[name] = {
800
+ filePath: fullPath,
801
+ extension: ext
802
+ };
803
+ } else node.metadataRoutes[name] = {
804
+ filePath: fullPath,
805
+ extension: ext
806
+ };
807
+ }
808
+ }
809
+ if (node.route && node.page) throw new Error(`Build error: route.ts and page.* cannot coexist in the same segment.\n route.ts: ${node.route.filePath}\n page: ${node.page.filePath}\nA URL is either an API endpoint or a rendered page, not both.`);
810
+ if (node.route && getCsrfExport(node.route.filePath) === "exempt") node.csrfExempt = true;
811
+ }
812
+ /**
813
+ * Throw a build error for two files claiming the same convention slot in
814
+ * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first
815
+ * is platform-dependent (APFS sorts entries, ext4 does not) — silently
816
+ * picking one would let macOS dev and Linux CI serve different
817
+ * implementations of the same route.
818
+ */
819
+ function throwDuplicateConvention(convention, firstPath, secondPath) {
820
+ throw new Error(`Build error: duplicate '${convention}' files in the same route segment.\n File 1: ${firstPath}\n File 2: ${secondPath}\nEach segment may define '${convention}' at most once. Remove one of the files.`);
821
+ }
822
+ /**
823
+ * Recursively scan child directories and build the segment tree.
824
+ */
825
+ function scanChildren(dirPath, parentNode, extSet) {
826
+ let entries;
827
+ try {
828
+ entries = readdirSync(dirPath);
829
+ } catch (err) {
830
+ swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: "warn" });
831
+ return;
832
+ }
833
+ for (const entry of entries) {
834
+ const fullPath = join(dirPath, entry);
835
+ try {
836
+ if (!statSync(fullPath).isDirectory()) continue;
837
+ } catch {
838
+ continue;
839
+ }
840
+ if (ENCODED_SEPARATOR_RE.test(entry)) throw new Error(`Build error: directory name contains an encoded path delimiter (%2F or %5C).\n Directory: ${fullPath}\nEncoded separators in directory names cause route collisions when decoded. Rename the directory to remove the encoded delimiter.`);
841
+ if (NULL_BYTE_RE.test(entry)) throw new Error(`Build error: directory name contains an encoded null byte (%00).\n Directory: ${fullPath}\nEncoded null bytes in directory names are not allowed. Rename the directory to remove the null byte encoding.`);
842
+ const { type, paramName, paramPrefix, paramSuffix, interceptionMarker, interceptedSegmentName } = classifySegment(entry);
843
+ if (type === "private") continue;
844
+ const childNode = createSegmentNode(entry, type, computeUrlPath(parentNode.urlPath, entry, type), paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix);
845
+ scanSegmentFiles(fullPath, childNode, extSet);
846
+ scanChildren(fullPath, childNode, extSet);
847
+ if (type === "slot") {
848
+ const slotName = entry.slice(1);
849
+ parentNode.slots[slotName] = childNode;
850
+ } else parentNode.children.push(childNode);
851
+ }
852
+ }
853
+ /**
854
+ * Validate that no route chain contains duplicate dynamic param names.
855
+ *
856
+ * Example violation:
857
+ * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.
858
+ *
859
+ * Route groups are transparent — params accumulate through them.
860
+ * Slots are independent — duplicate detection does NOT cross slot boundaries.
861
+ *
862
+ * See design/07-routing.md §"Duplicate Param Name Detection"
863
+ */
864
+ function validateDuplicateParamNames(root) {
865
+ walkForDuplicateParams(root, /* @__PURE__ */ new Map());
866
+ }
867
+ /**
868
+ * Recursively walk the segment tree, tracking seen param names → segment paths.
869
+ * Throws on the first duplicate found.
870
+ */
871
+ function walkForDuplicateParams(node, seen) {
872
+ const { paramName } = effectiveUrlSegment(node);
873
+ if (paramName) {
874
+ const existing = seen.get(paramName);
875
+ if (existing) throw new Error(`[timber] Duplicate param name '${paramName}' in route chain.\n First defined at: ${existing}\n Duplicate at: ${node.urlPath || "/"}\n Rename one of the segments to avoid ambiguity.`);
876
+ seen = new Map(seen);
877
+ seen.set(paramName, node.urlPath || "/");
878
+ }
879
+ for (const child of node.children) walkForDuplicateParams(child, seen);
880
+ for (const slotNode of Object.values(node.slots)) walkForDuplicateParams(slotNode, new Map(seen));
881
+ }
882
+ /**
883
+ * Validate that each param name uses a single bracket form across the entire route tree.
884
+ *
885
+ * Different bracket forms produce different types:
886
+ * [id] → string
887
+ * [...id] → string[]
888
+ * [[...id]] → string[] | undefined
889
+ *
890
+ * If the same param name appears with multiple forms, the no-argument
891
+ * getSegmentParams() / useSegmentParams() return type becomes ambiguous.
892
+ *
893
+ * Same name + same form across different routes is fine and expected.
894
+ */
895
+ function validateUniqueBracketForms(root) {
896
+ collectBracketForms(root, /* @__PURE__ */ new Map());
897
+ }
898
+ function collectBracketForms(node, forms) {
899
+ const { paramName, segmentType } = effectiveUrlSegment(node);
900
+ if (paramName && segmentType !== "static" && segmentType !== "group") {
901
+ const existing = forms.get(paramName);
902
+ if (existing && existing.segmentType !== segmentType) {
903
+ const bracketExamples = {
904
+ "dynamic": `[${paramName}]`,
905
+ "catch-all": `[...${paramName}]`,
906
+ "optional-catch-all": `[[...${paramName}]]`
907
+ };
908
+ throw new Error(`[timber] Param name '${paramName}' uses multiple bracket forms.\n ${bracketExamples[existing.segmentType] ?? existing.segmentType} at: ${existing.urlPath}\n ${bracketExamples[segmentType] ?? segmentType} at: ${node.urlPath || "/"}\n Each param name must use a single bracket form across all routes.\n Rename one of the segments to fix this (e.g., [${paramName}] → [${paramName}Id]).`);
909
+ }
910
+ if (!existing) forms.set(paramName, {
911
+ segmentType,
912
+ urlPath: node.urlPath || "/"
913
+ });
914
+ }
915
+ for (const child of node.children) collectBracketForms(child, forms);
916
+ for (const slotNode of Object.values(node.slots)) collectBracketForms(slotNode, forms);
917
+ }
918
+ /**
919
+ * Validate that no sibling affixed dynamic segments have equal specificity.
920
+ *
921
+ * Among affixed siblings, longer combined prefix+suffix length wins. When two
922
+ * siblings tie (same total affix length), the router would fall back to
923
+ * filesystem scan order — which is platform-dependent. This is a build error.
924
+ *
925
+ * Route groups are URL-transparent, so affixed segments inside different groups
926
+ * at the same level still conflict with each other.
927
+ *
928
+ * Ambiguity requires the two segments to be candidates for the *same* URL
929
+ * part, which is narrower than "same parent" once interception is involved:
930
+ *
931
+ * - Plain children and intercepting children never compete. They are resolved
932
+ * by different walks — `findSlotMatch` matches the slot subtree (where
933
+ * `tree-match.ts` ignores intercepting nodes outright) and
934
+ * `findInterceptingMatch` builds a synthetic parent holding only
935
+ * interceptors.
936
+ * - Two interceptors compete only at the same anchor. `(.)a-[id]` and
937
+ * `(..)[slug]-b` in one slot are based at different URL depths, so no
938
+ * pathname reaches both, and `anchorIndex` rejects the one whose base does
939
+ * not match the target. Grouping them together would fail the build for a
940
+ * pair that can never be ambiguous.
941
+ *
942
+ * So candidates are keyed by the position they contend for, then by affix
943
+ * length. See design/07-routing.md §"Priority" and §"Intercepting Routes".
944
+ */
945
+ function validateAffixedSiblingConflicts(node) {
946
+ const affixed = collectEffectiveAffixed(node);
947
+ if (affixed.length >= 2) {
948
+ const byLength = /* @__PURE__ */ new Map();
949
+ for (const child of affixed) {
950
+ const key = `${contentionKey(node, child)}\0${affixLengthOf(child)}`;
951
+ const group = byLength.get(key);
952
+ if (group) group.push(child);
953
+ else byLength.set(key, [child]);
954
+ }
955
+ for (const [, group] of byLength) if (group.length >= 2) throw new Error(`Build error: ambiguous affixed dynamic siblings with equal specificity.\n Parent: ${node.urlPath || "/"}\n Segments: ${group.map((s) => s.segmentName).join(", ")}\n Combined prefix+suffix length: ${affixLengthOf(group[0])}\nThe router cannot deterministically choose between these — filesystem scan order is platform-dependent.\nRename one segment to give it a longer or shorter combined affix.`);
956
+ }
957
+ for (const child of node.children) validateAffixedSiblingConflicts(child);
958
+ for (const slotNode of Object.values(node.slots)) validateAffixedSiblingConflicts(slotNode);
959
+ }
960
+ /**
961
+ * The URL position a child contends for, as a comparable key.
962
+ *
963
+ * Plain children contend for the parent's next part. An intercepting child
964
+ * contends for a part determined by its marker's intercepted base, so two
965
+ * markers of different depth are simply different positions — and two markers
966
+ * that compute the *same* base do contend, which is why the key is the base
967
+ * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).
968
+ *
969
+ * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical
970
+ * statement of that grouping — it is what the resolver walks and what the
971
+ * collision validator checks. This computes the same key from the same
972
+ * `computeInterceptedBase` rather than calling it, because affix ambiguity is
973
+ * decided per *child* and `collectEffectiveAffixed` looks through route groups,
974
+ * so the two do not partition the same set of nodes.
975
+ */
976
+ function contentionKey(parent, child) {
977
+ if (child.segmentType !== "intercepting") return "child";
978
+ return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? "(.)")}`;
979
+ }
980
+ /** Combined affix length of a node, read through its effective identity. */
981
+ function affixLengthOf(node) {
982
+ const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);
983
+ return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);
984
+ }
985
+ /**
986
+ * Collect affixed dynamic segments that are effective children of a node.
987
+ * Route groups are URL-transparent, so we look through them recursively.
988
+ *
989
+ * Segments are read through `effectiveUrlSegment`, so an intercepting
990
+ * directory counts as the affixed segment it intercepts: `(.)a-[id]` is
991
+ * `a-[id]`. The proxy the slot resolver builds hands those affixes to
992
+ * `matchUrlParts`, whose equal-length sort is not stable across equal
993
+ * specificity — so two intercepting siblings with the same combined affix
994
+ * length would resolve by filesystem enumeration order, which is precisely
995
+ * what this validator exists to prevent for ordinary siblings (TIM-1288).
996
+ */
997
+ function collectEffectiveAffixed(node) {
998
+ const result = [];
999
+ for (const child of node.children) {
1000
+ const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);
1001
+ if (segmentType === "dynamic" && (paramPrefix || paramSuffix)) result.push(child);
1002
+ else if (segmentType === "group") result.push(...collectEffectiveAffixed(child));
1003
+ }
1004
+ return result;
1005
+ }
1006
+ /**
1007
+ * Find a fixed-extension file (proxy.ts) in a directory.
1008
+ */
1009
+ function findFixedFile(dirPath, name) {
1010
+ for (const ext of ["ts", "tsx"]) {
1011
+ const fullPath = join(dirPath, `${name}.${ext}`);
1012
+ try {
1013
+ if (statSync(fullPath).isFile()) return {
1014
+ filePath: fullPath,
1015
+ extension: ext
1016
+ };
1017
+ } catch {}
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Find a file with script extensions (tsx, ts, jsx, js) in a directory.
1022
+ * Used for app-root conventions like global-error that only accept script
1023
+ * extensions (TIM-1505).
1024
+ */
1025
+ function findScriptExtFile(dirPath, name) {
1026
+ for (const ext of [
1027
+ "tsx",
1028
+ "ts",
1029
+ "jsx",
1030
+ "js"
1031
+ ]) {
1032
+ const fullPath = join(dirPath, `${name}.${ext}`);
1033
+ try {
1034
+ if (statSync(fullPath).isFile()) return {
1035
+ filePath: fullPath,
1036
+ extension: ext
1037
+ };
1038
+ } catch {}
1039
+ }
1040
+ }
1041
+ export { fileHasDefaultExport as a, getCsrfExport as c, fileHasAnyExport as i, getPrerenderExport as l, scanRoutes as n, fileHasDirective as o, fileDefaultExportIsLocalValue as r, fileHasStarExport as s, isRouteConventionFile as t, readFileCached as u };
1042
+
1043
+ //# sourceMappingURL=scanner-DSAJjH0x.js.map