@timber-js/app 0.2.0-alpha.249 → 0.2.0-alpha.250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{actions-C7_xl9iA.js → actions-DH_TCxJb.js} +2 -2
- package/dist/_chunks/{actions-C7_xl9iA.js.map → actions-DH_TCxJb.js.map} +1 -1
- package/dist/_chunks/dev-span-0aG7Q_Ph.js.map +1 -1
- package/dist/_chunks/{dist-GyaJm4GA.js → dist-ob734WH3.js} +20 -19
- package/dist/_chunks/dist-ob734WH3.js.map +1 -0
- package/dist/_chunks/{error-boundary-wuNvAJ4n.js → error-boundary-BR21tTQc.js} +3 -3
- package/dist/_chunks/{error-boundary-wuNvAJ4n.js.map → error-boundary-BR21tTQc.js.map} +1 -1
- package/dist/_chunks/global-context-DbxNWeBP.js +47 -0
- package/dist/_chunks/global-context-DbxNWeBP.js.map +1 -0
- package/dist/_chunks/{navigation-root-Cvb7P1ud.js → navigation-root-AuCD35Sv.js} +42 -47
- package/dist/_chunks/navigation-root-AuCD35Sv.js.map +1 -0
- package/dist/_chunks/ssr-data-BfsCqCLl.js +47 -0
- package/dist/_chunks/ssr-data-BfsCqCLl.js.map +1 -0
- package/dist/client/browser-entry/post-hydration.d.ts +2 -2
- package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
- package/dist/client/browser-entry/scroll.d.ts +11 -8
- package/dist/client/browser-entry/scroll.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/index.js +12 -9
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.d.ts +0 -2
- package/dist/client/internal.d.ts.map +1 -1
- package/dist/client/internal.js +6 -6
- package/dist/client/internal.js.map +1 -1
- package/dist/client/link.d.ts.map +1 -1
- package/dist/client/ssr-data.d.ts +35 -38
- package/dist/client/ssr-data.d.ts.map +1 -1
- package/dist/client/state.d.ts +1 -8
- package/dist/client/state.d.ts.map +1 -1
- package/dist/client/use-cookie.d.ts.map +1 -1
- package/dist/client/use-search-params.d.ts.map +1 -1
- package/dist/cookies/index.js +3 -3
- package/dist/cookies/index.js.map +1 -1
- package/dist/native/rsc/client/global-context.js +20 -0
- package/dist/native/rsc/client/global-context.js.map +1 -0
- package/dist/native/rsc/client/ssr-data.js +9 -4
- package/dist/native/rsc/client/ssr-data.js.map +1 -1
- package/dist/native/rsc/client/use-cookie.js +4 -4
- package/dist/native/rsc/client/use-cookie.js.map +1 -1
- package/dist/native/rsc/manifest.json +1 -1
- package/dist/native/rsc/server/build-manifest.js +1 -4
- package/dist/native/rsc/server/build-manifest.js.map +1 -1
- package/dist/native/rsc/server/html-injectors.js +6 -7
- package/dist/native/rsc/server/html-injectors.js.map +1 -1
- package/dist/native/rsc/server/react-cache-bridge.js +2 -2
- package/dist/native/rsc/server/react-cache-bridge.js.map +1 -1
- package/dist/native/rsc/server/rsc-entry/render-route.js +3 -5
- package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
- package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +3 -2
- package/dist/native/rsc/server/rsc-entry/ssr-renderer.js.map +1 -1
- package/dist/native/ssr/client/link.js +10 -8
- package/dist/native/ssr/client/link.js.map +1 -1
- package/dist/native/ssr/client/ssr-data.js +10 -6
- package/dist/native/ssr/client/ssr-data.js.map +1 -1
- package/dist/native/ssr/client/state.js +1 -5
- package/dist/native/ssr/client/state.js.map +1 -1
- package/dist/native/ssr/client/use-cookie.js +2 -2
- package/dist/native/ssr/client/use-cookie.js.map +1 -1
- package/dist/native/ssr/client/use-search-params.js +3 -2
- package/dist/native/ssr/client/use-search-params.js.map +1 -1
- package/dist/native/ssr/server/ssr-wrappers.js +11 -4
- package/dist/native/ssr/server/ssr-wrappers.js.map +1 -1
- package/dist/server/build-manifest.d.ts +0 -7
- package/dist/server/build-manifest.d.ts.map +1 -1
- package/dist/server/html-injectors.d.ts +5 -4
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal.js +1 -1
- package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -0
- package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
- package/dist/server/ssr-bridge-types.d.ts +6 -0
- package/dist/server/ssr-bridge-types.d.ts.map +1 -1
- package/dist/server/ssr-entry.d.ts.map +1 -1
- package/dist/server/ssr-wrappers.d.ts +14 -9
- package/dist/server/ssr-wrappers.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/client/browser-entry/post-hydration.ts +27 -22
- package/src/client/browser-entry/scroll.ts +12 -9
- package/src/client/internal.ts +0 -4
- package/src/client/link.tsx +14 -13
- package/src/client/ssr-data.ts +50 -57
- package/src/client/state.ts +1 -14
- package/src/client/use-cookie.ts +4 -3
- package/src/client/use-search-params.ts +5 -4
- package/src/server/build-manifest.ts +0 -10
- package/src/server/html-injectors.ts +11 -13
- package/src/server/rsc-entry/render-route.ts +9 -8
- package/src/server/rsc-entry/ssr-renderer.ts +4 -1
- package/src/server/ssr-bridge-types.ts +6 -0
- package/src/server/ssr-entry.ts +180 -207
- package/src/server/ssr-wrappers.tsx +52 -14
- package/dist/_chunks/dist-GyaJm4GA.js.map +0 -1
- package/dist/_chunks/navigation-root-Cvb7P1ud.js.map +0 -1
- package/dist/_chunks/ssr-data-9hPtcNOr.js +0 -48
- package/dist/_chunks/ssr-data-9hPtcNOr.js.map +0 -1
- package/dist/_chunks/state-B-EBjeER.js +0 -49
- package/dist/_chunks/state-B-EBjeER.js.map +0 -1
- package/dist/native/rsc/client/state.js +0 -14
- package/dist/native/rsc/client/state.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.js","names":[],"sources":["../../src/client/segment-cache.ts","../../src/client/history.ts","../../src/client/router-lifecycle.ts","../../src/client/router-pipeline.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// Segment Cache — the mounted segment tree, and prefetched payloads.\n// See design/19-client-navigation.md for architecture details.\n\nimport type { PublishedParams } from '../shared/payload-root.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport { createSingleflight } from '../cache/singleflight.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n /**\n * Completion of the full Flight stream, when the prefetch is still decoding.\n * Carried through to the navigation that consumes the entry so a decode\n * failure reaches *that* navigation's recovery rather than dying with the\n * prefetch (TIM-1275).\n */\n decodePromise?: Promise<void> | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /**\n * The params published beside `payload`, split off the same payload root.\n * Carried so a consumed prefetch publishes the params of the tree it is\n * about to render, and not the ones already on screen.\n */\n params?: PublishedParams | Promise<PublishedParams>;\n}\n\n// ─── Segment Cache ───────────────────────────────────────────────\n\n/**\n * The client's record of which layout-bearing segments are mounted — the\n * `treePaths` half of `X-Timber-State-Tree`, which the server reads for\n * interception scoping (TIM-1282).\n *\n * Content reuse is not decided here. The outlet content cache holds what the\n * client can reuse, keyed by key digest (client/outlet-content-cache.ts,\n * design/53-segment-lifetime.md).\n *\n * Written only by a navigation's commit (`navigation-commit.ts`), so a\n * superseded navigation never describes the mounted tree (TIM-1301).\n */\nexport class SegmentCache {\n private paths: string[] = [];\n\n /** Replace the record with the chain a committed page mounted. */\n record(segmentInfo: readonly SegmentInfo[]): void {\n this.paths = segmentInfo.flatMap((info) => (info.treePath ? [info.treePath] : []));\n }\n\n clear(): void {\n this.paths = [];\n }\n\n /** The `app/` directory paths of the mounted segments, root first. */\n treePaths(): string[] {\n return [...this.paths];\n }\n}\n\n// ─── Prefetch Cache ──────────────────────────────────────────────\n\ninterface ReadyEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/** Sentinel value for negative cache entries (URL is not a route). */\nconst NEGATIVE_ENTRY: PrefetchResult = Object.freeze({ payload: null });\n\n/**\n * Timeout for the in-flight singleflight (TIM-1438). Per CLAUDE.md's\n * singleflight rule: \"Never write a coalescing Map without a timeout.\"\n * A hung prefetch cannot block clicks or suppress hovers forever.\n */\nconst PREFETCH_SINGLEFLIGHT_TIMEOUT_MS = 5_000;\n\n/**\n * Identifies a prefetched payload. A payload is addressed by *every* input that\n * changes the server's answer, not by the destination alone.\n *\n * The server's answer for a destination depends on where the request came\n * from — that is the whole mechanism behind intercepting routes, and it also\n * drives slot-skip resolution. A prefetch issued from `/gallery` is a modal\n * payload; the same URL prefetched from `/` is the full page. Keying on the\n * destination alone let the first click after a hover be answered with\n * whichever variant happened to be fetched (TIM-1265).\n *\n * `from` alone stopped being enough in TIM-1282. It is a pathname, and once\n * interception scope comes from the rendered tree rather than the address, one\n * pathname no longer names one source tree: `/photo/1` is the address both for\n * a modal open over `(browse)` and for `(landing)`'s canonical page. A key\n * without the scope hands the modal payload to the canonical page's click,\n * which renders it without the server's scope check ever running.\n *\n * The two reads happen at different instants — `scope` is sampled at hover and\n * again at click — which is why a tree that changed in between produces a\n * *miss* and a refetch rather than a wrong hit.\n */\nexport interface PrefetchKey {\n /** Destination URL — hash-less `pathname + search`, as navigate() fetches it. */\n url: string;\n /** Departing pathname — the `X-Timber-URL` the prefetch was issued with. */\n from: string;\n /**\n * The rendered scope the prefetch was issued with — the `treePaths` half of\n * `X-Timber-State-Tree`, joined. Empty when none crossed.\n */\n scope: string;\n}\n\n/**\n * Compose the map key. Length-prefixed rather than delimiter-joined for the\n * same reason `shared/rsc-cache-key.ts` is: any delimiter is forgeable by a\n * value containing it, and a URL may contain any character a delimiter could.\n */\nfunction prefetchMapKey(key: PrefetchKey): string {\n return `${key.from.length}:${key.from}:${key.scope.length}:${key.scope}:${key.url}`;\n}\n\n/**\n * The `scope` half of a `PrefetchKey`, derived from the state tree that will\n * actually be sent. Taking it from the header value rather than re-walking the\n * cache is the point: the key varies by exactly what the request varies by.\n */\nexport function prefetchScopeOf(stateTree: StateTree | undefined): string {\n return stateTree?.treePaths?.join('\\u0000') ?? '';\n}\n\n/** Outcome of a prefetch flight — discriminated so NonRscResponse is a\n * success (stores a negative entry) rather than a rejection.\n * `startGen` is the eviction generation at flight start — joiners that\n * started after a gen bump must reject pre-invalidation results (TIM-1464). */\nexport type FlightOutcome =\n | { kind: 'ready'; result: PrefetchResult; startGen: number }\n | { kind: 'non-route'; startGen: number };\n\n/**\n * Short-lived cache for hover-triggered prefetches. Entries expire after\n * 30 seconds. When a link is clicked, the prefetched payload is consumed\n * (moved to the history stack) and removed from this cache.\n *\n * In-flight dedup (TIM-1438): concurrent fetches for the same key are\n * coalesced by a `createSingleflight` instance. A hover starts a flight;\n * a click for the same key joins it instead of issuing a duplicate. The\n * singleflight enforces a 5-second timeout and cleans up automatically\n * on settlement.\n *\n * timber.js does NOT prefetch on viewport intersection — only explicit\n * hover on <Link prefetch> triggers a prefetch.\n */\nexport class PrefetchCache {\n private static readonly TTL_MS = 30_000;\n private entries = new Map<string, ReadyEntry>();\n private flights = createSingleflight({ timeoutMs: PREFETCH_SINGLEFLIGHT_TIMEOUT_MS });\n private evictionGen = 0;\n\n set(key: PrefetchKey, result: PrefetchResult): void {\n this.entries.set(prefetchMapKey(key), {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(key: PrefetchKey): PrefetchResult | undefined {\n const mapKey = prefetchMapKey(key);\n const entry = this.entries.get(mapKey);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(mapKey);\n return undefined;\n }\n return entry.result;\n }\n\n /** True if a ready or negative entry exists for this key. */\n has(key: PrefetchKey): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(key: PrefetchKey): PrefetchResult | undefined {\n const result = this.get(key);\n if (result !== undefined) {\n this.entries.delete(prefetchMapKey(key));\n }\n return result;\n }\n\n /**\n * Fetch or coalesce with an in-flight fetch for this key (TIM-1438).\n *\n * Concurrent callers (hover + click, repeated hovers) get the same\n * promise. On success the result is stored as a ready entry. On\n * NonRscResponse a negative entry is stored and the outcome is\n * `{ kind: 'non-route' }`. Other errors (network, version skew)\n * reject — the singleflight cleans up the key and subsequent callers\n * retry.\n *\n * The singleflight signal is passed to `doFetch` so a timed-out flight\n * aborts the underlying fetch rather than leaving it running.\n */\n fetchOrCoalesce(\n key: PrefetchKey,\n doFetch: (signal: AbortSignal) => Promise<PrefetchResult>,\n isNonRoute: (error: unknown) => boolean\n ): Promise<FlightOutcome> {\n // Capture the eviction generation before the flight starts. If an\n // action evicts caches while this flight is in progress, the gen\n // will have bumped and the stale result is discarded (TIM-1476).\n // The starting gen is also included in the outcome so joiners\n // that started after a gen bump can detect pre-invalidation\n // results (TIM-1464).\n const genAtStart = this.evictionGen;\n return this.flights.do(prefetchMapKey(key), async (signal) => {\n try {\n const result = await doFetch(signal);\n if (!signal.aborted && this.evictionGen === genAtStart) this.set(key, result);\n return { kind: 'ready' as const, result, startGen: genAtStart };\n } catch (err) {\n if (isNonRoute(err)) {\n if (!signal.aborted && this.evictionGen === genAtStart) this.setNegative(key);\n return { kind: 'non-route' as const, startGen: genAtStart };\n }\n throw err;\n }\n });\n }\n\n /**\n * Join an in-flight singleflight fetch if one exists for this key.\n * Returns the in-flight promise or undefined. Used by the click path to\n * coalesce with a hover prefetch without starting a new flight — when no\n * flight exists, the click issues its own fetch with the navigation's\n * abort signal so superseded navigations abort immediately (TIM-1438).\n */\n joinInflight(key: PrefetchKey): Promise<FlightOutcome> | undefined {\n return this.flights.get(prefetchMapKey(key)) as Promise<FlightOutcome> | undefined;\n }\n\n /**\n * Store a negative entry — the URL is not a route (non-RSC Content-Type).\n *\n * Keyed like every other entry even though \"not a route\" does not actually\n * vary by departing URL: a source-independent negative would be a second\n * keying rule to keep correct, and the only cost of the uniform one is a\n * repeated fetch for a link hovered from a second page.\n */\n setNegative(key: PrefetchKey): void {\n this.set(key, NEGATIVE_ENTRY);\n }\n\n /** Check if the entry is a negative cache entry (URL is not a route). */\n isNegative(key: PrefetchKey): boolean {\n return this.get(key) === NEGATIVE_ENTRY;\n }\n\n /**\n * Evict all ready entries and fence in-flight singleflights (TIM-1476).\n * Called after a server action that revalidated data — the mutation may\n * affect any route, not just the paths the server named. In-flight\n * singleflights are not aborted (they may carry post-mutation data),\n * but their results are discarded if they complete after eviction:\n * `fetchOrCoalesce` captures the generation before the flight and\n * skips the store when it has been bumped.\n *\n * Consumers that join an in-flight flight via `joinInflight` must\n * check `getEvictionGen()` before and after the await: if the gen\n * changed, the result predates the eviction and must be discarded\n * (codex on #1131 round 2).\n */\n clearReady(): void {\n this.entries.clear();\n this.evictionGen++;\n }\n\n getEvictionGen(): number {\n return this.evictionGen;\n }\n}\n","// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { SegmentInfo } from '../shared/segment-info.ts';\nimport { routerUrlKey } from './router-url.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * The params that payload published. Replaying the tree republishes them,\n * because the client owns the provider now and reads it from here\n * (TIM-1297).\n *\n * Stored beside the tree but never *produced* beside it: both come out of\n * one `splitPayloadRoot` on one decoded root and travel together through\n * `prepareNavigation`, the only producer of an entry. That is the property\n * that matters — when they were derived from separate channels, a replay\n * could restore one route's tree with another route's params (TIM-1037,\n * TIM-1285).\n */\n params: ParamsSource;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next navigation reports the tree paths\n * actually mounted. Without this, the segment cache retains the *previous*\n * page's tree after back-button, and interception scoping reads a tree\n * that is not on screen (TIM-1282).\n */\n segmentInfo?: SegmentInfo[] | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Entries are keyed by pathname + search in the browser's own spelling\n * (`routerUrlKey`), whatever spelling a caller passes: an entry stored by\n * `navigate('/café')` is found by a traversal that reads `/caf%C3%A9` off\n * the address bar, and `/a?` is `/a` (TIM-1541). Used with the History API\n * fallback and the Navigation API.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries have no expiry, but only the 50 most recently used URLs are kept\n * by default. Traversing to an evicted entry fetches a fresh payload.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n private readonly maxEntries: number;\n\n constructor({ maxEntries = 50 }: { maxEntries?: number } = {}) {\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new RangeError('HistoryStack maxEntries must be a positive integer');\n }\n this.maxEntries = maxEntries;\n }\n\n push(url: string, entry: HistoryEntry): void {\n url = routerUrlKey(url);\n // Push runs when a page becomes current (or hydration seeds it). Promote\n // replacements too, so the current page always survives overflow.\n this.entries.delete(url);\n this.entries.set(url, entry);\n if (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next();\n if (!oldest.done) this.entries.delete(oldest.value);\n }\n }\n\n get(url: string): HistoryEntry | undefined {\n url = routerUrlKey(url);\n const entry = this.entries.get(url);\n if (entry) {\n this.entries.delete(url);\n this.entries.set(url, entry);\n }\n return entry;\n }\n\n /** Presence checks (such as hover prefetch probes) do not promote entries. */\n has(url: string): boolean {\n return this.entries.has(routerUrlKey(url));\n }\n\n /**\n * Evict every entry (TIM-1476). Called after a server action that\n * revalidated data — history entries are equally stale since they replay\n * on back/forward without a server check. Clearing forces a fresh fetch on\n * the next traversal.\n *\n * The current page's entry goes too. Nothing reads it for anything but a\n * replay: the segment metadata a revalidation needs is the committer's\n * record of the current page, not this stack's (TIM-1541).\n */\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Navigation Lifecycle — who owns the router, and when a fetch may be cut.\n *\n * One navigation at a time owns the router. This module holds that ownership\n * as a single `RenderOwner` slot, the rule for taking it (`createNavOwner`\n * supersedes), the wrapper every navigation runs inside (`runNavigation`),\n * and the pending store that `TopLoader` and `usePendingNavigation()`\n * subscribe to.\n *\n * TIM-1481: replaced the transition counter, the `handedOffNavAborts` set,\n * and the `AbortController`-as-owner pattern with `RenderOwner`. Supersession\n * is \"take the slot\": settle the previous owner and abort its fetch unless\n * handed off.\n *\n * See design/19-client-navigation.md §\"How Pending State Works\".\n */\n\nimport { createRenderOwner, type RenderOwner } from './navigation-transition.ts';\nimport type { RouterPhase } from './router-types.ts';\n\n/**\n * A snapshot of \"which page, and was a navigation in flight\" at one instant.\n * Captured before an action's POST and compared at response time so the\n * router can tell whether the response still describes the page on screen.\n *\n * `seq` is a monotonic counter bumped on every `createNavOwner` — covering\n * every path through `runNavigation`. `idle` is false when the router is\n * mid-navigation OR a handed-off tree has not yet committed (the\n * handover-to-commit window on the History API fallback).\n *\n * See design/19-client-navigation.md §State Update Invariants (TIM-1474).\n */\nexport interface NavigationEpoch {\n readonly seq: number;\n readonly idle: boolean;\n}\n\nexport interface NavigationLifecycle {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n /**\n * Take ownership of the router, superseding whatever held it. Returns\n * a fresh `RenderOwner` for the new navigation. See the implementation\n * for the two parts of superseding.\n */\n createNavOwner: (\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ) => RenderOwner;\n /**\n * Run `fn` inside the abort/pending/cleanup lifecycle. AbortErrors are\n * swallowed (not application errors); all other errors propagate.\n */\n runNavigation: (\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ) => Promise<void>;\n /**\n * Record that `owner`'s payload has reached React, so its stream is no\n * longer cuttable. No-op when `owner` no longer owns the router.\n */\n markHandedOff: (owner: RenderOwner) => void;\n /** React has committed `owner`'s tree — every earlier handoff is off screen. */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n\n /**\n * Whether a navigation is in flight: from its start until its payload has\n * decoded AND React has committed its tree, whichever is later.\n */\n isPending: () => boolean;\n /** The URL currently being navigated to, or null if idle. */\n getPendingUrl: () => string | null;\n /** Subscribe to pending state changes. */\n onPendingChange: (listener: (pending: boolean) => void) => () => void;\n\n /**\n * Place a revalidation owner in the slot without bumping the navigation\n * sequence. Unlike `createNavOwner`, this does not supersede what's in the\n * slot — the caller (applyActionResult) has already verified the slot is\n * idle via the epoch check. A concurrent navigation will supersede this\n * owner through the normal `createNavOwner` path.\n */\n placeRevalidationOwner: (owner: RenderOwner) => void;\n /** Snapshot the router's navigation state (TIM-1474). */\n epoch: () => NavigationEpoch;\n /** True iff no navigation has started or is in flight since `e` was taken. */\n isEpochCurrent: (e: NavigationEpoch) => boolean;\n /**\n * Run `task` now if the router is idle, otherwise once when it next becomes\n * idle (pending false AND commit done). Single slot — a later request\n * replaces an earlier one (TIM-1474).\n */\n runWhenIdle: (task: () => void) => void;\n /**\n * Subscribe to the router becoming idle (pending false AND commit done):\n * `listener` runs on every such transition until unsubscribed. Unlike\n * `runWhenIdle`, any number of listeners may wait.\n */\n onIdle: (listener: () => void) => () => void;\n /**\n * Subscribe to React committing a navigation's tree — the tree on screen\n * has changed, whether or not its stream has finished decoding (so the\n * router may still be pending). Runs on every commit until unsubscribed,\n * with the committing navigation's `epoch().seq`: a tree handed to React\n * before a later navigation started can still commit after it, and the\n * sequence says which one it was.\n */\n onTreeCommit: (listener: (seq: number) => void) => () => void;\n /**\n * Settle any handed-off-but-uncommitted owners as superseded, then flush\n * the idle task if the router is now idle. Called by `syncShallowSearch`\n * when a shallow URL update displaces a suspended transition — without\n * it, `hasUncommittedNav` stays true indefinitely and `runWhenIdle`\n * tasks never fire (TIM-1480).\n */\n settleHandoffs: () => void;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\nexport function createNavigationLifecycle(): NavigationLifecycle {\n // The single ownership slot. One navigation at a time.\n let current: RenderOwner | null = null;\n\n // A handed-off-but-uncommitted owner that `runNavigation`'s finally has\n // already cleared from `current`. Tracked separately so `createNavOwner`\n // can settle it as superseded if a new navigation starts before the\n // commit (P1 from codex on #1127). Cleared by `forgetOlderHandoffs`\n // (commit) or by `createNavOwner` (supersession).\n let pendingCommit: RenderOwner | null = null;\n\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n let navigationSeq = 0;\n let idleTask: (() => void) | null = null;\n const idleListeners = new Set<() => void>();\n const treeCommitListeners = new Set<(seq: number) => void>();\n // The navigationSeq each owner ran under, for tree-commit listeners.\n const ownerSeq = new WeakMap<RenderOwner, number>();\n\n /**\n * Whether a handed-off tree has not yet committed. Derived from the slot:\n * true when `current` is handed off but not yet settled.\n */\n function hasUncommittedNav(): boolean {\n return (\n pendingCommit !== null || (current !== null && current.handedOff && current.outcome === null)\n );\n }\n\n /**\n * Cancel a navigation's RSC fetch — unless its tree is the one on screen.\n *\n * THE only place a navigation controller is aborted. Every path that gives\n * up on a navigation calls this, so the \"is this tree displayed?\" question\n * is asked once rather than at each site. A new abort path is a call to\n * this, not a copy of `controller.abort()`.\n *\n * See design/19-client-navigation.md §\"A navigation that reached React\n * keeps its stream\".\n */\n function abortUnlessHandedOff(owner: RenderOwner): void {\n if (owner.handedOff) return;\n owner.fetchAbort.abort();\n }\n\n /**\n * Create a new RenderOwner for a navigation, superseding any previous\n * in-flight navigation. Optionally links to an external signal (e.g.,\n * from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with two parts:\n * 1. Abort the previous navigation's fetch — UNLESS its tree is the one on\n * screen, in which case tearing the stream down would error the page the\n * user is currently looking at. See `RenderOwner.handedOff`.\n * 2. Settle the previous owner as 'superseded' so its transition detects\n * it lost and never hands a stale tree to React. This replaces both\n * `supersedeNavigationTransitions()` and the transition counter bump.\n */\n function createNavOwner(\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ): RenderOwner {\n if (current) {\n abortUnlessHandedOff(current);\n current.settle('superseded');\n }\n // A handed-off owner whose runNavigation has already finished but whose\n // tree hasn't committed yet. Settle it so its `committed` resolves.\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n pendingCommit = null;\n }\n navigationSeq += 1;\n const owner = createRenderOwner(kind);\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n //\n // This is a second, independent way a navigation dies, and it fires for\n // the same reason as the branch above: the browser aborts a\n // NavigateEvent's signal when that navigation is superseded. So it needs\n // the same guard — without it, an intercepted push/replace or traversal\n // whose tree is already on screen still loses its stream, and the guard\n // above only appears to work because plain `router.navigate()` carries no\n // external signal (codex on #1004).\n if (externalSignal) {\n if (externalSignal.aborted) {\n abortUnlessHandedOff(owner);\n } else {\n externalSignal.addEventListener('abort', () => abortUnlessHandedOff(owner), { once: true });\n }\n }\n\n return owner;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify subscribers. This is the ONLY pending representation — React and\n // non-React consumers alike read it, React ones through\n // `usePendingNavigation()`'s `useSyncExternalStore` (TIM-1307).\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavOwner + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const owner = createNavOwner('navigation', externalSignal);\n setPending(true, url);\n let failed = false;\n try {\n await fn(owner);\n } catch (error) {\n if (isAbortError(error)) return;\n failed = true;\n throw error;\n } finally {\n if (current === owner) {\n current = null;\n // A tree handed to React but not yet committed is still loading as\n // far as the user can see: React may be rendering it for a while\n // after the stream finishes decoding. Pending stays on until the\n // commit (forgetOlderHandoffs) or a supersession clears it, so the\n // loader ends on the later of decode and commit. A navigation that\n // failed ends now: its tree may never commit (design/19 §\"How\n // Pending State Works\").\n if (failed || pendingCommit !== owner) {\n setPending(false);\n flushIdleTask();\n }\n }\n }\n }\n\n // Every place the router may have just become idle calls this.\n function flushIdleTask(): void {\n if (routerPhase.phase !== 'idle' || hasUncommittedNav()) return;\n for (const listener of [...idleListeners]) listener();\n if (!idleTask) return;\n const task = idleTask;\n idleTask = null;\n task();\n }\n\n return {\n currentOwner: () => current,\n createNavOwner,\n runNavigation,\n\n // Guarded on still owning the router. A superseded navigation can still\n // reach here: a prefetch hit answers from `prefetchCache`, whose payload\n // was fetched under the PREFETCH's controller, so aborting this\n // navigation's controller does not stop it and `perform()` runs to\n // completion. `navigateTransition`'s stale check happens after\n // `perform()` returns, so without this the loser would claim ownership\n // moments before being discarded — and the next navigation would then\n // abort the winner's still-streaming response, erroring the visible tree\n // (codex on #1004).\n markHandedOff(owner: RenderOwner): void {\n if (current !== owner) return;\n owner.handedOff = true;\n pendingCommit = owner;\n },\n\n // React has committed THIS tree, so every earlier one is unmounted and\n // their streams no longer feed anything on screen. The owner's `handedOff`\n // boolean already captured the individual state; settling clears the\n // \"uncommitted\" window. Unlike the old `handedOffNavAborts` set, there is\n // no set to prune — the single slot means at most one owner is current.\n forgetOlderHandoffs(owner: RenderOwner): void {\n owner.settle('committed');\n if (pendingCommit === owner) {\n pendingCommit = null;\n // runNavigation already finished decoding and left pending on for\n // this commit. If it is still decoding, its finally clears pending.\n if (current !== owner) setPending(false);\n }\n const seq = ownerSeq.get(owner) ?? navigationSeq;\n for (const listener of [...treeCommitListeners]) listener(seq);\n flushIdleTask();\n },\n\n placeRevalidationOwner(owner: RenderOwner): void {\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n },\n\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n\n epoch(): NavigationEpoch {\n return {\n seq: navigationSeq,\n idle: routerPhase.phase === 'idle' && !hasUncommittedNav(),\n };\n },\n isEpochCurrent(e: NavigationEpoch): boolean {\n return (\n e.idle && routerPhase.phase === 'idle' && !hasUncommittedNav() && navigationSeq === e.seq\n );\n },\n runWhenIdle(task: () => void): void {\n if (routerPhase.phase === 'idle' && !hasUncommittedNav()) {\n task();\n return;\n }\n idleTask = task;\n },\n\n onIdle(listener) {\n idleListeners.add(listener);\n return () => idleListeners.delete(listener);\n },\n\n onTreeCommit(listener) {\n treeCommitListeners.add(listener);\n return () => treeCommitListeners.delete(listener);\n },\n\n settleHandoffs(): void {\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n // Its runNavigation may already have finished and left pending on\n // for a commit that will now never come.\n if (current !== pendingCommit) setPending(false);\n pendingCommit = null;\n }\n if (current !== null && current.handedOff && current.outcome === null) {\n current.settle('superseded');\n }\n flushIdleTask();\n },\n };\n}\n","/**\n * Navigation Pipeline — URL in, tree in React's hands.\n *\n * Everything between \"the user asked for this URL\" and \"React is holding the\n * destination's tree\": consult the prefetch cache or fetch, prepare the commit\n * that makes the page current, and hand the result over inside a transition.\n *\n * `router.ts` keeps the *operations* — `navigate`, `refresh`, `handlePopState`,\n * `prefetch`, `applyActionResult` — and each of them is a call into here. The\n * split is the same one `router-effects.ts` and `router-lifecycle.ts` made\n * (design/18-build-system.md §\"No file >500 lines\").\n *\n * See design/19-client-navigation.md §\"Partial Rendering\" and §\"Prefetching\".\n */\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport type { FetchResult } from './rsc-fetch.ts';\nimport { readPublishedParams } from '../shared/payload-root.ts';\nimport type { PrefetchCache, PrefetchKey } from './segment-cache.ts';\nimport { prefetchScopeOf } from './segment-cache.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport type { NavigationCommitter } from './navigation-commit.ts';\nimport type { RouterDeps } from './router-types.ts';\nimport type { NavigationHandle, RenderOwner } from './navigation-transition.ts';\nimport { recordSkew } from './router-skew.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport { SingleflightTimeoutError } from '../cache/singleflight.ts';\n\n/**\n * Race a promise against an abort signal. The promise continues regardless —\n * only the *await* gives up. Used so a click superseded by a newer navigation\n * stops waiting for a shared prefetch flight without aborting the flight\n * itself (TIM-1438).\n */\nfunction raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(signal.reason);\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n }),\n ]);\n}\n\n/** A fetched payload plus the state update that makes it the current page. */\nexport type NavigationPayload = FetchResult & {\n navState: NavigationState;\n commit: () => void;\n};\n\n/** Options for a single `performNavigationFetch` call. */\nexport interface NavigationFetchOptions {\n replace: boolean;\n commitUrl?: string;\n signal?: AbortSignal;\n departingUrl?: string;\n}\n\nexport interface NavigationPipelineDeps extends Pick<\n NavigationCommitter,\n 'prepareNavigation' | 'currentStateTree'\n> {\n deps: RouterDeps;\n prefetchCache: PrefetchCache;\n /** Record that this navigation's tree reached React (router-lifecycle.ts). */\n markHandedOff: (owner: RenderOwner) => void;\n /** React committed this navigation's tree (router-lifecycle.ts). */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n}\n\nexport interface NavigationPipeline {\n /** Fetch (or replay a prefetch), then stage the commit. */\n performNavigationFetch: (\n url: string,\n options: NavigationFetchOptions\n ) => Promise<NavigationPayload>;\n /** Hand a payload to React inside a transition. */\n renderViaTransition: (\n url: string,\n owner: RenderOwner,\n /** The view transition types the render adds (`NavigationRender`). */\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ) => NavigationHandle;\n}\n\n/**\n * Normalize a departing URL to the pathname the server is told about.\n *\n * This is the value sent as `X-Timber-URL` *and* the source half of the\n * prefetch cache key — one function so a prefetch and the click that consumes\n * it can never disagree about what \"where we came from\" means (TIM-1265). The\n * query is dropped deliberately: it would land in the `_rsc` digest, which is\n * logged (TIM-1268), and nothing downstream reads it — interception scope\n * compares pathnames.\n *\n * Absolute inputs parse against the base and ignore it, so one call handles\n * both `location.href` and a bare pathname.\n */\nexport function departingPathname(raw: string): string {\n return parseRouterUrl(raw).pathname;\n}\n\n/**\n * The prefetch cache key for a destination.\n *\n * Both halves of the cache are keyed through here — the hover that writes an\n * entry (`router.ts`'s `prefetch()`) and the click that consumes it\n * (`performNavigationFetch` below) — so the two cannot disagree about what\n * identifies a payload. That is the whole point of the key: `from` scopes it\n * to the page the link was on (TIM-1265) and `scope` to the tree that was\n * mounted (TIM-1282), and an entry written under one reading of either would\n * simply never be found under the other, silently costing every prefetch.\n *\n * `departingPathname` is applied here rather than by callers for the same\n * reason: it is also what goes out as `X-Timber-URL`, so the key and the\n * request describe the same departure point.\n */\nexport function prefetchKeyFor(\n url: string,\n departingUrl: string,\n stateTree: StateTree | undefined\n): PrefetchKey {\n return { url, from: departingPathname(departingUrl), scope: prefetchScopeOf(stateTree) };\n}\n\n/**\n * Inspect a decode rejection for version skew before handing the promise on,\n * without changing what the consumer sees.\n *\n * The decode rejects independently of the fetch, and not every consumer\n * awaits it — NavigationRoot drops it outright when the transition has been\n * superseded. A stale client reference arriving that way is still evidence\n * the bundle is superseded, so record it here where every consumer is fed\n * from, rather than at each place that might drop it (TIM-1275).\n */\nfunction observeSkew(decodePromise: Promise<void> | null): Promise<void> | null {\n decodePromise?.catch((error: unknown) => void recordSkew(error));\n return decodePromise;\n}\n\nexport function createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n}: NavigationPipelineDeps): NavigationPipeline {\n /**\n * Hand a payload to React via navigateTransition. The perform callback should fetch data, prepare the commit, and return the\n * FetchResult plus the NavigationState and the commit thunk.\n *\n * The thunk is handed *through* to NavigationRoot rather than called here:\n * state management (segment cache, history stack, address bar) has to happen on\n * the far side of the supersession check, which only NavigationRoot can\n * make (TIM-1301).\n */\n function renderViaTransition(\n url: string,\n owner: RenderOwner,\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ): NavigationHandle {\n // Record that THIS navigation's payload has reached React, at the moment\n // the tree is built and handed back for `navigateTransition` to give to\n // React — NOT on commit, which is a whole commit phase too late. See\n // `RenderOwner.handedOff` in router-lifecycle.ts.\n const handOff = (): void => markHandedOff(owner);\n\n // Settle the owner as committed once React has committed this tree.\n // Wrapped around the commit thunk so it runs on React's commit and not\n // at handover; see `forgetOlderHandoffs`.\n const commitAndForget = (commit: () => void) => (): void => {\n forgetOlderHandoffs(owner);\n commit();\n };\n\n return deps.navigateTransition(url, owner, types, async (wrapPayload) => {\n const result = await perform();\n // Await the payload's *root row* — the same thing React would suspend\n // on to render the tree, and the first thing Flight emits. The\n // previous UI stays on screen while this resolves: nothing has been\n // handed to React yet, and when it is, NavigationRoot hands it over\n // inside a transition so a tree that is still streaming does not\n // displace the departing page (TIM-1306).\n //\n // Reading them here rather than with `use()` above the tree is what\n // keeps a decode failure contained: `result.params` never rejects, so\n // it can never take down the provider above every error boundary\n // (TIM-1297). A failure after the root row reaches React through the\n // tree, inside whatever boundary the app put around it.\n const params = await result.params;\n // And the tree itself — settled by the same root row, so this adds no\n // wait, but it is the half that *rejects*: a root row that fails to\n // decode fails this navigation here, before anything is wrapped or\n // handed over, and the router takes its recovery path (TIM-1541).\n // This used to happen by accident — the payload went through an\n // `async` identity helper whose return adopted the thenable — and\n // only on the paths that called it.\n const payload = await result.payload;\n\n // Every navigation renders the payload root. Segments the server\n // skipped render the content the client holds for them, in place\n // (client/segment-outlet.tsx), so their state survives.\n const element = wrapPayload(payload, result.navState, params);\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n });\n }\n\n /**\n * Fetch (or take from the prefetch cache) a navigation's payload and\n * prepare — without publishing — the commit that makes it current.\n */\n async function performNavigationFetch(\n url: string,\n options: NavigationFetchOptions\n ): Promise<NavigationPayload> {\n // Both halves of the key are sampled here, before the prefetch cache is\n // consulted, and both are reused for the request itself:\n //\n // - the departing page, because an entry fetched from somewhere else\n // answers a different question (TIM-1265). `getCurrentUrl()` can't be\n // read any later either — the Navigation API may have already committed\n // the destination URL (TIM-1232).\n // - the mounted tree, so the entry this navigation looks up is keyed by\n // the same scope the fetch would have been issued with (TIM-1282).\n //\n // `currentUrl` is read back off the key rather than computed beside it, so\n // the pathname sent as X-Timber-URL is the one the lookup used.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(url, options.departingUrl ?? deps.getCurrentUrl(), stateTree);\n const currentUrl = cacheKey.from;\n\n // Check prefetch cache first. A negative entry means a prior prefetch\n // determined this URL is not a route (non-RSC Content-Type). Hard-navigate\n // immediately without a second fetch. See TIM-1231.\n if (prefetchCache.isNegative(cacheKey)) {\n prefetchCache.consume(cacheKey);\n throw new NonRscResponse(url);\n }\n\n // PrefetchResult has optional segmentInfo/params fields — normalize\n // to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(cacheKey);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n // A prefetch that predates this field (or the negative-entry\n // sentinel) publishes nothing rather than the previous route's.\n params: prefetched.params ?? readPublishedParams(undefined),\n // Carry the prefetch's stream completion through. It may still be\n // decoding, and a stale client reference arriving after the click\n // must reach *this* navigation's recovery rather than dying with\n // the prefetch that started it (TIM-1275).\n decodePromise: prefetched.decodePromise ?? null,\n segmentInfo: prefetched.segmentInfo ?? null,\n }\n : undefined;\n\n // If a hover prefetch is in-flight, join it instead of issuing a\n // duplicate (TIM-1438). The click races its await against its own signal\n // so a superseded navigation gives up immediately — the shared flight\n // continues for other consumers. On flight failure (network error,\n // singleflight timeout), fall through to a fresh fetch — the failed\n // hover should not block a click that might succeed.\n if (result === undefined) {\n const inflight = prefetchCache.joinInflight(cacheKey);\n if (inflight) {\n // Capture the eviction generation before awaiting the flight.\n // If an action evicts caches while we wait, the result predates\n // the mutation and must be discarded (TIM-1476, codex on #1131).\n // Also check the flight's own starting gen: if the flight started\n // before a per-URL invalidation (TIM-1464), a joiner that arrived\n // after the bump would see genBefore === genAfter but the flight\n // still predates the invalidation.\n const genBefore = prefetchCache.getEvictionGen();\n try {\n const outcome = await raceAbort(inflight, options.signal);\n if (prefetchCache.getEvictionGen() !== genBefore || outcome.startGen !== genBefore) {\n // Eviction happened while we waited, or the flight predates\n // an invalidation we arrived after — discard stale result,\n // fall through to a fresh fetch below.\n } else if (outcome.kind === 'non-route') {\n throw new NonRscResponse(url);\n } else {\n // Consume the ready entry so a second click re-fetches\n prefetchCache.consume(cacheKey);\n result = {\n payload: outcome.result.payload,\n params: outcome.result.params ?? readPublishedParams(undefined),\n decodePromise: outcome.result.decodePromise ?? null,\n segmentInfo: outcome.result.segmentInfo ?? null,\n };\n }\n } catch (error) {\n // Supersession aborts propagate — don't retry a cancelled navigation\n if (error instanceof DOMException && error.name === 'AbortError') throw error;\n if (options.signal?.aborted) throw options.signal.reason;\n // Retriable failures fall through to a fresh fetch: singleflight\n // timeout (hover hung) and transport TypeError (transient network\n // error). Framework control-flow errors — NonRscResponse,\n // VersionSkewError, RedirectError, ServerErrorResponse — are\n // definitive server answers and must reach navigate's recovery.\n if (error instanceof SingleflightTimeoutError || error instanceof TypeError) {\n // fall through to fresh fetch below\n } else {\n throw error;\n }\n }\n }\n }\n\n if (result === undefined) {\n // No in-flight hover prefetch, or the joined flight failed — fetch\n // directly with the navigation's signal so superseded navigations\n // abort immediately. The state tree is resampled: hashes the client\n // recorded while it waited on a joined flight are worth advertising.\n const freshStateTree = currentStateTree();\n result = await fetchRscPayload(url, deps, freshStateTree, currentUrl, options.signal);\n }\n\n // Update the browser history. This is the only place a push/replace\n // navigation moves the address bar, with or without the Navigation API\n // (its listener leaves same-document pushState alone). The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n //\n // Deferred with the rest of the commit: the address bar is navigation\n // state like the segment cache and the history stack, and a superseded\n // navigation must not move it either. That guarantee used to hold only\n // because the superseded fetch was aborted before it got here — a\n // response that won the race anyway re-pushed the abandoned URL\n // (TIM-1022's failure mode, made unconditional by TIM-1301).\n const commitHistoryUrl = (): void => {\n const commitUrl = options.commitUrl ?? url;\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n };\n\n const params = await result.params;\n\n // Prepare the atomic navigation-state update. It is published by the\n // caller once this navigation is known to have won (TIM-1301).\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n });\n\n return {\n ...result,\n params,\n navState,\n commit: () => {\n commitHistoryUrl();\n commit();\n // Notify nuqs (and any other listener) that the URL is now the\n // destination's. It travels *inside* the commit rather than after\n // the navigation resolves because the listener answers it by reading\n // `window.location.search`, and the commit is what moves it — the\n // publish happens on React's commit of the tree, which can land after\n // the navigation promise settles (TIM-1301, codex on #998).\n window.dispatchEvent(new Event('timber:navigation-end'));\n },\n };\n }\n\n return { performNavigationFetch, renderViaTransition };\n}\n","// Segment Router — the operations a client-side navigation can be.\n//\n// `navigate`, `refresh`, `handlePopState`, `prefetch` and `applyActionResult`\n// live here; each is wiring over modules that own one concern apiece:\n//\n// router-types.ts — RouterDeps / RouterInstance / the option shapes\n// router-lifecycle.ts — ownership, supersede, pending store, handoff set\n// router-pipeline.ts — URL in, tree in React's hands\n// router-effects.ts — SPA exits, error recovery, post-paint scroll\n// navigation-commit.ts — every write that makes a page \"current\"\n//\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache } from './segment-cache.ts';\nimport { HistoryStack } from './history.ts';\nimport { createNavigationCommitter } from './navigation-commit.ts';\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport { readPayloadTree, readPublishedParams } from '../shared/payload-root.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport { isClientStale } from './stale-client.ts';\nimport {\n createScrollEffects,\n createSpaExits,\n createNavigationRecovery,\n runAsHandle,\n type NavigationEndings,\n} from './router-effects.ts';\nimport { createNavigationLifecycle } from './router-lifecycle.ts';\nimport { createNavigationPipeline, prefetchKeyFor } from './router-pipeline.ts';\nimport { recordSkew } from './router-skew.ts';\nimport type {\n NavigationOptions,\n NavigationTransitionType,\n RefreshOptions,\n RouterDeps,\n RouterInstance,\n TraverseDirection,\n} from './router-types.ts';\nimport { createRenderOwner, type NavigationHandle } from './navigation-transition.ts';\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n\n // Every write that makes a page \"current\", and the read that reports the\n // current page back to the server. See navigation-commit.ts.\n const { prepareNavigation, currentStateTree, committedSegmentInfo } = createNavigationCommitter({\n segmentCache,\n historyStack,\n outletDocuments: () => deps.outletContentCache?.documents() ?? {},\n });\n\n // Ownership of the router: who is navigating, whose fetch may be cut, and\n // the pending store TopLoader subscribes to. See router-lifecycle.ts.\n const lifecycle = createNavigationLifecycle();\n const {\n currentOwner,\n createNavOwner,\n runNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n isPending,\n getPendingUrl,\n onPendingChange,\n } = lifecycle;\n\n // Fetch → commit → hand to React. See router-pipeline.ts.\n const { performNavigationFetch, renderViaTransition } = createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n });\n\n // Post-paint scroll effects.\n const { restoreScrollAfterPaint, scrollToHashAfterPaint } = createScrollEffects(deps);\n\n // The only ways out of the SPA. Every failure branch that gives up on\n // client-side navigation goes through one of these, so the \"does this\n // navigation still own the router?\" question is asked once rather than\n // per branch (TIM-1275, TIM-1276).\n const { leaveSpaIfOwned, leaveSpaSuperseding } = createSpaExits({\n currentOwner,\n supersede: () => void createNavOwner('navigation'),\n });\n\n // Every way an RSC fetch can fail that the router answers rather than\n // rethrows. Shared by navigate(), refresh(), and traversals so a path that\n // grows a new branch grows it for all of them (TIM-1277).\n const recoverFromNavigationError = createNavigationRecovery({\n currentOwner,\n leaveSpaIfOwned,\n // Hoisted — `navigate` is a function declaration below.\n navigate: (url, { types, replace, scroll }) =>\n navigate(url, { replace, scroll, _renderTypes: types }),\n });\n\n /**\n * Write the current scroll position into the current history entry — the\n * Navigation API's entry state when available, otherwise history.state —\n * and return it. Back restores from there.\n */\n function saveScrollPosition(): number {\n const scrollY = deps.getScrollY();\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(scrollY);\n } else {\n deps.replaceState({ timber: true, scrollY }, '', deps.getCurrentUrl());\n }\n return scrollY;\n }\n\n function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {\n return runAsHandle((endings) => navigateWith(url, options, endings));\n }\n\n async function navigateWith(\n url: string,\n options: NavigationOptions,\n endings: NavigationEndings\n ): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n // A push, a replace, and a server action redirect all move the user\n // forward; the caller's own types ride beside it. A redirect this router\n // follows keeps the types of the render it interrupted instead.\n const types = options._renderTypes ?? [\n 'navigation-forward' satisfies NavigationTransitionType,\n ...(options.transitionTypes ?? []),\n ];\n\n // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The address bar moves only when the destination commits, so it still\n // names the page being left (TIM-1232).\n const departingUrl = deps.getCurrentUrl();\n\n // Save the departing page's scroll position, and keep it for\n // scroll={false} preservation.\n const currentScrollY = saveScrollPosition();\n\n // This bundle has been superseded. Every subsequent navigation is a full\n // document load — it is the only way to get code that matches the server,\n // and it is the recovery for a skew detected on an earlier navigation.\n // Deliberately *not* a reload: recovery rides on navigations the user\n // asked for, so a rollout that keeps serving mismatched builds costs one\n // document load per click instead of a self-issued reload loop (TIM-1275).\n // Scroll is saved above, so back-navigation still restores correctly.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, departingUrl);\n }\n\n await runNavigation(url, async (owner) => {\n try {\n const render = renderViaTransition(fetchUrl, owner, types, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: owner.fetchAbort.signal,\n departingUrl,\n })\n );\n endings.track(render);\n await render;\n\n // Scroll-to-top on forward navigation, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n // `url` is where the user asked to go and `departingUrl` is where\n // they were: a failure here finishes the click as a full document\n // load of the destination, fragment included (TIM-1234). Reloading\n // instead would rebuild the page they were *leaving* and discard\n // the click (TIM-1275).\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n departingUrl,\n { types, replace, scroll },\n endings\n )\n ) {\n return;\n }\n throw error;\n }\n });\n }\n\n /**\n * Fetch a URL's RSC payload, commit it, and render — the pipeline shared by\n * refresh() and an uncached back/forward traversal. Both can be the path\n * that discovers a version skew, and both recover the same way (TIM-1275).\n *\n * Not `performNavigationFetch`: neither caller consults the prefetch cache\n * (there is no link to have hovered) and neither moves the address bar (the\n * browser is already where it is going), so the fetch is a plain one.\n */\n async function fetchCommitAndRender(\n url: string,\n /** The view transition type the render adds. */\n type: NavigationTransitionType,\n endings: NavigationEndings,\n opts: {\n /** Omitted by refresh(): the server renders the complete payload. */\n stateTree?: StateTree;\n /** Restored after paint when present — traversals only. */\n scrollY?: number;\n externalSignal?: AbortSignal;\n } = {}\n ): Promise<void> {\n await runNavigation(\n url,\n async (owner) => {\n try {\n const render = renderViaTransition(url, owner, [type], async () => {\n const result = await fetchRscPayload(\n url,\n deps,\n opts.stateTree,\n undefined,\n owner.fetchAbort.signal\n );\n const params = await result.params;\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, params, navState, commit };\n });\n endings.track(render);\n await render;\n } catch (error) {\n // Neither path is a navigate(), and neither has a caller that\n // handles a rejection — `refresh()` is `void`-called everywhere it\n // is used, and nobody awaits a traversal at all. Without the same\n // recovery `navigate()` gets, a 500 on Back left the user on the\n // old document with an unhandled rejection in the console\n // (TIM-1277).\n //\n // `url` is both the destination and the departure point: the\n // browser has already traversed, and `refresh()` is by definition\n // where it already is. So `hardNavigate()` takes its same-document\n // branch and reloads rather than pushing an entry.\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n url,\n { types: [type], replace: true, scroll: true },\n endings\n )\n )\n return;\n throw error;\n }\n\n if (opts.scrollY !== undefined) restoreScrollAfterPaint(opts.scrollY);\n },\n opts.externalSignal\n );\n }\n\n function refresh(options: RefreshOptions = {}): NavigationHandle {\n return runAsHandle((endings) => refreshWith(options, endings));\n }\n\n async function refreshWith(options: RefreshOptions, endings: NavigationEndings): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n // A refresh on a stale client is a full document load of the current URL.\n // Same rule as navigate(): the RSC fetch would only be answered with\n // another reload signal, and this is caller-initiated, not spontaneous\n // (TIM-1275).\n if (isClientStale()) {\n await leaveSpaSuperseding(currentUrl, currentUrl);\n }\n\n await fetchCommitAndRender(currentUrl, options.transitionType ?? 'refresh', endings);\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal,\n direction: TraverseDirection = 'navigation-traverse'\n ): Promise<void> {\n // A stale client hard-navigates on back/forward too — this path never\n // reaches navigate(), so it needs the same check. `url` is where the\n // browser has *already* traversed to, so leaveSpa's same-document\n // branch reloads there rather than pushing a new entry (TIM-1275).\n //\n // This overrides the cached-payload replay below on purpose. Replaying\n // would work — the payload was decoded by this bundle — but it would keep\n // the user on superseded code for as long as they browse within history.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, url);\n }\n\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip.\n //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async (owner) => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n //\n // No fetch to be superseded — `runNavigation` has already superseded\n // whatever was in flight before it (TIM-1022) — but the render still\n // goes out through a transition React may hold (a replayed tree can\n // suspend), so the publish rides that commit rather than running\n // here. Publishing first would report the replayed route's tree\n // paths while the departing tree is still on screen (TIM-1423,\n // codex on #1108).\n //\n // Routed through renderViaTransition so the replay gets the same\n // lifecycle every other render has — handoff tracking, commit-on-\n // commit, forgetOlderHandoffs — rather than a hand-rolled publish\n // that misses one of them (TIM-1478). The perform resolves\n // immediately: there is no fetch, and the cached payload is\n // already decoded.\n await renderViaTransition(url, owner, [direction], async () => {\n const { navState, commit } = prepareNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n return {\n payload: entry.payload,\n params: entry.params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo: entry.segmentInfo ?? null,\n };\n });\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n await runAsHandle((endings) =>\n fetchCommitAndRender(url, direction, endings, {\n stateTree: currentStateTree(),\n scrollY,\n externalSignal,\n })\n );\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n *\n * Concurrent hovers and a click during the round-trip coalesce via the\n * singleflight inside PrefetchCache (TIM-1438).\n */\n function prefetch(url: string): void {\n // A stale client hard-navigates on every navigation, so a prefetched RSC\n // payload could never be consumed — and the fetch would be answered with\n // another reload signal anyway (TIM-1275).\n if (isClientStale()) return;\n\n // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The page the link is on. Sent as X-Timber-URL so the prefetched payload\n // is the one the click would have produced — an intercepting link hovered\n // from /gallery must prefetch the modal, not the full page — and stored\n // under the same source so only a click departing from here consumes it\n // (TIM-1265). The key is built by the pipeline, which is also what builds\n // the one the click looks up with, so the two cannot disagree.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(fetchUrl, deps.getCurrentUrl(), stateTree);\n const from = cacheKey.from;\n\n // Don't prefetch if already cached (ready or negative)\n if (prefetchCache.has(cacheKey)) return;\n\n // Fire-and-forget. Concurrent hovers coalesce in the singleflight;\n // a click during the round-trip joins the same flight via\n // fetchOrCoalesce in performNavigationFetch (TIM-1438).\n void prefetchCache\n .fetchOrCoalesce(\n cacheKey,\n (signal) => fetchRscPayload(fetchUrl, deps, stateTree, from, signal),\n (err) => err instanceof NonRscResponse\n )\n .then(\n (outcome) => {\n if (outcome.kind === 'ready') {\n // The decode rejects separately from the fetch, so the stale\n // shapes reach us here rather than in the rejection handler\n // below — swallowing it wholesale threw away the same evidence\n // (TIM-1275).\n outcome.result.decodePromise?.catch((error: unknown) => void recordSkew(error));\n }\n },\n (error) => {\n // A prefetch can be the first thing to learn we are stale —\n // during a rollout it may reach the new deployment while the\n // click that follows reaches the old one and completes as an\n // ordinary SPA navigation, throwing the evidence away. Record\n // it, but never recover from here: nobody navigated, and a page\n // load triggered by a hover is exactly the unasked-for reload\n // this design removed. The next click takes the document-load\n // path (TIM-1275).\n recordSkew(error);\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n saveScrollPosition: () => void saveScrollPosition(),\n isPending,\n getPendingUrl,\n onPendingChange,\n prefetch,\n epoch: () => lifecycle.epoch(),\n isEpochCurrent: (epoch) => lifecycle.isEpochCurrent(epoch),\n\n async applyActionResult(epoch, tree) {\n if (!lifecycle.isEpochCurrent(epoch)) return false;\n if (tree === undefined) {\n // Await through the commit so the next queued action captures a\n // current epoch — refresh() alone resolves before React commits\n // on the History API fallback (codex on #1125). The outcome\n // distinguishes a committed refresh from one superseded by a\n // navigation the user started while the refresh was in flight\n // (TIM-1477).\n const refreshed = refresh({ transitionType: 'revalidate' });\n await refreshed.catch(() => {});\n return (await refreshed.committed) === 'committed';\n }\n // Render the piggybacked payload from a server action response.\n // Routed through renderViaTransition so the piggybacked tree gets\n // the same commit lifecycle every other render has (TIM-1478).\n // The perform resolves immediately — the payload is already in hand.\n const currentUrl = deps.getCurrentUrl();\n const payloadTree = readPayloadTree(tree);\n const params = readPublishedParams(tree);\n // The response carries no segment metadata; the page it re-renders is\n // the one the last commit made current, and the committer kept that\n // page's. Not a history-stack lookup by `currentUrl`: the stack is keyed\n // by the spelling `navigate()` was given, which need not be\n // `window.location`'s (TIM-1541).\n const segmentInfo = committedSegmentInfo();\n\n // Place in the lifecycle's slot so a concurrent navigation supersedes\n // this owner. The epoch check above ensures the slot is idle. Don't use\n // createNavOwner — that bumps navigationSeq, which is reserved for\n // navigations (the epoch test pins this: TIM-1474).\n const owner = createRenderOwner('revalidation');\n lifecycle.placeRevalidationOwner(owner);\n const render = renderViaTransition(\n currentUrl,\n owner,\n ['revalidate' satisfies NavigationTransitionType],\n async () => {\n const { navState, commit } = prepareNavigation(currentUrl, {\n payload: payloadTree,\n params,\n segmentInfo,\n });\n return {\n payload: payloadTree,\n params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo,\n };\n }\n );\n await render.catch(() => {});\n return (await render.committed) === 'committed';\n },\n runWhenIdle: (task: () => void) => lifecycle.runWhenIdle(task),\n onIdle: (listener) => lifecycle.onIdle(listener),\n onTreeCommit: (listener) => lifecycle.onTreeCommit(listener),\n settleHandoffs: () => lifecycle.settleHandoffs(),\n evictStaleCaches(): void {\n prefetchCache.clearReady();\n historyStack.clear();\n },\n hydrate(page) {\n // Where hydration seeds the current page: the same prepare-and-commit\n // every navigation goes through, so the segment cache, the committed\n // segment metadata and the history entry are written by one commit\n // rather than by bootstrap reaching into each (TIM-1541). Committed\n // here, at once — see `RouterInstance.hydrate` for why not on React's\n // hydration commit.\n //\n // Replaying this entry on a Back re-renders `payload` and republishes\n // `params`. Both came out of one split of one decoded payload root\n // (rsc-stream.ts), so the entry cannot replay with another route's\n // params (TIM-1037, TIM-1285).\n const { navState, commit } = prepareNavigation(deps.getCurrentUrl(), {\n payload: page.payload,\n params: page.params,\n segmentInfo: page.segmentInfo,\n });\n commit();\n return navState;\n },\n segmentCache,\n prefetchCache,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * One unconditional read of NavigationContext, on every side (TIM-1425):\n *\n * - In the browser, the provider is updated atomically with the RSC tree\n * during full navigations, AND by syncShallowSearch() for shallow URL\n * updates (nuqs shallow: true, replaceUrl, or any external\n * pushState/replaceState that changes the query string). See router-init.ts.\n * - During SSR, the wrapper chain mounts the same provider carrying the\n * request's RAW query string (TIM-1424), so repeated keys\n * (`?tag=a&tag=b`) survive — the collapsed record the ALS context holds\n * cannot represent them.\n * - In the RSC environment, this module is never evaluated — the shims plugin\n * resolves next/navigation to navigation-rsc.ts (TIM-1420).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.ts';\nimport { useNavigationContext } from './navigation-context.ts';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.ts';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Throws when no NavigationProvider is above the caller.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n const nav = useNavigationContext();\n if (nav === null) {\n throw new Error(\n '[timber] useSearchParams() was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n // On the server, return a fresh instance per call. The module-level cache\n // below exists to give client code stable identity for effect deps; on the\n // server it would be shared mutable state across concurrent requests\n // (design/13-security.md, \"no global fallback state\"). Both halves of the\n // check matter: `window` is absent in a plain Node SSR render, and\n // getSsrData() catches SSR environments that do define `window` (handleSsr\n // always runs inside the ALS scope). Pinned by tests/ssr-provider-hooks.test.ts.\n if (typeof window === 'undefined' || getSsrData()) {\n return new URLSearchParams(nav.search);\n }\n return getSearchParams(nav.search);\n}\n"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,OAAO,IAAI,gBAAgB,IAAI,MAAM;CAEvC,OAAO,gBAAgB,IAAI,MAAM;AACnC"}
|
|
1
|
+
{"version":3,"file":"internal.js","names":[],"sources":["../../src/client/segment-cache.ts","../../src/client/history.ts","../../src/client/router-lifecycle.ts","../../src/client/router-pipeline.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// Segment Cache — the mounted segment tree, and prefetched payloads.\n// See design/19-client-navigation.md for architecture details.\n\nimport type { PublishedParams } from '../shared/payload-root.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport { createSingleflight } from '../cache/singleflight.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n /**\n * Completion of the full Flight stream, when the prefetch is still decoding.\n * Carried through to the navigation that consumes the entry so a decode\n * failure reaches *that* navigation's recovery rather than dying with the\n * prefetch (TIM-1275).\n */\n decodePromise?: Promise<void> | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /**\n * The params published beside `payload`, split off the same payload root.\n * Carried so a consumed prefetch publishes the params of the tree it is\n * about to render, and not the ones already on screen.\n */\n params?: PublishedParams | Promise<PublishedParams>;\n}\n\n// ─── Segment Cache ───────────────────────────────────────────────\n\n/**\n * The client's record of which layout-bearing segments are mounted — the\n * `treePaths` half of `X-Timber-State-Tree`, which the server reads for\n * interception scoping (TIM-1282).\n *\n * Content reuse is not decided here. The outlet content cache holds what the\n * client can reuse, keyed by key digest (client/outlet-content-cache.ts,\n * design/53-segment-lifetime.md).\n *\n * Written only by a navigation's commit (`navigation-commit.ts`), so a\n * superseded navigation never describes the mounted tree (TIM-1301).\n */\nexport class SegmentCache {\n private paths: string[] = [];\n\n /** Replace the record with the chain a committed page mounted. */\n record(segmentInfo: readonly SegmentInfo[]): void {\n this.paths = segmentInfo.flatMap((info) => (info.treePath ? [info.treePath] : []));\n }\n\n clear(): void {\n this.paths = [];\n }\n\n /** The `app/` directory paths of the mounted segments, root first. */\n treePaths(): string[] {\n return [...this.paths];\n }\n}\n\n// ─── Prefetch Cache ──────────────────────────────────────────────\n\ninterface ReadyEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/** Sentinel value for negative cache entries (URL is not a route). */\nconst NEGATIVE_ENTRY: PrefetchResult = Object.freeze({ payload: null });\n\n/**\n * Timeout for the in-flight singleflight (TIM-1438). Per CLAUDE.md's\n * singleflight rule: \"Never write a coalescing Map without a timeout.\"\n * A hung prefetch cannot block clicks or suppress hovers forever.\n */\nconst PREFETCH_SINGLEFLIGHT_TIMEOUT_MS = 5_000;\n\n/**\n * Identifies a prefetched payload. A payload is addressed by *every* input that\n * changes the server's answer, not by the destination alone.\n *\n * The server's answer for a destination depends on where the request came\n * from — that is the whole mechanism behind intercepting routes, and it also\n * drives slot-skip resolution. A prefetch issued from `/gallery` is a modal\n * payload; the same URL prefetched from `/` is the full page. Keying on the\n * destination alone let the first click after a hover be answered with\n * whichever variant happened to be fetched (TIM-1265).\n *\n * `from` alone stopped being enough in TIM-1282. It is a pathname, and once\n * interception scope comes from the rendered tree rather than the address, one\n * pathname no longer names one source tree: `/photo/1` is the address both for\n * a modal open over `(browse)` and for `(landing)`'s canonical page. A key\n * without the scope hands the modal payload to the canonical page's click,\n * which renders it without the server's scope check ever running.\n *\n * The two reads happen at different instants — `scope` is sampled at hover and\n * again at click — which is why a tree that changed in between produces a\n * *miss* and a refetch rather than a wrong hit.\n */\nexport interface PrefetchKey {\n /** Destination URL — hash-less `pathname + search`, as navigate() fetches it. */\n url: string;\n /** Departing pathname — the `X-Timber-URL` the prefetch was issued with. */\n from: string;\n /**\n * The rendered scope the prefetch was issued with — the `treePaths` half of\n * `X-Timber-State-Tree`, joined. Empty when none crossed.\n */\n scope: string;\n}\n\n/**\n * Compose the map key. Length-prefixed rather than delimiter-joined for the\n * same reason `shared/rsc-cache-key.ts` is: any delimiter is forgeable by a\n * value containing it, and a URL may contain any character a delimiter could.\n */\nfunction prefetchMapKey(key: PrefetchKey): string {\n return `${key.from.length}:${key.from}:${key.scope.length}:${key.scope}:${key.url}`;\n}\n\n/**\n * The `scope` half of a `PrefetchKey`, derived from the state tree that will\n * actually be sent. Taking it from the header value rather than re-walking the\n * cache is the point: the key varies by exactly what the request varies by.\n */\nexport function prefetchScopeOf(stateTree: StateTree | undefined): string {\n return stateTree?.treePaths?.join('\\u0000') ?? '';\n}\n\n/** Outcome of a prefetch flight — discriminated so NonRscResponse is a\n * success (stores a negative entry) rather than a rejection.\n * `startGen` is the eviction generation at flight start — joiners that\n * started after a gen bump must reject pre-invalidation results (TIM-1464). */\nexport type FlightOutcome =\n | { kind: 'ready'; result: PrefetchResult; startGen: number }\n | { kind: 'non-route'; startGen: number };\n\n/**\n * Short-lived cache for hover-triggered prefetches. Entries expire after\n * 30 seconds. When a link is clicked, the prefetched payload is consumed\n * (moved to the history stack) and removed from this cache.\n *\n * In-flight dedup (TIM-1438): concurrent fetches for the same key are\n * coalesced by a `createSingleflight` instance. A hover starts a flight;\n * a click for the same key joins it instead of issuing a duplicate. The\n * singleflight enforces a 5-second timeout and cleans up automatically\n * on settlement.\n *\n * timber.js does NOT prefetch on viewport intersection — only explicit\n * hover on <Link prefetch> triggers a prefetch.\n */\nexport class PrefetchCache {\n private static readonly TTL_MS = 30_000;\n private entries = new Map<string, ReadyEntry>();\n private flights = createSingleflight({ timeoutMs: PREFETCH_SINGLEFLIGHT_TIMEOUT_MS });\n private evictionGen = 0;\n\n set(key: PrefetchKey, result: PrefetchResult): void {\n this.entries.set(prefetchMapKey(key), {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(key: PrefetchKey): PrefetchResult | undefined {\n const mapKey = prefetchMapKey(key);\n const entry = this.entries.get(mapKey);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(mapKey);\n return undefined;\n }\n return entry.result;\n }\n\n /** True if a ready or negative entry exists for this key. */\n has(key: PrefetchKey): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(key: PrefetchKey): PrefetchResult | undefined {\n const result = this.get(key);\n if (result !== undefined) {\n this.entries.delete(prefetchMapKey(key));\n }\n return result;\n }\n\n /**\n * Fetch or coalesce with an in-flight fetch for this key (TIM-1438).\n *\n * Concurrent callers (hover + click, repeated hovers) get the same\n * promise. On success the result is stored as a ready entry. On\n * NonRscResponse a negative entry is stored and the outcome is\n * `{ kind: 'non-route' }`. Other errors (network, version skew)\n * reject — the singleflight cleans up the key and subsequent callers\n * retry.\n *\n * The singleflight signal is passed to `doFetch` so a timed-out flight\n * aborts the underlying fetch rather than leaving it running.\n */\n fetchOrCoalesce(\n key: PrefetchKey,\n doFetch: (signal: AbortSignal) => Promise<PrefetchResult>,\n isNonRoute: (error: unknown) => boolean\n ): Promise<FlightOutcome> {\n // Capture the eviction generation before the flight starts. If an\n // action evicts caches while this flight is in progress, the gen\n // will have bumped and the stale result is discarded (TIM-1476).\n // The starting gen is also included in the outcome so joiners\n // that started after a gen bump can detect pre-invalidation\n // results (TIM-1464).\n const genAtStart = this.evictionGen;\n return this.flights.do(prefetchMapKey(key), async (signal) => {\n try {\n const result = await doFetch(signal);\n if (!signal.aborted && this.evictionGen === genAtStart) this.set(key, result);\n return { kind: 'ready' as const, result, startGen: genAtStart };\n } catch (err) {\n if (isNonRoute(err)) {\n if (!signal.aborted && this.evictionGen === genAtStart) this.setNegative(key);\n return { kind: 'non-route' as const, startGen: genAtStart };\n }\n throw err;\n }\n });\n }\n\n /**\n * Join an in-flight singleflight fetch if one exists for this key.\n * Returns the in-flight promise or undefined. Used by the click path to\n * coalesce with a hover prefetch without starting a new flight — when no\n * flight exists, the click issues its own fetch with the navigation's\n * abort signal so superseded navigations abort immediately (TIM-1438).\n */\n joinInflight(key: PrefetchKey): Promise<FlightOutcome> | undefined {\n return this.flights.get(prefetchMapKey(key)) as Promise<FlightOutcome> | undefined;\n }\n\n /**\n * Store a negative entry — the URL is not a route (non-RSC Content-Type).\n *\n * Keyed like every other entry even though \"not a route\" does not actually\n * vary by departing URL: a source-independent negative would be a second\n * keying rule to keep correct, and the only cost of the uniform one is a\n * repeated fetch for a link hovered from a second page.\n */\n setNegative(key: PrefetchKey): void {\n this.set(key, NEGATIVE_ENTRY);\n }\n\n /** Check if the entry is a negative cache entry (URL is not a route). */\n isNegative(key: PrefetchKey): boolean {\n return this.get(key) === NEGATIVE_ENTRY;\n }\n\n /**\n * Evict all ready entries and fence in-flight singleflights (TIM-1476).\n * Called after a server action that revalidated data — the mutation may\n * affect any route, not just the paths the server named. In-flight\n * singleflights are not aborted (they may carry post-mutation data),\n * but their results are discarded if they complete after eviction:\n * `fetchOrCoalesce` captures the generation before the flight and\n * skips the store when it has been bumped.\n *\n * Consumers that join an in-flight flight via `joinInflight` must\n * check `getEvictionGen()` before and after the await: if the gen\n * changed, the result predates the eviction and must be discarded\n * (codex on #1131 round 2).\n */\n clearReady(): void {\n this.entries.clear();\n this.evictionGen++;\n }\n\n getEvictionGen(): number {\n return this.evictionGen;\n }\n}\n","// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { SegmentInfo } from '../shared/segment-info.ts';\nimport { routerUrlKey } from './router-url.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * The params that payload published. Replaying the tree republishes them,\n * because the client owns the provider now and reads it from here\n * (TIM-1297).\n *\n * Stored beside the tree but never *produced* beside it: both come out of\n * one `splitPayloadRoot` on one decoded root and travel together through\n * `prepareNavigation`, the only producer of an entry. That is the property\n * that matters — when they were derived from separate channels, a replay\n * could restore one route's tree with another route's params (TIM-1037,\n * TIM-1285).\n */\n params: ParamsSource;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next navigation reports the tree paths\n * actually mounted. Without this, the segment cache retains the *previous*\n * page's tree after back-button, and interception scoping reads a tree\n * that is not on screen (TIM-1282).\n */\n segmentInfo?: SegmentInfo[] | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Entries are keyed by pathname + search in the browser's own spelling\n * (`routerUrlKey`), whatever spelling a caller passes: an entry stored by\n * `navigate('/café')` is found by a traversal that reads `/caf%C3%A9` off\n * the address bar, and `/a?` is `/a` (TIM-1541). Used with the History API\n * fallback and the Navigation API.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries have no expiry, but only the 50 most recently used URLs are kept\n * by default. Traversing to an evicted entry fetches a fresh payload.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n private readonly maxEntries: number;\n\n constructor({ maxEntries = 50 }: { maxEntries?: number } = {}) {\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new RangeError('HistoryStack maxEntries must be a positive integer');\n }\n this.maxEntries = maxEntries;\n }\n\n push(url: string, entry: HistoryEntry): void {\n url = routerUrlKey(url);\n // Push runs when a page becomes current (or hydration seeds it). Promote\n // replacements too, so the current page always survives overflow.\n this.entries.delete(url);\n this.entries.set(url, entry);\n if (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next();\n if (!oldest.done) this.entries.delete(oldest.value);\n }\n }\n\n get(url: string): HistoryEntry | undefined {\n url = routerUrlKey(url);\n const entry = this.entries.get(url);\n if (entry) {\n this.entries.delete(url);\n this.entries.set(url, entry);\n }\n return entry;\n }\n\n /** Presence checks (such as hover prefetch probes) do not promote entries. */\n has(url: string): boolean {\n return this.entries.has(routerUrlKey(url));\n }\n\n /**\n * Evict every entry (TIM-1476). Called after a server action that\n * revalidated data — history entries are equally stale since they replay\n * on back/forward without a server check. Clearing forces a fresh fetch on\n * the next traversal.\n *\n * The current page's entry goes too. Nothing reads it for anything but a\n * replay: the segment metadata a revalidation needs is the committer's\n * record of the current page, not this stack's (TIM-1541).\n */\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Navigation Lifecycle — who owns the router, and when a fetch may be cut.\n *\n * One navigation at a time owns the router. This module holds that ownership\n * as a single `RenderOwner` slot, the rule for taking it (`createNavOwner`\n * supersedes), the wrapper every navigation runs inside (`runNavigation`),\n * and the pending store that `TopLoader` and `usePendingNavigation()`\n * subscribe to.\n *\n * TIM-1481: replaced the transition counter, the `handedOffNavAborts` set,\n * and the `AbortController`-as-owner pattern with `RenderOwner`. Supersession\n * is \"take the slot\": settle the previous owner and abort its fetch unless\n * handed off.\n *\n * See design/19-client-navigation.md §\"How Pending State Works\".\n */\n\nimport { createRenderOwner, type RenderOwner } from './navigation-transition.ts';\nimport type { RouterPhase } from './router-types.ts';\n\n/**\n * A snapshot of \"which page, and was a navigation in flight\" at one instant.\n * Captured before an action's POST and compared at response time so the\n * router can tell whether the response still describes the page on screen.\n *\n * `seq` is a monotonic counter bumped on every `createNavOwner` — covering\n * every path through `runNavigation`. `idle` is false when the router is\n * mid-navigation OR a handed-off tree has not yet committed (the\n * handover-to-commit window on the History API fallback).\n *\n * See design/19-client-navigation.md §State Update Invariants (TIM-1474).\n */\nexport interface NavigationEpoch {\n readonly seq: number;\n readonly idle: boolean;\n}\n\nexport interface NavigationLifecycle {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n /**\n * Take ownership of the router, superseding whatever held it. Returns\n * a fresh `RenderOwner` for the new navigation. See the implementation\n * for the two parts of superseding.\n */\n createNavOwner: (\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ) => RenderOwner;\n /**\n * Run `fn` inside the abort/pending/cleanup lifecycle. AbortErrors are\n * swallowed (not application errors); all other errors propagate.\n */\n runNavigation: (\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ) => Promise<void>;\n /**\n * Record that `owner`'s payload has reached React, so its stream is no\n * longer cuttable. No-op when `owner` no longer owns the router.\n */\n markHandedOff: (owner: RenderOwner) => void;\n /** React has committed `owner`'s tree — every earlier handoff is off screen. */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n\n /**\n * Whether a navigation is in flight: from its start until its payload has\n * decoded AND React has committed its tree, whichever is later.\n */\n isPending: () => boolean;\n /** The URL currently being navigated to, or null if idle. */\n getPendingUrl: () => string | null;\n /** Subscribe to pending state changes. */\n onPendingChange: (listener: (pending: boolean) => void) => () => void;\n\n /**\n * Place a revalidation owner in the slot without bumping the navigation\n * sequence. Unlike `createNavOwner`, this does not supersede what's in the\n * slot — the caller (applyActionResult) has already verified the slot is\n * idle via the epoch check. A concurrent navigation will supersede this\n * owner through the normal `createNavOwner` path.\n */\n placeRevalidationOwner: (owner: RenderOwner) => void;\n /** Snapshot the router's navigation state (TIM-1474). */\n epoch: () => NavigationEpoch;\n /** True iff no navigation has started or is in flight since `e` was taken. */\n isEpochCurrent: (e: NavigationEpoch) => boolean;\n /**\n * Run `task` now if the router is idle, otherwise once when it next becomes\n * idle (pending false AND commit done). Single slot — a later request\n * replaces an earlier one (TIM-1474).\n */\n runWhenIdle: (task: () => void) => void;\n /**\n * Subscribe to the router becoming idle (pending false AND commit done):\n * `listener` runs on every such transition until unsubscribed. Unlike\n * `runWhenIdle`, any number of listeners may wait.\n */\n onIdle: (listener: () => void) => () => void;\n /**\n * Subscribe to React committing a navigation's tree — the tree on screen\n * has changed, whether or not its stream has finished decoding (so the\n * router may still be pending). Runs on every commit until unsubscribed,\n * with the committing navigation's `epoch().seq`: a tree handed to React\n * before a later navigation started can still commit after it, and the\n * sequence says which one it was.\n */\n onTreeCommit: (listener: (seq: number) => void) => () => void;\n /**\n * Settle any handed-off-but-uncommitted owners as superseded, then flush\n * the idle task if the router is now idle. Called by `syncShallowSearch`\n * when a shallow URL update displaces a suspended transition — without\n * it, `hasUncommittedNav` stays true indefinitely and `runWhenIdle`\n * tasks never fire (TIM-1480).\n */\n settleHandoffs: () => void;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\nexport function createNavigationLifecycle(): NavigationLifecycle {\n // The single ownership slot. One navigation at a time.\n let current: RenderOwner | null = null;\n\n // A handed-off-but-uncommitted owner that `runNavigation`'s finally has\n // already cleared from `current`. Tracked separately so `createNavOwner`\n // can settle it as superseded if a new navigation starts before the\n // commit (P1 from codex on #1127). Cleared by `forgetOlderHandoffs`\n // (commit) or by `createNavOwner` (supersession).\n let pendingCommit: RenderOwner | null = null;\n\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n let navigationSeq = 0;\n let idleTask: (() => void) | null = null;\n const idleListeners = new Set<() => void>();\n const treeCommitListeners = new Set<(seq: number) => void>();\n // The navigationSeq each owner ran under, for tree-commit listeners.\n const ownerSeq = new WeakMap<RenderOwner, number>();\n\n /**\n * Whether a handed-off tree has not yet committed. Derived from the slot:\n * true when `current` is handed off but not yet settled.\n */\n function hasUncommittedNav(): boolean {\n return (\n pendingCommit !== null || (current !== null && current.handedOff && current.outcome === null)\n );\n }\n\n /**\n * Cancel a navigation's RSC fetch — unless its tree is the one on screen.\n *\n * THE only place a navigation controller is aborted. Every path that gives\n * up on a navigation calls this, so the \"is this tree displayed?\" question\n * is asked once rather than at each site. A new abort path is a call to\n * this, not a copy of `controller.abort()`.\n *\n * See design/19-client-navigation.md §\"A navigation that reached React\n * keeps its stream\".\n */\n function abortUnlessHandedOff(owner: RenderOwner): void {\n if (owner.handedOff) return;\n owner.fetchAbort.abort();\n }\n\n /**\n * Create a new RenderOwner for a navigation, superseding any previous\n * in-flight navigation. Optionally links to an external signal (e.g.,\n * from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with two parts:\n * 1. Abort the previous navigation's fetch — UNLESS its tree is the one on\n * screen, in which case tearing the stream down would error the page the\n * user is currently looking at. See `RenderOwner.handedOff`.\n * 2. Settle the previous owner as 'superseded' so its transition detects\n * it lost and never hands a stale tree to React. This replaces both\n * `supersedeNavigationTransitions()` and the transition counter bump.\n */\n function createNavOwner(\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ): RenderOwner {\n if (current) {\n abortUnlessHandedOff(current);\n current.settle('superseded');\n }\n // A handed-off owner whose runNavigation has already finished but whose\n // tree hasn't committed yet. Settle it so its `committed` resolves.\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n pendingCommit = null;\n }\n navigationSeq += 1;\n const owner = createRenderOwner(kind);\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n //\n // This is a second, independent way a navigation dies, and it fires for\n // the same reason as the branch above: the browser aborts a\n // NavigateEvent's signal when that navigation is superseded. So it needs\n // the same guard — without it, an intercepted push/replace or traversal\n // whose tree is already on screen still loses its stream, and the guard\n // above only appears to work because plain `router.navigate()` carries no\n // external signal (codex on #1004).\n if (externalSignal) {\n if (externalSignal.aborted) {\n abortUnlessHandedOff(owner);\n } else {\n externalSignal.addEventListener('abort', () => abortUnlessHandedOff(owner), { once: true });\n }\n }\n\n return owner;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify subscribers. This is the ONLY pending representation — React and\n // non-React consumers alike read it, React ones through\n // `usePendingNavigation()`'s `useSyncExternalStore` (TIM-1307).\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavOwner + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const owner = createNavOwner('navigation', externalSignal);\n setPending(true, url);\n let failed = false;\n try {\n await fn(owner);\n } catch (error) {\n if (isAbortError(error)) return;\n failed = true;\n throw error;\n } finally {\n if (current === owner) {\n current = null;\n // A tree handed to React but not yet committed is still loading as\n // far as the user can see: React may be rendering it for a while\n // after the stream finishes decoding. Pending stays on until the\n // commit (forgetOlderHandoffs) or a supersession clears it, so the\n // loader ends on the later of decode and commit. A navigation that\n // failed ends now: its tree may never commit (design/19 §\"How\n // Pending State Works\").\n if (failed || pendingCommit !== owner) {\n setPending(false);\n flushIdleTask();\n }\n }\n }\n }\n\n // Every place the router may have just become idle calls this.\n function flushIdleTask(): void {\n if (routerPhase.phase !== 'idle' || hasUncommittedNav()) return;\n for (const listener of [...idleListeners]) listener();\n if (!idleTask) return;\n const task = idleTask;\n idleTask = null;\n task();\n }\n\n return {\n currentOwner: () => current,\n createNavOwner,\n runNavigation,\n\n // Guarded on still owning the router. A superseded navigation can still\n // reach here: a prefetch hit answers from `prefetchCache`, whose payload\n // was fetched under the PREFETCH's controller, so aborting this\n // navigation's controller does not stop it and `perform()` runs to\n // completion. `navigateTransition`'s stale check happens after\n // `perform()` returns, so without this the loser would claim ownership\n // moments before being discarded — and the next navigation would then\n // abort the winner's still-streaming response, erroring the visible tree\n // (codex on #1004).\n markHandedOff(owner: RenderOwner): void {\n if (current !== owner) return;\n owner.handedOff = true;\n pendingCommit = owner;\n },\n\n // React has committed THIS tree, so every earlier one is unmounted and\n // their streams no longer feed anything on screen. The owner's `handedOff`\n // boolean already captured the individual state; settling clears the\n // \"uncommitted\" window. Unlike the old `handedOffNavAborts` set, there is\n // no set to prune — the single slot means at most one owner is current.\n forgetOlderHandoffs(owner: RenderOwner): void {\n owner.settle('committed');\n if (pendingCommit === owner) {\n pendingCommit = null;\n // runNavigation already finished decoding and left pending on for\n // this commit. If it is still decoding, its finally clears pending.\n if (current !== owner) setPending(false);\n }\n const seq = ownerSeq.get(owner) ?? navigationSeq;\n for (const listener of [...treeCommitListeners]) listener(seq);\n flushIdleTask();\n },\n\n placeRevalidationOwner(owner: RenderOwner): void {\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n },\n\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n\n epoch(): NavigationEpoch {\n return {\n seq: navigationSeq,\n idle: routerPhase.phase === 'idle' && !hasUncommittedNav(),\n };\n },\n isEpochCurrent(e: NavigationEpoch): boolean {\n return (\n e.idle && routerPhase.phase === 'idle' && !hasUncommittedNav() && navigationSeq === e.seq\n );\n },\n runWhenIdle(task: () => void): void {\n if (routerPhase.phase === 'idle' && !hasUncommittedNav()) {\n task();\n return;\n }\n idleTask = task;\n },\n\n onIdle(listener) {\n idleListeners.add(listener);\n return () => idleListeners.delete(listener);\n },\n\n onTreeCommit(listener) {\n treeCommitListeners.add(listener);\n return () => treeCommitListeners.delete(listener);\n },\n\n settleHandoffs(): void {\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n // Its runNavigation may already have finished and left pending on\n // for a commit that will now never come.\n if (current !== pendingCommit) setPending(false);\n pendingCommit = null;\n }\n if (current !== null && current.handedOff && current.outcome === null) {\n current.settle('superseded');\n }\n flushIdleTask();\n },\n };\n}\n","/**\n * Navigation Pipeline — URL in, tree in React's hands.\n *\n * Everything between \"the user asked for this URL\" and \"React is holding the\n * destination's tree\": consult the prefetch cache or fetch, prepare the commit\n * that makes the page current, and hand the result over inside a transition.\n *\n * `router.ts` keeps the *operations* — `navigate`, `refresh`, `handlePopState`,\n * `prefetch`, `applyActionResult` — and each of them is a call into here. The\n * split is the same one `router-effects.ts` and `router-lifecycle.ts` made\n * (design/18-build-system.md §\"No file >500 lines\").\n *\n * See design/19-client-navigation.md §\"Partial Rendering\" and §\"Prefetching\".\n */\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport type { FetchResult } from './rsc-fetch.ts';\nimport { readPublishedParams } from '../shared/payload-root.ts';\nimport type { PrefetchCache, PrefetchKey } from './segment-cache.ts';\nimport { prefetchScopeOf } from './segment-cache.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport type { NavigationCommitter } from './navigation-commit.ts';\nimport type { RouterDeps } from './router-types.ts';\nimport type { NavigationHandle, RenderOwner } from './navigation-transition.ts';\nimport { recordSkew } from './router-skew.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport { SingleflightTimeoutError } from '../cache/singleflight.ts';\n\n/**\n * Race a promise against an abort signal. The promise continues regardless —\n * only the *await* gives up. Used so a click superseded by a newer navigation\n * stops waiting for a shared prefetch flight without aborting the flight\n * itself (TIM-1438).\n */\nfunction raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(signal.reason);\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n }),\n ]);\n}\n\n/** A fetched payload plus the state update that makes it the current page. */\nexport type NavigationPayload = FetchResult & {\n navState: NavigationState;\n commit: () => void;\n};\n\n/** Options for a single `performNavigationFetch` call. */\nexport interface NavigationFetchOptions {\n replace: boolean;\n commitUrl?: string;\n signal?: AbortSignal;\n departingUrl?: string;\n}\n\nexport interface NavigationPipelineDeps extends Pick<\n NavigationCommitter,\n 'prepareNavigation' | 'currentStateTree'\n> {\n deps: RouterDeps;\n prefetchCache: PrefetchCache;\n /** Record that this navigation's tree reached React (router-lifecycle.ts). */\n markHandedOff: (owner: RenderOwner) => void;\n /** React committed this navigation's tree (router-lifecycle.ts). */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n}\n\nexport interface NavigationPipeline {\n /** Fetch (or replay a prefetch), then stage the commit. */\n performNavigationFetch: (\n url: string,\n options: NavigationFetchOptions\n ) => Promise<NavigationPayload>;\n /** Hand a payload to React inside a transition. */\n renderViaTransition: (\n url: string,\n owner: RenderOwner,\n /** The view transition types the render adds (`NavigationRender`). */\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ) => NavigationHandle;\n}\n\n/**\n * Normalize a departing URL to the pathname the server is told about.\n *\n * This is the value sent as `X-Timber-URL` *and* the source half of the\n * prefetch cache key — one function so a prefetch and the click that consumes\n * it can never disagree about what \"where we came from\" means (TIM-1265). The\n * query is dropped deliberately: it would land in the `_rsc` digest, which is\n * logged (TIM-1268), and nothing downstream reads it — interception scope\n * compares pathnames.\n *\n * Absolute inputs parse against the base and ignore it, so one call handles\n * both `location.href` and a bare pathname.\n */\nexport function departingPathname(raw: string): string {\n return parseRouterUrl(raw).pathname;\n}\n\n/**\n * The prefetch cache key for a destination.\n *\n * Both halves of the cache are keyed through here — the hover that writes an\n * entry (`router.ts`'s `prefetch()`) and the click that consumes it\n * (`performNavigationFetch` below) — so the two cannot disagree about what\n * identifies a payload. That is the whole point of the key: `from` scopes it\n * to the page the link was on (TIM-1265) and `scope` to the tree that was\n * mounted (TIM-1282), and an entry written under one reading of either would\n * simply never be found under the other, silently costing every prefetch.\n *\n * `departingPathname` is applied here rather than by callers for the same\n * reason: it is also what goes out as `X-Timber-URL`, so the key and the\n * request describe the same departure point.\n */\nexport function prefetchKeyFor(\n url: string,\n departingUrl: string,\n stateTree: StateTree | undefined\n): PrefetchKey {\n return { url, from: departingPathname(departingUrl), scope: prefetchScopeOf(stateTree) };\n}\n\n/**\n * Inspect a decode rejection for version skew before handing the promise on,\n * without changing what the consumer sees.\n *\n * The decode rejects independently of the fetch, and not every consumer\n * awaits it — NavigationRoot drops it outright when the transition has been\n * superseded. A stale client reference arriving that way is still evidence\n * the bundle is superseded, so record it here where every consumer is fed\n * from, rather than at each place that might drop it (TIM-1275).\n */\nfunction observeSkew(decodePromise: Promise<void> | null): Promise<void> | null {\n decodePromise?.catch((error: unknown) => void recordSkew(error));\n return decodePromise;\n}\n\nexport function createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n}: NavigationPipelineDeps): NavigationPipeline {\n /**\n * Hand a payload to React via navigateTransition. The perform callback should fetch data, prepare the commit, and return the\n * FetchResult plus the NavigationState and the commit thunk.\n *\n * The thunk is handed *through* to NavigationRoot rather than called here:\n * state management (segment cache, history stack, address bar) has to happen on\n * the far side of the supersession check, which only NavigationRoot can\n * make (TIM-1301).\n */\n function renderViaTransition(\n url: string,\n owner: RenderOwner,\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ): NavigationHandle {\n // Record that THIS navigation's payload has reached React, at the moment\n // the tree is built and handed back for `navigateTransition` to give to\n // React — NOT on commit, which is a whole commit phase too late. See\n // `RenderOwner.handedOff` in router-lifecycle.ts.\n const handOff = (): void => markHandedOff(owner);\n\n // Settle the owner as committed once React has committed this tree.\n // Wrapped around the commit thunk so it runs on React's commit and not\n // at handover; see `forgetOlderHandoffs`.\n const commitAndForget = (commit: () => void) => (): void => {\n forgetOlderHandoffs(owner);\n commit();\n };\n\n return deps.navigateTransition(url, owner, types, async (wrapPayload) => {\n const result = await perform();\n // Await the payload's *root row* — the same thing React would suspend\n // on to render the tree, and the first thing Flight emits. The\n // previous UI stays on screen while this resolves: nothing has been\n // handed to React yet, and when it is, NavigationRoot hands it over\n // inside a transition so a tree that is still streaming does not\n // displace the departing page (TIM-1306).\n //\n // Reading them here rather than with `use()` above the tree is what\n // keeps a decode failure contained: `result.params` never rejects, so\n // it can never take down the provider above every error boundary\n // (TIM-1297). A failure after the root row reaches React through the\n // tree, inside whatever boundary the app put around it.\n const params = await result.params;\n // And the tree itself — settled by the same root row, so this adds no\n // wait, but it is the half that *rejects*: a root row that fails to\n // decode fails this navigation here, before anything is wrapped or\n // handed over, and the router takes its recovery path (TIM-1541).\n // This used to happen by accident — the payload went through an\n // `async` identity helper whose return adopted the thenable — and\n // only on the paths that called it.\n const payload = await result.payload;\n\n // Every navigation renders the payload root. Segments the server\n // skipped render the content the client holds for them, in place\n // (client/segment-outlet.tsx), so their state survives.\n const element = wrapPayload(payload, result.navState, params);\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n });\n }\n\n /**\n * Fetch (or take from the prefetch cache) a navigation's payload and\n * prepare — without publishing — the commit that makes it current.\n */\n async function performNavigationFetch(\n url: string,\n options: NavigationFetchOptions\n ): Promise<NavigationPayload> {\n // Both halves of the key are sampled here, before the prefetch cache is\n // consulted, and both are reused for the request itself:\n //\n // - the departing page, because an entry fetched from somewhere else\n // answers a different question (TIM-1265). `getCurrentUrl()` can't be\n // read any later either — the Navigation API may have already committed\n // the destination URL (TIM-1232).\n // - the mounted tree, so the entry this navigation looks up is keyed by\n // the same scope the fetch would have been issued with (TIM-1282).\n //\n // `currentUrl` is read back off the key rather than computed beside it, so\n // the pathname sent as X-Timber-URL is the one the lookup used.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(url, options.departingUrl ?? deps.getCurrentUrl(), stateTree);\n const currentUrl = cacheKey.from;\n\n // Check prefetch cache first. A negative entry means a prior prefetch\n // determined this URL is not a route (non-RSC Content-Type). Hard-navigate\n // immediately without a second fetch. See TIM-1231.\n if (prefetchCache.isNegative(cacheKey)) {\n prefetchCache.consume(cacheKey);\n throw new NonRscResponse(url);\n }\n\n // PrefetchResult has optional segmentInfo/params fields — normalize\n // to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(cacheKey);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n // A prefetch that predates this field (or the negative-entry\n // sentinel) publishes nothing rather than the previous route's.\n params: prefetched.params ?? readPublishedParams(undefined),\n // Carry the prefetch's stream completion through. It may still be\n // decoding, and a stale client reference arriving after the click\n // must reach *this* navigation's recovery rather than dying with\n // the prefetch that started it (TIM-1275).\n decodePromise: prefetched.decodePromise ?? null,\n segmentInfo: prefetched.segmentInfo ?? null,\n }\n : undefined;\n\n // If a hover prefetch is in-flight, join it instead of issuing a\n // duplicate (TIM-1438). The click races its await against its own signal\n // so a superseded navigation gives up immediately — the shared flight\n // continues for other consumers. On flight failure (network error,\n // singleflight timeout), fall through to a fresh fetch — the failed\n // hover should not block a click that might succeed.\n if (result === undefined) {\n const inflight = prefetchCache.joinInflight(cacheKey);\n if (inflight) {\n // Capture the eviction generation before awaiting the flight.\n // If an action evicts caches while we wait, the result predates\n // the mutation and must be discarded (TIM-1476, codex on #1131).\n // Also check the flight's own starting gen: if the flight started\n // before a per-URL invalidation (TIM-1464), a joiner that arrived\n // after the bump would see genBefore === genAfter but the flight\n // still predates the invalidation.\n const genBefore = prefetchCache.getEvictionGen();\n try {\n const outcome = await raceAbort(inflight, options.signal);\n if (prefetchCache.getEvictionGen() !== genBefore || outcome.startGen !== genBefore) {\n // Eviction happened while we waited, or the flight predates\n // an invalidation we arrived after — discard stale result,\n // fall through to a fresh fetch below.\n } else if (outcome.kind === 'non-route') {\n throw new NonRscResponse(url);\n } else {\n // Consume the ready entry so a second click re-fetches\n prefetchCache.consume(cacheKey);\n result = {\n payload: outcome.result.payload,\n params: outcome.result.params ?? readPublishedParams(undefined),\n decodePromise: outcome.result.decodePromise ?? null,\n segmentInfo: outcome.result.segmentInfo ?? null,\n };\n }\n } catch (error) {\n // Supersession aborts propagate — don't retry a cancelled navigation\n if (error instanceof DOMException && error.name === 'AbortError') throw error;\n if (options.signal?.aborted) throw options.signal.reason;\n // Retriable failures fall through to a fresh fetch: singleflight\n // timeout (hover hung) and transport TypeError (transient network\n // error). Framework control-flow errors — NonRscResponse,\n // VersionSkewError, RedirectError, ServerErrorResponse — are\n // definitive server answers and must reach navigate's recovery.\n if (error instanceof SingleflightTimeoutError || error instanceof TypeError) {\n // fall through to fresh fetch below\n } else {\n throw error;\n }\n }\n }\n }\n\n if (result === undefined) {\n // No in-flight hover prefetch, or the joined flight failed — fetch\n // directly with the navigation's signal so superseded navigations\n // abort immediately. The state tree is resampled: hashes the client\n // recorded while it waited on a joined flight are worth advertising.\n const freshStateTree = currentStateTree();\n result = await fetchRscPayload(url, deps, freshStateTree, currentUrl, options.signal);\n }\n\n // Update the browser history. This is the only place a push/replace\n // navigation moves the address bar, with or without the Navigation API\n // (its listener leaves same-document pushState alone). The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n //\n // Deferred with the rest of the commit: the address bar is navigation\n // state like the segment cache and the history stack, and a superseded\n // navigation must not move it either. That guarantee used to hold only\n // because the superseded fetch was aborted before it got here — a\n // response that won the race anyway re-pushed the abandoned URL\n // (TIM-1022's failure mode, made unconditional by TIM-1301).\n const commitHistoryUrl = (): void => {\n const commitUrl = options.commitUrl ?? url;\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n };\n\n const params = await result.params;\n\n // Prepare the atomic navigation-state update. It is published by the\n // caller once this navigation is known to have won (TIM-1301).\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n });\n\n return {\n ...result,\n params,\n navState,\n commit: () => {\n commitHistoryUrl();\n commit();\n // Notify nuqs (and any other listener) that the URL is now the\n // destination's. It travels *inside* the commit rather than after\n // the navigation resolves because the listener answers it by reading\n // `window.location.search`, and the commit is what moves it — the\n // publish happens on React's commit of the tree, which can land after\n // the navigation promise settles (TIM-1301, codex on #998).\n window.dispatchEvent(new Event('timber:navigation-end'));\n },\n };\n }\n\n return { performNavigationFetch, renderViaTransition };\n}\n","// Segment Router — the operations a client-side navigation can be.\n//\n// `navigate`, `refresh`, `handlePopState`, `prefetch` and `applyActionResult`\n// live here; each is wiring over modules that own one concern apiece:\n//\n// router-types.ts — RouterDeps / RouterInstance / the option shapes\n// router-lifecycle.ts — ownership, supersede, pending store, handoff set\n// router-pipeline.ts — URL in, tree in React's hands\n// router-effects.ts — SPA exits, error recovery, post-paint scroll\n// navigation-commit.ts — every write that makes a page \"current\"\n//\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache } from './segment-cache.ts';\nimport { HistoryStack } from './history.ts';\nimport { createNavigationCommitter } from './navigation-commit.ts';\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport { readPayloadTree, readPublishedParams } from '../shared/payload-root.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport { isClientStale } from './stale-client.ts';\nimport {\n createScrollEffects,\n createSpaExits,\n createNavigationRecovery,\n runAsHandle,\n type NavigationEndings,\n} from './router-effects.ts';\nimport { createNavigationLifecycle } from './router-lifecycle.ts';\nimport { createNavigationPipeline, prefetchKeyFor } from './router-pipeline.ts';\nimport { recordSkew } from './router-skew.ts';\nimport type {\n NavigationOptions,\n NavigationTransitionType,\n RefreshOptions,\n RouterDeps,\n RouterInstance,\n TraverseDirection,\n} from './router-types.ts';\nimport { createRenderOwner, type NavigationHandle } from './navigation-transition.ts';\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n\n // Every write that makes a page \"current\", and the read that reports the\n // current page back to the server. See navigation-commit.ts.\n const { prepareNavigation, currentStateTree, committedSegmentInfo } = createNavigationCommitter({\n segmentCache,\n historyStack,\n outletDocuments: () => deps.outletContentCache?.documents() ?? {},\n });\n\n // Ownership of the router: who is navigating, whose fetch may be cut, and\n // the pending store TopLoader subscribes to. See router-lifecycle.ts.\n const lifecycle = createNavigationLifecycle();\n const {\n currentOwner,\n createNavOwner,\n runNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n isPending,\n getPendingUrl,\n onPendingChange,\n } = lifecycle;\n\n // Fetch → commit → hand to React. See router-pipeline.ts.\n const { performNavigationFetch, renderViaTransition } = createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n });\n\n // Post-paint scroll effects.\n const { restoreScrollAfterPaint, scrollToHashAfterPaint } = createScrollEffects(deps);\n\n // The only ways out of the SPA. Every failure branch that gives up on\n // client-side navigation goes through one of these, so the \"does this\n // navigation still own the router?\" question is asked once rather than\n // per branch (TIM-1275, TIM-1276).\n const { leaveSpaIfOwned, leaveSpaSuperseding } = createSpaExits({\n currentOwner,\n supersede: () => void createNavOwner('navigation'),\n });\n\n // Every way an RSC fetch can fail that the router answers rather than\n // rethrows. Shared by navigate(), refresh(), and traversals so a path that\n // grows a new branch grows it for all of them (TIM-1277).\n const recoverFromNavigationError = createNavigationRecovery({\n currentOwner,\n leaveSpaIfOwned,\n // Hoisted — `navigate` is a function declaration below.\n navigate: (url, { types, replace, scroll }) =>\n navigate(url, { replace, scroll, _renderTypes: types }),\n });\n\n /**\n * Write the current scroll position into the current history entry — the\n * Navigation API's entry state when available, otherwise history.state —\n * and return it. Back restores from there.\n */\n function saveScrollPosition(): number {\n const scrollY = deps.getScrollY();\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(scrollY);\n } else {\n deps.replaceState({ timber: true, scrollY }, '', deps.getCurrentUrl());\n }\n return scrollY;\n }\n\n function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {\n return runAsHandle((endings) => navigateWith(url, options, endings));\n }\n\n async function navigateWith(\n url: string,\n options: NavigationOptions,\n endings: NavigationEndings\n ): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n // A push, a replace, and a server action redirect all move the user\n // forward; the caller's own types ride beside it. A redirect this router\n // follows keeps the types of the render it interrupted instead.\n const types = options._renderTypes ?? [\n 'navigation-forward' satisfies NavigationTransitionType,\n ...(options.transitionTypes ?? []),\n ];\n\n // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The address bar moves only when the destination commits, so it still\n // names the page being left (TIM-1232).\n const departingUrl = deps.getCurrentUrl();\n\n // Save the departing page's scroll position, and keep it for\n // scroll={false} preservation.\n const currentScrollY = saveScrollPosition();\n\n // This bundle has been superseded. Every subsequent navigation is a full\n // document load — it is the only way to get code that matches the server,\n // and it is the recovery for a skew detected on an earlier navigation.\n // Deliberately *not* a reload: recovery rides on navigations the user\n // asked for, so a rollout that keeps serving mismatched builds costs one\n // document load per click instead of a self-issued reload loop (TIM-1275).\n // Scroll is saved above, so back-navigation still restores correctly.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, departingUrl);\n }\n\n await runNavigation(url, async (owner) => {\n try {\n const render = renderViaTransition(fetchUrl, owner, types, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: owner.fetchAbort.signal,\n departingUrl,\n })\n );\n endings.track(render);\n await render;\n\n // Scroll-to-top on forward navigation, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n // `url` is where the user asked to go and `departingUrl` is where\n // they were: a failure here finishes the click as a full document\n // load of the destination, fragment included (TIM-1234). Reloading\n // instead would rebuild the page they were *leaving* and discard\n // the click (TIM-1275).\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n departingUrl,\n { types, replace, scroll },\n endings\n )\n ) {\n return;\n }\n throw error;\n }\n });\n }\n\n /**\n * Fetch a URL's RSC payload, commit it, and render — the pipeline shared by\n * refresh() and an uncached back/forward traversal. Both can be the path\n * that discovers a version skew, and both recover the same way (TIM-1275).\n *\n * Not `performNavigationFetch`: neither caller consults the prefetch cache\n * (there is no link to have hovered) and neither moves the address bar (the\n * browser is already where it is going), so the fetch is a plain one.\n */\n async function fetchCommitAndRender(\n url: string,\n /** The view transition type the render adds. */\n type: NavigationTransitionType,\n endings: NavigationEndings,\n opts: {\n /** Omitted by refresh(): the server renders the complete payload. */\n stateTree?: StateTree;\n /** Restored after paint when present — traversals only. */\n scrollY?: number;\n externalSignal?: AbortSignal;\n } = {}\n ): Promise<void> {\n await runNavigation(\n url,\n async (owner) => {\n try {\n const render = renderViaTransition(url, owner, [type], async () => {\n const result = await fetchRscPayload(\n url,\n deps,\n opts.stateTree,\n undefined,\n owner.fetchAbort.signal\n );\n const params = await result.params;\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, params, navState, commit };\n });\n endings.track(render);\n await render;\n } catch (error) {\n // Neither path is a navigate(), and neither has a caller that\n // handles a rejection — `refresh()` is `void`-called everywhere it\n // is used, and nobody awaits a traversal at all. Without the same\n // recovery `navigate()` gets, a 500 on Back left the user on the\n // old document with an unhandled rejection in the console\n // (TIM-1277).\n //\n // `url` is both the destination and the departure point: the\n // browser has already traversed, and `refresh()` is by definition\n // where it already is. So `hardNavigate()` takes its same-document\n // branch and reloads rather than pushing an entry.\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n url,\n { types: [type], replace: true, scroll: true },\n endings\n )\n )\n return;\n throw error;\n }\n\n if (opts.scrollY !== undefined) restoreScrollAfterPaint(opts.scrollY);\n },\n opts.externalSignal\n );\n }\n\n function refresh(options: RefreshOptions = {}): NavigationHandle {\n return runAsHandle((endings) => refreshWith(options, endings));\n }\n\n async function refreshWith(options: RefreshOptions, endings: NavigationEndings): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n // A refresh on a stale client is a full document load of the current URL.\n // Same rule as navigate(): the RSC fetch would only be answered with\n // another reload signal, and this is caller-initiated, not spontaneous\n // (TIM-1275).\n if (isClientStale()) {\n await leaveSpaSuperseding(currentUrl, currentUrl);\n }\n\n await fetchCommitAndRender(currentUrl, options.transitionType ?? 'refresh', endings);\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal,\n direction: TraverseDirection = 'navigation-traverse'\n ): Promise<void> {\n // A stale client hard-navigates on back/forward too — this path never\n // reaches navigate(), so it needs the same check. `url` is where the\n // browser has *already* traversed to, so leaveSpa's same-document\n // branch reloads there rather than pushing a new entry (TIM-1275).\n //\n // This overrides the cached-payload replay below on purpose. Replaying\n // would work — the payload was decoded by this bundle — but it would keep\n // the user on superseded code for as long as they browse within history.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, url);\n }\n\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip.\n //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async (owner) => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n //\n // No fetch to be superseded — `runNavigation` has already superseded\n // whatever was in flight before it (TIM-1022) — but the render still\n // goes out through a transition React may hold (a replayed tree can\n // suspend), so the publish rides that commit rather than running\n // here. Publishing first would report the replayed route's tree\n // paths while the departing tree is still on screen (TIM-1423,\n // codex on #1108).\n //\n // Routed through renderViaTransition so the replay gets the same\n // lifecycle every other render has — handoff tracking, commit-on-\n // commit, forgetOlderHandoffs — rather than a hand-rolled publish\n // that misses one of them (TIM-1478). The perform resolves\n // immediately: there is no fetch, and the cached payload is\n // already decoded.\n await renderViaTransition(url, owner, [direction], async () => {\n const { navState, commit } = prepareNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n return {\n payload: entry.payload,\n params: entry.params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo: entry.segmentInfo ?? null,\n };\n });\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n await runAsHandle((endings) =>\n fetchCommitAndRender(url, direction, endings, {\n stateTree: currentStateTree(),\n scrollY,\n externalSignal,\n })\n );\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n *\n * Concurrent hovers and a click during the round-trip coalesce via the\n * singleflight inside PrefetchCache (TIM-1438).\n */\n function prefetch(url: string): void {\n // A stale client hard-navigates on every navigation, so a prefetched RSC\n // payload could never be consumed — and the fetch would be answered with\n // another reload signal anyway (TIM-1275).\n if (isClientStale()) return;\n\n // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The page the link is on. Sent as X-Timber-URL so the prefetched payload\n // is the one the click would have produced — an intercepting link hovered\n // from /gallery must prefetch the modal, not the full page — and stored\n // under the same source so only a click departing from here consumes it\n // (TIM-1265). The key is built by the pipeline, which is also what builds\n // the one the click looks up with, so the two cannot disagree.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(fetchUrl, deps.getCurrentUrl(), stateTree);\n const from = cacheKey.from;\n\n // Don't prefetch if already cached (ready or negative)\n if (prefetchCache.has(cacheKey)) return;\n\n // Fire-and-forget. Concurrent hovers coalesce in the singleflight;\n // a click during the round-trip joins the same flight via\n // fetchOrCoalesce in performNavigationFetch (TIM-1438).\n void prefetchCache\n .fetchOrCoalesce(\n cacheKey,\n (signal) => fetchRscPayload(fetchUrl, deps, stateTree, from, signal),\n (err) => err instanceof NonRscResponse\n )\n .then(\n (outcome) => {\n if (outcome.kind === 'ready') {\n // The decode rejects separately from the fetch, so the stale\n // shapes reach us here rather than in the rejection handler\n // below — swallowing it wholesale threw away the same evidence\n // (TIM-1275).\n outcome.result.decodePromise?.catch((error: unknown) => void recordSkew(error));\n }\n },\n (error) => {\n // A prefetch can be the first thing to learn we are stale —\n // during a rollout it may reach the new deployment while the\n // click that follows reaches the old one and completes as an\n // ordinary SPA navigation, throwing the evidence away. Record\n // it, but never recover from here: nobody navigated, and a page\n // load triggered by a hover is exactly the unasked-for reload\n // this design removed. The next click takes the document-load\n // path (TIM-1275).\n recordSkew(error);\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n saveScrollPosition: () => void saveScrollPosition(),\n isPending,\n getPendingUrl,\n onPendingChange,\n prefetch,\n epoch: () => lifecycle.epoch(),\n isEpochCurrent: (epoch) => lifecycle.isEpochCurrent(epoch),\n\n async applyActionResult(epoch, tree) {\n if (!lifecycle.isEpochCurrent(epoch)) return false;\n if (tree === undefined) {\n // Await through the commit so the next queued action captures a\n // current epoch — refresh() alone resolves before React commits\n // on the History API fallback (codex on #1125). The outcome\n // distinguishes a committed refresh from one superseded by a\n // navigation the user started while the refresh was in flight\n // (TIM-1477).\n const refreshed = refresh({ transitionType: 'revalidate' });\n await refreshed.catch(() => {});\n return (await refreshed.committed) === 'committed';\n }\n // Render the piggybacked payload from a server action response.\n // Routed through renderViaTransition so the piggybacked tree gets\n // the same commit lifecycle every other render has (TIM-1478).\n // The perform resolves immediately — the payload is already in hand.\n const currentUrl = deps.getCurrentUrl();\n const payloadTree = readPayloadTree(tree);\n const params = readPublishedParams(tree);\n // The response carries no segment metadata; the page it re-renders is\n // the one the last commit made current, and the committer kept that\n // page's. Not a history-stack lookup by `currentUrl`: the stack is keyed\n // by the spelling `navigate()` was given, which need not be\n // `window.location`'s (TIM-1541).\n const segmentInfo = committedSegmentInfo();\n\n // Place in the lifecycle's slot so a concurrent navigation supersedes\n // this owner. The epoch check above ensures the slot is idle. Don't use\n // createNavOwner — that bumps navigationSeq, which is reserved for\n // navigations (the epoch test pins this: TIM-1474).\n const owner = createRenderOwner('revalidation');\n lifecycle.placeRevalidationOwner(owner);\n const render = renderViaTransition(\n currentUrl,\n owner,\n ['revalidate' satisfies NavigationTransitionType],\n async () => {\n const { navState, commit } = prepareNavigation(currentUrl, {\n payload: payloadTree,\n params,\n segmentInfo,\n });\n return {\n payload: payloadTree,\n params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo,\n };\n }\n );\n await render.catch(() => {});\n return (await render.committed) === 'committed';\n },\n runWhenIdle: (task: () => void) => lifecycle.runWhenIdle(task),\n onIdle: (listener) => lifecycle.onIdle(listener),\n onTreeCommit: (listener) => lifecycle.onTreeCommit(listener),\n settleHandoffs: () => lifecycle.settleHandoffs(),\n evictStaleCaches(): void {\n prefetchCache.clearReady();\n historyStack.clear();\n },\n hydrate(page) {\n // Where hydration seeds the current page: the same prepare-and-commit\n // every navigation goes through, so the segment cache, the committed\n // segment metadata and the history entry are written by one commit\n // rather than by bootstrap reaching into each (TIM-1541). Committed\n // here, at once — see `RouterInstance.hydrate` for why not on React's\n // hydration commit.\n //\n // Replaying this entry on a Back re-renders `payload` and republishes\n // `params`. Both came out of one split of one decoded payload root\n // (rsc-stream.ts), so the entry cannot replay with another route's\n // params (TIM-1037, TIM-1285).\n const { navState, commit } = prepareNavigation(deps.getCurrentUrl(), {\n payload: page.payload,\n params: page.params,\n segmentInfo: page.segmentInfo,\n });\n commit();\n return navState;\n },\n segmentCache,\n prefetchCache,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * One unconditional read of NavigationContext, on every side (TIM-1425):\n *\n * - In the browser, the provider is updated atomically with the RSC tree\n * during full navigations, AND by syncShallowSearch() for shallow URL\n * updates (nuqs shallow: true, replaceUrl, or any external\n * pushState/replaceState that changes the query string). See router-init.ts.\n * - During SSR, the wrapper chain mounts the same provider carrying the\n * request's RAW query string (TIM-1424), so repeated keys\n * (`?tag=a&tag=b`) survive — the collapsed record the ALS context holds\n * cannot represent them.\n * - In the RSC environment, this module is never evaluated — the shims plugin\n * resolves next/navigation to navigation-rsc.ts (TIM-1420).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { useSsrData } from './ssr-data.ts';\nimport { useNavigationContext } from './navigation-context.ts';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.ts';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Throws when no NavigationProvider is above the caller.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n const nav = useNavigationContext();\n const ssrData = useSsrData();\n if (nav === null) {\n throw new Error(\n '[timber] useSearchParams() was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n // On the server, return a fresh instance per call. The module-level cache\n // below exists to give client code stable identity for effect deps; on the\n // server it would be shared mutable state across concurrent requests\n // (design/13-security.md, \"no global fallback state\"). Both halves of the\n // check matter: `window` is absent in a plain Node SSR render, and\n // the SSR data context catches SSR environments that do define `window`\n // (wrapSsrElement always provides it). Pinned by tests/ssr-provider-hooks.test.ts.\n if (typeof window === 'undefined' || ssrData) {\n return new URLSearchParams(nav.search);\n }\n return getSearchParams(nav.search);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2CA,IAAa,eAAb,MAA0B;CACxB,QAA0B,CAAC;;CAG3B,OAAO,aAA2C;EAChD,KAAK,QAAQ,YAAY,SAAS,SAAU,KAAK,WAAW,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAE;CACnF;CAEA,QAAc;EACZ,KAAK,QAAQ,CAAC;CAChB;;CAGA,YAAsB;EACpB,OAAO,CAAC,GAAG,KAAK,KAAK;CACvB;AACF;;AAUA,IAAM,iBAAiC,OAAO,OAAO,EAAE,SAAS,KAAK,CAAC;;;;;;AAOtE,IAAM,mCAAmC;;;;;;AAyCzC,SAAS,eAAe,KAA0B;CAChD,OAAO,GAAG,IAAI,KAAK,OAAO,GAAG,IAAI,KAAK,GAAG,IAAI,MAAM,OAAO,GAAG,IAAI,MAAM,GAAG,IAAI;AAChF;;;;;;AAOA,SAAgB,gBAAgB,WAA0C;CACxE,OAAO,WAAW,WAAW,KAAK,IAAQ,KAAK;AACjD;;;;;;;;;;;;;;;AAwBA,IAAa,gBAAb,MAAa,cAAc;CACzB,OAAwB,SAAS;CACjC,0BAAkB,IAAI,IAAwB;CAC9C,UAAkB,mBAAmB,EAAE,WAAW,iCAAiC,CAAC;CACpF,cAAsB;CAEtB,IAAI,KAAkB,QAA8B;EAClD,KAAK,QAAQ,IAAI,eAAe,GAAG,GAAG;GACpC;GACA,WAAW,KAAK,IAAI,IAAI,cAAc;EACxC,CAAC;CACH;CAEA,IAAI,KAA8C;EAChD,MAAM,SAAS,eAAe,GAAG;EACjC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QAAiC;CACxD,IAAI,WAAW,cAAc;EAC3B,MAAM,SAAS,IAAI,gBAAgB,MAAM;EACzC,iBAAiB,QAAQ,MAAM;EAC/B,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAmC;CACjD,MAAM,MAAM,qBAAqB;CACjC,MAAM,UAAU,WAAW;CAC3B,IAAI,QAAQ,MACV,MAAM,IAAI,MACR,8JAGF;CASF,IAAI,OAAO,WAAW,eAAe,SACnC,OAAO,IAAI,gBAAgB,IAAI,MAAM;CAEvC,OAAO,gBAAgB,IAAI,MAAM;AACnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../../src/client/link.tsx"],"names":[],"mappings":"AAqBA,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,SAAS,EAEf,MAAM,OAAO,CAAC;AAEf,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,EACL,sBAAsB,IAAI,gBAAgB,EAC1C,cAAc,EACf,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../../src/client/link.tsx"],"names":[],"mappings":"AAqBA,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,SAAS,EAEf,MAAM,OAAO,CAAC;AAEf,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,EACL,sBAAsB,IAAI,gBAAgB,EAC1C,cAAc,EACf,MAAM,8BAA8B,CAAC;AA0CtC,MAAM,MAAM,eAAe,GAAG;IAC5B,cAAc,EAAE,MAAM,IAAI,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,C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3C,CAAC;AACF,MAAM,MAAM,SAAS,GAAG,gBAAgB,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,CAAC;AAI5C,UAAU,eAAe;IACvB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,GAAG;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACpC,YAAY,CAAC,EAAE,eAAe,CAAC;CAChC,GACA,eAAe,CAIjB;AAkCD;;;;;;;;;;;;;;;;GAgBG;AAIH,eAAO,MAAM,IAAI,EAAE,YAgMlB,CAAC"}
|
|
@@ -1,52 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* SSR Data —
|
|
2
|
+
* SSR Data — the request values client code reads while rendering on the server.
|
|
3
3
|
*
|
|
4
|
-
* `useCookie()` and `<Link preserveSearchParams>` have no
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* `ParamsContext`, decoded from the payload root.
|
|
4
|
+
* `useCookie()` and `<Link preserveSearchParams>` have no other way to see the
|
|
5
|
+
* request's cookies and search string during SSR, so the SSR wrapper chain
|
|
6
|
+
* (server/ssr-wrappers.tsx) provides them here. `useSearchParams()` reads
|
|
7
|
+
* NavigationContext and checks this context only to tell that it is
|
|
8
|
+
* rendering on the server. Route params travel in `ParamsContext`, decoded
|
|
9
|
+
* from the payload root.
|
|
11
10
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* render (in the browser, or before the provider is registered) there is no
|
|
17
|
-
* request, and getSsrData() returns undefined.
|
|
11
|
+
* Link reads the search string here rather than from NavigationContext
|
|
12
|
+
* because this context never changes in the browser: subscribing every Link
|
|
13
|
+
* to NavigationContext would re-render all of them on each navigation.
|
|
14
|
+
* wrapSsrElement fills both from the same `search` option.
|
|
18
15
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
16
|
+
* Why a React context, not AsyncLocalStorage: Fizz resumes a suspended
|
|
17
|
+
* subtree (an async layout, a lazy Flight row) from whatever callback
|
|
18
|
+
* resolved it. On Node that is a `data` event of the Flight stream, which
|
|
19
|
+
* runs in the async context of the RSC render that produced the chunk, not
|
|
20
|
+
* the SSR request's. An ALS store set around `handleSsr` was gone there, so
|
|
21
|
+
* every cookie read below the first streamed chunk came back empty. A
|
|
22
|
+
* context value is part of the request's element tree: React restores it
|
|
23
|
+
* wherever it resumes the tree, and concurrent requests cannot see each
|
|
24
|
+
* other's.
|
|
23
25
|
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
+
* In the browser no provider is mounted and `useSsrData()` returns null.
|
|
27
|
+
*
|
|
28
|
+
* IMPORTANT: This module is imported by 'use client' hooks bundled for the
|
|
29
|
+
* browser. It must not import node:async_hooks or other Node-only APIs.
|
|
26
30
|
*/
|
|
31
|
+
import * as React from 'react';
|
|
27
32
|
export interface SsrData {
|
|
28
33
|
/**
|
|
29
34
|
* The request's raw app-visible query string (`''` or `?…`), matching what
|
|
30
|
-
* `window.location.search` will hold after hydration.
|
|
31
|
-
*
|
|
32
|
-
* (`?tag=a&tag=b`), which a collapsed `Record<string, string>` cannot
|
|
33
|
-
* (TIM-1428). Parse with `new URLSearchParams(search)` where needed.
|
|
35
|
+
* `window.location.search` will hold after hydration. Raw, so repeated keys
|
|
36
|
+
* (`?tag=a&tag=b`) survive (TIM-1428).
|
|
34
37
|
*/
|
|
35
38
|
search: string;
|
|
36
39
|
/** The request's cookies as name→value pairs */
|
|
37
|
-
cookies:
|
|
40
|
+
cookies: ReadonlyMap<string, string>;
|
|
38
41
|
}
|
|
39
|
-
/**
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
* Read the current request's SSR data. Returns undefined when called
|
|
47
|
-
* outside an SSR render (i.e. on the client after hydration).
|
|
48
|
-
*
|
|
49
|
-
* Used by client hooks' server snapshot functions.
|
|
50
|
-
*/
|
|
51
|
-
export declare function getSsrData(): SsrData | undefined;
|
|
42
|
+
/** The current request's SSR data, or null outside a server render. */
|
|
43
|
+
export declare function useSsrData(): SsrData | null;
|
|
44
|
+
/** Provides the request's SSR data to the tree. Mounted by wrapSsrElement only. */
|
|
45
|
+
export declare function SsrDataProvider({ value, children, }: {
|
|
46
|
+
value: SsrData;
|
|
47
|
+
children?: React.ReactNode;
|
|
48
|
+
}): React.ReactElement;
|
|
52
49
|
//# sourceMappingURL=ssr-data.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-data.d.ts","sourceRoot":"","sources":["../../src/client/ssr-data.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"ssr-data.d.ts","sourceRoot":"","sources":["../../src/client/ssr-data.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,MAAM,WAAW,OAAO;IACtB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC;AAUD,uEAAuE;AACvE,wBAAgB,UAAU,IAAI,OAAO,GAAG,IAAI,CAE3C;AAED,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,EAC9B,KAAK,EACL,QAAQ,GACT,EAAE;IACD,KAAK,EAAE,OAAO,CAAC;IACf,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;CAC5B,GAAG,KAAK,CAAC,YAAY,CAErB"}
|
package/dist/client/state.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Centralized client singleton state registry.
|
|
3
3
|
*
|
|
4
4
|
* ALL mutable module-level state that must have singleton semantics across
|
|
5
|
-
* the client bundle lives here. Individual modules (router-ref.ts,
|
|
5
|
+
* the client bundle lives here. Individual modules (router-ref.ts,
|
|
6
6
|
* use-segment-params.ts, use-search-params.ts, unload-guard.ts) import from this file
|
|
7
7
|
* and re-export thin wrapper functions.
|
|
8
8
|
*
|
|
@@ -19,16 +19,9 @@
|
|
|
19
19
|
* §"Singleton State Registry".
|
|
20
20
|
*/
|
|
21
21
|
import type { RouterInstance } from './router-types.ts';
|
|
22
|
-
import type { SsrData } from './ssr-data.ts';
|
|
23
22
|
/** The global router singleton — set once during bootstrap. */
|
|
24
23
|
export declare let globalRouter: RouterInstance | null;
|
|
25
24
|
export declare function _setGlobalRouter(router: RouterInstance | null): void;
|
|
26
|
-
/**
|
|
27
|
-
* ALS-backed SSR data provider, registered by the SSR entry. getSsrData()
|
|
28
|
-
* reads through it; unset in the browser.
|
|
29
|
-
*/
|
|
30
|
-
export declare let ssrDataProvider: (() => SsrData | undefined) | undefined;
|
|
31
|
-
export declare function _setSsrDataProvider(provider: (() => SsrData | undefined) | undefined): void;
|
|
32
25
|
/** Cached search string — avoids reparsing when URL hasn't changed. */
|
|
33
26
|
export declare let cachedSearch: string;
|
|
34
27
|
export declare let cachedSearchParams: URLSearchParams;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/client/state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/client/state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAIxD,+DAA+D;AAC/D,eAAO,IAAI,YAAY,EAAE,cAAc,GAAG,IAAW,CAAC;AAEtD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,GAAG,IAAI,CAEpE;AAID,uEAAuE;AACvE,eAAO,IAAI,YAAY,QAAK,CAAC;AAC7B,eAAO,IAAI,kBAAkB,iBAAwB,CAAC;AAEtD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,IAAI,CAG9E;AAID,oDAAoD;AACpD,eAAO,IAAI,SAAS,SAAQ,CAAC;AAE7B,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAElD;AAID;;;;;GAKG;AACH,eAAO,IAAI,kBAAkB,SAAQ,CAAC;AAEtC,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAE3D;AAED;;;;;GAKG;AACH,eAAO,IAAI,oBAAoB,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;AAE1D,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,CAEhF"}
|