@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +4960 -935
  5. package/package.json +70 -60
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +294 -0
  8. package/skills/caching/SKILL.md +93 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +167 -0
  13. package/skills/handler-use/SKILL.md +362 -0
  14. package/skills/hooks/SKILL.md +334 -72
  15. package/skills/host-router/SKILL.md +218 -0
  16. package/skills/intercept/SKILL.md +151 -8
  17. package/skills/layout/SKILL.md +122 -3
  18. package/skills/links/SKILL.md +92 -31
  19. package/skills/loader/SKILL.md +404 -44
  20. package/skills/middleware/SKILL.md +205 -37
  21. package/skills/migrate-nextjs/SKILL.md +560 -0
  22. package/skills/migrate-react-router/SKILL.md +764 -0
  23. package/skills/mime-routes/SKILL.md +128 -0
  24. package/skills/parallel/SKILL.md +263 -1
  25. package/skills/prerender/SKILL.md +685 -0
  26. package/skills/rango/SKILL.md +87 -16
  27. package/skills/response-routes/SKILL.md +411 -0
  28. package/skills/route/SKILL.md +281 -14
  29. package/skills/router-setup/SKILL.md +210 -32
  30. package/skills/tailwind/SKILL.md +129 -0
  31. package/skills/theme/SKILL.md +9 -8
  32. package/skills/typesafety/SKILL.md +328 -89
  33. package/skills/use-cache/SKILL.md +324 -0
  34. package/src/__internal.ts +102 -4
  35. package/src/bin/rango.ts +321 -0
  36. package/src/browser/action-coordinator.ts +97 -0
  37. package/src/browser/action-response-classifier.ts +99 -0
  38. package/src/browser/app-version.ts +14 -0
  39. package/src/browser/event-controller.ts +92 -64
  40. package/src/browser/history-state.ts +80 -0
  41. package/src/browser/intercept-utils.ts +52 -0
  42. package/src/browser/link-interceptor.ts +24 -4
  43. package/src/browser/logging.ts +55 -0
  44. package/src/browser/merge-segment-loaders.ts +20 -12
  45. package/src/browser/navigation-bridge.ts +317 -560
  46. package/src/browser/navigation-client.ts +206 -68
  47. package/src/browser/navigation-store.ts +73 -55
  48. package/src/browser/navigation-transaction.ts +297 -0
  49. package/src/browser/network-error-handler.ts +61 -0
  50. package/src/browser/partial-update.ts +343 -316
  51. package/src/browser/prefetch/cache.ts +216 -0
  52. package/src/browser/prefetch/fetch.ts +206 -0
  53. package/src/browser/prefetch/observer.ts +65 -0
  54. package/src/browser/prefetch/policy.ts +48 -0
  55. package/src/browser/prefetch/queue.ts +160 -0
  56. package/src/browser/prefetch/resource-ready.ts +77 -0
  57. package/src/browser/rango-state.ts +112 -0
  58. package/src/browser/react/Link.tsx +253 -74
  59. package/src/browser/react/NavigationProvider.tsx +87 -11
  60. package/src/browser/react/context.ts +11 -0
  61. package/src/browser/react/filter-segment-order.ts +11 -0
  62. package/src/browser/react/index.ts +12 -12
  63. package/src/browser/react/location-state-shared.ts +95 -53
  64. package/src/browser/react/location-state.ts +60 -15
  65. package/src/browser/react/mount-context.ts +6 -1
  66. package/src/browser/react/nonce-context.ts +23 -0
  67. package/src/browser/react/shallow-equal.ts +27 -0
  68. package/src/browser/react/use-action.ts +29 -51
  69. package/src/browser/react/use-client-cache.ts +5 -3
  70. package/src/browser/react/use-handle.ts +30 -126
  71. package/src/browser/react/use-href.tsx +2 -2
  72. package/src/browser/react/use-link-status.ts +6 -5
  73. package/src/browser/react/use-navigation.ts +44 -65
  74. package/src/browser/react/use-params.ts +65 -0
  75. package/src/browser/react/use-pathname.ts +47 -0
  76. package/src/browser/react/use-router.ts +76 -0
  77. package/src/browser/react/use-search-params.ts +56 -0
  78. package/src/browser/react/use-segments.ts +80 -97
  79. package/src/browser/response-adapter.ts +73 -0
  80. package/src/browser/rsc-router.tsx +214 -58
  81. package/src/browser/scroll-restoration.ts +127 -52
  82. package/src/browser/segment-reconciler.ts +243 -0
  83. package/src/browser/segment-structure-assert.ts +16 -0
  84. package/src/browser/server-action-bridge.ts +510 -603
  85. package/src/browser/shallow.ts +6 -1
  86. package/src/browser/types.ts +141 -48
  87. package/src/browser/validate-redirect-origin.ts +29 -0
  88. package/src/build/generate-manifest.ts +235 -24
  89. package/src/build/generate-route-types.ts +39 -0
  90. package/src/build/index.ts +13 -0
  91. package/src/build/route-trie.ts +291 -0
  92. package/src/build/route-types/ast-helpers.ts +25 -0
  93. package/src/build/route-types/ast-route-extraction.ts +98 -0
  94. package/src/build/route-types/codegen.ts +102 -0
  95. package/src/build/route-types/include-resolution.ts +418 -0
  96. package/src/build/route-types/param-extraction.ts +48 -0
  97. package/src/build/route-types/per-module-writer.ts +128 -0
  98. package/src/build/route-types/router-processing.ts +618 -0
  99. package/src/build/route-types/scan-filter.ts +85 -0
  100. package/src/build/runtime-discovery.ts +231 -0
  101. package/src/cache/background-task.ts +34 -0
  102. package/src/cache/cache-key-utils.ts +44 -0
  103. package/src/cache/cache-policy.ts +125 -0
  104. package/src/cache/cache-runtime.ts +342 -0
  105. package/src/cache/cache-scope.ts +167 -309
  106. package/src/cache/cf/cf-cache-store.ts +571 -17
  107. package/src/cache/cf/index.ts +13 -3
  108. package/src/cache/document-cache.ts +116 -77
  109. package/src/cache/handle-capture.ts +81 -0
  110. package/src/cache/handle-snapshot.ts +41 -0
  111. package/src/cache/index.ts +1 -15
  112. package/src/cache/memory-segment-store.ts +191 -13
  113. package/src/cache/profile-registry.ts +73 -0
  114. package/src/cache/read-through-swr.ts +134 -0
  115. package/src/cache/segment-codec.ts +256 -0
  116. package/src/cache/taint.ts +153 -0
  117. package/src/cache/types.ts +72 -122
  118. package/src/client.rsc.tsx +3 -1
  119. package/src/client.tsx +135 -301
  120. package/src/component-utils.ts +4 -4
  121. package/src/components/DefaultDocument.tsx +5 -1
  122. package/src/context-var.ts +156 -0
  123. package/src/debug.ts +19 -9
  124. package/src/errors.ts +108 -2
  125. package/src/handle.ts +55 -29
  126. package/src/handles/MetaTags.tsx +73 -20
  127. package/src/handles/breadcrumbs.ts +66 -0
  128. package/src/handles/index.ts +1 -0
  129. package/src/handles/meta.ts +30 -13
  130. package/src/host/cookie-handler.ts +21 -15
  131. package/src/host/errors.ts +8 -8
  132. package/src/host/index.ts +4 -7
  133. package/src/host/pattern-matcher.ts +27 -27
  134. package/src/host/router.ts +61 -39
  135. package/src/host/testing.ts +8 -8
  136. package/src/host/types.ts +15 -7
  137. package/src/host/utils.ts +1 -1
  138. package/src/href-client.ts +119 -29
  139. package/src/index.rsc.ts +155 -19
  140. package/src/index.ts +251 -30
  141. package/src/internal-debug.ts +11 -0
  142. package/src/loader.rsc.ts +26 -157
  143. package/src/loader.ts +27 -10
  144. package/src/network-error-thrower.tsx +3 -1
  145. package/src/outlet-provider.tsx +45 -0
  146. package/src/prerender/param-hash.ts +37 -0
  147. package/src/prerender/store.ts +186 -0
  148. package/src/prerender.ts +524 -0
  149. package/src/reverse.ts +354 -0
  150. package/src/root-error-boundary.tsx +41 -29
  151. package/src/route-content-wrapper.tsx +7 -4
  152. package/src/route-definition/dsl-helpers.ts +1121 -0
  153. package/src/route-definition/helper-factories.ts +200 -0
  154. package/src/route-definition/helpers-types.ts +478 -0
  155. package/src/route-definition/index.ts +55 -0
  156. package/src/route-definition/redirect.ts +101 -0
  157. package/src/route-definition/resolve-handler-use.ts +149 -0
  158. package/src/route-definition.ts +1 -1428
  159. package/src/route-map-builder.ts +217 -123
  160. package/src/route-name.ts +53 -0
  161. package/src/route-types.ts +77 -8
  162. package/src/router/content-negotiation.ts +215 -0
  163. package/src/router/debug-manifest.ts +72 -0
  164. package/src/router/error-handling.ts +9 -9
  165. package/src/router/find-match.ts +160 -0
  166. package/src/router/handler-context.ts +438 -86
  167. package/src/router/intercept-resolution.ts +402 -0
  168. package/src/router/lazy-includes.ts +237 -0
  169. package/src/router/loader-resolution.ts +356 -128
  170. package/src/router/logging.ts +251 -0
  171. package/src/router/manifest.ts +163 -35
  172. package/src/router/match-api.ts +555 -0
  173. package/src/router/match-context.ts +5 -3
  174. package/src/router/match-handlers.ts +440 -0
  175. package/src/router/match-middleware/background-revalidation.ts +108 -93
  176. package/src/router/match-middleware/cache-lookup.ts +460 -10
  177. package/src/router/match-middleware/cache-store.ts +98 -26
  178. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  179. package/src/router/match-middleware/segment-resolution.ts +80 -6
  180. package/src/router/match-pipelines.ts +10 -45
  181. package/src/router/match-result.ts +135 -35
  182. package/src/router/metrics.ts +240 -15
  183. package/src/router/middleware-cookies.ts +55 -0
  184. package/src/router/middleware-types.ts +220 -0
  185. package/src/router/middleware.ts +324 -369
  186. package/src/router/navigation-snapshot.ts +182 -0
  187. package/src/router/pattern-matching.ts +211 -43
  188. package/src/router/prerender-match.ts +502 -0
  189. package/src/router/preview-match.ts +98 -0
  190. package/src/router/request-classification.ts +310 -0
  191. package/src/router/revalidation.ts +137 -38
  192. package/src/router/route-snapshot.ts +245 -0
  193. package/src/router/router-context.ts +41 -21
  194. package/src/router/router-interfaces.ts +484 -0
  195. package/src/router/router-options.ts +618 -0
  196. package/src/router/router-registry.ts +24 -0
  197. package/src/router/segment-resolution/fresh.ts +748 -0
  198. package/src/router/segment-resolution/helpers.ts +268 -0
  199. package/src/router/segment-resolution/loader-cache.ts +199 -0
  200. package/src/router/segment-resolution/revalidation.ts +1379 -0
  201. package/src/router/segment-resolution/static-store.ts +67 -0
  202. package/src/router/segment-resolution.ts +21 -0
  203. package/src/router/segment-wrappers.ts +291 -0
  204. package/src/router/telemetry-otel.ts +299 -0
  205. package/src/router/telemetry.ts +300 -0
  206. package/src/router/timeout.ts +148 -0
  207. package/src/router/trie-matching.ts +239 -0
  208. package/src/router/types.ts +78 -3
  209. package/src/router.ts +740 -4252
  210. package/src/rsc/handler-context.ts +45 -0
  211. package/src/rsc/handler.ts +907 -797
  212. package/src/rsc/helpers.ts +140 -6
  213. package/src/rsc/index.ts +0 -20
  214. package/src/rsc/loader-fetch.ts +229 -0
  215. package/src/rsc/manifest-init.ts +90 -0
  216. package/src/rsc/nonce.ts +14 -0
  217. package/src/rsc/origin-guard.ts +141 -0
  218. package/src/rsc/progressive-enhancement.ts +391 -0
  219. package/src/rsc/response-error.ts +37 -0
  220. package/src/rsc/response-route-handler.ts +347 -0
  221. package/src/rsc/rsc-rendering.ts +246 -0
  222. package/src/rsc/runtime-warnings.ts +42 -0
  223. package/src/rsc/server-action.ts +356 -0
  224. package/src/rsc/ssr-setup.ts +128 -0
  225. package/src/rsc/types.ts +46 -11
  226. package/src/search-params.ts +230 -0
  227. package/src/segment-content-promise.ts +67 -0
  228. package/src/segment-loader-promise.ts +122 -0
  229. package/src/segment-system.tsx +134 -36
  230. package/src/server/context.ts +341 -61
  231. package/src/server/cookie-store.ts +190 -0
  232. package/src/server/fetchable-loader-store.ts +37 -0
  233. package/src/server/handle-store.ts +113 -15
  234. package/src/server/loader-registry.ts +24 -64
  235. package/src/server/request-context.ts +607 -81
  236. package/src/server.ts +35 -130
  237. package/src/ssr/index.tsx +103 -30
  238. package/src/static-handler.ts +126 -0
  239. package/src/theme/ThemeProvider.tsx +21 -15
  240. package/src/theme/ThemeScript.tsx +5 -5
  241. package/src/theme/constants.ts +5 -2
  242. package/src/theme/index.ts +4 -14
  243. package/src/theme/theme-context.ts +4 -30
  244. package/src/theme/theme-script.ts +21 -18
  245. package/src/types/boundaries.ts +158 -0
  246. package/src/types/cache-types.ts +198 -0
  247. package/src/types/error-types.ts +192 -0
  248. package/src/types/global-namespace.ts +100 -0
  249. package/src/types/handler-context.ts +791 -0
  250. package/src/types/index.ts +88 -0
  251. package/src/types/loader-types.ts +210 -0
  252. package/src/types/route-config.ts +170 -0
  253. package/src/types/route-entry.ts +120 -0
  254. package/src/types/segments.ts +150 -0
  255. package/src/types.ts +1 -1623
  256. package/src/urls/include-helper.ts +207 -0
  257. package/src/urls/index.ts +53 -0
  258. package/src/urls/path-helper-types.ts +372 -0
  259. package/src/urls/path-helper.ts +364 -0
  260. package/src/urls/pattern-types.ts +107 -0
  261. package/src/urls/response-types.ts +116 -0
  262. package/src/urls/type-extraction.ts +372 -0
  263. package/src/urls/urls-function.ts +98 -0
  264. package/src/urls.ts +1 -802
  265. package/src/use-loader.tsx +161 -81
  266. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  267. package/src/vite/discovery/discover-routers.ts +348 -0
  268. package/src/vite/discovery/prerender-collection.ts +439 -0
  269. package/src/vite/discovery/route-types-writer.ts +258 -0
  270. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  271. package/src/vite/discovery/state.ts +117 -0
  272. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  273. package/src/vite/index.ts +15 -1133
  274. package/src/vite/plugin-types.ts +103 -0
  275. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  276. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  277. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  278. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  279. package/src/vite/plugins/expose-id-utils.ts +299 -0
  280. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  281. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  282. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  283. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  284. package/src/vite/plugins/expose-ids/types.ts +45 -0
  285. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  286. package/src/vite/plugins/performance-tracks.ts +88 -0
  287. package/src/vite/plugins/refresh-cmd.ts +127 -0
  288. package/src/vite/plugins/use-cache-transform.ts +323 -0
  289. package/src/vite/plugins/version-injector.ts +83 -0
  290. package/src/vite/plugins/version-plugin.ts +266 -0
  291. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  292. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  293. package/src/vite/rango.ts +462 -0
  294. package/src/vite/router-discovery.ts +918 -0
  295. package/src/vite/utils/ast-handler-extract.ts +517 -0
  296. package/src/vite/utils/banner.ts +36 -0
  297. package/src/vite/utils/bundle-analysis.ts +137 -0
  298. package/src/vite/utils/manifest-utils.ts +70 -0
  299. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  300. package/src/vite/utils/prerender-utils.ts +221 -0
  301. package/src/vite/utils/shared-utils.ts +170 -0
  302. package/CLAUDE.md +0 -43
  303. package/src/browser/lru-cache.ts +0 -69
  304. package/src/browser/request-controller.ts +0 -164
  305. package/src/cache/memory-store.ts +0 -253
  306. package/src/href-context.ts +0 -33
  307. package/src/href.ts +0 -255
  308. package/src/server/route-manifest-cache.ts +0 -173
  309. package/src/vite/expose-handle-id.ts +0 -209
  310. package/src/vite/expose-loader-id.ts +0 -426
  311. package/src/vite/expose-location-state-id.ts +0 -177
  312. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -1,442 +1,46 @@
