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

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