@timber-js/app 0.2.0-alpha.243 → 0.2.0-alpha.245

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 (143) hide show
  1. package/dist/_chunks/{actions-DoTj0Jd3.js → actions-C7_xl9iA.js} +12 -8
  2. package/dist/_chunks/actions-C7_xl9iA.js.map +1 -0
  3. package/dist/_chunks/als-registry-C-iwbtvI.js.map +1 -1
  4. package/dist/_chunks/{cli-check-DlQBSKIN.js → cli-check-CetL-6Us.js} +5 -5
  5. package/dist/_chunks/cli-check-CetL-6Us.js.map +1 -0
  6. package/dist/_chunks/{codegen-vaCyFyVN.js → codegen-BxJGInWa.js} +76 -20
  7. package/dist/_chunks/codegen-BxJGInWa.js.map +1 -0
  8. package/dist/_chunks/{convention-lint-CGGcseNn.js → convention-lint-BWbKAV4x.js} +51 -15
  9. package/dist/_chunks/convention-lint-BWbKAV4x.js.map +1 -0
  10. package/dist/_chunks/{dev-server-LO4McfQi.js → dev-server-BZxFJNih.js} +66 -9
  11. package/dist/_chunks/{dev-server-LO4McfQi.js.map → dev-server-BZxFJNih.js.map} +1 -1
  12. package/dist/_chunks/dev-server-C72bB9Kg.js +1 -0
  13. package/dist/_chunks/{key-headers-uIig1_mU.js → key-headers-CVpa6fpW.js} +6 -2
  14. package/dist/_chunks/key-headers-CVpa6fpW.js.map +1 -0
  15. package/dist/cli-check.d.ts +3 -3
  16. package/dist/cli-check.d.ts.map +1 -1
  17. package/dist/cli.js +2 -2
  18. package/dist/config-types.d.ts +43 -22
  19. package/dist/config-types.d.ts.map +1 -1
  20. package/dist/config-validation.d.ts.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +4 -4
  24. package/dist/index.js.map +1 -1
  25. package/dist/native/rsc/manifest.json +2 -0
  26. package/dist/native/rsc/routing/descendant-params.js +28 -0
  27. package/dist/native/rsc/routing/descendant-params.js.map +1 -0
  28. package/dist/native/rsc/server/als-registry.js.map +1 -1
  29. package/dist/native/rsc/server/request-context.js +1 -1
  30. package/dist/native/rsc/server/request-context.js.map +1 -1
  31. package/dist/native/rsc/server/route-element-builder.js +4 -3
  32. package/dist/native/rsc/server/route-element-builder.js.map +1 -1
  33. package/dist/native/rsc/server/route-module-loader.js +5 -4
  34. package/dist/native/rsc/server/route-module-loader.js.map +1 -1
  35. package/dist/native/rsc/server/rsc-entry/render-route.js +1 -1
  36. package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
  37. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +1 -1
  38. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js.map +1 -1
  39. package/dist/native/rsc/server/segment-lifetime/outlet-gate.js +2 -1
  40. package/dist/native/rsc/server/segment-lifetime/outlet-gate.js.map +1 -1
  41. package/dist/native/rsc/server/segment-lifetime/read-rule.js +9 -5
  42. package/dist/native/rsc/server/segment-lifetime/read-rule.js.map +1 -1
  43. package/dist/native/rsc/server/segment-lifetime/read-scope.js +3 -1
  44. package/dist/native/rsc/server/segment-lifetime/read-scope.js.map +1 -1
  45. package/dist/native/rsc/server/segment-lifetime/segment-key.js +15 -9
  46. package/dist/native/rsc/server/segment-lifetime/segment-key.js.map +1 -1
  47. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js +6 -5
  48. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js.map +1 -1
  49. package/dist/native/rsc/shared/key-headers.js +4 -1
  50. package/dist/native/rsc/shared/key-headers.js.map +1 -1
  51. package/dist/native/rsc/shared/layout-defaults.js +19 -0
  52. package/dist/native/rsc/shared/layout-defaults.js.map +1 -0
  53. package/dist/native/ssr/manifest.json +1 -0
  54. package/dist/native/ssr/server/als-registry.js.map +1 -1
  55. package/dist/native/ssr/server/request-context.js +1 -1
  56. package/dist/native/ssr/server/request-context.js.map +1 -1
  57. package/dist/native/ssr/server/segment-lifetime/outlet-gate.js +1 -0
  58. package/dist/native/ssr/server/segment-lifetime/outlet-gate.js.map +1 -1
  59. package/dist/native/ssr/server/segment-lifetime/read-rule.js +9 -5
  60. package/dist/native/ssr/server/segment-lifetime/read-rule.js.map +1 -1
  61. package/dist/native/ssr/server/segment-lifetime/read-scope.js.map +1 -1
  62. package/dist/native/ssr/shared/key-headers.js +4 -1
  63. package/dist/native/ssr/shared/key-headers.js.map +1 -1
  64. package/dist/native/ssr/shared/layout-defaults.js +9 -0
  65. package/dist/native/ssr/shared/layout-defaults.js.map +1 -0
  66. package/dist/plugins/entries.d.ts.map +1 -1
  67. package/dist/routing/codegen-types.d.ts +9 -0
  68. package/dist/routing/codegen-types.d.ts.map +1 -1
  69. package/dist/routing/codegen.d.ts.map +1 -1
  70. package/dist/routing/convention-lint.d.ts +2 -2
  71. package/dist/routing/convention-lint.d.ts.map +1 -1
  72. package/dist/routing/descendant-params.d.ts +46 -0
  73. package/dist/routing/descendant-params.d.ts.map +1 -0
  74. package/dist/routing/index.js +1 -1
  75. package/dist/routing/route-options-lint.d.ts +2 -2
  76. package/dist/routing/route-options-lint.d.ts.map +1 -1
  77. package/dist/routing/route-options.d.ts +1 -1
  78. package/dist/routing/route-options.d.ts.map +1 -1
  79. package/dist/server/als-registry.d.ts +13 -0
  80. package/dist/server/als-registry.d.ts.map +1 -1
  81. package/dist/server/index.js +1 -1
  82. package/dist/server/internal.js +1 -1
  83. package/dist/server/internal.js.map +1 -1
  84. package/dist/server/route-element-builder.d.ts.map +1 -1
  85. package/dist/server/route-module-loader.d.ts +4 -3
  86. package/dist/server/route-module-loader.d.ts.map +1 -1
  87. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  88. package/dist/server/rsc-entry/render-route.d.ts +3 -3
  89. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  90. package/dist/server/rsc-entry/revalidate-renderer.d.ts +3 -3
  91. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -1
  92. package/dist/server/segment-lifetime/outlet-gate.d.ts +5 -5
  93. package/dist/server/segment-lifetime/outlet-gate.d.ts.map +1 -1
  94. package/dist/server/segment-lifetime/read-rule.d.ts +8 -1
  95. package/dist/server/segment-lifetime/read-rule.d.ts.map +1 -1
  96. package/dist/server/segment-lifetime/read-scope.d.ts +8 -2
  97. package/dist/server/segment-lifetime/read-scope.d.ts.map +1 -1
  98. package/dist/server/segment-lifetime/segment-key.d.ts +28 -20
  99. package/dist/server/segment-lifetime/segment-key.d.ts.map +1 -1
  100. package/dist/server/segment-lifetime/slot-outlets.d.ts +2 -3
  101. package/dist/server/segment-lifetime/slot-outlets.d.ts.map +1 -1
  102. package/dist/server/types.d.ts +7 -5
  103. package/dist/server/types.d.ts.map +1 -1
  104. package/dist/shared/key-headers.d.ts +2 -0
  105. package/dist/shared/key-headers.d.ts.map +1 -1
  106. package/dist/shared/layout-defaults.d.ts +30 -0
  107. package/dist/shared/layout-defaults.d.ts.map +1 -0
  108. package/docs/api/30-api-server.mdx +2 -2
  109. package/docs/api/34-api-config.mdx +20 -3
  110. package/package.json +1 -1
  111. package/src/cli-check.ts +6 -6
  112. package/src/config-types.ts +44 -22
  113. package/src/config-validation.ts +96 -20
  114. package/src/index.ts +1 -1
  115. package/src/plugins/entries.ts +6 -3
  116. package/src/plugins/routing.ts +1 -1
  117. package/src/routing/codegen-types.ts +9 -0
  118. package/src/routing/codegen.ts +34 -20
  119. package/src/routing/convention-lint.ts +5 -3
  120. package/src/routing/descendant-params.ts +76 -0
  121. package/src/routing/route-options-lint.ts +34 -15
  122. package/src/routing/route-options.ts +3 -2
  123. package/src/server/als-registry.ts +13 -0
  124. package/src/server/request-context.ts +1 -1
  125. package/src/server/route-element-builder.ts +10 -3
  126. package/src/server/route-module-loader.ts +7 -6
  127. package/src/server/rsc-entry/index.ts +7 -8
  128. package/src/server/rsc-entry/render-route.ts +4 -4
  129. package/src/server/rsc-entry/revalidate-renderer.ts +4 -4
  130. package/src/server/segment-lifetime/outlet-gate.ts +6 -6
  131. package/src/server/segment-lifetime/read-rule.ts +37 -5
  132. package/src/server/segment-lifetime/read-scope.ts +11 -2
  133. package/src/server/segment-lifetime/segment-key.ts +50 -27
  134. package/src/server/segment-lifetime/slot-outlets.ts +10 -12
  135. package/src/server/types.ts +7 -5
  136. package/src/shared/key-headers.ts +5 -0
  137. package/src/shared/layout-defaults.ts +43 -0
  138. package/dist/_chunks/actions-DoTj0Jd3.js.map +0 -1
  139. package/dist/_chunks/cli-check-DlQBSKIN.js.map +0 -1
  140. package/dist/_chunks/codegen-vaCyFyVN.js.map +0 -1
  141. package/dist/_chunks/convention-lint-CGGcseNn.js.map +0 -1
  142. package/dist/_chunks/dev-server-DrjLscqT.js +0 -1
  143. package/dist/_chunks/key-headers-uIig1_mU.js.map +0 -1