1
1
  import type {
2
2
  NavigationBridge,
3
3
  NavigationBridgeConfig,
4
- NavigateOptions,
5
- NavigationStore,
4
+ NavigateOptionsInternal,
6
5
  ResolvedSegment,
7
6
  } from "./types.js";
7
+ import { setAppVersion } from "./app-version.js";
8
+ import * as React from "react";
9
+ import { startTransition } from "react";
8
10
  import {
9
- isLocationStateEntry,
10
- resolveLocationStateEntries,
11
- } from "./react/location-state-shared.js";
11
+ createNavigationTransaction,
12
+ resolveNavigationState,
13
+ } from "./navigation-transaction.js";
14
+ import { buildHistoryState } from "./history-state.js";
15
+ import {
16
+ handleNavigationStart,
17
+ handleNavigationEnd,
18
+ ensureHistoryKey,
19
+ } from "./scroll-restoration.js";
12
20
 
13
- /**
14
- * Check if state is from typed LocationStateEntry[] (has __rsc_ls_ keys)
15
- */
16
- function isTypedLocationState(
17
- state: unknown
18
- ): state is Record<string, unknown> {
19
- if (state === null || typeof state !== "object") return false;
20
- return Object.keys(state).some((key) => key.startsWith("__rsc_ls_"));
21
- }
21
+ // addTransitionType is only available in React experimental
22
+ const addTransitionType: ((type: string) => void) | undefined =
23
+ "addTransitionType" in React ? (React as any).addTransitionType : undefined;
22
24
 
