@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.5

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