@timber-js/app 0.2.0-alpha.123 → 0.2.0-alpha.125

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 (88) hide show
  1. package/dist/_chunks/{actions-ZlcKx0H9.js → actions-418ygYKC.js} +2 -2
  2. package/dist/_chunks/{actions-ZlcKx0H9.js.map → actions-418ygYKC.js.map} +1 -1
  3. package/dist/_chunks/{build-output-helper-DYOWsPjZ.js → build-output-helper-K7oUCRqU.js} +1 -1
  4. package/dist/_chunks/{build-output-helper-DYOWsPjZ.js.map → build-output-helper-K7oUCRqU.js.map} +1 -1
  5. package/dist/_chunks/{cli-schema-sync-VcCf1TFY.js → cli-schema-sync-DFHBj6yZ.js} +59 -12
  6. package/dist/_chunks/{cli-schema-sync-VcCf1TFY.js.map → cli-schema-sync-DFHBj6yZ.js.map} +1 -1
  7. package/dist/_chunks/cli-schema-sync-vdobDWwX.js +2 -0
  8. package/dist/_chunks/{define-C0V_eKiW.js → define-BJMwm0c4.js} +2 -2
  9. package/dist/_chunks/{define-C0V_eKiW.js.map → define-BJMwm0c4.js.map} +1 -1
  10. package/dist/_chunks/{navigation-root-Ds_hDtRW.js → navigation-root-CeNTCxzS.js} +6 -6
  11. package/dist/_chunks/navigation-root-CeNTCxzS.js.map +1 -0
  12. package/dist/_chunks/{stale-reload-BN2kcE06.js → stale-reload-CCqb62Z3.js} +22 -2
  13. package/dist/_chunks/{stale-reload-BN2kcE06.js.map → stale-reload-CCqb62Z3.js.map} +1 -1
  14. package/dist/_chunks/{use-segment-params-Du7u25cK.js → use-segment-params-ByGqwUuO.js} +3 -2
  15. package/dist/_chunks/use-segment-params-ByGqwUuO.js.map +1 -0
  16. package/dist/_chunks/{walkers-tkw7sDlj.js → walkers-DMSGZeCk.js} +2 -2
  17. package/dist/_chunks/{walkers-tkw7sDlj.js.map → walkers-DMSGZeCk.js.map} +1 -1
  18. package/dist/adapters/cloudflare.js +1 -1
  19. package/dist/adapters/nitro.js +1 -1
  20. package/dist/cli-schema-sync.d.ts +6 -4
  21. package/dist/cli-schema-sync.d.ts.map +1 -1
  22. package/dist/cli.d.ts +1 -1
  23. package/dist/cli.d.ts.map +1 -1
  24. package/dist/cli.js +12 -6
  25. package/dist/cli.js.map +1 -1
  26. package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
  27. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
  28. package/dist/client/browser-entry/router-init.d.ts +4 -1
  29. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  30. package/dist/client/index.js +4 -4
  31. package/dist/client/index.js.map +1 -1
  32. package/dist/client/internal.js +147 -301
  33. package/dist/client/internal.js.map +1 -1
  34. package/dist/client/link-pending-store.d.ts +19 -17
  35. package/dist/client/link-pending-store.d.ts.map +1 -1
  36. package/dist/client/link.d.ts.map +1 -1
  37. package/dist/client/navigation-context.d.ts +1 -0
  38. package/dist/client/navigation-context.d.ts.map +1 -1
  39. package/dist/client/navigation-root.d.ts +4 -1
  40. package/dist/client/navigation-root.d.ts.map +1 -1
  41. package/dist/client/router.d.ts +10 -7
  42. package/dist/client/router.d.ts.map +1 -1
  43. package/dist/client/rsc-fetch.d.ts.map +1 -1
  44. package/dist/client/segment-cache.d.ts +2 -0
  45. package/dist/client/segment-cache.d.ts.map +1 -1
  46. package/dist/client/segment-outlet.d.ts +23 -37
  47. package/dist/client/segment-outlet.d.ts.map +1 -1
  48. package/dist/client/segment-update-context.d.ts +21 -0
  49. package/dist/client/segment-update-context.d.ts.map +1 -0
  50. package/dist/client/use-search-params.d.ts +7 -5
  51. package/dist/client/use-search-params.d.ts.map +1 -1
  52. package/dist/index.js +3 -3
  53. package/dist/routing/index.js +2 -2
  54. package/dist/segment-params/index.js +1 -1
  55. package/dist/server/index.js +1 -1
  56. package/dist/server/internal.js +58 -2
  57. package/dist/server/internal.js.map +1 -1
  58. package/dist/server/route-element-builder.d.ts.map +1 -1
  59. package/dist/server/rsc-entry/helpers.d.ts +1 -0
  60. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  61. package/dist/server/state-tree-diff.d.ts +12 -5
  62. package/dist/server/state-tree-diff.d.ts.map +1 -1
  63. package/package.json +1 -1
  64. package/src/cli-schema-sync.ts +80 -13
  65. package/src/cli.ts +18 -7
  66. package/src/client/browser-entry/hydrate.ts +9 -1
  67. package/src/client/browser-entry/index.ts +3 -1
  68. package/src/client/browser-entry/post-hydration.ts +1 -13
  69. package/src/client/browser-entry/router-init.ts +50 -24
  70. package/src/client/link-pending-store.ts +22 -17
  71. package/src/client/link.tsx +12 -6
  72. package/src/client/navigation-context.ts +2 -1
  73. package/src/client/navigation-root.tsx +40 -18
  74. package/src/client/router.ts +113 -99
  75. package/src/client/rsc-fetch.ts +85 -6
  76. package/src/client/segment-cache.ts +5 -2
  77. package/src/client/segment-outlet.tsx +40 -49
  78. package/src/client/segment-update-context.ts +42 -0
  79. package/src/client/use-search-params.ts +25 -44
  80. package/src/server/route-element-builder.ts +69 -2
  81. package/src/server/rsc-entry/helpers.ts +18 -14
  82. package/src/server/state-tree-diff.ts +26 -22
  83. package/dist/_chunks/cli-schema-sync-4HcQIziG.js +0 -2
  84. package/dist/_chunks/navigation-root-Ds_hDtRW.js.map +0 -1
  85. package/dist/_chunks/use-segment-params-Du7u25cK.js.map +0 -1
  86. package/dist/client/segment-merger.d.ts +0 -119
  87. package/dist/client/segment-merger.d.ts.map +0 -1
  88. package/src/client/segment-merger.ts +0 -339
@@ -1,33 +1,31 @@
1
1
  /**
2
2
  * SegmentOutlet — client component boundary at each layout segment.
3
3
  *
4
- * Replaces the post-hoc tree walking in segment-merger.ts with an explicit
5
- * client component at each segment boundary. Each outlet:
4
+ * Each layout in the segment tree is wrapped with a SegmentOutlet that:
5
+ * 1. Knows its segment path (prop from the server)
6
+ * 2. Reads from SegmentUpdateContext for partial navigation updates
7
+ * 3. Caches its rendered content in a ref across navigations
6
8
  *
7
- * 1. Knows its own segment path (prop from the server)
8
- * 2. Caches its children in a ref across navigations
9
- * 3. When `keepCurrent` is true (partial navigation, this segment skipped),
10
- * returns the previously cached children — layout state is preserved
11
- * 4. When `keepCurrent` is false (full navigation or this segment changed),
12
- * stores and renders the new children
9
+ * On full navigation: receives new children via props, caches and renders them.
10
+ * On partial navigation (this segment skipped): the context map has no entry
11
+ * for this path, so the outlet returns cached content — preserving layout state.
12
+ * On partial navigation (this segment updated): the context map has content
13
+ * for this path, so the outlet renders the update.
13
14
  *
14
- * This eliminates the need for client-side element tree walking, which
15
- * breaks on real RSC trees due to opaque client component lazy refs,
16
- * Suspense thenables, and AccessGate wrappers.
15
+ * Uses React context instead of useSyncExternalStore to stay compatible
16
+ * with concurrent rendering (transitions). All outlets re-render when the
17
+ * context value changes, but each bails out quickly if its segment has
18
+ * no update — same approach as Next.js LayoutRouter.
17
19
  *
18
- * Architecture is similar to Next.js's `<LayoutRouter>` client component —
19
- * each layout boundary is an explicit client component that manages its
20
- * own subtree. See design/19-client-navigation.md.
21
- *
22
- * Security: This is a performance optimization only. The server always
23
- * runs all access.ts files regardless of segment skipping. A fabricated
24
- * keepCurrent prop can only cause stale layouts — never auth bypass.
20
+ * Security: performance optimization only. The server always runs all
21
+ * access.ts files regardless of segment skipping.
25
22
  * See design/13-security.md §"State tree manipulation".
26
23
  */
27
24
 
28
25
  'use client';
29
26
 
30
- import { useRef, type ReactNode } from 'react';
27
+ import { useContext, useRef, type ReactNode } from 'react';
28
+ import { SegmentUpdateContext } from './segment-update-context.js';
31
29
 