23
- /**
24
- * Resolve navigation state - handles both LocationStateEntry[] and legacy formats
25
- */
26
- function resolveNavigationState(state: unknown): unknown {
27
- // Check if it's an array of LocationStateEntry
28
- if (
29
- Array.isArray(state) &&
30
- state.length > 0 &&
31
- isLocationStateEntry(state[0])
32
- ) {
33
- return resolveLocationStateEntries(state);
34
- }
35
- // Return as-is for legacy formats
36
- return state;
37
- }
38
-
39
- /**
40
- * Build history state object from user state
41
- * - Typed state: spread directly into history.state
42
- * - Legacy state: store in history.state.state
43
- */
44
- function buildHistoryState(
45
- userState: unknown,
46
- routerState?: { intercept?: boolean; sourceUrl?: string }
47
- ): Record<string, unknown> | null {
48
- const result: Record<string, unknown> = {};
49
-
50
- // Add router internal state
51
- if (routerState?.intercept) {
52
- result.intercept = true;
53
- if (routerState.sourceUrl) {
54
- result.sourceUrl = routerState.sourceUrl;
55
- }
56
- }
57
-
58
- // Add user state
59
- if (userState !== undefined) {
60
- if (isTypedLocationState(userState)) {
61
- // Typed state: spread directly
62
- Object.assign(result, userState);
63
- } else {
64
- // Legacy state: store in .state
65
- result.state = userState;
66
- }
67
- }
68
-
69
- return Object.keys(result).length > 0 ? result : null;
70
- }
71
25
  import { setupLinkInterception } from "./link-interceptor.js";
72
26
  import { createPartialUpdater } from "./partial-update.js";
73
27
  import { generateHistoryKey } from "./navigation-store.js";
28
+ import type { EventController } from "./event-controller.js";
29
+ import { isInterceptOnlyCache } from "./intercept-utils.js";
74
30
  import {
75
- handleNavigationStart,
76
- handleNavigationEnd,
77
- ensureHistoryKey,
78
- } from "./scroll-restoration.js";
79
- import type { EventController, NavigationHandle } from "./event-controller.js";
80
- import { NetworkError, isNetworkError } from "../errors.js";
81
- import { NetworkErrorThrower } from "../network-error-thrower.js";
82
- import { createElement, startTransition } from "react";
31
+ toNetworkError,
32
+ emitNetworkError,
33
+ isBackgroundSuppressible,
34
+ } from "./network-error-handler.js";
35
+ import { debugLog } from "./logging.js";
36
+ import { ServerRedirect } from "../errors.js";
37
+ import { validateRedirectOrigin } from "./validate-redirect-origin.js";
83
38
 
84
39
  // Polyfill Symbol.dispose for Safari and older browsers
85
40
  if (typeof Symbol.dispose === "undefined") {
86
41
  (Symbol as any).dispose = Symbol("Symbol.dispose");
87
42
  }
88
43
 