@@ -18,6 +18,47 @@ export interface ClientJavascriptConfig {
18
18
  enableHMRInDev?: boolean;
19
19
  }
20
20
 
21
+ /**
22
+ * What every layout takes when it does not declare its own (`layoutDefaults`).
23
+ * An explicit subset of `LayoutOptions`: options that already apply app-wide
24
+ * from a root layout (`prerender`, `deferSuspenseFor`) are not here.
25
+ */
26
+ export interface LayoutDefaults {
27
+ /**
28
+ * The lifetime of every layout that does not declare one. A layout's own
29
+ * `layoutOptions.lifetime` wins.
30
+ *
31
+ * `'document'` renders each layout on the document request and skips it on
32
+ * client navigations until its key changes. Every `'document'` rule
33
+ * applies: the default key is every param on the layout's path (plus
34
+ * `key.headers` below), and the layout may read only the request inputs in
35
+ * its key. Check three things before turning it on: a layout that reads
36
+ * anything else (a header, a cookie outside its key) is reported (the dev
37
+ * overlay, or a warning) and renders as `'request'` for that visitor; a
38
+ * layout that shows data that changes during a visit (a cart badge) keeps
39
+ * the value it had at load; and a layout that hides its children in its
40
+ * body no longer keeps them out of the payload, since a skip never runs it.
41
+ * Declare `layoutOptions = { lifetime: 'request' }` on those, and gate in
42
+ * `access.ts`. Layouts in and below an intercepting directory take no
43
+ * options and no defaults, and stay `'request'`.
44
+ *
45
+ * Default: `'request'`.
46
+ */
47
+ lifetime?: SegmentLifetime;
48
+ key?: {
49
+ /**
50
+ * The `key.headers` of every `'document'` layout whose key does not
51
+ * declare `headers` — declared `'document'` or defaulted. A layout that
52
+ * declares `key.headers` replaces this list rather than adding to it.
53
+ * Each header in it makes those layouts re-render when its value changes,
54
+ * so name headers that are stable across a visit (`user-agent`). The
55
+ * same names are refused as in a layout's own key: `cookie`, credential
56
+ * headers and invalid names stop startup.
57
+ */
58
+ headers?: readonly string[];
59
+ };
60
+ }
61
+
21
62
  export interface TimberUserConfig {
22
63
  output?: 'server' | 'static';
23
64
  /**
@@ -329,29 +370,10 @@ export interface TimberUserConfig {
329
370
  */
330
371
  buildDir?: string;
331
372
  /**
332
- * The lifetime of every layout that does not declare one, slot layouts
333
- * included. Pages are unaffected, and a layout's own
334
- * `layoutOptions.lifetime` wins.
335
- *
336
- * `'document'` renders each layout on the document request and skips it on
337
- * client navigations until its key changes. Every `'document'` rule
338
- * applies: the default key is every param on the layout's path, and the
339
- * layout may read only the request inputs in its key. Check three things
340
- * before turning it on: a layout that reads anything else (a header, a
341
- * cookie outside its key) is reported (the dev overlay, or a warning) and
342
- * renders as `'request'` for that visitor; a layout that shows data that changes
343
- * during a visit (a cart badge) keeps the value it had at load; and a layout
344
- * that hides its children in its body no longer keeps them out of the
345
- * payload, since a skip never runs it. Declare
346
- * `layoutOptions = { lifetime: 'request' }` on those, and gate in
347
- * `access.ts`. Layouts in and below an intercepting directory take no
348
- * options and stay `'request'`.
349
- *
350
- * Default: `'request'`.
351
- *
352
- * See design/53-segment-lifetime.md §"App-wide default".
373
+ * Defaults for every layout, slot layouts included. Pages are unaffected.
374
+ * See `LayoutDefaults` and design/53-segment-lifetime.md §"App-wide defaults".
353
375
  */
354
- defaultLayoutLifetime?: SegmentLifetime;
376
+ layoutDefaults?: LayoutDefaults;
355
377
  /**
356
378
  * Cache behavior configuration.
357
379
  */
@@ -9,8 +9,9 @@
9
9
  */
10
10
 
11
11
  import { createRequire } from 'node:module';
12
- import type { TimberUserConfig } from './config-types.ts';
12
+ import type { LayoutDefaults, TimberUserConfig } from './config-types.ts';
13
13
  import { devHostnameError } from './plugins/dev-hostname.ts';
14
+ import { headerKeyProblem, isHeaderList } from './shared/key-headers.ts';
14
15
  import { DEFAULT_RENDER_TIMEOUT_MS, RENDER_TIMEOUT_CEILING_MS } from './server/render-timeout.ts';
15
16
 
16
17
  // ─── Types ──────────────────────────────────────────────────────────────────
@@ -56,7 +57,7 @@ const KNOWN_CONFIG_KEYS = {
56
57
  sitemap: true,
57
58
  buildDir: true,
58
59
  cache: true,
59
- defaultLayoutLifetime: true,
60
+ layoutDefaults: true,
60
61
  topLoader: true,
61
62
  budget: true,
62
63
  } satisfies Record<keyof TimberUserConfig, true>;
@@ -193,21 +194,8 @@ export function validateConfig(config: TimberUserConfig): ConfigError[] {
193
194
  }
194
195
  }