32
30
  export interface SegmentOutletProps {
33
31
  /**
@@ -38,17 +36,6 @@ export interface SegmentOutletProps {
38
36
  */
39
37
  segmentPath: string;
40
38
 
41
- /**
42
- * When true, the outlet returns its previously cached children instead
43
- * of rendering the new children prop. Set by the server when this
44
- * segment was skipped (the client already has the layout mounted).
45
- *
46
- * On the first render (SSR/hydration), this is always false — there's
47
- * no cached content yet. On subsequent partial navigations, the server
48
- * sets this to true for segments it skipped rendering.
49
- */
50
- keepCurrent?: boolean;
51
-
52
39
  /** The segment's React subtree (layout + inner content). */
53
40
  children: ReactNode;
54
41
  }
@@ -56,31 +43,35 @@ export interface SegmentOutletProps {
56
43
  /**
57
44
  * Client component boundary at each layout segment in the element tree.
58
45
  *
59
- * On full navigation: receives new children, stores them, renders them.
60
- * On partial navigation (keepCurrent=true): ignores children prop,
61
- * returns previously stored content — React reconciles the same elements,
62
- * preserving all client component state in the layout subtree.
46
+ * On full navigation (context map is empty): renders children, caches in ref.
47
+ * On partial navigation: checks the context map for an update at segmentPath.
48
+ * - Update found → renders update, caches in ref.
49
+ * - No update → returns cached content (layout state preserved).
63
50
  *
64
- * React preserves the ref across `reactRoot.render()` calls because:
65
- * - SegmentOutlet has a stable type (client component module reference)
66
- * - It appears at the same tree position on every navigation
67
- * - React reconciles same-type, same-position → instance preserved
51
+ * React preserves component instances across reactRoot.render() calls
52
+ * when the same type appears at the same tree position. The ref persists
53
+ * across navigations because SegmentOutlet is reconciled, not remounted.
68
54
  */
69
- export function SegmentOutlet({
70
- segmentPath: _segmentPath,
71
- keepCurrent = false,
72
- children,
73
- }: SegmentOutletProps) {
74
- // Store content in a ref to avoid triggering re-renders on cache updates.
75
- // The ref persists across reactRoot.render() calls because React reconciles
76
- // the same component type at the same tree position.
55
+ export function SegmentOutlet({ segmentPath, children }: SegmentOutletProps) {
56
+ const updates = useContext(SegmentUpdateContext);
77
57
  const contentRef = useRef<ReactNode>(null);
78
58
 
79
- if (!keepCurrent) {
80
- // Full render or this segment was re-rendered — store and render new content
59
+ const update = updates.get(segmentPath);
60
+
61
+ if (update !== undefined) {
62
+ contentRef.current = update;
63
+ return update;
64
+ }
65
+
66
+ if (contentRef.current === null) {
67
+ contentRef.current = children;
68
+ return children;
69
+ }
70
+
71
+ if (children !== contentRef.current) {
81
72
  contentRef.current = children;
73
+ return children;
82
74
  }
83
- // else: keepCurrent=true — return previously cached content
84
75
 
85
76
  return contentRef.current;
86
77
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * SegmentUpdateContext — React context for partial navigation updates.
3
+ *
4
+ * During partial navigation (server skips unchanged sync layouts), the
5
+ * router builds a Map of segment path → ReactNode updates and passes it
6
+ * as the context value. Mounted SegmentOutlet components read from this
7
+ * context to decide whether to render the update or their cached content.
8
+ *
9
+ * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as
10
+ * NavigationContext. The RSC client bundler can duplicate this module
11
+ * across chunks (browser-entry graph + client-reference graph). With
12
+ * ESM output, each chunk gets its own module scope — a bare createContext
13
+ * at module level would create separate instances per chunk. globalThis
14
+ * guarantees a single instance regardless of duplication.
15
+ *
16
+ * See design/19-client-navigation.md §"Singleton Guarantee via globalThis"
17
+ */
18
+
19
+ 'use client';
20
+
21
+ import React, { type ReactNode } from 'react';
22
+
23
+ export const EMPTY_SEGMENT_UPDATES = new Map<string, ReactNode>();
24
+
25
+ const CTX_KEY = Symbol.for('__timber_segment_update_ctx');
26
+
27
+ function getOrCreateContext(): React.Context<Map<string, ReactNode>> {
28
+ const existing = (globalThis as Record<symbol, unknown>)[CTX_KEY] as
29
+ | React.Context<Map<string, ReactNode>>
30
+ | undefined;
31
+ if (existing !== undefined) return existing;
32
+ if (typeof React.createContext === 'function') {
33
+ const ctx = React.createContext<Map<string, ReactNode>>(EMPTY_SEGMENT_UPDATES);
34
+ (globalThis as Record<symbol, unknown>)[CTX_KEY] = ctx;
35
+ return ctx;
36
+ }
37
+ // RSC environment — createContext not available. Return a dummy that
38
+ // won't be used (outlets only render on the client).
39
+ return undefined as unknown as React.Context<Map<string, ReactNode>>;
40
+ }
41
+
42
+ export const SegmentUpdateContext = getOrCreateContext();
@@ -4,9 +4,12 @@
4
4
  * Returns a read-only URLSearchParams instance reflecting the current
5
5
  * URL's query string. Updates when client-side navigation changes the URL.
6
6
  *
7
- * This is a thin wrapper over window.location.search, provided for
8
- * Next.js API compatibility (libraries like nuqs import useSearchParams
9
- * from next/navigation).
7
+ * On the client, reads from NavigationContext which is updated atomically
8
+ * with the RSC tree render. This replaces the previous useSyncExternalStore
9
+ * approach which read window.location.search directly — causing React to
10
+ * detect external store tearing during transitions and fall back to
11
+ * synchronous rendering (renderRootSync instead of renderRootConcurrent),
12
+ * blocking the main thread and freezing animations.
10
13
  *
11
14
  * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard
12
15
  * URLSearchParams. Mutation methods (set, delete, append) work on the
@@ -15,42 +18,14 @@
15
18
  * During SSR, reads the request search params from the SSR ALS context
16
19
  * (populated by ssr-entry.ts) instead of window.location.
17
20
  *
18
- * All mutable state is delegated to client/state.ts for singleton guarantees.
19
- * See design/18-build-system.md §"Singleton State Registry"
21
+ * Compatible with Next.js's `useSearchParams()` from `next/navigation`.
20
22
  */
21
23
 
22
- import { useSyncExternalStore } from 'react';
23
24
  import { getSsrData } from './ssr-data.js';
25
+ import { useNavigationContext } from './navigation-context.js';
24
26
  import { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.js';
25
27
 
26
- function getSearch(): string {
27
- if (typeof window !== 'undefined') return window.location.search;
28
- const data = getSsrData();
29
- if (!data) return '';
30
- const sp = new URLSearchParams(data.searchParams);
31
- const str = sp.toString();
32
- return str ? `?${str}` : '';
33
- }
34
-
35
- function getServerSearch(): string {
36
- const data = getSsrData();
37
- if (!data) return '';
38
- const sp = new URLSearchParams(data.searchParams);
39
- const str = sp.toString();
40
- return str ? `?${str}` : '';
41
- }
42
-
43
- function subscribe(callback: () => void): () => void {
44
- window.addEventListener('popstate', callback);
45
- return () => window.removeEventListener('popstate', callback);
46
- }
47
-
48
- // Cache the last search string and its parsed URLSearchParams to avoid
49
- // creating a new object on every render when the URL hasn't changed.
50
- // State lives in client/state.ts for singleton guarantees.
51
-
52
- function getSearchParams(): URLSearchParams {
53
- const search = getSearch();
28
+ function getSearchParams(search: string): URLSearchParams {
54
29
  if (search !== cachedSearch) {
55
30
  const params = new URLSearchParams(search);
56
31
  _setCachedSearch(search, params);
@@ -59,20 +34,26 @@ function getSearchParams(): URLSearchParams {
59
34
  return cachedSearchParams;
60
35
  }
61
36
 
62
- function getServerSearchParams(): URLSearchParams {
63
- const data = getSsrData();
64
- return data ? new URLSearchParams(data.searchParams) : new URLSearchParams();
65
- }
66
-
67
37
  /**
68
38
  * Read the current URL search params.
69
39
  *
70
40
  * Compatible with Next.js's `useSearchParams()` from `next/navigation`.
71
41
  */
72
42
  export function useSearchParams(): URLSearchParams {
73
- // useSyncExternalStore needs a primitive snapshot for comparison.
74
- // We use the raw search string as the snapshot, then return the
75
- // parsed URLSearchParams.
76
- useSyncExternalStore(subscribe, getSearch, getServerSearch);
77
- return typeof window !== 'undefined' ? getSearchParams() : getServerSearchParams();
43
+ try {
44
+ const navContext = useNavigationContext();
45
+ if (navContext !== null) {
46
+ return getSearchParams(navContext.search);
47
+ }
48
+ } catch {
49
+ // No React dispatcher available (called outside a component).
50
+ }
51
+
52
+ // SSR path: read from ALS-backed SSR data context.
53
+ const ssrData = getSsrData();
54
+ if (ssrData) return new URLSearchParams(ssrData.searchParams);
55
+
56
+ // Final fallback: window.location (tests, edge cases).
57
+ if (typeof window !== 'undefined') return getSearchParams(window.location.search);
58
+ return new URLSearchParams();
78
59
  }
@@ -44,12 +44,37 @@ import {
44
44
  import type { DenyPageEntry } from './deny-boundary.js';
45
45
  import { resolveSlotElement } from './slot-resolver.js';
46
46
  import { SegmentProvider } from '../client/segment-context.js';
47
+ import { SegmentOutlet } from '../client/segment-outlet.js';
47
48
 
48
49
  import { wrapSegmentWithErrorBoundaries } from './error-boundary-wrapper.js';
49
50
  import type { InterceptionContext } from './pipeline.js';
50
51
  import { shouldSkipSegment } from './state-tree-diff.js';
51
52
  import { loadModule } from './safe-load.js';
52
53
 
54
+ /**
55
+ * Replace the outermost SegmentOutlet in a partial payload with its
56
+ * SegmentProvider child. Walks through AccessGate wrappers (which sit
57
+ * outside SegmentOutlet) to find the outlet.
58
+ */
59
+ function replaceOutermostSegmentOutlet(
60
+ element: React.ReactElement,
61
+ replacement: React.ReactElement
62
+ ): React.ReactElement {
63
+ if (element.type === SegmentOutlet) {
64
+ return replacement;
65
+ }
66
+ // AccessGate wraps outside SegmentOutlet — recurse through it.
67
+ const props = element.props as Record<string, unknown>;
68
+ if (element.type === AccessGate && props.children) {
69
+ const inner = replaceOutermostSegmentOutlet(props.children as React.ReactElement, replacement);
70
+ return createElement(element.type as React.FunctionComponent<Record<string, unknown>>, {
71
+ ...props,
72
+ children: inner,
73
+ });
74
+ }
75
+ return element;
76
+ }
77
+
53
78
  // ─── Client Reference Detection ──────────────────────────────────────────
54
79
 
55
80
  /**
@@ -445,6 +470,12 @@ export async function buildRouteElement(
445
470
  // Without this guard, skipping the innermost layout causes the merger
446
471
  // to drop the layout entirely and replace it with just the page.
447
472
  let hasRenderedLayoutBelow = false;
473
+ let outermostSegmentProvider: React.ReactElement | null = null;
474
+ // Track whether any rendered inner layout also exists in the client's
475
+ // state tree. This prevents cross-section skipping: e.g., navigating
476
+ // from /(group-a) to /dashboard shouldn't skip root "/" because the
477
+ // client has no mounted outlet at "/dashboard".
478
+ let innerRenderedInClientTree = false;
448
479
 
449
480
  for (let i = segments.length - 1; i >= 0; i--) {
450
481
  const segment = segments[i];
@@ -461,10 +492,14 @@ export async function buildRouteElement(
461
492
  // - Route groups are never skipped because sibling groups share the
462
493
  // same urlPath (e.g., /(marketing) and /(app) both have "/"),
463
494
  // which would cause the wrong cached layout to be reused
495
+ // - At least one inner rendered layout must exist in the client's
496
+ // state tree, ensuring the client has a mounted outlet to receive
497
+ // the partial payload
464
498
  const skip =
465
499
  shouldSkipSegment(segment.urlPath, layoutComponent, isLeaf, clientStateTree ?? null) &&
466
500
  hasRenderedLayoutBelow &&
467
- segment.segmentType !== 'group';
501
+ segment.segmentType !== 'group' &&
502
+ innerRenderedInClientTree;
468
503
 
469
504
  if (skip) {
470
505
  // Skip this segment's layout/error boundaries — the client uses its cached version.
@@ -496,6 +531,17 @@ export async function buildRouteElement(
496
531
  // a rendered layout below them and can safely be skipped.
497
532
  if (layoutComponent) {
498
533
  hasRenderedLayoutBelow = true;
534
+ // Use segmentId for the client state tree check. Route groups share
535
+ // their parent's urlPath (both "/"), but their segmentId includes
536
+ // the group name (e.g., "/(group-a)"), so the check correctly
537
+ // fails when the client has never visited that group.
538
+ const outletKey =
539
+ segment.segmentType === 'group'
540
+ ? `${segment.urlPath === '/' ? '' : segment.urlPath}/${segment.segmentName}`
541
+ : segment.urlPath;
542
+ if (clientStateTree?.has(outletKey)) {
543
+ innerRenderedInClientTree = true;
544
+ }
499
545
  }
500
546
 
501
547
  // Wrap with error boundaries from this segment (inside layout).
@@ -585,12 +631,24 @@ export async function buildRouteElement(
585
631
  });
586
632
  }
587
633
 
588
- element = h(SegmentProvider, {
634
+ const segmentProviderElement = h(SegmentProvider, {
589
635
  segments: segmentPath,
590
636
  segmentId,
591
637
  parallelRouteKeys,
592
638
  children: layoutElement,
593
639
  });
640
+
641
+ element = h(SegmentOutlet, {
642
+ segmentPath: segmentId,
643
+ children: segmentProviderElement,
644
+ });
645
+
646
+ // Track the SegmentProvider for the outermost rendered layout.
647
+ // On partial navigation (segments skipped above), the client already
648
+ // has a SegmentOutlet mounted at this position. Sending another one
649
+ // in the payload causes double-wrapping and infinite context recursion.
650
+ // We'll strip the outermost SegmentOutlet after the loop.
651
+ outermostSegmentProvider = segmentProviderElement;
594
652
  }
595
653
 
596
654
  // Wrap in AccessGate OUTSIDE the layout.
@@ -611,6 +669,15 @@ export async function buildRouteElement(
611
669
  }
612
670
  }
613
671
 
672
+ // On partial navigation (some segments skipped), the client already has a
673
+ // SegmentOutlet mounted at the outermost non-skipped segment's position.
674
+ // Sending another SegmentOutlet in the payload causes double-wrapping —
675
+ // the inner outlet reads the same context update and recurses infinitely.
676
+ // Replace the outermost SegmentOutlet with just its SegmentProvider child.
677
+ if (skippedSegments.length > 0 && outermostSegmentProvider) {
678
+ element = replaceOutermostSegmentOutlet(element, outermostSegmentProvider);
679
+ }
680
+
614
681
  return {
615
682
  element,
616
683
  headElements: headElements as HeadElement[],
@@ -180,32 +180,36 @@ export function buildSegmentInfo(
180
180
  component: (...args: unknown[]) => unknown;
181
181
  segment: ManifestSegmentNode;
182
182
  }>
183
- ): Array<{ path: string; isAsync: boolean }> {
183
+ ): Array<{ path: string; segmentId?: string; isAsync: boolean }> {
184
184
  const layoutBySegment = new Map(
185
185
  layoutComponents.map(({ component, segment }) => [segment, component])
186
186
  );
187
187
 
188
- // Deduplicate by path — route groups are transparent and share their
189
- // parent's urlPath. When a group has its own layout, update the entry
190
- // to reflect the group's async status (the layout is what matters for
191
- // segment diffing). Without dedup, the state tree would contain
192
- // duplicate paths that break the server's skip logic.
193
- const byPath = new Map<string, { path: string; isAsync: boolean }>();
188
+ const result: Array<{ path: string; segmentId?: string; isAsync: boolean }> = [];
194
189
 
195
190
  for (const segment of segments) {
196
191
  const component = layoutBySegment.get(segment);
197
192
  const isAsync = component?.constructor?.name === 'AsyncFunction';
198
193
 
199
- const existing = byPath.get(segment.urlPath);
200
- if (!existing) {
201
- byPath.set(segment.urlPath, { path: segment.urlPath, isAsync });
202
- } else if (component) {
203
- // Group with a layout overrides the parent entry's async status
204
- existing.isAsync = isAsync;
194
+ // Compute segmentId — matches the key used by SegmentOutlet.
195
+ // Route groups share their parent's urlPath, so include the group
196
+ // name to disambiguate (e.g., "/(marketing)" vs "/").
197
+ const segmentId =
198
+ segment.segmentType === 'group'
199
+ ? `${segment.urlPath === '/' ? '' : segment.urlPath}/${segment.segmentName}`
200
+ : segment.urlPath;
201
+
202
+ const entry: { path: string; segmentId?: string; isAsync: boolean } = {
203
+ path: segment.urlPath,
204
+ isAsync,
205
+ };
206
+ if (segmentId !== segment.urlPath) {
207
+ entry.segmentId = segmentId;
205
208
  }
209
+ result.push(entry);
206
210
  }
207
211
 
208
- return Array.from(byPath.values());
212
+ return result;
209
213
  }
210
214
 
211
215
  /**
@@ -45,12 +45,19 @@ export function parseClientStateTree(req: Request): Set<string> | null {
45
45
  * Determine whether a segment's layout rendering can be skipped.
46
46
  *
47
47
  * A segment is skipped when ALL of the following are true:
48
- * 1. The client has the segment in its state tree (clientSegments contains urlPath)
49
- * 2. The layout is sync (not an async function — async layouts always re-render)
50
- * 3. The segment is NOT the leaf (pages are never cached across navigations)
48
+ * 1. The client sent a state tree (clientSegments is non-null)
49
+ * 2. The client has this segment cached (clientSegments contains urlPath)
50
+ * 3. The segment has a layout (otherwise nothing to skip)
51
+ * 4. The layout is sync (not an async function — async layouts may depend
52
+ * on per-request data and must always re-render)
53
+ * 5. The segment is NOT the leaf (pages are never cached across navigations)
54
+ *
55
+ * Additional constraints enforced by the caller (buildRouteElement):
56
+ * - Must have a rendered layout below (so SegmentOutlet has content to show)
57
+ * - Route groups are never skipped (siblings share urlPath)
51
58
  *
52
59
  * Access.ts still runs for skipped segments — this is enforced by the caller
53
- * (buildRouteElement) which runs all access checks before building the tree.
60
+ * which wraps with AccessGate regardless of skip status.
54
61
  *
55
62
  * @param urlPath - The segment's URL path (e.g., "/", "/dashboard")
56
63
  * @param layoutComponent - The loaded layout component function
@@ -58,23 +65,20 @@ export function parseClientStateTree(req: Request): Set<string> | null {
58
65
  * @param clientSegments - Set of paths from X-Timber-State-Tree, or null
59
66
  */
60
67
  export function shouldSkipSegment(
61
- _urlPath: string,
62
- _layoutComponent: ((...args: unknown[]) => unknown) | undefined,
63
- _isLeaf: boolean,
64
- _clientSegments: Set<string> | null
68
+ urlPath: string,
69
+ layoutComponent: ((...args: unknown[]) => unknown) | undefined,
70
+ isLeaf: boolean,
71
+ clientSegments: Set<string> | null
65
72
  ): boolean {
66
- // DISABLED: Client-side segment merging via React element tree walking
67
- // is too fragile for production. The merger's replaceInnerSegment relies
68
- // on walking RSC-decoded element trees to find SegmentProvider boundaries,
69
- // but production trees contain structures the walker can't handle:
70
- // Suspense wrappers, error boundaries, AccessGate components, React lazy
71
- // refs, and client component module references.
72
- //
73
- // The merger infrastructure (segment-merger.ts, element cache, state tree
74
- // filtering) is in place and tested. Re-enable when the merger can handle
75
- // real RSC element trees — likely requires a SegmentOutlet client component
76
- // approach instead of post-hoc element tree walking.
77
- //
78
- // See design/19-client-navigation.md §"X-Timber-State-Tree Header"
79
- return false;
73
+ if (!clientSegments) return false;
74
+ if (!clientSegments.has(urlPath)) return false;
75
+ if (!layoutComponent) return false;
76
+ if (isLeaf) return false;
77
+
78
+ // Async layouts always re-render — they may depend on per-request data
79
+ // (cookies, headers, database queries) that changes between navigations.
80
+ // constructor.name check: AsyncFunction.name === 'AsyncFunction'
81
+ if (layoutComponent.constructor.name === 'AsyncFunction') return false;
82
+
83
+ return true;
80
84
  }
@@ -1,2 +0,0 @@
1
- import { i as runSchemaSync } from "./cli-schema-sync-VcCf1TFY.js";
2
- export { runSchemaSync };
@@ -1 +0,0 @@
1
- {"version":3,"file":"navigation-root-Ds_hDtRW.js","names":[],"sources":["../../src/client/link-pending-store.ts","../../src/client/top-loader.tsx","../../src/client/navigation-root.tsx"],"sourcesContent":["/**\n * Link Pending Store — per-link optimistic pending state.\n *\n * Tracks which link instance is currently navigating so that only the\n * clicked link shows pending. Uses `useOptimistic` from React 19 —\n * the optimistic value (isPending=true) is set inside NavigationRoot's\n * async startTransition so it persists for the duration of the RSC\n * fetch, then auto-reverts to idle when the transition settles.\n *\n * Flow:\n * 1. Link click → setLinkForCurrentNavigation(instance) stores the ref\n * 2. NavigationRoot startTransition → activateLinkPending() calls\n * instance.setIsPending(LINK_PENDING) inside the async transition\n * 3. Transition settles → useOptimistic auto-reverts to LINK_IDLE\n *\n * SINGLETON GUARANTEE: Uses `globalThis` via `Symbol.for` keys because\n * the RSC client bundler can duplicate this module across chunks.\n *\n * See design/19-client-navigation.md §\"Per-Link Pending State\"\n */\n\nimport type { LinkStatus } from './use-link-status.js';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface LinkPendingInstance {\n setIsPending: (status: LinkStatus) => void;\n}\n\n// ─── Constants ───────────────────────────────────────────────────\n\nconst LINK_PENDING_KEY = Symbol.for('__timber_link_pending');\n\n/** Status object: link navigation in flight */\nexport const LINK_PENDING: LinkStatus = { isPending: true };\n\n/** Status object: link idle */\nexport const LINK_IDLE: LinkStatus = { isPending: false };\n\n// ─── Singleton Storage ───────────────────────────────────────────\n\nfunction getStore(): { current: LinkPendingInstance | null } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[LINK_PENDING_KEY]) {\n g[LINK_PENDING_KEY] = { current: null };\n }\n return g[LINK_PENDING_KEY] as { current: LinkPendingInstance | null };\n}\n\n// ─── Public API ──────────────────────────────────────────────────\n\n/**\n * Register the link instance that initiated the current navigation.\n * Called from Link's click handler. Does NOT call setIsPending —\n * that happens inside NavigationRoot's startTransition via\n * activateLinkPending().\n *\n * Resets the previous link to idle immediately (the old link's\n * useOptimistic reverts since its transition already settled).\n */\nexport function setLinkForCurrentNavigation(link: LinkPendingInstance | null): void {\n const store = getStore();\n store.current = link;\n}\n\n/**\n * Activate pending state on the current link instance.\n * MUST be called inside NavigationRoot's async startTransition —\n * this is what makes useOptimistic persist for the navigation duration.\n */\nexport function activateLinkPending(): void {\n const store = getStore();\n store.current?.setIsPending(LINK_PENDING);\n}\n\n/**\n * Reset the current link's pending state. With useOptimistic this is\n * handled automatically when the transition settles. Kept for callers\n * that explicitly need to clear on error paths.\n */\nexport function resetLinkPending(): void {\n const store = getStore();\n if (store.current) {\n store.current.setIsPending(LINK_IDLE);\n store.current = null;\n }\n}\n\n/**\n * @deprecated No longer needed with useOptimistic. Kept for callers.\n */\nexport function getCurrentNavId(): number {\n return 0;\n}\n\n/**\n * Clean up the link pending store entirely.\n */\nexport function clearLinkPendingSetter(): void {\n getStore().current = null;\n}\n\n/**\n * Unmount a link instance from navigation tracking.\n */\nexport function unmountLinkForCurrentNavigation(link: LinkPendingInstance): void {\n const store = getStore();\n if (store.current === link) {\n store.current = null;\n }\n}\n","/**\n * TopLoader — Built-in progress bar for client navigations.\n *\n * Shows an animated progress bar at the top of the viewport while an RSC\n * navigation is in flight. Injected automatically by the framework into\n * NavigationRoot — users never render this component directly.\n *\n * Configuration is via timber.config.ts `topLoader` key. Enabled by default.\n * Users who want a fully custom progress indicator disable the built-in one\n * (`topLoader: { enabled: false }`) and use `usePendingNavigation()` directly.\n *\n * Animation approach: pure CSS @keyframes. The bar crawls from 0% to ~90%\n * width over ~30s using ease-out timing. When navigation completes, the bar\n * snaps to 100% and fades out over 200ms. No JS animation loops (RAF, setInterval).\n *\n * Phase transitions are derived synchronously during render (React's\n * getDerivedStateFromProps pattern) — no useEffect needed for state tracking.\n * The finishing → hidden cleanup uses onTransitionEnd from the CSS transition.\n *\n * When delay > 0, CSS animation-delay + a visibility keyframe ensure the bar\n * stays invisible during the delay period. If navigation finishes before the\n * delay, the bar was never visible so the finish transition is also invisible.\n *\n * See design/19-client-navigation.md §\"usePendingNavigation()\"\n * See LOCAL-336 for design decisions.\n */\n\n'use client';\n\nimport { useState, createElement } from 'react';\nimport { usePendingNavigationUrl } from './navigation-context.js';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TopLoaderConfig {\n /** Whether the top-loader is enabled. Default: true. */\n enabled?: boolean;\n /** Bar color. Default: '#2299DD'. */\n color?: string;\n /** Bar height in pixels. Default: 3. */\n height?: number;\n /** Show subtle glow/shadow effect. Default: false. */\n shadow?: boolean;\n /** Delay in ms before showing the bar. Default: 0. */\n delay?: number;\n /** CSS z-index. Default: 1600. */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#2299DD';\nconst DEFAULT_HEIGHT = 3;\nconst DEFAULT_SHADOW = false;\nconst DEFAULT_DELAY = 0;\nconst DEFAULT_Z_INDEX = 1600;\n\n// ─── Keyframes ───────────────────────────────────────────────────\n\n// Unique keyframes name to avoid collisions with user styles.\nconst CRAWL_KEYFRAMES = '__timber_top_loader_crawl';\nconst APPEAR_KEYFRAMES = '__timber_top_loader_appear';\nconst FINISH_KEYFRAMES = '__timber_top_loader_finish';\n\n// Track whether the @keyframes rules have been injected into the document.\nlet keyframesInjected = false;\n\n/**\n * Inject the @keyframes rules into the document head once.\n * Called during render (idempotent). Uses a <style> tag so the\n * animations are available for inline-styled elements.\n */\nfunction ensureKeyframes(): void {\n if (keyframesInjected) return;\n if (typeof document === 'undefined') return;\n\n const style = document.createElement('style');\n style.textContent = `\n@keyframes ${CRAWL_KEYFRAMES} {\n 0% { width: 0%; }\n 100% { width: 90%; }\n}\n@keyframes ${APPEAR_KEYFRAMES} {\n from { opacity: 0; }\n to { opacity: 1; }\n}\n@keyframes ${FINISH_KEYFRAMES} {\n 0% { width: 90%; opacity: 1; }\n 50% { width: 100%; opacity: 1; }\n 100% { width: 100%; opacity: 0; }\n}\n`;\n document.head.appendChild(style);\n keyframesInjected = true;\n}\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Internal top-loader component. Injected by NavigationRoot.\n *\n * Reads pending navigation state from PendingNavigationContext.\n * Phase transitions are derived synchronously during render:\n *\n * hidden → crawling: when isPending becomes true\n * crawling → finishing: when isPending becomes false\n * finishing → hidden: when CSS transition ends (onTransitionEnd)\n * finishing → crawling: when isPending becomes true again\n *\n * No useEffect — all state changes are either derived during render\n * (getDerivedStateFromProps pattern) or triggered by DOM events.\n */\nexport function TopLoader({ config }: { config?: TopLoaderConfig }): React.ReactElement | null {\n const pendingUrl = usePendingNavigationUrl();\n // Navigation is pending when the React-based pending URL is set.\n // pendingUrl is set as an urgent update in navigateTransition() —\n // React commits it before the next paint, so the TopLoader appears\n // immediately when a real RSC navigation starts.\n //\n // We intentionally do NOT check hasNativeNavigationTransition() here.\n // The Navigation API's transition is active for ALL intercepted\n // navigations, including shallow URL updates (nuqs search param\n // changes with shallow: true) and prevented navigations. Those\n // briefly set navigation.transition via event.intercept() but do\n // NOT trigger RSC fetches — showing the TopLoader would be incorrect.\n // pendingUrl is the authoritative signal for \"we're fetching RSC data.\"\n const isPending = pendingUrl !== null;\n\n const color = config?.color ?? DEFAULT_COLOR;\n const height = config?.height ?? DEFAULT_HEIGHT;\n const shadow = config?.shadow ?? DEFAULT_SHADOW;\n const delay = config?.delay ?? DEFAULT_DELAY;\n const zIndex = config?.zIndex ?? DEFAULT_Z_INDEX;\n\n const [phase, setPhase] = useState<'hidden' | 'crawling' | 'finishing'>('hidden');\n\n // ─── Synchronous phase derivation (getDerivedStateFromProps) ──\n // React allows setState during render if the value changes — it\n // immediately re-renders with the updated state before committing.\n\n if (isPending && (phase === 'hidden' || phase === 'finishing')) {\n setPhase('crawling');\n }\n if (!isPending && phase === 'crawling') {\n setPhase('finishing');\n }\n\n // Inject keyframes on first visible render (idempotent)\n if (phase !== 'hidden') {\n ensureKeyframes();\n }\n\n if (phase === 'hidden') return null;\n\n // ─── Styles ──────────────────────────────────────────────────\n\n const containerStyle: React.CSSProperties = {\n position: 'fixed',\n top: 0,\n left: 0,\n width: '100%',\n height: `${height}px`,\n zIndex,\n pointerEvents: 'none',\n };\n\n const barStyle: React.CSSProperties = {\n height: '100%',\n backgroundColor: color,\n ...(phase === 'crawling'\n ? {\n // Crawl from 0% to 90% over 30s. When delay > 0, both the crawl\n // and a visibility animation are delayed — the bar stays at width 0%\n // and opacity 0 during the delay, then appears and starts crawling.\n // With delay 0, the appear animation is instant (0s duration, no delay).\n animation: [\n `${CRAWL_KEYFRAMES} 30s ease-out ${delay}ms forwards`,\n `${APPEAR_KEYFRAMES} 0s ${delay}ms both`,\n ].join(', '),\n }\n : {\n // Finishing: fill to 100% then fade out via a keyframe animation.\n // We use a keyframe instead of a CSS transition because the\n // animation-to-transition handoff is unreliable — the browser\n // may not capture the animated width as the transition's \"from\"\n // value when both the animation removal and transition are\n // applied in the same render frame.\n animation: `${FINISH_KEYFRAMES} 400ms ease forwards`,\n }),\n ...(shadow\n ? {\n boxShadow: `0 0 10px ${color}, 0 0 5px ${color}`,\n }\n : {}),\n };\n\n // Clean up the finishing phase when the finish animation completes.\n const handleAnimationEnd =\n phase === 'finishing'\n ? (e: React.AnimationEvent) => {\n if (e.animationName === FINISH_KEYFRAMES) {\n setPhase('hidden');\n }\n }\n : undefined;\n\n return createElement(\n 'div',\n {\n 'style': containerStyle,\n 'aria-hidden': 'true',\n 'data-timber-top-loader': '',\n },\n createElement('div', { style: barStyle, onAnimationEnd: handleAnimationEnd })\n );\n}\n","/**\n * NavigationRoot — Wrapper component for transition-based rendering.\n *\n * Solves the \"new boundary has no old content\" problem for client-side\n * navigation. When React renders a completely new Suspense boundary via\n * root.render(), it shows the fallback immediately — root.render() is\n * always an urgent update regardless of startTransition.\n *\n * NavigationRoot holds the current element in React state. Navigation\n * updates call startTransition(() => setState(newElement)), which IS\n * a transition update. React keeps the old committed tree visible while\n * any new Suspense boundaries in the transition resolve.\n *\n * Also manages `pendingUrl` as React state with an urgent/transition split:\n * - Navigation START: `setPendingUrl(url)` is an urgent update — React\n * commits it before the next paint, showing the spinner immediately.\n * - Navigation END: `setPendingUrl(null)` is inside `startTransition`\n * alongside `setElement(newTree)` — both commit atomically, so the\n * spinner disappears in the same frame as the new content appears.\n *\n * Hard navigation guard: When a hard navigation is triggered (500 error,\n * version skew), the component throws an unresolved thenable AFTER all\n * hooks to suspend forever — preventing React from rendering children\n * during page teardown. The throw must come after hooks to satisfy\n * React's rules (same hook count every render) while still preventing\n * child renders that could hit hook count mismatches in components\n * whose positions shift during teardown. This pattern is borrowed from\n * Next.js (app-router.tsx pushRef.mpaNavigation — also after hooks).\n *\n * See design/05-streaming.md §\"deferSuspenseFor\"\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { createElement, Fragment, startTransition, useState, type ReactNode } from 'react';\nimport { activateLinkPending, resetLinkPending } from './link-pending-store.js';\nimport { PendingNavigationProvider } from './navigation-context.js';\nimport { TopLoader, type TopLoaderConfig } from './top-loader.js';\n\n// ─── Navigation Transition Counter ──────────────────────────────\n// Monotonically increasing counter that increments each time\n// navigateTransition() is called. Used to detect stale transitions:\n// if a newer transition started while the current one's perform()\n// was in flight, the current transition is stale and should reject.\n//\n// Separate from the link-pending navId (which only increments on\n// link clicks). This counter covers all navigation types: link clicks,\n// programmatic navigate(), refresh(), and handlePopState().\n//\n// Uses globalThis for singleton guarantee across chunks — same pattern\n// as NavigationContext and the link pending store.\n\nconst NAV_TRANSITION_KEY = Symbol.for('__timber_nav_transition_counter');\n\nfunction getTransitionCounter(): { id: number } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[NAV_TRANSITION_KEY]) {\n g[NAV_TRANSITION_KEY] = { id: 0 };\n }\n return g[NAV_TRANSITION_KEY] as { id: number };\n}\n\n// ─── Hard Navigation Guard ──────────────────────────────────────\n\n/**\n * Module-level flag indicating a hard (MPA) navigation is in progress.\n *\n * When true:\n * - NavigationRoot throws an unresolved thenable to suspend forever,\n * preventing React from rendering children during page teardown\n * (avoids \"Rendered more hooks\" crashes).\n * - The Navigation API handler skips interception, letting the browser\n * perform a full page load (prevents infinite loops where\n * window.location.href → navigate event → router.navigate → 500 →\n * window.location.href → ...).\n *\n * Uses globalThis for singleton guarantee across chunks (same pattern\n * as NavigationContext). See design/19-client-navigation.md §\"Singleton\n * Guarantee via globalThis\".\n */\nconst HARD_NAV_KEY = Symbol.for('__timber_hard_navigating');\n\nfunction getHardNavStore(): { value: boolean } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[HARD_NAV_KEY]) {\n g[HARD_NAV_KEY] = { value: false };\n }\n return g[HARD_NAV_KEY] as { value: boolean };\n}\n\n/**\n * Set the hard-navigating flag. Call this BEFORE setting\n * window.location.href or window.location.reload() to prevent:\n * 1. React from rendering children during page teardown\n * 2. Navigation API from intercepting the hard navigation\n */\nexport function setHardNavigating(value: boolean): void {\n getHardNavStore().value = value;\n}\n\n/**\n * Check if a hard navigation is in progress.\n * Used by NavigationRoot (throw unresolvedThenable) and by the\n * Navigation API handler (skip interception).\n */\nexport function isHardNavigating(): boolean {\n return getHardNavStore().value;\n}\n\n/**\n * A thenable that never resolves. When thrown during React render,\n * it causes the component to suspend forever — React keeps the\n * old committed tree visible and never attempts to render children.\n *\n * This is the same pattern Next.js uses in app-router.tsx for MPA\n * navigations (pushRef.mpaNavigation → throw unresolvedThenable).\n */\n// for React's Suspense mechanism. Same pattern as Next.js's unresolvedThenable.\n// eslint-disable-next-line unicorn/no-thenable -- Intentionally a never-resolving thenable\nconst unresolvedThenable = { then() {} } as PromiseLike<never>;\n\n// ─── Module-level functions ──────────────────────────────────────\n\n/**\n * Module-level reference to the state setter wrapped in startTransition.\n * Used for non-navigation renders (applyRevalidation, popstate replay).\n */\nlet _transitionRender: ((element: ReactNode) => void) | null = null;\n\n/**\n * Module-level reference to the navigation transition function.\n * Wraps a full navigation (fetch + render) in a single startTransition\n * with the pending URL.\n */\nlet _navigateTransition:\n | ((pendingUrl: string, perform: () => Promise<ReactNode>) => Promise<void>)\n | null = null;\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Root wrapper component that enables transition-based rendering.\n *\n * Renders PendingNavigationProvider around children for the pending URL\n * context. The DOM tree matches the server-rendered HTML during hydration\n * (the provider renders no extra DOM elements).\n *\n * Usage in browser-entry.ts:\n * const rootEl = createElement(NavigationRoot, { initial: wrapped });\n * reactRoot = hydrateRoot(document, rootEl);\n *\n * Subsequent navigations:\n * navigateTransition(url, async () => { fetch; return wrappedElement; });\n *\n * Non-navigation renders:\n * transitionRender(newWrappedElement);\n */\nexport function NavigationRoot({\n initial,\n topLoaderConfig,\n}: {\n initial: ReactNode;\n topLoaderConfig?: TopLoaderConfig;\n}): ReactNode {\n const [element, setElement] = useState<ReactNode>(initial);\n const [pendingUrl, setPendingUrl] = useState<string | null>(null);\n\n // NOTE: We use standalone `startTransition` (imported from 'react'),\n // NOT `useTransition`. The `useTransition` hook's `startTransition`\n // is tied to a single fiber and tracks one async callback at a time.\n // When two navigations overlap (click slow-page, then click dashboard),\n // calling useTransition's startTransition twice with concurrent async\n // callbacks corrupts React's internal hook tracking — causing\n // \"Rendered more hooks than during the previous render.\"\n //\n // Standalone `startTransition` creates independent transition lanes\n // for each call, so concurrent navigations don't interfere. We don't\n // need useTransition's `isPending` — we track pending state via our\n // own `pendingUrl` useState.\n //\n // This matches the Next.js pattern (TIM-625): \"No useTransition in\n // the router at all — only standalone startTransition.\"\n\n // Non-navigation render (revalidation, popstate cached replay).\n _transitionRender = (newElement: ReactNode) => {\n startTransition(() => {\n setElement(newElement);\n });\n };\n\n // Full navigation transition.\n // setPendingUrl(url) is an URGENT update — React commits it before the next\n // paint, so the pending spinner appears immediately when navigation starts.\n // Inside startTransition: the async fetch + setElement + setPendingUrl(null)\n // are deferred. When the transition commits, the new tree and pendingUrl=null\n // both apply in the same React commit — making the pending→active transition\n // atomic (no frame where pending is false but the old tree is still visible).\n _navigateTransition = (url: string, perform: () => Promise<ReactNode>) => {\n // Urgent: show pending state immediately (for TopLoader / usePendingNavigation)\n setPendingUrl(url);\n\n // Increment the transition counter SYNCHRONOUSLY (before startTransition\n // schedules the async work). Each call gets a unique transId; the counter\n // is the same globalThis singleton, so a newer call always has a higher id.\n const counter = getTransitionCounter();\n const transId = ++counter.id;\n\n return new Promise<void>((resolve, reject) => {\n startTransition(async () => {\n // Activate per-link pending state inside this async transition.\n // useOptimistic persists the isPending=true value for the duration\n // of this transition, then auto-reverts when it settles.\n activateLinkPending();\n try {\n const newElement = await perform();\n // Only commit state if this is still the active navigation.\n // A superseded transition's updates must be dropped entirely.\n if (counter.id === transId) {\n setElement(newElement);\n setPendingUrl(null);\n resolve();\n } else {\n // Stale transition — a newer navigation has superseded this one.\n // Reject so the caller (navigate/refresh/handlePopState) doesn't\n // run post-transition side effects (applyHead, scroll, event\n // dispatch) with stale data. All callers catch AbortError.\n reject(new DOMException('Navigation superseded', 'AbortError'));\n }\n } catch (err) {\n // Only clear pending if this is still the active navigation.\n if (counter.id === transId) {\n setPendingUrl(null);\n resetLinkPending();\n }\n reject(err);\n }\n });\n });\n };\n\n // ─── Hard navigation guard ─────────────────────────────────\n // When a hard navigation is in progress (500 error, version skew),\n // suspend forever to prevent React from rendering children during\n // page teardown. This avoids \"Rendered more hooks\" crashes in\n // CHILD components whose hook counts may shift during teardown.\n //\n // CRITICAL: This throw MUST come AFTER all hooks (the two\n // useState calls above). React requires the same hooks to run on\n // every render. If we threw before hooks, React would see 0 hooks\n // on the re-render vs 2 hooks on the initial render — triggering\n // the exact \"Rendered more hooks\" error we're trying to prevent.\n //\n // By placing it after hooks but before the return, all hooks\n // satisfy React's rules, but the thrown thenable prevents any\n // children from rendering. Same pattern as Next.js app-router.tsx\n // (pushRef.mpaNavigation — also placed after all hooks).\n if (isHardNavigating()) {\n throw unresolvedThenable;\n }\n\n // Inject TopLoader alongside the element tree inside PendingNavigationProvider.\n // The TopLoader reads pendingUrl from context to show/hide the progress bar.\n // It is rendered only when not explicitly disabled via config.\n const showTopLoader = topLoaderConfig?.enabled !== false;\n const children = showTopLoader\n ? createElement(Fragment, null, createElement(TopLoader, { config: topLoaderConfig }), element)\n : element;\n return createElement(PendingNavigationProvider, { value: pendingUrl }, children);\n}\n\n// ─── Public API ──────────────────────────────────────────────────\n\n/**\n * Trigger a transition render for non-navigation updates.\n * React keeps the old committed tree visible while any new Suspense\n * boundaries in the update resolve.\n *\n * Used for: applyRevalidation, popstate replay with cached payload.\n */\nexport function transitionRender(element: ReactNode): void {\n if (_transitionRender) {\n _transitionRender(element);\n }\n}\n\n/**\n * Run a full navigation inside a React transition with optimistic pending URL.\n *\n * The `perform` callback runs inside `startTransition` — it should fetch the\n * RSC payload, update router state, and return the wrapped React element.\n * The pending URL shows immediately (urgent update) and reverts\n * to null when the transition commits (atomic with the new tree).\n *\n * Returns a Promise that resolves when the async work completes (note: the\n * React transition may not have committed yet, but all state updates are done).\n *\n * Used for: navigate(), refresh(), popstate with fetch.\n */\nexport function navigateTransition(\n pendingUrl: string,\n perform: () => Promise<ReactNode>\n): Promise<void> {\n if (_navigateTransition) {\n return _navigateTransition(pendingUrl, perform);\n }\n // Fallback: no NavigationRoot mounted (shouldn't happen in production)\n return perform().then(() => {});\n}\n\n/**\n * Check if the NavigationRoot is mounted and ready for renders.\n * Used by browser-entry.ts to guard against renders before hydration.\n */\nexport function isNavigationRootReady(): boolean {\n return _transitionRender !== null;\n}\n\n/**\n * Install one-shot deferred callbacks for the no-RSC bootstrap path (TIM-600).\n *\n * When there's no RSC payload, we can't create a React root immediately —\n * `createRoot(document).render(...)` would blank the SSR HTML. Instead,\n * this sets up `_transitionRender` and `_navigateTransition` so that the\n * first client navigation triggers root creation via `createAndMount`.\n *\n * After `createAndMount` runs, NavigationRoot renders and overwrites these\n * callbacks with its real `startTransition`-based implementations.\n */\nexport function installDeferredNavigation(createAndMount: (initial: ReactNode) => void): void {\n let mounted = false;\n const mountOnce = (element: ReactNode) => {\n if (mounted) return;\n mounted = true;\n createAndMount(element);\n };\n _transitionRender = (element: ReactNode) => {\n mountOnce(element);\n };\n _navigateTransition = async (_pendingUrl: string, perform: () => Promise<ReactNode>) => {\n const element = await perform();\n mountOnce(element);\n };\n}\n"],"mappings":";;;AA+BA,IAAM,mBAAmB,OAAO,IAAI,wBAAwB;;AAM5D,IAAa,YAAwB,EAAE,WAAW,OAAO;AAIzD,SAAS,WAAoD;CAC3D,MAAM,IAAI;AACV,KAAI,CAAC,EAAE,kBACL,GAAE,oBAAoB,EAAE,SAAS,MAAM;AAEzC,QAAO,EAAE;;;;;;;;;;;AAcX,SAAgB,4BAA4B,MAAwC;CAClF,MAAM,QAAQ,UAAU;AACxB,OAAM,UAAU;;;;;AA2ClB,SAAgB,gCAAgC,MAAiC;CAC/E,MAAM,QAAQ,UAAU;AACxB,KAAI,MAAM,YAAY,KACpB,OAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AE7BpB,IAAM,eAAe,OAAO,IAAI,2BAA2B;AAE3D,SAAS,kBAAsC;CAC7C,MAAM,IAAI;AACV,KAAI,CAAC,EAAE,cACL,GAAE,gBAAgB,EAAE,OAAO,OAAO;AAEpC,QAAO,EAAE;;;;;;;;AASX,SAAgB,kBAAkB,OAAsB;AACtD,kBAAiB,CAAC,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-segment-params-Du7u25cK.js","names":[],"sources":["../../src/client/navigation-context.ts","../../src/client/use-segment-params.ts"],"sourcesContent":["'use client';\n\n/**\n * NavigationContext — React context for navigation state.\n *\n * Holds the current route params and pathname, updated atomically\n * with the RSC tree on each navigation. This replaces the previous\n * useSyncExternalStore approach for useSegmentParams() and usePathname(),\n * which suffered from a timing gap: the new tree could commit before\n * the external store re-renders fired, causing a frame where both\n * old and new active states were visible simultaneously.\n *\n * By wrapping the RSC payload element in NavigationProvider inside\n * renderRoot(), the context value and the element tree are passed to\n * reactRoot.render() in the same call — atomic by construction.\n * All consumers (useParams, usePathname) see the new values in the\n * same render pass as the new tree.\n *\n * During SSR, no NavigationProvider is mounted. Hooks fall back to\n * the ALS-backed getSsrData() for per-request isolation.\n *\n * IMPORTANT: createContext and useContext are NOT available in the RSC\n * environment (React Server Components use a stripped-down React).\n * The context is lazily initialized on first access, and all functions\n * that depend on these APIs are safe to call from any environment —\n * they return null or no-op when the APIs aren't available.\n *\n * SINGLETON GUARANTEE: All shared mutable state uses globalThis via\n * Symbol.for keys. The RSC client bundler can duplicate this module\n * across chunks (browser-entry graph + client-reference graph). With\n * ESM output, each chunk gets its own module scope — module-level\n * variables would create separate singleton instances per chunk.\n * globalThis guarantees a single instance regardless of duplication.\n *\n * This workaround will be removed when Rolldown ships `format: 'app'`\n * (module registry format that deduplicates like webpack/Turbopack).\n * See design/27-chunking-strategy.md.\n *\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport React, { createElement, type ReactNode } from 'react';\n\n// ---------------------------------------------------------------------------\n// Context type\n// ---------------------------------------------------------------------------\n\nexport interface NavigationState {\n params: Record<string, string | string[]>;\n pathname: string;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy context initialization\n// ---------------------------------------------------------------------------\n\n/**\n * The context is created lazily to avoid calling createContext at module\n * level. In the RSC environment, React.createContext doesn't exist —\n * calling it at import time would crash the server.\n *\n * Context instances are stored on globalThis (NOT in module-level\n * variables) because the ESM bundler can duplicate this module across\n * chunks. Module-level variables would create separate instances per\n * chunk — the provider in NavigationRoot (index chunk) would use\n * context A while the consumer in usePendingNavigation (shared chunk)\n * reads from context B. globalThis guarantees a single instance.\n *\n * See design/27-chunking-strategy.md §\"Singleton Safety\"\n *\n * NOTE: Despite similar naming, `usePendingNavigationUrl()` here is an\n * internal helper — the public hook is `usePendingNavigation()` in\n * use-pending-navigation.ts.\n */\n\n// Symbol keys for globalThis storage — prevents collisions with user code\nconst NAV_CTX_KEY = Symbol.for('__timber_nav_ctx');\nconst PENDING_CTX_KEY = Symbol.for('__timber_pending_nav_ctx');\n\nfunction getOrCreateContext(): React.Context<NavigationState | null> | undefined {\n const existing = (globalThis as Record<symbol, unknown>)[NAV_CTX_KEY] as\n | React.Context<NavigationState | null>\n | undefined;\n if (existing !== undefined) return existing;\n // createContext may not exist in the RSC environment\n if (typeof React.createContext === 'function') {\n const ctx = React.createContext<NavigationState | null>(null);\n (globalThis as Record<symbol, unknown>)[NAV_CTX_KEY] = ctx;\n return ctx;\n }\n return undefined;\n}\n\n/**\n * Read the navigation context. Returns null during SSR (no provider)\n * or in the RSC environment (no context available).\n * Internal — used by useSegmentParams() and usePathname().\n */\nexport function useNavigationContext(): NavigationState | null {\n const ctx = getOrCreateContext();\n if (!ctx) return null;\n // useContext may not exist in the RSC environment — caller wraps in try/catch\n if (typeof React.useContext !== 'function') return null;\n return React.useContext(ctx);\n}\n\n// ---------------------------------------------------------------------------\n// Provider component\n// ---------------------------------------------------------------------------\n\nexport interface NavigationProviderProps {\n value: NavigationState;\n children?: ReactNode;\n}\n\n/**\n * Wraps children with NavigationContext.Provider.\n *\n * Used in browser-entry.ts renderRoot to wrap the RSC payload element\n * so that navigation state updates atomically with the tree render.\n */\nexport function NavigationProvider({\n value,\n children,\n}: NavigationProviderProps): React.ReactElement {\n const ctx = getOrCreateContext();\n if (!ctx) {\n // RSC environment — no context available. Return children as-is.\n return children as React.ReactElement;\n }\n return createElement(ctx.Provider, { value }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Module-level state for renderRoot to read\n// ---------------------------------------------------------------------------\n\n/**\n * Navigation state communicated between the router and renderRoot.\n *\n * The router calls setNavigationState() before renderRoot(). The\n * renderRoot callback reads via getNavigationState() to create the\n * NavigationProvider with the correct params/pathname.\n *\n * This is NOT used by hooks directly — hooks read from React context.\n *\n * Stored on globalThis (like the context instances above) because the\n * router lives in one chunk while renderRoot lives in another. Module-\n * level variables would be separate per chunk.\n */\nconst NAV_STATE_KEY = Symbol.for('__timber_nav_state');\n\nfunction _getNavStateStore(): { current: NavigationState } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[NAV_STATE_KEY]) {\n g[NAV_STATE_KEY] = { current: { params: {}, pathname: '/' } };\n }\n return g[NAV_STATE_KEY] as { current: NavigationState };\n}\n\nexport function setNavigationState(state: NavigationState): void {\n _getNavStateStore().current = state;\n}\n\nexport function getNavigationState(): NavigationState {\n return _getNavStateStore().current;\n}\n\n// ---------------------------------------------------------------------------\n// Pending Navigation Context (same module for singleton guarantee)\n// ---------------------------------------------------------------------------\n\n/**\n * Separate context for the in-flight navigation URL. Provided by\n * NavigationRoot (urgent useState), consumed by usePendingNavigation\n * and TopLoader. Per-link pending state uses useOptimistic instead\n * (see link-pending-store.ts).\n *\n * Uses globalThis via Symbol.for for the same reason as NavigationContext\n * above — the bundler may duplicate this module across chunks, and module-\n * level variables would create separate context instances.\n */\n\nfunction getOrCreatePendingContext(): React.Context<string | null> | undefined {\n const existing = (globalThis as Record<symbol, unknown>)[PENDING_CTX_KEY] as\n | React.Context<string | null>\n | undefined;\n if (existing !== undefined) return existing;\n if (typeof React.createContext === 'function') {\n const ctx = React.createContext<string | null>(null);\n (globalThis as Record<symbol, unknown>)[PENDING_CTX_KEY] = ctx;\n return ctx;\n }\n return undefined;\n}\n\n/**\n * Read the pending navigation URL from context.\n * Returns null during SSR (no provider) or in the RSC environment.\n */\nexport function usePendingNavigationUrl(): string | null {\n const ctx = getOrCreatePendingContext();\n if (!ctx) return null;\n if (typeof React.useContext !== 'function') return null;\n return React.useContext(ctx);\n}\n\n/**\n * Provider for the pending navigation URL. Wraps children with\n * the pending context Provider.\n */\nexport function PendingNavigationProvider({\n value,\n children,\n}: {\n value: string | null;\n children?: ReactNode;\n}): React.ReactElement {\n const ctx = getOrCreatePendingContext();\n if (!ctx) {\n return children as React.ReactElement;\n }\n return createElement(ctx.Provider, { value }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Navigation API transition state (optional progressive enhancement)\n// ---------------------------------------------------------------------------\n\n/**\n * Check if the browser's Navigation API has an active transition.\n *\n * When the Navigation API is available and a navigation has been intercepted\n * via event.intercept(), `navigation.transition` is non-null until the\n * handler resolves. This provides browser-native progress tracking that\n * can be used alongside the existing pendingUrl mechanism.\n *\n * Returns false when Navigation API is unavailable or no transition is active.\n */\nexport function hasNativeNavigationTransition(): boolean {\n if (typeof window === 'undefined') return false;\n const nav = (window as unknown as { navigation?: { transition?: unknown } }).navigation;\n return nav?.transition != null;\n}\n","/**\n * useParams() — client-side hook for accessing route params.\n *\n * Returns the dynamic route parameters for the current URL.\n * When called with a route pattern argument, TypeScript narrows\n * the return type to the exact params shape for that route.\n *\n * Two layers of type narrowing work together:\n * 1. The generic overload here uses the Routes interface directly —\n * `useParams<R>()` returns `Routes[R]['segmentParams']`.\n * 2. Build-time codegen generates per-route string-literal overloads\n * in the .d.ts file for IDE autocomplete (see routing/codegen.ts).\n *\n * When the Routes interface is empty (no codegen yet), the generic\n * overload has `keyof Routes = never`, so only the fallback matches.\n *\n * During SSR, params are read from the ALS-backed SSR data context\n * (populated by ssr-entry.ts) to ensure correct per-request isolation\n * across concurrent requests with streaming Suspense.\n *\n * Reactivity: On the client, useParams() reads from NavigationContext\n * which is updated atomically with the RSC tree render. This replaces\n * the previous useSyncExternalStore approach that suffered from a\n * timing gap between tree render and store notification — causing\n * preserved layout components to briefly show stale active state.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n *\n * Design doc: design/09-typescript.md §\"Typed Routes\"\n */\n\nimport type { Routes } from '../index.js';\nimport { getSsrData } from './ssr-data.js';\nimport { currentParams, _setCurrentParams, paramsListeners } from './state.js';\nimport { useNavigationContext } from './navigation-context.js';\n\n// ---------------------------------------------------------------------------\n// Module-level subscribe/notify pattern — kept for backward compat and tests\n// ---------------------------------------------------------------------------\n\n/**\n * Subscribe to params changes.\n * Retained for backward compatibility with tests that verify the\n * subscribe/notify contract. On the client, useParams() reads from\n * NavigationContext instead.\n */\nexport function subscribe(callback: () => void): () => void {\n paramsListeners.add(callback);\n return () => paramsListeners.delete(callback);\n}\n\n/**\n * Get the current params snapshot (module-level fallback).\n * Used by tests and by the hook when called outside a React component.\n */\nexport function getSnapshot(): Record<string, string | string[]> {\n return currentParams;\n}\n\n// ---------------------------------------------------------------------------\n// Framework API — called by the segment router on each navigation\n// ---------------------------------------------------------------------------\n\n/**\n * Set the current route params in the module-level store.\n *\n * Called by the router on each navigation. This updates the fallback\n * snapshot used by tests and by the hook when called outside a React\n * component (no NavigationContext available).\n *\n * On the client, the primary reactivity path is NavigationContext —\n * the router calls setNavigationState() then renderRoot() which wraps\n * the element in NavigationProvider. setCurrentParams is still called\n * for the module-level fallback.\n *\n * During SSR, params are also available via getSsrData().params\n * (ALS-backed).\n */\nexport function setCurrentParams(params: Record<string, string | string[]>): void {\n _setCurrentParams(params);\n}\n\n/**\n * Notify all legacy subscribers that params have changed.\n *\n * Retained for backward compatibility with tests. On the client,\n * the NavigationContext + renderRoot pattern replaces this — params\n * update atomically with the tree render, so explicit notification\n * is no longer needed.\n */\nexport function notifyParamsListeners(): void {\n for (const listener of paramsListeners) {\n listener();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public hook\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current route's dynamic params.\n *\n * The optional `_route` argument exists only for TypeScript narrowing —\n * it does not affect the runtime return value.\n *\n * On the client, reads from NavigationContext (provided by\n * NavigationProvider in renderRoot). This ensures params update\n * atomically with the RSC tree — no timing gap.\n *\n * During SSR, reads from the ALS-backed SSR data context to ensure\n * per-request isolation across concurrent requests with streaming Suspense.\n *\n * When called outside a React component (e.g., in test assertions),\n * falls back to the module-level snapshot.\n *\n * @overload Typed — when a known segment path is passed, returns the\n * exact params shape from the generated Routes interface.\n * @overload Fallback — returns the generic params record.\n */\nexport function useSegmentParams<R extends keyof Routes>(\n segmentPath: R\n): Routes[R] extends { segmentParams: infer P } ? P : Record<string, string | string[]>;\nexport function useSegmentParams(segmentPath?: string): Record<string, string | string[]>;\nexport function useSegmentParams(_segmentPath?: string): Record<string, string | string[]> {\n // Try reading from NavigationContext (client-side, inside React tree).\n // During SSR, no NavigationProvider is mounted, so this returns null.\n // When called outside a React component, useContext throws — caught below.\n try {\n const navContext = useNavigationContext();\n if (navContext !== null) {\n return navContext.params;\n }\n } catch {\n // No React dispatcher available (called outside a component).\n // Fall through to module-level snapshot below.\n }\n\n // SSR path: read from ALS-backed SSR data context.\n // Falls back to module-level currentParams for tests.\n return getSsrData()?.params ?? currentParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,IAAM,cAAc,OAAO,IAAI,mBAAmB;AAClD,IAAM,kBAAkB,OAAO,IAAI,2BAA2B;AAE9D,SAAS,qBAAwE;CAC/E,MAAM,WAAY,WAAuC;AAGzD,KAAI,aAAa,KAAA,EAAW,QAAO;AAEnC,KAAI,OAAO,MAAM,kBAAkB,YAAY;EAC7C,MAAM,MAAM,MAAM,cAAsC,KAAK;AAC5D,aAAuC,eAAe;AACvD,SAAO;;;;;;;;AAUX,SAAgB,uBAA+C;CAC7D,MAAM,MAAM,oBAAoB;AAChC,KAAI,CAAC,IAAK,QAAO;AAEjB,KAAI,OAAO,MAAM,eAAe,WAAY,QAAO;AACnD,QAAO,MAAM,WAAW,IAAI;;;;;;;;AAkB9B,SAAgB,mBAAmB,EACjC,OACA,YAC8C;CAC9C,MAAM,MAAM,oBAAoB;AAChC,KAAI,CAAC,IAEH,QAAO;AAET,QAAO,cAAc,IAAI,UAAU,EAAE,OAAO,EAAE,SAAS;;;;;;;;;;;;;;;AAoBzD,IAAM,gBAAgB,OAAO,IAAI,qBAAqB;AAEtD,SAAS,oBAAkD;CACzD,MAAM,IAAI;AACV,KAAI,CAAC,EAAE,eACL,GAAE,iBAAiB,EAAE,SAAS;EAAE,QAAQ,EAAE;EAAE,UAAU;EAAK,EAAE;AAE/D,QAAO,EAAE;;AAGX,SAAgB,mBAAmB,OAA8B;AAC/D,oBAAmB,CAAC,UAAU;;AAGhC,SAAgB,qBAAsC;AACpD,QAAO,mBAAmB,CAAC;;;;;;;;;;;;AAkB7B,SAAS,4BAAsE;CAC7E,MAAM,WAAY,WAAuC;AAGzD,KAAI,aAAa,KAAA,EAAW,QAAO;AACnC,KAAI,OAAO,MAAM,kBAAkB,YAAY;EAC7C,MAAM,MAAM,MAAM,cAA6B,KAAK;AACnD,aAAuC,mBAAmB;AAC3D,SAAO;;;;;;;AASX,SAAgB,0BAAyC;CACvD,MAAM,MAAM,2BAA2B;AACvC,KAAI,CAAC,IAAK,QAAO;AACjB,KAAI,OAAO,MAAM,eAAe,WAAY,QAAO;AACnD,QAAO,MAAM,WAAW,IAAI;;;;;;;;;;;;;;;;;;;AC7H9B,SAAgB,iBAAiB,QAAiD;AAChF,mBAAkB,OAAO;;AA6C3B,SAAgB,iBAAiB,cAA0D;AAIzF,KAAI;EACF,MAAM,aAAa,sBAAsB;AACzC,MAAI,eAAe,KACjB,QAAO,WAAW;SAEd;AAOR,QAAO,YAAY,EAAE,UAAU"}