89
- /**
90
- * Check if a segment is an intercept segment
91
- * Intercept segments have namespace starting with "intercept:" or ID containing .@
92
- */
93
- function isInterceptSegment(s: ResolvedSegment): boolean {
94
- return (
95
- s.namespace?.startsWith("intercept:") ||
96
- (s.type === "parallel" && s.id.includes(".@"))
97
- );
98
- }
99
-
100
- /**
101
- * Check if cached segments are intercept-only (no main route segments)
102
- * Intercept responses shouldn't be used for optimistic rendering since
103
- * whether interception happens depends on the current page context
104
- */
105
- function isInterceptOnlyCache(segments: ResolvedSegment[]): boolean {
106
- return segments.some(isInterceptSegment);
107
- }
108
-
109
- /**
110
- * Options for committing a navigation transaction
111
- */
112
- interface CommitOptions {
113
- url: string;
114
- segmentIds: string[];
115
- segments: ResolvedSegment[];
116
- replace?: boolean;
117
- scroll?: boolean;
118
- /** User-provided state to store in history.state */
119
- state?: unknown;
120
- /** If true, only update store without changing URL/history (for server actions) */
121
- storeOnly?: boolean;
122
- /** If true, this is an intercept route - store in history.state for popstate handling */
123
- intercept?: boolean;
124
- /** Source URL where the intercept was triggered from (stored in history.state) */
125
- interceptSourceUrl?: string;
126
- /** If true, only update cache without touching store or history (for background stale revalidation) */
127
- cacheOnly?: boolean;
128
- }
129
-
130
- /**
131
- * Options that can override the pre-configured commit settings
132
- */
133
- interface BoundCommitOverrides {
134
- /** Override scroll behavior (e.g., disable for intercepts) */
135
- scroll?: boolean;
136
- /** Override replace behavior (e.g., force replace for intercepts) */
137
- replace?: boolean;
138
- /** Override user-provided state */
139
- state?: unknown;
140
- /** Mark this as an intercept route */
141
- intercept?: boolean;
142
- /** Source URL where intercept was triggered from */
143
- interceptSourceUrl?: string;
144
- /** If true, only update cache (for stale revalidation) */
145
- cacheOnly?: boolean;
146
- }
147
-
148
- /**
149
- * Token for tracking an active stream - call end() when stream completes
150
- */
151
- export interface StreamingToken {
152
- end(): void;
153
- }
154
-
155
- /**
156
- * Bound transaction with pre-configured commit options (without segmentIds/segments)
157
- */
158
- export interface BoundTransaction {
159
- readonly currentUrl: string;
160
- /** Start streaming and get a token to end it when the stream completes */
161
- startStreaming(): StreamingToken;
162
- commit(
163
- segmentIds: string[],
164
- segments: ResolvedSegment[],
165
- overrides?: BoundCommitOverrides
166
- ): void;
167
- }
168
-
169
- /**
170
- * Navigation transaction for managing state during navigation
171
- * Uses the event controller handle for lifecycle management
172
- */
173
- interface NavigationTransaction extends Disposable {
174
- /** Optimistically commit from cache - instant render before revalidation */
175
- optimisticCommit(options: CommitOptions): void;
176
- /** Final commit with server data (or reconciliation after optimistic) */
177
- commit(options: CommitOptions): void;
178
- with(
179
- options: Omit<CommitOptions, "segmentIds" | "segments">
180
- ): BoundTransaction;
181
- /** The navigation handle from the event controller */
182
- handle: NavigationHandle;
183
- }
184
-
185
- /**
186
- * Creates a navigation transaction that coordinates with the event controller.
187
- * Handles loading state transitions and cleanup on completion/abort.
188
- *
189
- * Supports optimistic navigation: render from cache immediately,
190
- * then revalidate in background and reconcile if data changed.
191
- */
192
- function createNavigationTransaction(
193
- store: NavigationStore,
194
- eventController: EventController,
195
- url: string,
196
- options?: NavigateOptions & { skipLoadingState?: boolean }
197
- ): NavigationTransaction {
198
- let committed = false;
199
- let optimisticallyCommitted = false;
200
- let earlyStatePushed = false;
201
- const currentUrl = window.location.href;
202
-
203
- // Start navigation in event controller (this sets loading state)
204
- const handle = eventController.startNavigation(url, options);
205
-
206
- // If state is provided, push it to history immediately so loading UI can access it
207
- // This enables "optimistic state" - showing product names in skeletons etc.
208
- if (options?.state !== undefined && !options?.replace) {
209
- const earlyHistoryState = buildHistoryState(options.state);
210
- window.history.pushState(earlyHistoryState, "", url);
211
- earlyStatePushed = true;
212
- }
213
-
214
- /**
215
- * Optimistically commit from cache - renders immediately before revalidation
216
- * Sets optimisticallyCommitted flag so final commit() knows to reconcile
217
- */
218
- function optimisticCommit(opts: CommitOptions): void {
219
- optimisticallyCommitted = true;
220
-
221
- const { url, segmentIds, segments, replace, scroll } = opts;
222
- const parsedUrl = new URL(url, window.location.origin);
223
-
224
- // Save current scroll position before navigating
225
- handleNavigationStart();
226
-
227
- // Update segment state
228
- store.setSegmentIds(segmentIds);
229
- store.setCurrentUrl(url);
230
- store.setPath(parsedUrl.pathname);
231
-
232
- // Generate history key from URL
233
- const historyKey = generateHistoryKey(url);
234
- store.setHistoryKey(historyKey);
235
-
236
- // Cache segments with current handleData (will be overwritten by fresh data on final commit)
237
- const currentHandleData = eventController.getHandleState().data;
238
- store.cacheSegmentsForHistory(historyKey, segments, currentHandleData);
239
-
240
- // Build history state with user state if provided
241
- const historyState = buildHistoryState(opts.state);
242
-
243
- // Update browser URL
244
- // Use replaceState if we already pushed early (for optimistic state access)
245
- if (replace || earlyStatePushed) {
246
- window.history.replaceState(historyState, "", url);
247
- } else {
248
- window.history.pushState(historyState, "", url);
249
- }
250
-
251
- // Ensure new history entry has a scroll restoration key
252
- ensureHistoryKey();
253
-
254
- // Complete the navigation in event controller (sets idle state)
255
- handle.complete(parsedUrl);
256
-
257
- // Handle scroll after navigation
258
- handleNavigationEnd({ scroll });
259
-
260
- console.log(
261
- "[Browser] Optimistic commit from cache, historyKey:",
262
- historyKey
263
- );
264
- }
265
-
266
- /**
267
- * Commit the navigation - updates store and URL atomically
268
- * If optimisticCommit was called, this becomes a reconciliation
269
- */
270
- function commit(opts: CommitOptions): void {
271
- committed = true;
272
-
273
- // If optimistic commit already done, adjust options for reconciliation
274
- const isReconciliation = optimisticallyCommitted;
275
- const {
276
- url,
277
- segmentIds,
278
- segments,
279
- storeOnly,
280
- intercept,
281
- interceptSourceUrl,
282
- cacheOnly,
283
- } = opts;
284
- // For reconciliation: always replace (URL already pushed), no scroll
285
- const replace = isReconciliation ? true : opts.replace;
286
- const scroll = isReconciliation ? false : opts.scroll;
287
-
288
- const parsedUrl = new URL(url, window.location.origin);
289
-
290
- // Generate history key from URL (with intercept suffix for separate caching)
291
- const historyKey = generateHistoryKey(url, { intercept });
292
-
293
- // For cache-only commits (stale revalidation), only update cache and return
294
- // Don't touch store state or history - user may have navigated elsewhere
295
- if (cacheOnly) {
296
- const currentHandleData = eventController.getHandleState().data;
297
- store.cacheSegmentsForHistory(historyKey, segments, currentHandleData);
298
- console.log("[Browser] Cache-only commit, historyKey:", historyKey);
299
- return;
300
- }
301
-
302
- // Save current scroll position before navigating (only for non-reconciliation)
303
- if (!isReconciliation) {
304
- handleNavigationStart();
305
- }
306
-
307
- // Update segment state atomically
308
- store.setSegmentIds(segmentIds);
309
- store.setCurrentUrl(url);
310
- store.setPath(parsedUrl.pathname);
311
-
312
- store.setHistoryKey(historyKey);
313
-
314
- // Cache segments with current handleData for this history entry (fresh data overwrites optimistic)
315
- const currentHandleData = eventController.getHandleState().data;
316
- store.cacheSegmentsForHistory(historyKey, segments, currentHandleData);
317
-
318
- // For server actions, skip URL/history updates but still complete navigation
319
- if (storeOnly) {
320
- console.log("[Browser] Store updated (action)");
321
- // Complete navigation to clear loading state
322
- handle.complete(parsedUrl);
323
- return;
324
- }
325
-
326
- // Build history state - include user state and intercept info for popstate handling
327
- const historyState = buildHistoryState(opts.state, {
328
- intercept,
329
- sourceUrl: interceptSourceUrl,
330
- });
331
-
332
- // Update browser URL (skip if reconciliation - already done in optimisticCommit)
333
- if (!isReconciliation) {
334
- // Use replaceState if we already pushed early (for optimistic state access) or replace requested
335
- if (replace || earlyStatePushed) {
336
- window.history.replaceState(historyState, "", url);
337
- } else {
338
- window.history.pushState(historyState, "", url);
339
- }
340
- // Ensure new history entry has a scroll restoration key
341
- ensureHistoryKey();
342
- }
343
-
344
- // Complete the navigation in event controller (sets idle state, updates location)
345
- handle.complete(parsedUrl);
346
-
347
- // Handle scroll after navigation (skip if reconciliation)
348
- if (!isReconciliation) {
349
- handleNavigationEnd({ scroll });
350
- }
351
-
352
- if (isReconciliation) {
353
- console.log("[Browser] Reconciliation commit, historyKey:", historyKey);
354
- } else {
355
- console.log(
356
- "[Browser] Navigation committed, historyKey:",
357
- historyKey,
358
- intercept ? "(intercept)" : ""
359
- );
360
- }
361
- }
362
-
363
- return {
364
- handle,
365
- optimisticCommit,
366
- commit,
367
-
368
- /**
369
- * Create a bound transaction with pre-configured URL options
370
- * segmentIds and segments provided at commit time (after they're resolved)
371
- */
372
- with(
373
- opts: Omit<CommitOptions, "segmentIds" | "segments">
374
- ): BoundTransaction {
375
- return {
376
- get currentUrl() {
377
- return currentUrl;
378
- },
379
- startStreaming() {
380
- return handle.startStreaming();
381
- },
382
- commit: (
383
- segmentIds: string[],
384
- segments: ResolvedSegment[],
385
- overrides?: BoundCommitOverrides
386
- ) => {
387
- // Allow overrides to disable scroll (e.g., for intercepts)
388
- const finalScroll =
389
- overrides?.scroll !== undefined ? overrides.scroll : opts.scroll;
390
- // Allow overrides to force replace (e.g., for intercepts)
391
- const finalReplace =
392
- overrides?.replace !== undefined ? overrides.replace : opts.replace;
393
- // Intercept info: overrides take precedence, fallback to opts
394
- const intercept =
395
- overrides?.intercept !== undefined
396
- ? overrides.intercept
397
- : opts.intercept;
398
- const interceptSourceUrl =
399
- overrides?.interceptSourceUrl !== undefined
400
- ? overrides.interceptSourceUrl
401
- : opts.interceptSourceUrl;
402
- // Cache-only mode: overrides take precedence, fallback to opts
403
- const cacheOnly =
404
- overrides?.cacheOnly !== undefined
405
- ? overrides.cacheOnly
406
- : opts.cacheOnly;
407
- // User state: overrides take precedence, fallback to opts
408
- const state =
409
- overrides?.state !== undefined ? overrides.state : opts.state;
410
- commit({
411
- ...opts,
412
- segmentIds,
413
- segments,
414
- scroll: finalScroll,
415
- replace: finalReplace,
416
- state,
417
- intercept,
418
- interceptSourceUrl,
419
- cacheOnly,
420
- });
421
- },
422
- };
423
- },
424
-
425
- [Symbol.dispose]() {
426
- // If aborted, another navigation took over - don't touch state
427
- if (handle.signal.aborted) return;
428
-
429
- // If not committed (and not optimistically committed), the handle's dispose
430
- // will reset state to idle via the event controller
431
- if (!committed && !optimisticallyCommitted) {
432
- handle[Symbol.dispose]();
433
- // The NavigationHandle's [Symbol.dispose] handles this
434
- }
435
- },
436
- };
437
- }
438
-
439
- // Export for use by server-action-bridge
440
44
  export { createNavigationTransaction };
