@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4027 -685
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4007 -687
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +51 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5291 -662
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/{context-logger.d.ts → server/context-logger.d.ts} +2 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -7
  68. package/{src → dist/server}/render/shell.ts +28 -13
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +79 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +80 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1232
  163. package/dist/render/assemble.d.ts +0 -15
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -45
  169. package/dist/router.js +0 -1671
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1120
  172. package/src/render/assemble.ts +0 -66
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -483
  176. package/src/render/loaders.ts +0 -117
  177. package/src/router.ts +0 -439
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,723 @@
1
+ import { log } from "evlog";
2
+ import type React from "react";
3
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
+ import { parseDeferredNdjson } from "../../shared/deferred-ndjson.ts";
5
+ import { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
6
+ import {
7
+ generateHistoryKey,
8
+ getHistoryKey,
9
+ isStaleDeployResponse,
10
+ SCROLL_STORAGE_KEY,
11
+ saveScrollPosition,
12
+ } from "./history.ts";
13
+ import {
14
+ applyRevalidateHeader,
15
+ normalizeHref,
16
+ shouldAutoRefreshPath,
17
+ shouldInterceptClick,
18
+ shouldRefetch,
19
+ stripHashFromHref,
20
+ toLogical,
21
+ } from "./link-utils.ts";
22
+ import {
23
+ buildDataEndpoint,
24
+ buildNotFoundPageElement,
25
+ classifySpaResponse,
26
+ detectStaticMode,
27
+ parsePageResponse,
28
+ } from "./spa-response.ts";
29
+ import type {
30
+ CacheEntry,
31
+ ClientSegmentBoundary,
32
+ LoadedClientRoute,
33
+ RouterProviderProps,
34
+ RouterState,
35
+ } from "./types.ts";
36
+
37
+ export function setPrefetchCacheEntry(
38
+ cache: Map<string, CacheEntry>,
39
+ href: string,
40
+ entry: CacheEntry,
41
+ maxSize: number
42
+ ): void {
43
+ if (cache.has(href)) {
44
+ cache.delete(href);
45
+ }
46
+ cache.set(href, entry);
47
+ if (cache.size > maxSize) {
48
+ const oldest = cache.keys().next().value;
49
+ if (typeof oldest === "string") {
50
+ cache.delete(oldest);
51
+ }
52
+ }
53
+ }
54
+
55
+ export function RouterProvider({
56
+ routes,
57
+ root,
58
+ initialMatch,
59
+ initialData,
60
+ initialDigest,
61
+ initialNotFound,
62
+ autoRefresh,
63
+ basePath,
64
+ defaultPreload,
65
+ defaultPreloadDelay,
66
+ defaultPreloadStaleTime,
67
+ prefetchCacheSize,
68
+ }: RouterProviderProps): React.ReactElement {
69
+ // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
70
+ // the provider boots into the inline not-found UI.
71
+ const [state, setState] = useState<RouterState>(() => ({
72
+ match: initialMatch,
73
+ data: initialData,
74
+ notFound: initialNotFound,
75
+ }));
76
+ const [isNavigating, setIsNavigating] = useState(false);
77
+ // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
78
+ // detection works with route patterns that never include the basePath prefix.
79
+ const [currentHref, setCurrentHref] = useState<string>(() => {
80
+ if (typeof window === "undefined") {
81
+ return "/";
82
+ }
83
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
84
+ });
85
+ const prefetchCache = useRef(new Map<string, CacheEntry>());
86
+ /** Monotonic counter to discard stale navigations (race condition guard). */
87
+ const navVersion = useRef(0);
88
+ /**
89
+ * AbortController for the current navigation. Cancelled when a newer
90
+ * navigation starts so any in-flight `parseDeferredNdjson` releases its
91
+ * pending deferred promises (resolvers reject with `AbortError`) and frees
92
+ * the underlying stream reader.
93
+ */
94
+ const navAbortRef = useRef<AbortController | null>(null);
95
+ /**
96
+ * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
97
+ * This replaces the fragile double-requestAnimationFrame pattern with a render-
98
+ * synchronous scroll that fires immediately after React commits the new route.
99
+ */
100
+ const pendingScrollRef = useRef<
101
+ { type: "restore"; key: string } | { type: "reset"; href: string } | null
102
+ >(null);
103
+ /**
104
+ * Tracks the last successfully rendered match for use in the no-route 404 path.
105
+ * `null` on the initial render when the URL didn't match any route and the
106
+ * provider booted directly into the not-found state; flips to a real match as
107
+ * soon as the user navigates away via `navigate()` or the back button.
108
+ */
109
+ const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
110
+ /**
111
+ * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
112
+ * fetch URL: runtime `/_furin/data` for SSR/ISR/dev, per-route
113
+ * `__furin_data.ndjson` for static exports.
114
+ */
115
+ const staticModeRef = useRef<boolean>(detectStaticMode());
116
+
117
+ /**
118
+ * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
119
+ * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
120
+ * handles it — the root `not-found.tsx` (depth 0) is the correct component to
121
+ * render inline instead of doing a full-page reload.
122
+ */
123
+ const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
124
+ for (const route of routes) {
125
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
126
+ if (depth0) {
127
+ return [depth0];
128
+ }
129
+ }
130
+ return;
131
+ }, [routes]);
132
+
133
+ /**
134
+ * Resolves the RouterState when no client-side route matched the URL. The
135
+ * server's `renderRootNotFound` produced the 404 HTML; we fetch the physical
136
+ * URL to detect the `__furinStatus: 404` signal and render the 404 UI inline
137
+ * (rather than triggering a jarring full-page reload).
138
+ */
139
+ const resolveNoMatchState = useCallback(
140
+ async (physicalHref: string, signal: AbortSignal | undefined): Promise<RouterState | null> => {
141
+ const res = await fetch(physicalHref, { signal });
142
+ if (isStaleDeployResponse(res)) {
143
+ window.location.href = physicalHref;
144
+ return null;
145
+ }
146
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
147
+ const kind = classifySpaResponse(res.status, data);
148
+ if (kind.kind !== "not-found") {
149
+ return null;
150
+ }
151
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
152
+ return {
153
+ match: currentMatchRef.current,
154
+ data: cleanData,
155
+ title,
156
+ finalHref,
157
+ notFound: kind.error,
158
+ notFoundBoundaries: rootBoundaries,
159
+ };
160
+ },
161
+ [basePath, rootBoundaries]
162
+ );
163
+
164
+ const fetchPageState = useCallback(
165
+ async (
166
+ rawLogicalHref: string,
167
+ signal: AbortSignal | undefined
168
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
169
+ ): Promise<RouterState | null> => {
170
+ // Normalize trailing slashes so "/docs/routing/" matches the route
171
+ // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
172
+ // redirect to or serve URLs with a trailing slash.
173
+ const logicalHref = normalizeHref(rawLogicalHref);
174
+ try {
175
+ // Physical href: what the browser/server actually receives.
176
+ // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
177
+ const physicalHref = basePath + logicalHref;
178
+ const url = new URL(physicalHref, window.location.origin);
179
+ // Route matching always uses the LOGICAL pathname (basePath stripped).
180
+ const logicalPathname = toLogical(url.pathname, basePath);
181
+ const match = routes.find((r) => r.regex.test(logicalPathname));
182
+ if (!match) {
183
+ return await resolveNoMatchState(physicalHref, signal);
184
+ }
185
+
186
+ // ── NDJSON data endpoint + JS chunk load (parallel) ──────────────────
187
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
188
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
189
+
190
+ // Stale-deploy detection: force a full page reload to pick up the new bundle.
191
+ if (isStaleDeployResponse(res)) {
192
+ window.location.href = physicalHref;
193
+ return null;
194
+ }
195
+
196
+ const body = res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() });
197
+ let parsed: {
198
+ syncData: Record<string, unknown>;
199
+ deferredPromises: Record<string, Promise<unknown>>;
200
+ };
201
+ try {
202
+ parsed = await parseDeferredNdjson(body, signal);
203
+ } catch (parseErr) {
204
+ log.warn({
205
+ action: "navigate_server_error",
206
+ href: physicalHref,
207
+ status: res.status,
208
+ error: String(parseErr),
209
+ });
210
+ return null;
211
+ }
212
+ const { syncData, deferredPromises } = parsed;
213
+
214
+ // Special fields injected by the server into syncData:
215
+ // __furinStatus — 404 signal
216
+ // __furinNotFound — not-found payload
217
+ // __furinRedirect — server-side redirect target (logical path)
218
+ // __furinError — error sentinel (digest, message, status)
219
+ // __furinTitle — document title resolved server-side from head()
220
+ const {
221
+ __furinStatus,
222
+ __furinNotFound,
223
+ __furinRedirect,
224
+ __furinError,
225
+ __furinTitle,
226
+ ...cleanSyncData
227
+ } = syncData as {
228
+ __furinStatus?: number;
229
+ __furinNotFound?: { data?: unknown; message?: string };
230
+ __furinRedirect?: string;
231
+ __furinError?: { digest: string; message: string; status: number };
232
+ __furinTitle?: string;
233
+ [key: string]: unknown;
234
+ };
235
+
236
+ const finalHref: string | undefined =
237
+ typeof __furinRedirect === "string" ? __furinRedirect : undefined;
238
+
239
+ // Merge sync data + deferred Promises.
240
+ const data = { ...cleanSyncData, ...deferredPromises };
241
+
242
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
243
+
244
+ const loadedMatch: LoadedClientRoute = {
245
+ ...match,
246
+ component: loadedMod.default.component,
247
+ pageRoute: loadedMod.default._route,
248
+ segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries,
249
+ };
250
+
251
+ // Loader threw a non-redirect Response (or an Error).
252
+ if (__furinError) {
253
+ return {
254
+ match: loadedMatch,
255
+ data: {},
256
+ title,
257
+ finalHref,
258
+ error: __furinError,
259
+ };
260
+ }
261
+
262
+ // Non-2xx without sentinel and not 404 → opaque server error.
263
+ if (!res.ok && res.status !== 404) {
264
+ log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
265
+ return null;
266
+ }
267
+
268
+ if (__furinStatus === 404) {
269
+ return {
270
+ match: loadedMatch,
271
+ data,
272
+ title,
273
+ finalHref,
274
+ notFound: (__furinNotFound as { data?: unknown; message?: string }) ?? {},
275
+ };
276
+ }
277
+
278
+ // Server-side redirect: do not mount the pre-redirect route.
279
+ if (finalHref) {
280
+ return { match: null, data, title, finalHref };
281
+ }
282
+
283
+ return { match: loadedMatch, data, title, finalHref };
284
+ } catch (err: unknown) {
285
+ log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
286
+ return null;
287
+ }
288
+ },
289
+ [routes, basePath, resolveNoMatchState]
290
+ );
291
+
292
+ const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
293
+ const normalizedPath = stripHashFromHref(path);
294
+
295
+ if (type === "page") {
296
+ for (const key of [...prefetchCache.current.keys()]) {
297
+ if (stripHashFromHref(key) === normalizedPath) {
298
+ prefetchCache.current.delete(key);
299
+ }
300
+ }
301
+ return;
302
+ }
303
+
304
+ // layout: prefix match — evict the path itself and all nested children
305
+ const prefix =
306
+ normalizedPath === "/" || normalizedPath.endsWith("/")
307
+ ? normalizedPath
308
+ : `${normalizedPath}/`;
309
+ for (const key of [...prefetchCache.current.keys()]) {
310
+ const normalizedKey = stripHashFromHref(key);
311
+ if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
312
+ prefetchCache.current.delete(key);
313
+ }
314
+ }
315
+ }, []);
316
+
317
+ const prefetch = useCallback(
318
+ (href: string, opts: { staleTime?: number } | undefined) => {
319
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
320
+ const existing = prefetchCache.current.get(href);
321
+ if (existing && !shouldRefetch(existing)) {
322
+ return;
323
+ }
324
+ setPrefetchCacheEntry(
325
+ prefetchCache.current,
326
+ href,
327
+ {
328
+ promise: fetchPageState(href, undefined),
329
+ createdAt: Date.now(),
330
+ staleTime,
331
+ },
332
+ prefetchCacheSize
333
+ );
334
+ },
335
+ [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
336
+ );
337
+
338
+ /** Loads the RouterState for a redirect target, respecting the nav version. */
339
+ async function resolveRedirectState(
340
+ redirectLogical: string,
341
+ myVersion: number,
342
+ signal: AbortSignal | undefined
343
+ ): Promise<RouterState | null> {
344
+ const cached = prefetchCache.current.get(redirectLogical);
345
+ const state =
346
+ cached && !shouldRefetch(cached)
347
+ ? await cached.promise
348
+ : await fetchPageState(redirectLogical, signal);
349
+ if (navVersion.current !== myVersion) {
350
+ return null;
351
+ }
352
+ return state;
353
+ }
354
+
355
+ const navigate = useCallback(
356
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — redirect follow, history management, and scroll handling require this depth
357
+ async function navigateTo(
358
+ rawLogicalHref: string,
359
+ opts: { replace?: boolean; resetScroll?: boolean } | undefined
360
+ ) {
361
+ const logicalHref = normalizeHref(rawLogicalHref);
362
+ const myVersion = ++navVersion.current;
363
+ navAbortRef.current?.abort();
364
+ const navAbort = new AbortController();
365
+ navAbortRef.current = navAbort;
366
+ const navSignal = navAbort.signal;
367
+ setIsNavigating(true);
368
+ try {
369
+ const cached = prefetchCache.current.get(logicalHref);
370
+ let newState =
371
+ cached && !shouldRefetch(cached)
372
+ ? await cached.promise
373
+ : await fetchPageState(logicalHref, navSignal);
374
+ if (navVersion.current !== myVersion) {
375
+ return;
376
+ }
377
+ if (newState && (!cached || shouldRefetch(cached))) {
378
+ setPrefetchCacheEntry(
379
+ prefetchCache.current,
380
+ logicalHref,
381
+ {
382
+ promise: Promise.resolve(newState),
383
+ createdAt: Date.now(),
384
+ staleTime: defaultPreloadStaleTime,
385
+ },
386
+ prefetchCacheSize
387
+ );
388
+ }
389
+ if (!newState) {
390
+ log.warn({
391
+ action: "navigate_fallback",
392
+ href: logicalHref,
393
+ reason: "prefetch_returned_null",
394
+ });
395
+ window.location.href = basePath + logicalHref;
396
+ return;
397
+ }
398
+
399
+ // Server-side redirect: replace current history entry and load target
400
+ let redirectLogical: string | undefined;
401
+ if (newState.finalHref && !newState.match && !newState.notFound) {
402
+ redirectLogical = normalizeHref(newState.finalHref);
403
+ const redirectPhysical = basePath + redirectLogical;
404
+ window.history.replaceState(
405
+ {
406
+ ...((history.state as object) ?? {}),
407
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
408
+ },
409
+ "",
410
+ redirectPhysical
411
+ );
412
+ setCurrentHref(redirectLogical);
413
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
414
+ if (!redirectState) {
415
+ if (navVersion.current === myVersion) {
416
+ window.location.href = redirectPhysical;
417
+ }
418
+ return;
419
+ }
420
+ newState = redirectState;
421
+ }
422
+
423
+ currentMatchRef.current = newState.match;
424
+ setState(newState);
425
+ if (newState.title) {
426
+ document.title = newState.title;
427
+ }
428
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
429
+ const physicalEffective = basePath + effectiveLogical;
430
+ if (opts?.replace) {
431
+ window.history.replaceState(
432
+ {
433
+ ...((history.state as object) ?? {}),
434
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
435
+ },
436
+ "",
437
+ physicalEffective
438
+ );
439
+ } else {
440
+ const currentKey = getHistoryKey(history.state);
441
+ if (currentKey) {
442
+ saveScrollPosition(currentKey);
443
+ }
444
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
445
+ }
446
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
447
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
448
+ setCurrentHref(logicalPath + effectiveUrl.search);
449
+ if (opts?.resetScroll ?? true) {
450
+ pendingScrollRef.current = { type: "reset", href: physicalEffective };
451
+ }
452
+ } finally {
453
+ if (navVersion.current === myVersion) {
454
+ setIsNavigating(false);
455
+ }
456
+ }
457
+ },
458
+ [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
459
+ );
460
+
461
+ const refresh = useCallback(
462
+ async (opts: { resetScroll?: boolean } | undefined) => {
463
+ const logicalPath = toLogical(window.location.pathname, basePath);
464
+ const logicalHref = logicalPath + window.location.search;
465
+ invalidatePrefetch(logicalHref, "page");
466
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
467
+ },
468
+ [navigate, invalidatePrefetch, basePath]
469
+ );
470
+
471
+ // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
472
+ // reload of a loader-bearing route the client re-fetches fresh data instead
473
+ // of rendering with stale initialData from the initial SSR payload.
474
+ useEffect(() => {
475
+ if (typeof window !== "undefined") {
476
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
477
+ (window as any).__FURIN_HMR_REFRESH__ = refresh;
478
+ return () => {
479
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
480
+ (window as any).__FURIN_HMR_REFRESH__ = undefined;
481
+ };
482
+ }
483
+ }, [refresh]);
484
+
485
+ const handlePopState = useCallback(() => {
486
+ const destKey = getHistoryKey(history.state);
487
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
488
+ const logicalHref = logicalPath + window.location.search;
489
+ const myVersion = ++navVersion.current;
490
+ navAbortRef.current?.abort();
491
+ const navAbort = new AbortController();
492
+ navAbortRef.current = navAbort;
493
+ const navSignal = navAbort.signal;
494
+ setIsNavigating(true);
495
+
496
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: popstate handler — cache check, redirect follow, and scroll restoration require this depth
497
+ (async () => {
498
+ try {
499
+ const cached = prefetchCache.current.get(logicalHref);
500
+ let newState: RouterState | null;
501
+ if (cached && !shouldRefetch(cached)) {
502
+ newState = await cached.promise;
503
+ } else {
504
+ newState = await fetchPageState(logicalHref, navSignal);
505
+ }
506
+ if (navVersion.current !== myVersion) {
507
+ return;
508
+ }
509
+ if (!newState) {
510
+ log.warn({
511
+ action: "popstate_fallback",
512
+ href: logicalHref,
513
+ reason: "fetchPageState_returned_null",
514
+ });
515
+ window.location.reload();
516
+ return;
517
+ }
518
+
519
+ // Server-side redirect: replace history entry and load target
520
+ let redirectLogical: string | undefined;
521
+ if (newState.finalHref && !newState.match && !newState.notFound) {
522
+ redirectLogical = normalizeHref(newState.finalHref);
523
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
524
+ setCurrentHref(redirectLogical);
525
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
526
+ if (!redirectState) {
527
+ if (navVersion.current === myVersion) {
528
+ window.location.reload();
529
+ }
530
+ return;
531
+ }
532
+ newState = redirectState;
533
+ }
534
+
535
+ currentMatchRef.current = newState.match;
536
+ setState(newState);
537
+ if (newState.title) {
538
+ document.title = newState.title;
539
+ }
540
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
541
+ if (newState.finalHref) {
542
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
543
+ }
544
+ setCurrentHref(normalizeHref(effectiveLogical));
545
+ if (destKey) {
546
+ pendingScrollRef.current = { type: "restore", key: destKey };
547
+ } else {
548
+ window.scrollTo({ top: 0, behavior: "instant" });
549
+ }
550
+ } finally {
551
+ if (navVersion.current === myVersion) {
552
+ setIsNavigating(false);
553
+ }
554
+ }
555
+ })();
556
+ }, [fetchPageState, basePath]);
557
+
558
+ // Disable native scroll restoration and assign a key to the initial history entry.
559
+ useEffect(() => {
560
+ history.scrollRestoration = "manual";
561
+ if (!getHistoryKey(history.state)) {
562
+ history.replaceState(
563
+ { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
564
+ ""
565
+ );
566
+ }
567
+ }, []);
568
+
569
+ // Render-synchronous scroll restoration.
570
+ useLayoutEffect(() => {
571
+ const instruction = pendingScrollRef.current;
572
+ if (!instruction) {
573
+ return;
574
+ }
575
+ pendingScrollRef.current = null;
576
+
577
+ if (instruction.type === "restore") {
578
+ try {
579
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
580
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
581
+ const y = positions[instruction.key] ?? 0;
582
+ window.scrollTo({ top: y, behavior: "instant" });
583
+ } catch {
584
+ window.scrollTo({ top: 0, behavior: "instant" });
585
+ }
586
+ return;
587
+ }
588
+
589
+ const destUrl = new URL(instruction.href, window.location.origin);
590
+ if (destUrl.hash) {
591
+ const id = decodeURIComponent(destUrl.hash.slice(1));
592
+ const element = document.getElementById(id);
593
+ if (element) {
594
+ element.scrollIntoView({ behavior: "instant", block: "start" });
595
+ }
596
+ } else {
597
+ window.scrollTo({ top: 0, behavior: "instant" });
598
+ }
599
+ }, [currentHref]);
600
+
601
+ // Handle browser back/forward
602
+ useEffect(() => {
603
+ window.addEventListener("popstate", handlePopState);
604
+ return () => window.removeEventListener("popstate", handlePopState);
605
+ }, [handlePopState]);
606
+
607
+ // Intercept clicks on native <a> tags so that internal links (including
608
+ // those rendered by MDX, CMS content, or third-party components) participate
609
+ // in SPA navigation instead of triggering full-page reloads.
610
+ useEffect(() => {
611
+ if (typeof window === "undefined") {
612
+ return;
613
+ }
614
+ const handler = (e: MouseEvent) => {
615
+ if (e.defaultPrevented) {
616
+ return;
617
+ }
618
+ const anchor = (e.target as HTMLElement).closest("a");
619
+ if (!(anchor instanceof HTMLAnchorElement)) {
620
+ return;
621
+ }
622
+ // Ignore Furin Link anchors — they handle their own navigation via
623
+ // LinkInteractive.handleClick.
624
+ if (anchor.closest("a[data-furin-link]")) {
625
+ return;
626
+ }
627
+ const logicalHref = shouldInterceptClick(
628
+ anchor,
629
+ e,
630
+ basePath,
631
+ window.location.origin,
632
+ window.location.pathname
633
+ );
634
+ if (logicalHref === null) {
635
+ return;
636
+ }
637
+ e.preventDefault();
638
+ navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
639
+ };
640
+ document.addEventListener("click", handler);
641
+ return () => document.removeEventListener("click", handler);
642
+ }, [navigate, basePath]);
643
+
644
+ // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
645
+ useEffect(() => {
646
+ if (typeof window === "undefined") {
647
+ return;
648
+ }
649
+ const originalFetch = window.fetch;
650
+ const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
651
+ const response = await originalFetch.apply(window, args);
652
+ const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
653
+ applyRevalidateHeader(response.headers, (path, type = "page") => {
654
+ invalidatePrefetch(path, type);
655
+ invalidated.push({ path, type });
656
+ });
657
+ if (autoRefresh && invalidated.length > 0) {
658
+ const currentLogicalPath =
659
+ normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
660
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
661
+ // fire-and-forget: don't block the original fetch caller
662
+ refresh(undefined);
663
+ }
664
+ }
665
+ return response;
666
+ };
667
+ // Copy static fetch methods so the patched value satisfies typeof fetch.
668
+ Object.assign(wrapped, originalFetch);
669
+ // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
670
+ window.fetch = wrapped as any;
671
+ return () => {
672
+ window.fetch = originalFetch;
673
+ };
674
+ }, [invalidatePrefetch, refresh, autoRefresh, basePath]);
675
+
676
+ let pageElement: React.ReactNode;
677
+ if (state.notFound || !state.match) {
678
+ pageElement = buildNotFoundPageElement(
679
+ state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
680
+ state.notFound ?? {}
681
+ );
682
+ } else {
683
+ pageElement = buildPageElement(
684
+ state.match,
685
+ root,
686
+ state.data,
687
+ {
688
+ onReset: () => {
689
+ refresh(undefined).catch((err: unknown) => {
690
+ log.error({ action: "boundary_reset_failed", error: String(err) });
691
+ });
692
+ },
693
+ resetKey: currentHref,
694
+ },
695
+ state.error
696
+ );
697
+ }
698
+
699
+ return buildRouterTree(
700
+ {
701
+ basePath,
702
+ currentHref,
703
+ navigate,
704
+ prefetch,
705
+ refresh,
706
+ invalidatePrefetch,
707
+ isNavigating,
708
+ defaultPreload,
709
+ defaultPreloadDelay,
710
+ defaultPreloadStaleTime,
711
+ },
712
+ pageElement,
713
+ {
714
+ digest: initialDigest,
715
+ onReset: () => {
716
+ refresh(undefined).catch((err: unknown) => {
717
+ log.error({ action: "boundary_reset_failed", error: String(err) });
718
+ });
719
+ },
720
+ resetKey: currentHref,
721
+ }
722
+ );
723
+ }