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

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 (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,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
+ 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
+ }