441
45
 
442
46
  /**
@@ -462,9 +66,10 @@ export interface NavigationBridgeConfigWithController extends NavigationBridgeCo
462
66
  * @returns NavigationBridge instance
463
67
  */
464
68
  export function createNavigationBridge(
465
- config: NavigationBridgeConfigWithController
69
+ config: NavigationBridgeConfigWithController,
466
70
  ): NavigationBridge {
467
- const { store, client, eventController, onUpdate, renderSegments, version } = config;
71
+ const { store, client, eventController, onUpdate, renderSegments } = config;
72
+ let version = config.version;
468
73
 
469
74
  // Create shared partial updater
470
75
  const fetchPartialUpdate = createPartialUpdater({
@@ -472,25 +77,127 @@ export function createNavigationBridge(
472
77
  client,
473
78
  onUpdate,
474
79
  renderSegments,
475
- version,
80
+ getVersion: () => version,
476
81
  });
477
82
 
478
83
  return {
479
84
  /**
480
85
  * Navigate to a URL
481
- * Uses optimistic rendering from cache when available (SWR pattern)
86
+ * Uses cached segments for SWR revalidation when available
482
87
  */
483
- async navigate(url: string, options?: NavigateOptions): Promise<void> {
88
+ async navigate(
89
+ url: string,
90
+ options?: NavigateOptionsInternal,
91
+ ): Promise<void> {
484
92
  // Resolve LocationStateEntry[] to flat object if needed
485
93
  const resolvedState =
486
94
  options?.state !== undefined
487
95
  ? resolveNavigationState(options.state)
488
96
  : undefined;
489
97
 
98
+ // Cross-origin URLs are not handled by SPA navigation.
99
+ // Fall back to a full browser navigation for http/https only.
100
+ let targetUrl: URL;
101
+ try {
102
+ targetUrl = new URL(url, window.location.origin);
103
+ } catch {
104
+ console.warn(`[rango] navigate() ignored: malformed URL "${url}"`);
105
+ return;
106
+ }
107
+ if (targetUrl.origin !== window.location.origin) {
108
+ if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
109
+ console.error(
110
+ `[rango] navigate() blocked: unsupported scheme "${targetUrl.protocol}"`,
111
+ );
112
+ return;
113
+ }
114
+ window.location.href = targetUrl.href;
115
+ return;
116
+ }
117
+
118
+ // Shallow navigation: skip RSC fetch when revalidate is false
119
+ // and the pathname hasn't changed (search param / hash only change).
120
+ if (
121
+ options?.revalidate === false &&
122
+ targetUrl.pathname === new URL(window.location.href).pathname
123
+ ) {
124
+ // Preserve intercept context from the current history entry so that
125
+ // popstate uses the correct cache key (:intercept suffix) and restores
126
+ // the right full-page vs modal semantics.
127
+ const currentHistoryState = window.history.state;
128
+ const isIntercept = currentHistoryState?.intercept === true;
129
+ const interceptSourceUrl = isIntercept
130
+ ? currentHistoryState?.sourceUrl
131
+ : undefined;
132
+
133
+ const historyKey = generateHistoryKey(url, { intercept: isIntercept });
134
+
135
+ // Copy current segments to the new history key so back/forward restores instantly
136
+ const currentKey = store.getHistoryKey();
137
+ const currentCache = store.getCachedSegments(currentKey);
138
+ if (currentCache?.segments) {
139
+ const currentHandleData = eventController.getHandleState().data;
140
+ store.cacheSegmentsForHistory(
141
+ historyKey,
142
+ currentCache.segments,
143
+ currentHandleData,
144
+ );
145
+ }
146
+
147
+ // Save current scroll position before changing URL
148
+ handleNavigationStart();
149
+
150
+ // Snapshot old state before pushState/replaceState overwrites it
151
+ const oldState = window.history.state;
152
+
153
+ // Update browser URL (carry intercept context into history state)
154
+ const historyState = buildHistoryState(
155
+ resolvedState,
156
+ {
157
+ intercept: isIntercept || undefined,
158
+ sourceUrl: interceptSourceUrl,
159
+ },
160
+ {},
161
+ );
162
+ if (options.replace) {
163
+ window.history.replaceState(historyState, "", url);
164
+ } else {
165
+ window.history.pushState(historyState, "", url);
166
+ }
167
+
168
+ // Ensure new history entry has a scroll restoration key
169
+ ensureHistoryKey();
170
+
171
+ // Notify useLocationState() hooks when state changes
172
+ const hasOldState =
173
+ oldState &&
174
+ typeof oldState === "object" &&
175
+ ("state" in oldState ||
176
+ Object.keys(oldState).some((k) => k.startsWith("__rsc_ls_")));
177
+ const hasNewState =
178
+ historyState &&
179
+ ("state" in historyState ||
180
+ Object.keys(historyState).some((k) => k.startsWith("__rsc_ls_")));
181
+ if (hasOldState || hasNewState) {
182
+ window.dispatchEvent(new Event("__rsc_locationstate"));
183
+ }
184
+
185
+ // Update store history key so future navigations reference the right cache
186
+ store.setHistoryKey(historyKey);
187
+ store.setCurrentUrl(url);
188
+
189
+ // Notify hooks — location updates, state stays idle
190
+ eventController.setLocation(targetUrl);
191
+
192
+ // Handle post-navigation scroll
193
+ handleNavigationEnd({ scroll: options.scroll });
194
+ return;
195
+ }
196
+
490
197
  // Only abort pending requests when navigating to a different route
491
198
  // Same-route navigation (e.g., /todos -> /todos) should not cancel in-flight actions
492
199
  const currentPath = new URL(window.location.href).pathname;
493
- const targetPath = new URL(url, window.location.origin).pathname;
200
+ const targetPath = targetUrl.pathname;
494
201
  if (currentPath !== targetPath) {
495
202
  eventController.abortNavigation();
496
203
  }
@@ -503,7 +210,9 @@ export function createNavigationBridge(
503
210
  const isLeavingIntercept = isCurrentlyIntercept && isSamePathNavigation;
504
211
 
505
212
  if (isLeavingIntercept) {
506
- console.log(`[Browser] Leaving intercept - same URL navigation from intercept`);
213
+ debugLog(
214
+ "[Browser] Leaving intercept - same URL navigation from intercept",
215
+ );
507
216
  // Clear intercept source URL to ensure server doesn't treat this as intercept
508
217
  store.setInterceptSourceUrl(null);
509
218
  }
@@ -517,7 +226,7 @@ export function createNavigationBridge(
517
226
  store.cacheSegmentsForHistory(
518
227
  sourceHistoryKey,
519
228
  sourceCached.segments,
520
- currentHandleData
229
+ currentHandleData,
521
230
  );
522
231
  }
523
232
 
@@ -532,7 +241,7 @@ export function createNavigationBridge(
532
241
  const cachedHandleData = cached?.handleData;
533
242
  if (cachedSegments && sourceCached?.segments) {
534
243
  const sourceSegmentMap = new Map(
535
- sourceCached.segments.map((s) => [s.id, s])
244
+ sourceCached.segments.map((s) => [s.id, s]),
536
245
  );
537
246
  cachedSegments = cachedSegments.map((targetSeg) => {
538
247
  const sourceSeg = sourceSegmentMap.get(targetSeg.id);
@@ -547,28 +256,40 @@ export function createNavigationBridge(
547
256
  const interceptHistoryKey = generateHistoryKey(url, { intercept: true });
548
257
  const hasInterceptCache = store.hasHistoryCache(interceptHistoryKey);
549
258
 
550
- // Skip optimistic rendering for:
259
+ // Skip cached SWR for:
551
260
  // 1. intercept caches - interception depends on source page context
552
261
  // 2. routes that CAN be intercepted - we don't know if this navigation will intercept
553
262
  // 3. when leaving intercept - we need fresh non-intercept segments from server
263
+ // 4. redirect-with-state - force re-render so hooks read fresh state
264
+ // 5. stale cache - server action invalidated it, need fresh data with loading state
554
265
  const hasUsableCache =
555
266
  cachedSegments &&
556
267
  cachedSegments.length > 0 &&
557
268
  !isInterceptOnlyCache(cachedSegments) &&
558
269
  !hasInterceptCache &&
559
- !isLeavingIntercept;
560
-
561
- using tx = createNavigationTransaction(store, eventController, url, {
270
+ !isLeavingIntercept &&
271
+ !cached?.stale &&
272
+ !options?._skipCache;
273
+
274
+ // Forward navigations always await fetchPartialUpdate before rendering,
275
+ // so useNavigation should always report "loading". skipLoadingState is
276
+ // only used for popstate background revalidation (line ~526) where
277
+ // cached content renders instantly without a network wait.
278
+ const tx = createNavigationTransaction(store, eventController, url, {
562
279
  ...options,
563
280
  state: resolvedState,
564
- skipLoadingState: hasUsableCache,
281
+ skipLoadingState: false,
565
282
  });
566
283
 
567
284
  // REVALIDATE: Fetch fresh data from server
568
285
  try {
569
286
  await fetchPartialUpdate(
570
287
  url,
571
- hasUsableCache ? cachedSegments!.map((s) => s.id) : undefined,
288
+ hasUsableCache
289
+ ? cachedSegments!.map((s) => s.id)
290
+ : options?._skipCache
291
+ ? [] // Action redirect: send no segments so server renders everything fresh
292
+ : undefined,
572
293
  false,
573
294
  tx.handle.signal,
574
295
  tx.with({
@@ -577,55 +298,56 @@ export function createNavigationBridge(
577
298
  scroll: options?.scroll,
578
299
  state: resolvedState,
579
300
  }),
580
- // Pass cached segments (merged with current page's fresh segments for shared IDs)
581
- // so the segment map is consistent with what we tell the server we have.
582
- // Server decides what needs revalidation based on route matching and custom functions.
583
- // No need for staleRevalidation flag - we're sending the freshest segments we have.
584
- // Also pass cached handle data for restoring breadcrumbs when server returns empty diff.
585
- // When leaving intercept, pass the flag so fetchPartialUpdate knows to filter segments.
586
301
  hasUsableCache
587
- ? { targetCacheSegments: cachedSegments, targetCacheHandleData: cachedHandleData }
302
+ ? {
303
+ type: "navigate" as const,
304
+ targetCacheSegments: cachedSegments,
305
+ targetCacheHandleData: cachedHandleData,
306
+ }
588
307
  : isLeavingIntercept
589
- ? { leavingIntercept: true }
590
- : undefined
308
+ ? { type: "leave-intercept" as const }
309
+ : undefined,
591
310
  );
592
311
  } catch (error) {
593
- // Ignore AbortError - navigation was cancelled by a newer navigation
312
+ // Server-side redirect with location state: the current transaction's
313
+ // cleanup resets loading state. Re-navigate to the redirect
314
+ // target carrying the server-set state into history.pushState.
315
+ if (error instanceof ServerRedirect) {
316
+ const redirectUrl = validateRedirectOrigin(
317
+ error.url,
318
+ window.location.origin,
319
+ );
320
+ if (!redirectUrl) {
321
+ return;
322
+ }
323
+ return this.navigate(redirectUrl, {
324
+ state: error.state,
325
+ replace: options?.replace,
326
+ _skipCache: true,
327
+ } as NavigateOptionsInternal);
328
+ }
329
+
594
330
  if (error instanceof DOMException && error.name === "AbortError") {
595
- console.log("[Browser] Navigation aborted by newer navigation");
331
+ debugLog("[Browser] Navigation aborted by newer navigation");
596
332
  return;
597
333
  }
598
334
 
599
- // Handle network errors by triggering root error boundary
600
- if (error instanceof NetworkError || isNetworkError(error)) {
601
- const networkError =
602
- error instanceof NetworkError
603
- ? error
604
- : new NetworkError(
605
- "Unable to connect to server. Please check your connection.",
606
- { cause: error, url, operation: "navigation" }
607
- );
608
-
335
+ const networkError = toNetworkError(error, {
336
+ url,
337
+ operation: "navigation",
338
+ });
339
+ if (networkError) {
609
340
  console.error(
610
341
  "[Browser] Network error during navigation:",
611
- networkError
342
+ networkError,
612
343
  );
613
-
614
- // Emit update with NetworkErrorThrower to trigger root error boundary
615
- startTransition(() => {
616
- onUpdate({
617
- root: createElement(NetworkErrorThrower, { error: networkError }),
618
- metadata: {
619
- pathname: url,
620
- segments: [],
621
- isError: true,
622
- },
623
- });
624
- });
344
+ emitNetworkError(onUpdate, networkError, url);
625
345
  return;
626
346
  }
627
347
 
628
348
  throw error;
349
+ } finally {
350
+ tx[Symbol.dispose]();
629
351
  }
630
352
  },
631
353
 
@@ -635,11 +357,11 @@ export function createNavigationBridge(
635
357
  async refresh(): Promise<void> {
636
358
  eventController.abortNavigation();
637
359
 
638
- using tx = createNavigationTransaction(
360
+ const tx = createNavigationTransaction(
639
361
  store,
640
362
  eventController,
641
363
  window.location.href,
642
- { replace: true }
364
+ { replace: true },
643
365
  );
644
366
 
645
367
  try {
@@ -649,41 +371,24 @@ export function createNavigationBridge(
649
371
  [],
650
372
  false,
651
373
  tx.handle.signal,
652
- tx.with({ url: window.location.href, replace: true, scroll: false })
374
+ tx.with({ url: window.location.href, replace: true, scroll: false }),
653
375
  );
654
376
  } catch (error) {
655
- // Handle network errors by triggering root error boundary
656
- if (error instanceof NetworkError || isNetworkError(error)) {
657
- const networkError =
658
- error instanceof NetworkError
659
- ? error
660
- : new NetworkError(
661
- "Unable to connect to server. Please check your connection.",
662
- {
663
- cause: error,
664
- url: window.location.href,
665
- operation: "revalidation",
666
- }
667
- );
668
-
377
+ const networkError = toNetworkError(error, {
378
+ url: window.location.href,
379
+ operation: "revalidation",
380
+ });
381
+ if (networkError) {
669
382
  console.error(
670
383
  "[Browser] Network error during refresh:",
671
- networkError
384
+ networkError,
672
385
  );
673
-
674
- startTransition(() => {
675
- onUpdate({
676
- root: createElement(NetworkErrorThrower, { error: networkError }),
677
- metadata: {
678
- pathname: window.location.href,
679
- segments: [],
680
- isError: true,
681
- },
682
- });
683
- });
386
+ emitNetworkError(onUpdate, networkError, window.location.href);
684
387
  return;
685
388
  }
686
389
  throw error;
390
+ } finally {
391
+ tx[Symbol.dispose]();
687
392
  }
688
393
  },
689
394
 
@@ -707,20 +412,29 @@ export function createNavigationBridge(
707
412
  const currentInterceptSource = store.getInterceptSourceUrl();
708
413
  const newInterceptSource = interceptSourceUrl ?? null;
709
414
  if (currentInterceptSource !== newInterceptSource) {
710
- console.log(
711
- `[Browser] Intercept context changing (${currentInterceptSource} -> ${newInterceptSource}), aborting in-flight actions`
415
+ debugLog(
416
+ `[Browser] Intercept context changing (${currentInterceptSource} -> ${newInterceptSource}), aborting in-flight actions`,
712
417
  );
713
418
  eventController.abortAllActions();
714
419
  }
715
420
 
421
+ // Popstate that exits an intercept to a non-intercept destination. The
422
+ // fallback fetch path below needs `leave-intercept` mode so it filters
423
+ // the cached @modal segment from the request and forces a re-render —
424
+ // otherwise a cache-miss popstate whose server response has an empty
425
+ // diff hits the "no changes" branch in partial-update and the modal
426
+ // stays on screen.
427
+ const isLeavingIntercept =
428
+ !isIntercept && currentInterceptSource !== null;
429
+
716
430
  // Compute history key from URL (with intercept suffix if applicable)
717
431
  const historyKey = generateHistoryKey(url, { intercept: isIntercept });
718
432
 
719
- console.log(
433
+ debugLog(
720
434
  "[Browser] Popstate -",
721
435
  isIntercept ? "intercept" : "normal",
722
436
  "key:",
723
- historyKey
437
+ historyKey,
724
438
  );
725
439
 
726
440
  // Update location in event controller
@@ -749,12 +463,27 @@ export function createNavigationBridge(
749
463
  store.setCurrentUrl(url);
750
464
  store.setPath(new URL(url).pathname);
751
465
 
466
+ // Restore router identity from cache so subsequent navigations
467
+ // don't falsely detect an app switch.
468
+ if (cached?.routerId) {
469
+ store.setRouterId?.(cached.routerId);
470
+ }
471
+
752
472
  // Render from cache - force await to skip loading fallbacks
753
473
  try {
754
- const root = renderSegments(cachedSegments, {
474
+ const root = await renderSegments(cachedSegments, {
755
475
  forceAwait: true,
756
476
  });
757
- onUpdate({
477
+ // Merge params from cached segments for useParams restoration.
478
+ // Set params on event controller before onUpdate so both location
479
+ // and params are current when the debounced notify() fires.
480
+ const cachedParams: Record<string, string> = {};
481
+ for (const s of cachedSegments) {
482
+ if (s.params) Object.assign(cachedParams, s.params);
483
+ }
484
+ eventController.setParams(cachedParams);
485
+
486
+ const popstateUpdate = {
758
487
  root,
759
488
  metadata: {
760
489
  pathname: new URL(url).pathname,
@@ -763,23 +492,33 @@ export function createNavigationBridge(
763
492
  matched: cachedSegments.map((s) => s.id),
764
493
  diff: [],
765
494
  cachedHandleData,
495
+ params: cachedParams,
766
496
  },
767
- });
768
-
769
- // Restore scroll position for back/forward navigation
770
- handleNavigationEnd({ restore: true, isStreaming });
497
+ scroll: { restore: true, isStreaming },
498
+ };
499
+ const hasTransition = cachedSegments.some((s) => s.transition);
500
+ if (hasTransition) {
501
+ startTransition(() => {
502
+ if (addTransitionType) {
503
+ addTransitionType("navigation-back");
504
+ }
505
+ onUpdate(popstateUpdate);
506
+ });
507
+ } else {
508
+ onUpdate(popstateUpdate);
509
+ }
771
510
 
772
511
  // SWR: If stale, trigger background revalidation
773
512
  if (isStale) {
774
- console.log("[Browser] Cache is stale, background revalidating...");
513
+ debugLog("[Browser] Cache is stale, background revalidating...");
775
514
  // Background revalidation - don't await, just fire and forget
776
515
  const segmentIds = cachedSegments.map((s) => s.id);
777
516
 
778
- using tx = createNavigationTransaction(
517
+ const tx = createNavigationTransaction(
779
518
  store,
780
519
  eventController,
781
520
  url,
782
- { skipLoadingState: true, replace: true }
521
+ { skipLoadingState: true, replace: true },
783
522
  );
784
523
 
785
524
  fetchPartialUpdate(
@@ -795,41 +534,33 @@ export function createNavigationBridge(
795
534
  interceptSourceUrl,
796
535
  cacheOnly: true,
797
536
  }),
798
- { staleRevalidation: true, interceptSourceUrl }
799
- ).catch((error) => {
800
- if (
801
- error instanceof DOMException &&
802
- error.name === "AbortError"
803
- ) {
804
- console.log("[Browser] Background revalidation aborted");
805
- return;
806
- }
807
- // For background revalidation, network errors are logged but don't trigger error boundary
808
- // since the user is already seeing cached content
809
- if (error instanceof NetworkError || isNetworkError(error)) {
810
- console.warn(
811
- "[Browser] Background revalidation network error (cached content preserved):",
812
- error.message
537
+ { type: "stale-revalidation", interceptSourceUrl },
538
+ )
539
+ .catch((error) => {
540
+ if (isBackgroundSuppressible(error)) return;
541
+ console.error(
542
+ "[Browser] Background revalidation failed:",
543
+ error,
813
544
  );
814
- return;
815
- }
816
- console.error("[Browser] Background revalidation failed:", error);
817
- });
545
+ })
546
+ .finally(() => {
547
+ tx[Symbol.dispose]();
548
+ });
818
549
  }
819
550
  return;
820
551
  } catch (error) {
821
552
  console.warn(
822
553
  "[Browser] Failed to render from cache, fetching:",
823
- error
554
+ error,
824
555
  );
825
556
  // Fall through to fetch
826
557
  }
827
558
  } else {
828
- console.log("[Browser] History cache miss for key:", historyKey);
559
+ debugLog("[Browser] History cache miss for key:", historyKey);
829
560
  }
830
561
 
831
562
  // Fetch if not cached
832
- using tx = createNavigationTransaction(store, eventController, url, {
563
+ const tx = createNavigationTransaction(store, eventController, url, {
833
564
  replace: true,
834
565
  });
835
566
 
@@ -839,45 +570,43 @@ export function createNavigationBridge(
839
570
  undefined,
840
571
  false,
841
572
  tx.handle.signal,
842
- tx.with({ url, replace: true, scroll: false })
573
+ tx.with({
574
+ url,
575
+ replace: true,
576
+ scroll: false,
577
+ intercept: isIntercept,
578
+ interceptSourceUrl,
579
+ }),
580
+ isIntercept
581
+ ? { type: "navigate", interceptSourceUrl }
582
+ : isLeavingIntercept
583
+ ? { type: "leave-intercept" }
584
+ : undefined,
843
585
  );
844
586
  // Restore scroll position after fetch completes
845
587
  handleNavigationEnd({ restore: true, isStreaming });
846
588
  } catch (error) {
847
589
  if (error instanceof DOMException && error.name === "AbortError") {
848
- console.log("[Browser] Popstate navigation aborted");
590
+ debugLog("[Browser] Popstate navigation aborted");
849
591
  return;
850
592
  }
851
593
 
852
- // Handle network errors by triggering root error boundary
853
- if (error instanceof NetworkError || isNetworkError(error)) {
854
- const networkError =
855
- error instanceof NetworkError
856
- ? error
857
- : new NetworkError(
858
- "Unable to connect to server. Please check your connection.",
859
- { cause: error, url, operation: "navigation" }
860
- );
861
-
594
+ const networkError = toNetworkError(error, {
595
+ url,
596
+ operation: "navigation",
597
+ });
598
+ if (networkError) {
862
599
  console.error(
863
- "[Browser] Network error during popstate navigation:",
864
- networkError
600
+ "[Browser] Network error during popstate:",
601
+ networkError,
865
602
  );
866
-
867
- startTransition(() => {
868
- onUpdate({
869
- root: createElement(NetworkErrorThrower, { error: networkError }),
870
- metadata: {
871
- pathname: url,
872
- segments: [],
873
- isError: true,
874
- },
875
- });
876
- });
603
+ emitNetworkError(onUpdate, networkError, url);
877
604
  return;
878
605
  }
879
606
 
880
607
  throw error;
608
+ } finally {
609
+ tx[Symbol.dispose]();
881
610
  }
882
611
  },
883
612
 
@@ -894,19 +623,47 @@ export function createNavigationBridge(
894
623
  this.handlePopstate();
895
624
  };
896
625
 
626
+ // When the browser restores a page from bfcache (back-forward cache),
627
+ // any in-flight navigation state is stale. This happens when:
628
+ // 1. A navigation triggers X-RSC-Reload (e.g., response route hit via SPA)
629
+ // 2. window.location.href does a hard navigation
630
+ // 3. The user presses back and the browser restores from bfcache
631
+ // At that point, currentNavigation is still set from step 1, so
632
+ // getState() returns "loading" and the progress bar shows.
633
+ // Abort the stale navigation to reset state to idle.
634
+ const handlePageShow = (event: PageTransitionEvent) => {
635
+ if (event.persisted) {
636
+ debugLog(
637
+ "[Browser] Page restored from bfcache, resetting navigation state",
638
+ );
639
+ eventController.abortNavigation();
640
+ // pagehide flips scrollRestoration to "auto" for bfcache compat;
641
+ // restore "manual" so the router controls scroll on SPA navigations.
642
+ window.history.scrollRestoration = "manual";
643
+ }
644
+ };
645
+
897
646
  // Register cross-tab refresh callback with the store
898
647
  store.setCrossTabRefreshCallback(() => {
899
648
  this.refresh();
900
649
  });
901
650
 
902
651
  window.addEventListener("popstate", handlePopstate);
903
- console.log("[Browser] Navigation bridge ready");
652
+ window.addEventListener("pageshow", handlePageShow);
653
+ debugLog("[Browser] Navigation bridge ready");
904
654
 
905
655
  return () => {
906
656
  cleanupLinks();
907
657
  window.removeEventListener("popstate", handlePopstate);
658
+ window.removeEventListener("pageshow", handlePageShow);
908
659
  };
909
660
  },
661
+
662
+ updateVersion(newVersion: string): void {
663
+ version = newVersion;
664
+ setAppVersion(newVersion);
665
+ store.clearHistoryCache();
666
+ },
910
667
  };
911
668
  }
912
669