195
196
 
196
- // defaultLayoutLifetime — not fatal: every reader treats a value other than
197
- // 'document' as 'request', the default, which is slower but never wrong
198
- // (design/53 §"App-wide default").
199
- if (
200
- config.defaultLayoutLifetime !== undefined &&
201
- config.defaultLayoutLifetime !== 'request' &&
202
- config.defaultLayoutLifetime !== 'document'
203
- ) {
204
- errors.push({
205
- field: 'defaultLayoutLifetime',
206
- message: `Invalid defaultLayoutLifetime value: ${JSON.stringify(config.defaultLayoutLifetime)}.`,
207
- value: config.defaultLayoutLifetime,
208
- suggestion: "Use 'request' (the default) or 'document'.",
209
- });
210
- }
197
+ if (config.layoutDefaults !== undefined)
198
+ errors.push(...layoutDefaultsErrors(config.layoutDefaults));
211
199
 
212
200
  // devBrowserLogs
213
201
  if (config.devBrowserLogs !== undefined) {
@@ -308,15 +296,23 @@ export function validateConfig(config: TimberUserConfig): ConfigError[] {
308
296
  }
309
297
 
310
298
  const MOVED_TO_CACHE_FILE = new Set(['cacheHandler', 'cdnPurge']);
299
+ // Removed, not aliased (design/53 §"App-wide defaults"); without this hint
300
+ // every layout would silently fall back to 'request'.
301
+ const REPLACED: Record<string, string> = {
302
+ defaultLayoutLifetime:
303
+ '"defaultLayoutLifetime" was replaced by layoutDefaults: use layoutDefaults: { lifetime: \'document\' }.',
304
+ };
311
305
 
312
306
  for (const key of Object.keys(config)) {
313
307
  if (!knownKeys.has(key)) {
314
308
  errors.push({
315
309
  field: key,
316
310
  message: `Unknown config option: "${key}".`,
317
- suggestion: MOVED_TO_CACHE_FILE.has(key)
318
- ? `"${key}" has moved to timber.cache.ts. Export cacheHandler as default, cdnPurge as a named export.`
319
- : `Check for typos. Known options: ${[...knownKeys].sort().join(', ')}.`,
311
+ suggestion: Object.hasOwn(REPLACED, key)
312
+ ? REPLACED[key]
313
+ : MOVED_TO_CACHE_FILE.has(key)
314
+ ? `"${key}" has moved to timber.cache.ts. Export cacheHandler as default, cdnPurge as a named export.`
315
+ : `Check for typos. Known options: ${[...knownKeys].sort().join(', ')}.`,
320
316
  });
321
317
  }
322
318
  }
@@ -532,3 +528,83 @@ export function formatMissingPeers(results: PeerDepResult[]): string {
532
528
 
533
529
  return lines.join('\n');
534
530
  }
531
+
532
+ // Drift-proof, like KNOWN_CONFIG_KEYS: a field added to `LayoutDefaults`
533
+ // without listing it here is a compile error, not an "unknown option" warning.
534
+ const LAYOUT_DEFAULTS_KEYS = { lifetime: true, key: true } satisfies Record<
535
+ keyof LayoutDefaults,
536
+ true
537
+ >;
538
+ const LAYOUT_DEFAULTS_KEY_PARTS = { headers: true } satisfies Record<
539
+ keyof NonNullable<LayoutDefaults['key']>,
540
+ true
541
+ >;
542
+
543
+ /**
544
+ * `layoutDefaults` (design/53 §"App-wide defaults"). A malformed shape is not
545
+ * fatal: `resolveLayoutDefaults` reads it as no default, which is slower but
546
+ * never wrong. A header the key may not name is: it would make a credential
547
+ * keyable, and readable, in every defaulted layout.
548
+ */
549
+ function layoutDefaultsErrors(defaults: unknown): ConfigError[] {
550
+ const field = 'layoutDefaults';
551
+ if (typeof defaults !== 'object' || defaults === null || Array.isArray(defaults)) {
552
+ return [{ field, message: 'layoutDefaults must be an object.', value: defaults }];
553
+ }
554
+ const errors: ConfigError[] = [];
555
+ for (const name of Object.keys(defaults)) {
556
+ if (!Object.hasOwn(LAYOUT_DEFAULTS_KEYS, name)) {
557
+ errors.push({
558
+ field: `${field}.${name}`,
559
+ message: `Unknown layoutDefaults option: ${name}.`,
560
+ suggestion:
561
+ 'layoutDefaults takes lifetime and key.headers. prerender and deferSuspenseFor ' +
562
+ 'already apply app-wide from the root layout.',
563
+ });
564
+ }
565
+ }
566
+ const lifetime = 'lifetime' in defaults ? defaults.lifetime : undefined;
567
+ if (lifetime !== undefined && lifetime !== 'request' && lifetime !== 'document') {
568
+ errors.push({
569
+ field: `${field}.lifetime`,
570
+ message: `Invalid layoutDefaults.lifetime value: ${JSON.stringify(lifetime)}.`,
571
+ value: lifetime,
572
+ suggestion: "Use 'request' (the default) or 'document'.",
573
+ });
574
+ }
575
+ const key = 'key' in defaults ? defaults.key : undefined;
576
+ if (key === undefined) return errors;
577
+ if (typeof key !== 'object' || key === null || Array.isArray(key)) {
578
+ return [...errors, { field: `${field}.key`, message: 'layoutDefaults.key must be an object.' }];
579
+ }
580
+ for (const name of Object.keys(key)) {
581
+ if (!Object.hasOwn(LAYOUT_DEFAULTS_KEY_PARTS, name)) {
582
+ errors.push({
583
+ field: `${field}.key.${name}`,
584
+ message: `layoutDefaults.key takes only headers, not ${name}.`,
585
+ suggestion:
586
+ 'Params default per path, and cookie or search-param keys belong on the layout ' +
587
+ 'that reads them.',
588
+ });
589
+ }
590
+ }
591
+ const headers = 'headers' in key ? key.headers : undefined;
592
+ if (headers === undefined) return errors;
593
+ if (!isHeaderList(headers)) {
594
+ return [
595
+ ...errors,
596
+ {
597
+ field: `${field}.key.headers`,
598
+ message: 'layoutDefaults.key.headers must be an array of header names.',
599
+ value: headers,
600
+ },
601
+ ];
602
+ }
603
+ for (const name of headers) {
604
+ const problem = headerKeyProblem(name);
605
+ if (problem) {
606
+ errors.push({ field: `${field}.key.headers`, message: problem, value: name, fatal: true });
607
+ }
608
+ }
609
+ return errors;
610
+ }
package/src/index.ts CHANGED
@@ -70,7 +70,7 @@ import {
70
70
 
71
71
  // ── Public API ────────────────────────────────────────────────────────────
72
72
 
73
- export type { TimberUserConfig } from './config-types.ts';
73
+ export type { LayoutDefaults, TimberUserConfig } from './config-types.ts';
74
74
 
75
75
  // Metadata route handler types — re-exported so user-authored metadata
76
76
  // route files (sitemap.ts, robots.ts, manifest.ts, icon.tsx, etc.) can
@@ -164,9 +164,12 @@ function generateConfigModule(ctx: PluginContext): string {
164
164
  // Per-build deployment ID for version skew detection (TIM-446).
165
165
  // Null in dev mode — HMR handles code updates without full reloads.
166
166
  deploymentId: ctx.deploymentId ?? null,
167
- // Read by the RSC entry only: the lifetime of a layout that declares none
168
- // (design/53 §"App-wide default").
169
- defaultLayoutLifetime: ctx.config.defaultLayoutLifetime === 'document' ? 'document' : 'request',
167
+ // What a layout takes when it declares no lifetime, or a key without
168
+ // headers (design/53 §"App-wide defaults"). Written in its config shape:
169
+ // the RSC entry resolves it with `resolveLayoutDefaults`, the one reader
170
+ // of that shape. It reaches the browser bundle too (the browser entry
171
+ // imports this module whole); header names are not secret.
172
+ layoutDefaults: ctx.config.layoutDefaults ?? null,
170
173
  cache: {
171
174
  strictKeyDiscipline: ctx.config.cache?.strictKeyDiscipline ?? false,
172
175
  },
@@ -115,7 +115,7 @@ export function timberRouting(ctx: PluginContext): Plugin {
115
115
  // deduplicated against `warnedFiles`: an error must not be downgraded to
116
116
  // silence by an earlier scan in the same process.
117
117
  const conventionWarnings = lintConventions(tree, ctx.appDir, {
118
- defaultLayoutLifetime: ctx.config.defaultLayoutLifetime,
118
+ layoutDefaults: ctx.config.layoutDefaults,
119
119
  });
120
120
  const fatal = conventionWarnings.filter((w) => w.level === 'error');
121
121
  if (fatal.length > 0) {
@@ -15,6 +15,15 @@ export interface RouteEntry {
15
15
  segmentPath: string;
16
16
  /** Accumulated params from all ancestor dynamic segments */
17
17
  params: ParamEntry[];
18
+ /**
19
+ * Params a segment on this segment's `children` chain defines below it.
20
+ * Present only on the routes that pass through that segment, so they are
21
+ * optional in the `getSegmentParams(SEGMENT_PATH)` overload, which code in
22
+ * this segment (a layout, middleware, access.ts) reads at runtime. Kept out
23
+ * of `TimberSegmentParams` and the urlPath-keyed emissions, which describe
24
+ * the route itself (design/53 §"Keying on a descendant's param").
25
+ */
26
+ descendantParams: ParamEntry[];
18
27
  /** Whether this is an API route (route.ts) vs page route */
19
28
  isApiRoute: boolean;
20
29
  /**
@@ -14,6 +14,7 @@ import type { RouteTree, SegmentNode } from './types.ts';
14
14
  import type { ParamEntry, RouteEntry } from './codegen-types.ts';
15
15
  import { buildSchemaParamType } from './codegen-shared.ts';
16
16
  import { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';
17
+ import { childrenChainParams } from './descendant-params.ts';
17
18
  import {
18
19
  buildResolvedPattern,
19
20
  formatLinkCatchAllOverloads,
@@ -100,13 +101,7 @@ function collectRoutes(
100
101
  // ancestor param too.
101
102
  const urlSegment = effectiveUrlSegment(node);
102
103
  const params = [...ancestorParams];
103
- if (urlSegment.paramName) {
104
- params.push({
105
- name: urlSegment.paramName,
106
- bracketName: bracketNameForSegment(urlSegment),
107
- type: paramTypeForSegment(urlSegment.segmentType),
108
- });
109
- }
104
+ if (urlSegment.paramName) params.push(paramEntry(urlSegment.paramName, urlSegment));
110
105
 
111
106
  // Check if this segment is a leaf route (has page or route file)
112
107
  const isPage = !!node.page;
@@ -132,6 +127,11 @@ function collectRoutes(
132
127
  urlPath: node.urlPath,
133
128
  segmentPath: treePath || '/',
134
129
  params,
130
+ // A page renders only for its own route; a layout, middleware or
131
+ // access.ts runs for the routes below, so their params may be present.
132
+ descendantParams: hostsCode
133
+ ? [...childrenChainParams(node)].map(([name, segment]) => paramEntry(name, segment))
134
+ : [],
135
135
  isApiRoute,
136
136
  isRoutable: isPage || isApiRoute,
137
137
  isSlotRoute: insideSlot,
@@ -195,9 +195,14 @@ function dedupeRoutesByUrlPath(routes: RouteEntry[]): RouteEntry[] {
195
195
  return [...byPath.values()];
196
196
  }
197
197
 
198
- /**
199
- * Determine the TypeScript type for a segment's param.
200
- */
198
+ function paramEntry(name: string, segment: UrlSegmentIdentity): ParamEntry {
199
+ return {
200
+ name,
201
+ bracketName: bracketNameForSegment(segment),
202
+ type: paramTypeForSegment(segment.segmentType),
203
+ };
204
+ }
205
+
201
206
  /**
202
207
  * Derive the bracket key for schema/codegen lookup.
203
208
  * For bare segments like `[id]` this is the segmentName itself.
@@ -402,15 +407,18 @@ function formatDeclarationFile(
402
407
  // getSegmentParams / useSegmentParams are segmentPath-keyed → full list,
403
408
  // so slot segments keep their own typed overloads.
404
409
  const dynamicRoutes = routes.filter((r) => r.params.length > 0);
410
+ // The server overloads also type what a segment's descendants define, as
411
+ // optional: a layout reads them at runtime, and may key on them (design/53).
412
+ const serverRoutes = routes.filter((r) => r.params.length > 0 || r.descendantParams.length > 0);
405
413
 
406
414
  // Generate @timber-js/app/server augmentation — typed getSegmentParams
407
- if (dynamicRoutes.length > 0) {
415
+ if (serverRoutes.length > 0) {
408
416
  lines.push("declare module '@timber-js/app/server' {");
409
417
  if (hasSchema) {
410
418
  lines.push(" import type { AllSegmentParams } from '@timber-js/app'");
411
419
  }
412
- for (const route of dynamicRoutes) {
413
- const paramsType = formatParamsType(route.params, hasSchema);
420
+ for (const route of serverRoutes) {
421
+ const paramsType = formatParamsType(route.params, hasSchema, route.descendantParams);
414
422
  lines.push(
415
423
  ` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`
416
424
  );
@@ -487,20 +495,26 @@ function formatDeclarationFile(
487
495
  }
488
496
 
489
497
  /**
490
- * Format the params type for a route entry.
498
+ * Format the params type for a route entry. `optional` params (those a
499
+ * descendant defines) may be absent: `name?: T | undefined`.
491
500
  */
492
- function formatParamsType(params: ParamEntry[], hasSchema?: boolean): string {
493
- if (params.length === 0) {
501
+ function formatParamsType(
502
+ params: ParamEntry[],
503
+ hasSchema?: boolean,
504
+ optional: ParamEntry[] = []
505
+ ): string {
506
+ if (params.length === 0 && optional.length === 0) {
494
507
  return '{}';
495
508
  }
496
509
 
497
510
  // Without a schema a URL segment is an uninterpreted string — that IS
498
511
  // its type. Per-segment codec chains used to narrow it here; TIM-1342
499
512
  // deleted them along with params.ts.
500
- const fields = params.map((p) => {
501
- const codecType = hasSchema ? buildSchemaParamType(p) : p.type;
502
- return `${p.name}: ${codecType}`;
503
- });
513
+ const codecType = (p: ParamEntry) => (hasSchema ? buildSchemaParamType(p) : p.type);
514
+ const fields = [
515
+ ...params.map((p) => `${p.name}: ${codecType(p)}`),
516
+ ...optional.map((p) => `${p.name}?: (${codecType(p)}) | undefined`),
517
+ ];
504
518
  return `{ ${fields.join('; ')} }`;
505
519
  }
506
520
 
@@ -34,7 +34,8 @@ import {
34
34
  isScriptExtension,
35
35
  } from './export-detect.ts';
36
36
  import { checkRouteOptions } from './route-options-lint.ts';
37
- import type { SegmentLifetime } from '../server/types.ts';
37
+ import type { LayoutDefaults } from '../config-types.ts';
38
+ import { resolveLayoutDefaults } from '../shared/layout-defaults.ts';
38
39
 
39
40
  // ─── Types ──────────────────────────────────────────────────────────────────
40
41
 
@@ -60,7 +61,7 @@ export function lintConventions(
60
61
  tree: RouteTree,
61
62
  appDir: string,
62
63
  /** The config the checks depend on, as the build resolved it. */
63
- config: { defaultLayoutLifetime: SegmentLifetime | undefined }
64
+ config: { layoutDefaults: LayoutDefaults | undefined }
64
65
  ): ConventionWarning[] {
65
66
  const warnings: ConventionWarning[] = [];
66
67
 
@@ -103,7 +104,8 @@ export function lintConventions(
103
104
 
104
105
  // Check 10: layoutOptions / pageOptions the build cannot read, unknown
105
106
  // keys, and the removed floating exports (design/53)
106
- checkRouteOptions(tree.root, warnings, 'main', config.defaultLayoutLifetime ?? 'request');
107
+ const { lifetime } = resolveLayoutDefaults(config.layoutDefaults);
108
+ checkRouteOptions(tree.root, warnings, 'main', lifetime);
107
109
 
108
110
  return warnings;
109
111
  }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The params a segment's `children` chain defines below it: what a layout may
3
+ * name in `key.segmentParams` besides the params on its path
4
+ * (design/53-segment-lifetime.md §"Keying on a descendant's param").
5
+ *
6
+ * Read by the build lint (`route-options-lint.ts`), codegen (`codegen.ts`) and
7
+ * the runtime read scope (`server/segment-lifetime/read-scope.ts`), so the three
8
+ * agree on what a layout can key.
9
+ *
10
+ * - **`children` only.** A slot's subtree is excluded at every depth: a
11
+ * main-chain layout reads the main route's params, so a name only a slot
12
+ * defines could never be present in what it reads.
13
+ * - **Intercepting directories count**, read through `effectiveUrlSegment`
14
+ * (`(.)[id]` defines `id`): a children-path interception publishes the
15
+ * intercepted params into the same store.
16
+ * - **Only params a page binds.** A param counts only when a `page` sits at or
17
+ * below the segment defining it: a layout never renders for a `route.ts`,
18
+ * or for a directory with no page, so a name only those define would never
19
+ * be present when the key is read.
20
+ * - **Memoized per node**, one post-order pass over the tree however many
21
+ * layouts ask. Keyed weakly on the node object, which the scanner (build)
22
+ * and the manifest (runtime) each build once.
23
+ */
24
+
25
+ import { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';
26
+ import type { SegmentType } from './types.ts';
27
+
28
+ /** The fields of a scanned or manifest segment node this walk reads. */
29
+ interface DescendantNode {
30
+ segmentName: string;
31
+ segmentType: SegmentType;
32
+ paramName?: string;
33
+ paramPrefix?: string;
34
+ paramSuffix?: string;
35
+ interceptedSegmentName?: string;
36
+ page?: unknown;
37
+ children: readonly DescendantNode[];
38
+ }
39
+
40
+ const MEMO = new WeakMap<DescendantNode, ReadonlyMap<string, UrlSegmentIdentity>>();
41
+ const RENDERS_PAGE = new WeakMap<DescendantNode, boolean>();
42
+
43
+ /** Whether a page sits at or below `node` on its `children` chain. */
44
+ function rendersPage(node: DescendantNode): boolean {
45
+ let found = RENDERS_PAGE.get(node);
46
+ if (found === undefined) {
47
+ found = !!node.page || node.children.some(rendersPage);
48
+ RENDERS_PAGE.set(node, found);
49
+ }
50
+ return found;
51
+ }
52
+
53
+ /**
54
+ * Every param a segment on `node`'s `children` chain defines, at any depth,
55
+ * by name, with the segment that defines it (its bracket form, for codegen).
56
+ * Excludes `node`'s own param. A name defined in several branches appears
57
+ * once: the scanner already requires one bracket form per name across the
58
+ * tree (`validateUniqueBracketForms`).
59
+ */
60
+ export function childrenChainParams(node: DescendantNode): ReadonlyMap<string, UrlSegmentIdentity> {
61
+ const memo = MEMO.get(node);
62
+ if (memo) return memo;
63
+ const params = new Map<string, UrlSegmentIdentity>();
64
+ for (const child of node.children) {
65
+ if (!rendersPage(child)) continue;
66
+ const identity = effectiveUrlSegment(child);
67
+ if (identity.paramName && !params.has(identity.paramName)) {
68
+ params.set(identity.paramName, identity);
69
+ }
70
+ for (const [name, deeper] of childrenChainParams(child)) {
71
+ if (!params.has(name)) params.set(name, deeper);
72
+ }
73
+ }
74
+ MEMO.set(node, params);
75
+ return params;
76
+ }
@@ -7,6 +7,7 @@
7
7
 
8
8
  import type { ConventionWarning } from './convention-lint.ts';
9
9
  import { fileHasAnyExport, isScriptExtension } from './export-detect.ts';
10
+ import { childrenChainParams } from './descendant-params.ts';
10
11
  import { readRouteOptions } from './route-options.ts';
11
12
  import type { RouteFile, SegmentNode } from './types.ts';
12
13
  import type { LayoutOptions, PageOptions, SegmentLifetime } from '../server/types.ts';
@@ -25,8 +26,8 @@ export function checkRouteOptions(
25
26
  node: SegmentNode,
26
27
  warnings: ConventionWarning[],
27
28
  position: RoutePosition,
28
- /** The app's `defaultLayoutLifetime` (design/53 §"App-wide default"). */
29
- defaultLayoutLifetime: SegmentLifetime,
29
+ /** `layoutDefaults.lifetime`, resolved (design/53 §"App-wide defaults"). */
30
+ layoutLifetimeDefault: SegmentLifetime,
30
31
  /** The params named on the path above this segment. */
31
32
  ancestorParams: readonly string[] = []
32
33
  ): void {
@@ -41,8 +42,12 @@ export function checkRouteOptions(
41
42
  const { options, problems } = readRouteOptions(file.filePath, kind);
42
43
  problems.push(
43
44
  ...inertOptions(options, here),
44
- ...paramsOffPath(options, pathParams),
45
- ...keyWithoutDocument(options, kind === 'layout' ? defaultLayoutLifetime : 'request')
45
+ ...unkeyableParams(
46
+ options,
47
+ pathParams,
48
+ kind === 'layout' && here === 'main' ? descendantsOf(node) : []
49
+ ),
50
+ ...keyWithoutDocument(options, kind === 'layout' ? layoutLifetimeDefault : 'request')
46
51
  );
47
52
  if (problems.length === 0) continue;
48
53
  warnings.push({
@@ -71,18 +76,18 @@ export function checkRouteOptions(
71
76
  }
72
77
  }
73
78
  for (const child of node.children) {
74
- checkRouteOptions(child, warnings, here, defaultLayoutLifetime, pathParams);
79
+ checkRouteOptions(child, warnings, here, layoutLifetimeDefault, pathParams);
75
80
  }
76
81
  for (const slot of Object.values(node.slots)) {
77
82
  const slotPosition = here === 'intercepting' ? here : 'slot';
78
- checkRouteOptions(slot, warnings, slotPosition, defaultLayoutLifetime, pathParams);
83
+ checkRouteOptions(slot, warnings, slotPosition, layoutLifetimeDefault, pathParams);
79
84
  }
80
85
  }
81
86
 
82
87
  /**
83
88
  * A `key` applies only to a `'document'` segment; on any other it would
84
89
  * silently do nothing. A layout that declares no lifetime takes the app's
85
- * `defaultLayoutLifetime`, so under a `'document'` default it may declare a
90
+ * `layoutDefaults.lifetime`, so under a `'document'` default it may declare a
86
91
  * key alone. A page always defaults to `'request'`.
87
92
  */
88
93
  function keyWithoutDocument(
@@ -95,25 +100,39 @@ function keyWithoutDocument(
95
100
  ];
96
101
  }
97
102
 
103
+ /** The params a layout's `children` chain defines below it, its path's excluded. */
104
+ function descendantsOf(node: SegmentNode): string[] {
105
+ return [...childrenChainParams(node).keys()];
106
+ }
107
+
98
108
  /**
99
109
  * A key's `segmentParams` must name params on the segment's path — the
100
- * segment's own and every ancestor's, slots included. Anything else could
101
- * never change, so the key would silently ignore what the author meant
102
- * (design/53 §"Segment keys").
110
+ * segment's own and every ancestor's, slots included — or, for a main-chain
111
+ * layout, a param a page on its `children` chain binds (design/53 §"Keying on
112
+ * a descendant's param"). A page never renders for a deeper route. A slot
113
+ * layout's key reads the slot's own record, and a slot's intercepting routes
114
+ * take no keys, so it keeps its path params. Any other name is never in the params the segment reads, so
115
+ * the key would silently ignore what the author meant (design/53 §"Segment
116
+ * keys").
103
117
  */
104
- function paramsOffPath(
118
+ function unkeyableParams(
105
119
  options: LayoutOptions | PageOptions | undefined,
106
- pathParams: readonly string[]
120
+ pathParams: readonly string[],
121
+ descendants: readonly string[]
107
122
  ): string[] {
108
123
  const declared = options?.key?.segmentParams ?? [];
109
124
  return declared
110
- .filter((name) => !pathParams.includes(name))
125
+ .filter((name) => !pathParams.includes(name) && !descendants.includes(name))
111
126
  .map(
112
127
  (name) =>
113
- `key.segmentParams names "${name}", which is not a param on this segment's path. ` +
128
+ `key.segmentParams names "${name}", which is not a param on this segment's path` +
129
+ (descendants.length > 0 ? ' or one its child routes define. ' : '. ') +
114
130
  (pathParams.length > 0
115
131
  ? `Params on the path: ${pathParams.join(', ')}.`
116
- : 'This path has no params.')
132
+ : 'This path has no params.') +
133
+ (descendants.length > 0
134
+ ? ` Params its child routes define: ${descendants.join(', ')}.`
135
+ : '')
117
136
  );
118
137
  }
119
138
 
@@ -11,7 +11,7 @@
11
11
  * `server/route-module-loader.ts`; `lifetime` and `key`, in
12
12
  * `server/segment-lifetime/segment-key.ts`). A key's `searchParams` and
13
13
  * `cookies` name definitions, so they are the one place a non-literal value is
14
- * accepted; `segmentParams` is checked against the segment's path by
14
+ * accepted; `segmentParams` is checked against the params the segment can key by
15
15
  * `routing/route-options-lint.ts`. The whole object follows one rule so that
16
16
  * every key is checkable: this reader accepts one spelling —
17
17
  * `export const xOptions = { … }` of literal values, optionally behind
@@ -196,7 +196,8 @@ function readLifetime(node: Node): Read<SegmentLifetime> {
196
196
  * and `cookies` name definitions — code the build cannot evaluate — so only
197
197
  * their shape is checked here; their values take effect from the loaded
198
198
  * module (`server/segment-lifetime/`). The route-options lint checks the
199
- * param names against the segment's path.
199
+ * param names against what the segment can key (its path, and for a layout its
200
+ * child routes' params).
200
201
  */
201
202
  type BuildTimeKey = Pick<SegmentKey, 'segmentParams' | 'headers'>;
202
203
 
@@ -351,6 +351,19 @@ export interface DocumentReadScope {
351
351
  segmentPath: string;
352
352
  /** Segment param names in the key. */
353
353
  params: ReadonlySet<string>;
354
+ /**
355
+ * Every param name a key may name: those on the segment's path and, for a
356
+ * layout, those its `children` chain defines (design/53 §"Keying on a
357
+ * descendant's param"). A refused read of any other has a different fix
358
+ * (`read-rule.ts`).
359
+ */
360
+ keyableParams: ReadonlySet<string>;
361
+ /**
362
+ * Every param name on the segment's path. A keyed name outside it is a
363
+ * descendant's, keyed from the main route's record, so it may be read only
364
+ * through that record, never through a slot's (`read-rule.ts`).
365
+ */
366
+ pathParams: ReadonlySet<string>;
354
367
  /**
355
368
  * The fields of the key's search-params definition, each with the codec and
356
369
  * URL key it is read through — a field of another definition matches only
@@ -150,7 +150,7 @@ export function getSegmentParams(segmentPath?: string): CoercedParams {
150
150
  // documented API cannot drift (TIM-1285).
151
151
  const slotResolved = resolveSegmentParams(store.segmentParams, store.slotParams, segmentPath);
152
152
  // Inside a 'document' segment, a param outside its key is refused (design/53).
153
- if (slotResolved !== store.segmentParams) return scopedParams(slotResolved);
153
+ if (slotResolved !== store.segmentParams) return scopedParams(slotResolved, 'slot');
154
154
 
155
155
  // Dev-mode validation: warn when the segment path expects dynamic
156
156
  // segments that don't exist on the actual matched segment. This catches