@teyik0/furin 0.1.0-alpha.11 → 0.1.0-alpha.13

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.
package/src/link.tsx CHANGED
@@ -1,1297 +1,17 @@
1
- import { log } from "evlog";
2
1
  import type React from "react";
2
+ import { createElement, useCallback, useEffect, useRef } from "react";
3
3
  import {
4
- createContext,
5
- createElement,
6
- useCallback,
7
- useContext,
8
- useEffect,
9
- useMemo,
10
- useRef,
11
- useState,
12
- } from "react";
13
- import type { RuntimeRoute } from "./client";
14
- import type { ErrorComponent } from "./error";
15
- import type { NotFoundComponent } from "./not-found";
16
- import { FurinErrorBoundary, FurinNotFoundBoundary } from "./render/boundaries.tsx";
17
- import { DefaultNotFoundScreen } from "./render/default-screens.tsx";
18
-
19
- // ── Types ─────────────────────────────────────────────────────────────────────
20
-
21
- /**
22
- * Augment this interface via declaration merging in furin-env.d.ts
23
- * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
24
- *
25
- * @example
26
- * // furin-env.d.ts (auto-generated by Furin at project root)
27
- * import "@teyik0/furin/link";
28
- * declare module "@teyik0/furin/link" {
29
- * interface RouteManifest {
30
- * "/blog": { search?: { page?: number; tag?: string } };
31
- * "/": { search?: never };
32
- * [key: `/blog/${string}`]: { search?: never };
33
- * }
34
- * }
35
- */
36
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
37
- export interface RouteManifest {}
38
-
39
- /**
40
- * The valid `to` pathname union derived from the augmented RouteManifest.
41
- * Falls back to `string` when furin-env.d.ts has not been generated yet.
42
- * When augmented, also includes `https://` and `http://` for external links.
43
- */
44
- export type RouteTo = keyof RouteManifest extends never
45
- ? string
46
- : keyof RouteManifest | `https://${string}` | `http://${string}`;
47
-
48
- /**
49
- * The typed search params for a given `to` pathname.
50
- * Falls back to a permissive record when RouteManifest is not augmented.
51
- */
52
- export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
53
- ? Record<string, string | number | boolean | null | undefined>
54
- : To extends keyof RouteManifest
55
- ? RouteManifest[To] extends { search?: infer S }
56
- ? S
57
- : undefined
58
- : undefined;
59
-
60
- export type PreloadStrategy = false | "intent" | "viewport" | "render";
61
-
62
- export interface LinkProps<To extends RouteTo = RouteTo>
63
- extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
64
- /**
65
- * Extra props merged onto the anchor when the link is active.
66
- * `isActive` is also passed so one function can handle both states.
67
- * Styles and classNames from `activeProps` win over the static props.
68
- */
69
- activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
70
- /** Static children or a render function receiving active state. */
71
- children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
72
- /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
73
- disabled?: boolean;
74
- /** Optional URL fragment (without the #). */
75
- hash?: string;
76
- /**
77
- * Extra props merged onto the anchor when the link is NOT active.
78
- * Styles and classNames from `inactiveProps` win over the static props.
79
- */
80
- inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
81
- /** Preload strategy. Default: "intent" (preload on hover/focus). */
82
- preload?: PreloadStrategy;
83
- /** Delay in ms before intent preload triggers. Default: 50. */
84
- preloadDelay?: number;
85
- /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
86
- preloadStaleTime?: number;
87
- /** If true, uses history.replaceState instead of pushState (no new history entry). */
88
- replace?: boolean;
89
- /**
90
- * Whether to scroll after SPA navigation. Default: true.
91
- * - If the destination href has a `#hash`, scrolls to that element.
92
- * - Otherwise scrolls to the top of the page.
93
- * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
94
- */
95
- resetScroll?: boolean;
96
- /** Typed search params for this route. Auto-completed from the route's query schema. */
97
- search?: RouteSearch<To>;
98
- to: To;
99
- }
100
-
101
- /**
102
- * Builds a full href string from a pathname, optional search params, and optional hash.
103
- * Null/undefined search values are omitted.
104
- *
105
- * @internal Exported for unit testing only.
106
- */
107
- export function buildHref(
108
- to: string,
109
- search?: Record<string, unknown> | null,
110
- hash?: string
111
- ): string {
112
- let url = to;
113
- if (search && Object.keys(search).length > 0) {
114
- const params = new URLSearchParams();
115
- for (const [k, v] of Object.entries(search)) {
116
- if (v != null) {
117
- params.set(k, String(v));
118
- }
119
- }
120
- const qs = params.toString();
121
- if (qs) {
122
- url += `?${qs}`;
123
- }
124
- }
125
- if (hash) {
126
- url += `#${hash}`;
127
- }
128
- return url;
129
- }
130
-
131
- // ── Revalidation helpers ────────────────────────────────────────────────────────
132
-
133
- /**
134
- * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
135
- * each path entry. Header format: `"/path1,/path2:layout,/path3"`
136
- *
137
- * Intended to be called from a `window.fetch` interceptor or SPA navigation
138
- * handler so that client-side prefetch caches are busted automatically whenever
139
- * a server-side `revalidatePath()` call is made within the same request.
140
- *
141
- * @example
142
- * ```ts
143
- * const res = await fetch("/api/publish");
144
- * applyRevalidateHeader(res.headers, (path, type) => {
145
- * console.log("invalidate", path, type);
146
- * });
147
- * ```
148
- */
149
- export function applyRevalidateHeader(
150
- headers: Headers,
151
- invalidate: (path: string, type?: "page" | "layout") => void
152
- ): void {
153
- const headerValue = headers.get("x-furin-revalidate");
154
- if (!headerValue) {
155
- return;
156
- }
157
- for (const entry of headerValue.split(",")) {
158
- const trimmed = entry.trim();
159
- if (!trimmed) {
160
- continue;
161
- }
162
- if (trimmed.endsWith(":layout")) {
163
- invalidate(trimmed.slice(0, -":layout".length), "layout");
164
- } else {
165
- invalidate(trimmed, "page");
166
- }
167
- }
168
- }
169
-
170
- // ── Auto-refresh helpers ───────────────────────────────────────────────────────
171
-
172
- /**
173
- * Returns `true` when `currentPath` is targeted by at least one invalidation entry,
174
- * using the same matching rules as `invalidatePrefetch`:
175
- * - `type: 'page'` — exact pathname match (query string stripped)
176
- * - `type: 'layout'` — prefix match: the path itself OR any descendant
177
- *
178
- * @internal Exported for unit testing only.
179
- */
180
- export function shouldAutoRefreshPath(
181
- currentPath: string,
182
- invalidations: ReadonlyArray<{ path: string; type: "page" | "layout" }>
183
- ): boolean {
184
- // Strip query string for comparison — revalidatePath works on pathnames
185
- const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
186
- return invalidations.some(({ path, type }) => {
187
- if (type === "page") {
188
- return path === normalizedCurrent;
189
- }
190
- // layout: match the path itself and all descendants
191
- const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
192
- return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
193
- });
194
- }
195
-
196
- // ── Router context ─────────────────────────────────────────────────────────────
197
-
198
- export interface RouterContextValue {
199
- /**
200
- * Sub-path prefix for static deployments (e.g. "/furin").
201
- * Empty string when the site is served from root.
202
- * Used by `Link` to build correct physical hrefs for the `<a>` element.
203
- */
204
- basePath: string;
205
- /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
206
- currentHref: string;
207
- defaultPreload: PreloadStrategy;
208
- defaultPreloadDelay: number;
209
- defaultPreloadStaleTime: number;
210
- /**
211
- * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
212
- * made on the server. Called automatically by the `window.fetch` interceptor when
213
- * the server emits `X-Furin-Revalidate` headers.
214
- *
215
- * - `type: 'page'` (default) — exact URL match
216
- * - `type: 'layout'` — prefix match (path + all nested children)
217
- */
218
- invalidatePrefetch: (path: string, type?: "page" | "layout") => void;
219
- isNavigating: boolean;
220
- navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
221
- prefetch: (href: string, opts?: { staleTime?: number }) => void;
222
- /**
223
- * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
224
- * loaders, and updates the rendered tree — without adding a history entry or
225
- * resetting scroll (unless `resetScroll: true` is passed).
226
- *
227
- * Prefer this over `navigate(window.location.pathname)` after a mutation.
228
- *
229
- * @example
230
- * ```tsx
231
- * const { refresh } = useRouter();
232
- * await apiClient.api.boards.post({ name });
233
- * await refresh();
234
- * ```
235
- */
236
- refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
237
- }
238
-
239
- export const RouterContext = createContext<RouterContextValue | null>(null);
240
-
241
- /**
242
- * Returns the current router context.
243
- * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
244
- */
245
- export function useRouter(): RouterContextValue {
246
- return (
247
- useContext(RouterContext) ?? {
248
- basePath: "",
249
- // Use the same "/" as SSR_FALLBACK_ROUTER so SSR and client render the
250
- // same active-state when no RouterProvider is present, avoiding hydration mismatches.
251
- currentHref: "/",
252
- navigate: (href) => {
253
- window.location.href = href;
254
- return Promise.resolve();
255
- },
256
- prefetch: () => {
257
- /* noop fallback */
258
- },
259
- invalidatePrefetch: () => {
260
- /* noop fallback */
261
- },
262
- refresh: () => {
263
- window.location.reload();
264
- return Promise.resolve();
265
- },
266
- isNavigating: false,
267
- defaultPreload: "intent",
268
- defaultPreloadDelay: 50,
269
- defaultPreloadStaleTime: 30_000,
270
- }
271
- );
272
- }
273
-
274
- // ── RouterProvider ─────────────────────────────────────────────────────────────
275
-
276
- /**
277
- * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
278
- * version this does NOT carry the directory path — it's purely a (depth,
279
- * fallback) pair because the client never reads files, only renders.
280
- *
281
- * Emitted by `generateHydrateEntry` from the scanned `segmentBoundaries`
282
- * array: each route's entry lists ONLY the directories on its path that
283
- * declare a convention file, so routes with no error.tsx / not-found.tsx
284
- * anywhere carry an empty list (or omit the field entirely).
285
- */
286
- export interface ClientSegmentBoundary {
287
- depth: number;
288
- error?: ErrorComponent;
289
- notFound?: NotFoundComponent;
290
- }
291
-
292
- export interface ClientRoute {
293
- component?: React.ComponentType<Record<string, unknown>>;
294
- load: () => Promise<{
295
- default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
296
- }>;
297
- pageRoute?: RuntimeRoute;
298
- pattern: string;
299
- regex: RegExp;
300
- /**
301
- * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
302
- * to the route-chain index used on the server side, so `buildPageElement`
303
- * can interleave boundaries at the exact same positions that the server
304
- * used in `buildElement` — guaranteeing hydration consistency.
305
- */
306
- segmentBoundaries?: ClientSegmentBoundary[];
307
- }
308
-
309
- /**
310
- * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
311
- * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
312
- * on navigation via fetchPageState.
313
- */
314
- export type LoadedClientRoute = ClientRoute & {
315
- component: React.ComponentType<Record<string, unknown>>;
316
- pageRoute: RuntimeRoute;
317
- };
318
-
319
- export interface RouterProviderProps {
320
- /**
321
- * When `true` (default), the router automatically re-fetches the current page
322
- * whenever a server `revalidatePath()` call targets it. The signal is the
323
- * `X-Furin-Revalidate` header detected on any `window.fetch` response.
324
- *
325
- * Set to `false` to opt out and call `router.refresh()` manually instead.
326
- */
327
- autoRefresh?: boolean;
328
- /**
329
- * Sub-path prefix for static deployments (e.g. "/furin").
330
- * Must start with "/" and have no trailing slash.
331
- * Default: "" (site served from root).
332
- *
333
- * When set:
334
- * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
335
- * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
336
- * - `fetch` calls use the physical path `basePath + logicalHref`.
337
- */
338
- basePath?: string;
339
- defaultPreload?: PreloadStrategy;
340
- defaultPreloadDelay?: number;
341
- defaultPreloadStaleTime?: number;
342
- initialData: Record<string, unknown>;
343
- /**
344
- * Slice 10 — server-logged error digest threaded from
345
- * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
346
- * `FurinErrorBoundary` so that if a client-side error escapes the
347
- * per-segment boundaries (root layout crash, hydration mismatch, …), the
348
- * fallback UI surfaces the id a user would find in server logs.
349
- * Undefined when the initial SSR response was successful (no server-side
350
- * error digest to correlate).
351
- */
352
- initialDigest: string | undefined;
353
- /**
354
- * The route matched at hydration time. `null` is a valid value ONLY when
355
- * `initialNotFound` is also provided — it signals the initial URL didn't
356
- * match any registered route (direct load to an unknown URL). The provider
357
- * then mounts in a "not-found" state so the root `not-found.tsx` hydrates
358
- * inside a live RouterContext — critical for Links in the not-found UI to
359
- * participate in SPA navigation instead of triggering a full-page reload.
360
- */
361
- initialMatch: LoadedClientRoute | null;
362
- /**
363
- * When set, the provider boots into the inline not-found state as if a
364
- * prior SPA navigation hit a 404. Callers set this when the server-rendered
365
- * HTML carries `__FURIN_DATA__.__furinStatus === 404` — either because the
366
- * loader threw `notFound()` (rare at hydration time) or, more commonly,
367
- * because the URL didn't match any client route and `initialMatch` is
368
- * `null`. In the unmatched-URL case the depth-0 `rootBoundaries` are used
369
- * as the boundary chain, matching the server's `renderRootNotFound` choice.
370
- */
371
- initialNotFound: { data?: unknown; message?: string } | undefined;
372
- /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
373
- prefetchCacheSize?: number;
374
- root: RuntimeRoute | null;
375
- routes: ClientRoute[];
376
- }
377
-
378
- interface RouterState {
379
- data: Record<string, unknown>;
380
- /** The canonical href after server-side redirects (e.g. query-default redirect). */
381
- finalHref?: string;
382
- /**
383
- * The currently rendered route.
384
- *
385
- * `null` is a valid value ONLY when `notFound` is also set — it signals the
386
- * initial URL didn't match any registered route (direct load to an unknown
387
- * URL). In that case the provider renders the root `not-found.tsx` directly
388
- * and waits for the next `navigate()` call to populate `match`. Every other
389
- * state (including loader-triggered `notFound()` on a matched route) keeps a
390
- * non-null `match`. Render code MUST guard on `notFound` before dereferencing.
391
- */
392
- match: LoadedClientRoute | null;
393
- /**
394
- * Slice 8 — set when the matched route's loader threw `notFound()` on the
395
- * server (signalled via `__FURIN_DATA__.__furinStatus === 404`). Triggers
396
- * inline rendering of the deepest segment-level not-found.tsx instead of
397
- * the normal layout+page tree, mirroring the server's `buildNotFoundElement`.
398
- */
399
- notFound?: { data?: unknown; message?: string };
400
- /**
401
- * Explicit boundary chain to use for the not-found render.
402
- *
403
- * - **Set** (typically to depth-0 only) when no client-side route matched the
404
- * navigation URL — the root `not-found.tsx` is the correct fallback and no
405
- * page-specific segment context exists.
406
- * - **Absent** when a matched route's loader called `notFound()`, in which
407
- * case `match.segmentBoundaries` is used (preserves per-route not-found).
408
- */
409
- notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
410
- title?: string;
411
- }
412
-
413
- /** @internal */
414
- export interface CacheEntry {
415
- createdAt: number;
416
- promise: Promise<RouterState | null>;
417
- staleTime: number;
418
- }
419
-
420
- /** @internal Exported for unit testing only. */
421
- export function shouldRefetch(entry: CacheEntry): boolean {
422
- return Date.now() - entry.createdAt > entry.staleTime;
423
- }
424
-
425
- const HASH_FRAGMENT_RE = /#.*$/;
426
-
427
- function stripHashFromHref(href: string): string {
428
- return href.replace(HASH_FRAGMENT_RE, "");
429
- }
430
-
431
- // ── Slice 8 helpers — SPA 404 inline rendering ─────────────────────────────────
432
-
433
- /**
434
- * Classification of a fetch response during SPA navigation. Returned by the
435
- * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
436
- *
437
- * - `ok` — 2xx response with usable loader data; render normally.
438
- * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`; the
439
- * caller should render the not-found UI inline (no full-page reload).
440
- * - `bail` — any other non-2xx (5xx, stale-deploy, unparseable payload…);
441
- * the caller falls back to a full-page navigation so the browser picks up
442
- * whatever the server wants to send (could be an error page, redirect, etc.).
443
- *
444
- * @internal Exported for unit testing only.
445
- */
446
- export type SpaResponseKind =
447
- | { kind: "ok" }
448
- | { kind: "not-found"; error: { data?: unknown; message?: string } }
449
- | { kind: "bail" };
450
-
451
- /**
452
- * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
453
- * already-parsed `__FURIN_DATA__` payload. The 404 signal is trusted over the
454
- * HTTP status (guards against proxies that rewrite status but preserve body),
455
- * while any other non-ok HTTP status triggers a bail even if the payload is
456
- * well-formed.
457
- *
458
- * @internal Exported for unit testing only.
459
- */
460
- export function classifySpaResponse(
461
- status: number,
462
- data: Record<string, unknown> | null
463
- ): SpaResponseKind {
464
- if (!data) {
465
- return { kind: "bail" };
466
- }
467
- if (((status >= 200 && status < 300) || status === 404) && data.__furinStatus === 404) {
468
- const notFound = data.__furinNotFound as { data?: unknown; message?: string } | undefined;
469
- return { kind: "not-found", error: notFound ?? {} };
470
- }
471
- if (status >= 200 && status < 300) {
472
- return { kind: "ok" };
473
- }
474
- return { kind: "bail" };
475
- }
476
-
477
- /**
478
- * Picks the deepest not-found component declared on the match's boundary
479
- * chain. Mirrors the server's `route.notFound ?? root.notFound` selection:
480
- * since `segmentBoundaries` is ordered shallow→deep, the last entry with a
481
- * `notFound` wins. Returns undefined when no boundary on the chain declares
482
- * a not-found convention.
483
- *
484
- * @internal Exported for unit testing only.
485
- */
486
- export function pickDeepestNotFound(
487
- boundaries: ClientSegmentBoundary[] | undefined
488
- ): NotFoundComponent | undefined {
489
- if (!boundaries) {
490
- return;
491
- }
492
- for (let i = boundaries.length - 1; i >= 0; i--) {
493
- const seg = boundaries[i];
494
- if (seg?.notFound) {
495
- return seg.notFound;
496
- }
497
- }
498
- return;
499
- }
500
-
501
- const DefaultClientNotFoundFallback: NotFoundComponent = ({ error }) =>
502
- createElement(DefaultNotFoundScreen, { message: error.message });
503
-
504
- /**
505
- * Builds the bare not-found element rendered inline by RouterProvider on SPA
506
- * navigation when the server signalled a 404. Matches the server's
507
- * `buildNotFoundElement` exactly — NO layouts, NO segment boundaries, just the
508
- * deepest user-declared `not-found.tsx` (or the built-in default). Preserving
509
- * layouts on 404 is a deliberate non-goal for this slice: it would diverge
510
- * from the server's current behaviour and require coordinated changes on both
511
- * sides.
512
- *
513
- * Accepts the boundary chain directly (rather than a full `LoadedClientRoute`)
514
- * so callers can pass a subset (e.g. depth-0 only for unmatched URLs) without
515
- * fabricating a synthetic route object.
516
- *
517
- * @internal Exported for unit testing only.
518
- */
519
- export function buildNotFoundPageElement(
520
- boundaries: ClientSegmentBoundary[] | undefined,
521
- error: { data?: unknown; message?: string }
522
- ): React.ReactNode {
523
- const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
524
- return createElement(Fallback, { error });
525
- }
526
-
527
- /**
528
- * Root-level safety-net options forwarded onto the outermost
529
- * `FurinErrorBoundary` that wraps the entire RouterProvider tree. See
530
- * `buildRouterTree` for the full rationale.
531
- */
532
- export interface RootBoundaryOptions {
533
- /**
534
- * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
535
- * When the server's SSR response carried a digest (loader error or shell
536
- * recovery) this value lets the client's fallback UI display the SAME id a
537
- * user would find in the server logs — without having to recompute and
538
- * potentially produce a different hash from a different error instance.
539
- */
540
- digest?: string;
541
- onReset?: () => void;
542
- resetKey?: string | number;
543
- }
544
-
545
- /**
546
- * Composes the outermost tree produced by `RouterProvider`:
547
- *
548
- * <FurinErrorBoundary digest onReset resetKey>
549
- * <RouterContext.Provider value={context}>
550
- * {pageElement}
551
- * </RouterContext.Provider>
552
- * </FurinErrorBoundary>
553
- *
554
- * This top boundary is the LAST line of defence. Per-segment
555
- * `FurinErrorBoundary`s inserted by `buildPageElement` only wrap the page
556
- * subtree BELOW the root layout, so they cannot catch errors thrown in:
557
- * - the root layout itself,
558
- * - hydration mismatches (these tear the whole tree before any inner
559
- * boundary is reached),
560
- * - the RouterProvider / page-building scaffolding code.
561
- *
562
- * We deliberately omit the `fallback` prop so the boundary falls back to its
563
- * built-in `DefaultErrorFallback` — if a user-authored fallback crashed
564
- * during its own render, we'd still have a guaranteed-to-render UI here.
565
- * Users who want a custom *branded* global error UI author a root-level
566
- * `error.tsx`; that convention is already picked up by `segmentBoundaries`
567
- * at depth 0 and sits inside this top boundary.
568
- *
569
- * @internal Exported for unit testing only.
570
- */
571
- export function buildRouterTree(
572
- context: RouterContextValue,
573
- pageElement: React.ReactNode,
574
- options: RootBoundaryOptions
575
- ): React.ReactElement {
576
- return (
577
- <FurinErrorBoundary {...options}>
578
- <RouterContext.Provider value={context}>{pageElement}</RouterContext.Provider>
579
- </FurinErrorBoundary>
580
- );
581
- }
582
-
583
- /**
584
- * Options threaded from `RouterProvider` (or a test harness) into each
585
- * boundary that `buildPageElement` inserts:
586
- *
587
- * - `onReset` — invoked by `FurinErrorBoundary.reset` after it clears local
588
- * error state. RouterProvider wires this to `refresh()` so the user's
589
- * `reset()` prop re-runs the current route's loaders in addition to
590
- * remounting the subtree.
591
- * - `resetKey` — when it changes, both boundary classes clear their latched
592
- * error. RouterProvider passes `currentHref`, so navigating between
593
- * sibling routes that share a boundary (e.g. /blog/a → /blog/b) auto-clears
594
- * any stuck error state even when the boundary instance persists.
595
- */
596
- export interface BoundaryOptions {
597
- onReset?: () => void;
598
- resetKey?: string | number;
599
- }
600
-
601
- /**
602
- * Wraps `inner` with the client-side boundary pair declared at one depth.
603
- * Error boundary must be OUTSIDE the not-found boundary — see the detailed
604
- * justification in `render/element.tsx`'s `wrapInBoundaries`. The client
605
- * mirrors the server's wrap order exactly so hydration sees an identical
606
- * React tree.
607
- */
608
- function wrapPageBoundaries(
609
- inner: React.ReactNode,
610
- segment: ClientSegmentBoundary | undefined,
611
- options: BoundaryOptions | undefined
612
- ): React.ReactNode {
613
- if (!segment) {
614
- return inner;
615
- }
616
- let wrapped = inner;
617
- if (segment.notFound) {
618
- wrapped = (
619
- <FurinNotFoundBoundary fallback={segment.notFound} resetKey={options?.resetKey}>
620
- {wrapped}
621
- </FurinNotFoundBoundary>
622
- );
623
- }
624
- if (segment.error) {
625
- wrapped = (
626
- <FurinErrorBoundary
627
- fallback={segment.error}
628
- onReset={options?.onReset}
629
- resetKey={options?.resetKey}
630
- >
631
- {wrapped}
632
- </FurinErrorBoundary>
633
- );
634
- }
635
- return wrapped;
636
- }
637
-
638
- /** @internal Exported for unit testing only. */
639
- export function buildPageElement(
640
- match: LoadedClientRoute,
641
- root: RuntimeRoute | null,
642
- data: Record<string, unknown>,
643
- options: BoundaryOptions | undefined
644
- ): React.ReactNode {
645
- let element: React.ReactNode = createElement(match.component, data);
646
-
647
- // Collect non-root layouts from the route chain (bottom-up)
648
- const allLayouts: React.ComponentType<Record<string, unknown> & { children: React.ReactNode }>[] =
649
- [];
650
- let current: RuntimeRoute | undefined = match.pageRoute;
651
- while (current) {
652
- if (current.layout) {
653
- allLayouts.unshift(current.layout);
654
- }
655
- current = current.parent;
656
- }
657
-
658
- // If a root layout exists, the first entry in allLayouts IS the root — skip it here
659
- const layouts = root ? allLayouts.slice(1) : allLayouts;
660
-
661
- // Index boundaries by depth for O(1) lookup. `layouts[i]` corresponds to
662
- // route-chain depth `i + 1` (depth 0 = root layout, handled separately).
663
- const byDepth = new Map<number, ClientSegmentBoundary>();
664
- for (const segment of match.segmentBoundaries ?? []) {
665
- byDepth.set(segment.depth, segment);
666
- }
667
-
668
- // Inside-out: at each layout level wrap the subtree with its same-depth
669
- // boundary (so the boundary sits INSIDE the layout), then wrap with the
670
- // layout itself.
671
- for (let i = layouts.length - 1; i >= 0; i--) {
672
- element = wrapPageBoundaries(element, byDepth.get(i + 1), options);
673
- const Layout = layouts[i];
674
- if (Layout) {
675
- // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
676
- element = createElement(Layout, { ...data } as any, element);
677
- }
678
- }
679
-
680
- // Depth 0 boundary wraps EVERYTHING below the root layout.
681
- element = wrapPageBoundaries(element, byDepth.get(0), options);
682
-
683
- if (root?.layout) {
684
- // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
685
- element = createElement(root.layout, { ...data } as any, element);
686
- }
687
-
688
- return element;
689
- }
690
-
691
- /** Scrolls to a hash target or the top of the page after SPA navigation. */
692
- function handleScrollRestoration(
693
- href: string,
694
- navigationToken: number,
695
- navVersion: { current: number }
696
- ): void {
697
- const destUrl = new URL(href, window.location.origin);
698
- if (destUrl.hash) {
699
- const id = decodeURIComponent(destUrl.hash.slice(1));
700
- const scrollToHashTarget = () => {
701
- if (navVersion.current !== navigationToken) {
702
- return;
703
- }
704
-
705
- const element = document.getElementById(id);
706
- if (element) {
707
- element.scrollIntoView({ behavior: "instant", block: "start" });
708
- }
709
- };
710
-
711
- window.requestAnimationFrame(() => {
712
- scrollToHashTarget();
713
- if (document.getElementById(id)) {
714
- return;
715
- }
716
-
717
- window.requestAnimationFrame(() => {
718
- scrollToHashTarget();
719
- });
720
- });
721
- } else {
722
- window.scrollTo({ top: 0, behavior: "instant" });
723
- }
724
- }
725
-
726
- // ── Scroll restoration helpers ─────────────────────────────────────────────────
727
-
728
- const SCROLL_STORAGE_KEY = "__furin_scroll__";
729
-
730
- function getHistoryKey(state: unknown): string | undefined {
731
- return (state as { _furinKey?: string } | null)?._furinKey;
732
- }
733
-
734
- function generateHistoryKey(): string {
735
- return Math.random().toString(36).slice(2, 9);
736
- }
737
-
738
- function saveScrollPosition(key: string): void {
739
- try {
740
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
741
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
742
- positions[key] = window.scrollY;
743
- const keys = Object.keys(positions);
744
- if (keys.length > 50) {
745
- delete positions[keys[0] as string];
746
- }
747
- sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
748
- } catch {
749
- // sessionStorage unavailable (private mode, quota exceeded, etc.)
750
- }
751
- }
752
-
753
- function restoreScrollPosition(key: string, token: number, version: { current: number }): void {
754
- try {
755
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
756
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
757
- const y = positions[key] ?? 0;
758
- window.requestAnimationFrame(() => {
759
- window.requestAnimationFrame(() => {
760
- if (version.current !== token) {
761
- return;
762
- }
763
- window.scrollTo({ top: y, behavior: "instant" });
764
- });
765
- });
766
- } catch {
767
- window.scrollTo({ top: 0, behavior: "instant" });
768
- }
769
- }
770
-
771
- // ── Path helpers ───────────────────────────────────────────────────────────────
772
-
773
- /**
774
- * Returns `true` when the server reports a different build-id from the one
775
- * embedded in the initial HTML (`<meta name="furin-build-id">`). The client
776
- * bundle is then stale and SPA navigation would mount wrong components, so
777
- * the caller must force a full-page reload to pick up the new deploy.
778
- */
779
- function isStaleDeployResponse(res: Response): boolean {
780
- const serverBuildId = res.headers.get("x-furin-build-id");
781
- if (!serverBuildId) {
782
- return false;
783
- }
784
- const metaEl =
785
- typeof document === "undefined"
786
- ? null
787
- : document.querySelector<HTMLMetaElement>('meta[name="furin-build-id"]');
788
- const clientBuildId = metaEl?.content;
789
- return Boolean(clientBuildId && serverBuildId !== clientBuildId);
790
- }
791
-
792
- /**
793
- * Parses the HTML payload of a page response into the pieces `fetchPageState`
794
- * cares about: the document (for title), the __FURIN_DATA__ loader payload,
795
- * and the logical `finalHref` after any server-side redirect.
796
- */
797
- async function parsePageResponse(
798
- res: Response,
799
- basePath: string
800
- ): Promise<{ data: Record<string, unknown> | null; finalHref: string | undefined; title: string }> {
801
- let finalHref: string | undefined;
802
- if (res.redirected) {
803
- const final = new URL(res.url);
804
- finalHref = toLogical(final.pathname, basePath) + final.search;
805
- }
806
- const html = await res.text();
807
- const doc = new DOMParser().parseFromString(html, "text/html");
808
- const dataEl = doc.getElementById("__FURIN_DATA__");
809
- const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
810
- return { data, finalHref, title: doc.title };
811
- }
812
-
813
- /** Strips basePath prefix from a physical pathname, returning the logical path. */
814
- function toLogical(physicalPathname: string, basePath: string): string {
815
- if (
816
- basePath &&
817
- physicalPathname.startsWith(basePath) &&
818
- // Require a path boundary after the prefix so "/furin" doesn't match "/furinity/foo"
819
- (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")
820
- ) {
821
- return physicalPathname.slice(basePath.length) || "/";
822
- }
823
- return physicalPathname;
824
- }
825
-
826
- export function RouterProvider({
827
- routes,
828
- root,
829
- initialMatch,
830
- initialData,
831
- initialDigest,
832
- initialNotFound,
833
- autoRefresh = true,
834
- basePath = "",
835
- defaultPreload = "intent",
836
- defaultPreloadDelay = 50,
837
- defaultPreloadStaleTime = 30_000,
838
- prefetchCacheSize = 50,
839
- }: RouterProviderProps): React.ReactElement {
840
- // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
841
- // the provider boots into the inline not-found UI (see `initialNotFound` JSDoc).
842
- // `notFoundBoundaries` is left undefined so the render path can fall through to
843
- // the memoised `rootBoundaries` below (which isn't available yet at useState init).
844
- const [state, setState] = useState<RouterState>(() => ({
845
- match: initialMatch,
846
- data: initialData,
847
- notFound: initialNotFound,
848
- }));
849
- const [isNavigating, setIsNavigating] = useState(false);
850
- // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
851
- // detection works with route patterns that never include the basePath prefix.
852
- const [currentHref, setCurrentHref] = useState<string>(() => {
853
- if (typeof window === "undefined") {
854
- return "/";
855
- }
856
- return toLogical(window.location.pathname, basePath) + window.location.search;
857
- });
858
- const prefetchCache = useRef(new Map<string, CacheEntry>());
859
- /** Monotonic counter to discard stale navigations (race condition guard). */
860
- const navVersion = useRef(0);
861
- /**
862
- * Tracks the last successfully rendered match for use in the no-route 404 path.
863
- * `null` on the initial render when the URL didn't match any route and the
864
- * provider booted directly into the not-found state; flips to a real match as
865
- * soon as the user navigates away via `navigate()` or the back button.
866
- */
867
- const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
868
-
869
- /**
870
- * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
871
- * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
872
- * handles it — the root `not-found.tsx` (depth 0) is the correct component to
873
- * render inline instead of doing a full-page reload.
874
- * Computed once per `routes` change; stable across navigations.
875
- */
876
- const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
877
- for (const route of routes) {
878
- const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
879
- if (depth0) {
880
- return [depth0];
881
- }
882
- }
883
- return;
884
- }, [routes]);
885
-
886
- const fetchPageState = useCallback(
887
- async (logicalHref: string): Promise<RouterState | null> => {
888
- try {
889
- // Physical href: what the browser/server actually receives.
890
- // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
891
- const physicalHref = basePath + logicalHref;
892
- const url = new URL(physicalHref, window.location.origin);
893
- // Route matching always uses the LOGICAL pathname (basePath stripped).
894
- const logicalPathname = toLogical(url.pathname, basePath);
895
- const match = routes.find((r) => r.regex.test(logicalPathname));
896
- if (!match) {
897
- // No client-side route matched — the server will call renderRootNotFound.
898
- // Fetch the URL so we can detect the __furinStatus: 404 signal embedded
899
- // by renderRootNotFound and render the 404 UI inline (SPA) instead of
900
- // forcing a jarring full-page reload.
901
- const res = await fetch(physicalHref);
902
- if (isStaleDeployResponse(res)) {
903
- window.location.href = physicalHref;
904
- return null;
905
- }
906
- const { data, finalHref, title } = await parsePageResponse(res, basePath);
907
- const kind = classifySpaResponse(res.status, data);
908
- if (kind.kind !== "not-found") {
909
- // Non-404 server response for an unmatched URL (e.g. 5xx) — bail to
910
- // full-page navigation so the browser shows whatever the server sent.
911
- return null;
912
- }
913
- // Strip internal signals before surfacing loader data.
914
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
915
- return {
916
- match: currentMatchRef.current,
917
- data: cleanData,
918
- title,
919
- finalHref,
920
- notFound: kind.error,
921
- // Pass only depth-0 boundaries: for an unmatched URL the root
922
- // not-found.tsx is always the right component — no page-specific
923
- // segment context exists.
924
- notFoundBoundaries: rootBoundaries,
925
- };
926
- }
927
-
928
- // Parallelize HTML data fetch + JS chunk load for this route.
929
- // The browser module cache makes match.load() near-instant for already-loaded pages.
930
- const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
931
-
932
- // Stale-deploy detection: if the server reports a different buildId, the client
933
- // bundle is outdated and SPA navigation would mount wrong components / stale code.
934
- // Force a full page reload to pick up the new bundle.
935
- if (isStaleDeployResponse(res)) {
936
- window.location.href = physicalHref;
937
- return null;
938
- }
939
-
940
- // Parse the HTML payload BEFORE deciding whether to bail on !res.ok.
941
- // Slice 8: a 404 response still carries a valid __FURIN_DATA__ with a
942
- // `__furinStatus: 404` signal, which lets us render the not-found UI
943
- // inline instead of doing a jarring full-page reload. Any other
944
- // non-2xx still bails out (see `classifySpaResponse`).
945
- const { data, finalHref, title } = await parsePageResponse(res, basePath);
946
-
947
- const kind = classifySpaResponse(res.status, data);
948
- if (kind.kind === "bail") {
949
- log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
950
- return null;
951
- }
952
-
953
- const loadedMatch: LoadedClientRoute = {
954
- ...match,
955
- component: loadedMod.default.component,
956
- pageRoute: loadedMod.default._route,
957
- };
958
-
959
- if (kind.kind === "not-found") {
960
- // Strip the server-injected signals from `data` before handing it to
961
- // the component — the NotFound payload is surfaced via `state.notFound`
962
- // instead, and leaking __furinStatus into component props would be
963
- // noise. The caller (RouterProvider render) ignores `data` when
964
- // `notFound` is set anyway, but we keep it tidy for devtools.
965
- const { __furinStatus, __furinNotFound, ...cleanData } = data ?? {};
966
- return {
967
- match: loadedMatch,
968
- data: cleanData,
969
- title,
970
- finalHref,
971
- notFound: kind.error,
972
- };
973
- }
974
-
975
- return { match: loadedMatch, data: data ?? {}, title, finalHref };
976
- } catch (err: unknown) {
977
- log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
978
- return null;
979
- }
980
- },
981
- [routes, basePath, rootBoundaries]
982
- );
983
-
984
- const invalidatePrefetch = useCallback((path: string, type: "page" | "layout" = "page") => {
985
- const normalizedPath = stripHashFromHref(path);
986
-
987
- if (type === "page") {
988
- for (const key of [...prefetchCache.current.keys()]) {
989
- if (stripHashFromHref(key) === normalizedPath) {
990
- prefetchCache.current.delete(key);
991
- }
992
- }
993
- return;
994
- }
995
-
996
- // layout: prefix match — evict the path itself and all nested children
997
- const prefix =
998
- normalizedPath === "/" || normalizedPath.endsWith("/")
999
- ? normalizedPath
1000
- : `${normalizedPath}/`;
1001
- for (const key of [...prefetchCache.current.keys()]) {
1002
- const normalizedKey = stripHashFromHref(key);
1003
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
1004
- prefetchCache.current.delete(key);
1005
- }
1006
- }
1007
- }, []);
1008
-
1009
- const prefetch = useCallback(
1010
- (href: string, opts?: { staleTime?: number }) => {
1011
- const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
1012
- const existing = prefetchCache.current.get(href);
1013
- if (existing && !shouldRefetch(existing)) {
1014
- return;
1015
- }
1016
- prefetchCache.current.set(href, {
1017
- promise: fetchPageState(href),
1018
- createdAt: Date.now(),
1019
- staleTime,
1020
- });
1021
- // Evict the oldest entry when the cap is exceeded
1022
- if (prefetchCache.current.size > prefetchCacheSize) {
1023
- const oldest = prefetchCache.current.keys().next().value as string;
1024
- prefetchCache.current.delete(oldest);
1025
- }
1026
- },
1027
- [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
1028
- );
1029
-
1030
- const navigate = useCallback(
1031
- async (logicalHref: string, opts?: { replace?: boolean; resetScroll?: boolean }) => {
1032
- // logicalHref is the route-relative path (no basePath).
1033
- // The prefetch cache is keyed by logical hrefs.
1034
- prefetch(logicalHref);
1035
- const myVersion = ++navVersion.current;
1036
- setIsNavigating(true);
1037
- try {
1038
- const newState = await prefetchCache.current.get(logicalHref)?.promise;
1039
- // Discard if a newer navigation was started while we were waiting
1040
- if (navVersion.current !== myVersion) {
1041
- return;
1042
- }
1043
- if (!newState) {
1044
- log.warn({
1045
- action: "navigate_fallback",
1046
- href: logicalHref,
1047
- reason: "prefetch_returned_null",
1048
- });
1049
- // Fall back to full-page navigation using the physical URL.
1050
- window.location.href = basePath + logicalHref;
1051
- return;
1052
- }
1053
- currentMatchRef.current = newState.match;
1054
- setState(newState);
1055
- if (newState.title) {
1056
- document.title = newState.title;
1057
- }
1058
- // effectiveHref is logical (finalHref from fetchPageState is also logical).
1059
- const effectiveLogical = newState.finalHref ?? logicalHref;
1060
- // Push the PHYSICAL path to browser history.
1061
- const physicalEffective = basePath + effectiveLogical;
1062
- if (opts?.replace) {
1063
- // Preserve the existing key — same history entry, URL just updated.
1064
- window.history.replaceState(
1065
- {
1066
- ...((history.state as object) ?? {}),
1067
- _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
1068
- },
1069
- "",
1070
- physicalEffective
1071
- );
1072
- } else {
1073
- // Save current position before leaving, then push a fresh entry.
1074
- const currentKey = getHistoryKey(history.state);
1075
- if (currentKey) {
1076
- saveScrollPosition(currentKey);
1077
- }
1078
- window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
1079
- }
1080
- // Store the LOGICAL path in currentHref so Link active-state works.
1081
- const effectiveUrl = new URL(physicalEffective, window.location.origin);
1082
- const logicalPath = toLogical(effectiveUrl.pathname, basePath);
1083
- setCurrentHref(logicalPath + effectiveUrl.search);
1084
- if (opts?.resetScroll ?? true) {
1085
- handleScrollRestoration(physicalEffective, myVersion, navVersion);
1086
- }
1087
- } finally {
1088
- // Only clear navigating flag if this is still the latest navigation
1089
- if (navVersion.current === myVersion) {
1090
- setIsNavigating(false);
1091
- }
1092
- }
1093
- },
1094
- [prefetch, basePath]
1095
- );
1096
-
1097
- const refresh = useCallback(
1098
- async (opts?: { resetScroll?: boolean }) => {
1099
- // Convert the physical browser URL to a logical href before navigating.
1100
- const logicalPath = toLogical(window.location.pathname, basePath);
1101
- const logicalHref = logicalPath + window.location.search;
1102
- // Bust the cache for this exact logical page so navigate always re-fetches
1103
- invalidatePrefetch(logicalHref, "page");
1104
- await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
1105
- },
1106
- [navigate, invalidatePrefetch, basePath]
1107
- );
1108
-
1109
- // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
1110
- // reload of a loader-bearing route the client re-fetches fresh data instead
1111
- // of rendering with stale initialData from the initial SSR payload.
1112
- useEffect(() => {
1113
- if (typeof window !== "undefined") {
1114
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
1115
- (window as any).__FURIN_HMR_REFRESH__ = refresh;
1116
- return () => {
1117
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
1118
- (window as any).__FURIN_HMR_REFRESH__ = undefined;
1119
- };
1120
- }
1121
- }, [refresh]);
1122
-
1123
- const handlePopState = useCallback(async () => {
1124
- // Capture the destination key immediately — history.state is already the
1125
- // destination entry when popstate fires, before any awaits.
1126
- const destKey = getHistoryKey(history.state);
1127
- // Convert physical browser URL to logical href for cache lookup + fetchPageState.
1128
- const logicalPath = toLogical(window.location.pathname, basePath);
1129
- const logicalHref = logicalPath + window.location.search;
1130
- const myVersion = ++navVersion.current;
1131
- setIsNavigating(true);
1132
- try {
1133
- // Check prefetch cache before fetching fresh (keyed by logical href)
1134
- const cached = prefetchCache.current.get(logicalHref);
1135
- let newState: RouterState | null;
1136
- if (cached && !shouldRefetch(cached)) {
1137
- newState = await cached.promise;
1138
- } else {
1139
- newState = await fetchPageState(logicalHref);
1140
- }
1141
- // Discard if a newer navigation was started while we were waiting
1142
- if (navVersion.current !== myVersion) {
1143
- return;
1144
- }
1145
- if (!newState) {
1146
- log.warn({
1147
- action: "popstate_fallback",
1148
- href: logicalHref,
1149
- reason: "fetchPageState_returned_null",
1150
- });
1151
- window.location.reload();
1152
- return;
1153
- }
1154
- currentMatchRef.current = newState.match;
1155
- setState(newState);
1156
- if (newState.title) {
1157
- document.title = newState.title;
1158
- }
1159
- // effectiveHref is logical (includes search); push physical to history if server redirected.
1160
- const effectiveLogical = newState.finalHref ?? logicalHref;
1161
- if (newState.finalHref) {
1162
- // Preserve _furinKey so restoreScrollPosition still works after a redirect.
1163
- window.history.replaceState(history.state, "", basePath + effectiveLogical);
1164
- }
1165
- // effectiveLogical already contains the search params — no URL round-trip needed.
1166
- setCurrentHref(effectiveLogical);
1167
- // Restore the saved scroll position for this history entry (double rAF waits
1168
- // for React to finish painting the new page before scrolling).
1169
- if (destKey) {
1170
- restoreScrollPosition(destKey, myVersion, navVersion);
1171
- } else {
1172
- window.scrollTo({ top: 0, behavior: "instant" });
1173
- }
1174
- } finally {
1175
- if (navVersion.current === myVersion) {
1176
- setIsNavigating(false);
1177
- }
1178
- }
1179
- }, [fetchPageState, basePath]);
1180
-
1181
- // Disable native scroll restoration and assign a key to the initial history entry
1182
- useEffect(() => {
1183
- const prevScrollRestoration = history.scrollRestoration;
1184
- history.scrollRestoration = "manual";
1185
- if (!getHistoryKey(history.state)) {
1186
- history.replaceState(
1187
- { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
1188
- ""
1189
- );
1190
- }
1191
- return () => {
1192
- history.scrollRestoration = prevScrollRestoration;
1193
- };
1194
- }, []);
1195
-
1196
- // Handle browser back/forward
1197
- useEffect(() => {
1198
- window.addEventListener("popstate", handlePopState);
1199
- return () => window.removeEventListener("popstate", handlePopState);
1200
- }, [handlePopState]);
1201
-
1202
- // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
1203
- // This ensures that API routes calling revalidatePath() automatically bust the
1204
- // client prefetch cache, even for non-navigation fetches (e.g. form submissions).
1205
- // When autoRefresh=true (default), also re-fetches the current page if it was invalidated.
1206
- useEffect(() => {
1207
- if (typeof window === "undefined") {
1208
- return;
1209
- }
1210
- const originalFetch = window.fetch;
1211
- const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
1212
- const response = await originalFetch.apply(window, args);
1213
- const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
1214
- applyRevalidateHeader(response.headers, (path, type = "page") => {
1215
- invalidatePrefetch(path, type);
1216
- invalidated.push({ path, type });
1217
- });
1218
- if (autoRefresh && invalidated.length > 0) {
1219
- const currentPath = window.location.pathname + window.location.search;
1220
- if (shouldAutoRefreshPath(currentPath, invalidated)) {
1221
- // fire-and-forget: don't block the original fetch caller
1222
- refresh();
1223
- }
1224
- }
1225
- return response;
1226
- };
1227
- // Copy static fetch methods (e.g. preconnect) so the patched value satisfies typeof fetch.
1228
- Object.assign(wrapped, originalFetch);
1229
- // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
1230
- window.fetch = wrapped as any;
1231
- return () => {
1232
- window.fetch = originalFetch;
1233
- };
1234
- }, [invalidatePrefetch, refresh, autoRefresh]);
1235
-
1236
- // Slice 8 — when a prior SPA navigation hit a loader-thrown or catch-all 404,
1237
- // render the bare not-found element (mirrors server's `buildNotFoundElement`).
1238
- // - `notFoundBoundaries`: set when no route matched (always depth-0 / root
1239
- // not-found.tsx, since no page-specific context applies to unknown URLs).
1240
- // - Fallback to `match.segmentBoundaries`: set when a matched loader called
1241
- // `notFound()` (preserves the deepest route-level not-found.tsx).
1242
- // - Fallback to `rootBoundaries`: the initial-hydration "direct load to an
1243
- // unknown URL" case, where `state.match` is null because no client route
1244
- // matched the boot URL. The provider booted into not-found mode to give
1245
- // Links in the not-found UI a live RouterContext (so "Go Home" does SPA
1246
- // navigation, not a full reload).
1247
- // The render path is split explicitly rather than collapsed into a ternary
1248
- // so TypeScript can narrow `state.match` to non-null for `buildPageElement`
1249
- // — the invariant is "`state.match` is null only when `state.notFound` is set".
1250
- let pageElement: React.ReactNode;
1251
- if (state.notFound || !state.match) {
1252
- pageElement = buildNotFoundPageElement(
1253
- state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
1254
- state.notFound ?? {}
1255
- );
1256
- } else {
1257
- pageElement = buildPageElement(state.match, root, state.data, {
1258
- // User's `reset()` prop → clear local boundary state (handled by the
1259
- // boundary itself) → re-run loaders for the current route so transient
1260
- // errors (bad state, expired data) can recover without a full reload.
1261
- onReset: refresh,
1262
- // Auto-clear latched errors when navigating between routes that share
1263
- // a boundary instance — otherwise the new route would render INSIDE
1264
- // the previous route's error fallback.
1265
- resetKey: currentHref,
1266
- });
1267
- }
1268
-
1269
- // Slice 9 + 10 — wrap the entire tree in a root FurinErrorBoundary that
1270
- // catches anything per-segment boundaries missed (root layout crash,
1271
- // hydration mismatch, scaffolding errors). `digest` is seeded from the
1272
- // server's __FURIN_DATA__.__furinError.digest so client fallback UIs show
1273
- // the same id the server already logged.
1274
- return buildRouterTree(
1275
- {
1276
- basePath,
1277
- currentHref,
1278
- navigate,
1279
- prefetch,
1280
- refresh,
1281
- invalidatePrefetch,
1282
- isNavigating,
1283
- defaultPreload,
1284
- defaultPreloadDelay,
1285
- defaultPreloadStaleTime,
1286
- },
1287
- pageElement,
1288
- {
1289
- digest: initialDigest,
1290
- onReset: refresh,
1291
- resetKey: currentHref,
1292
- }
1293
- );
1294
- }
4
+ buildHref,
5
+ type LinkProps,
6
+ normalizeHref,
7
+ RouterContext,
8
+ type RouterContextValue,
9
+ type RouteTo,
10
+ useRouter,
11
+ } from "./router-provider.tsx";
12
+
13
+ // biome-ignore lint/performance/noBarrelFile: re-exporting router-provider symbols preserves backward compatibility for @teyik0/furin/link consumers
14
+ export * from "./router-provider.tsx";
1295
15
 
1296
16
  // ── Link ───────────────────────────────────────────────────────────────────────
1297
17
 
@@ -1328,8 +48,12 @@ function computeLinkView<To extends RouteTo>(
1328
48
  search as Record<string, unknown> | null | undefined,
1329
49
  undefined
1330
50
  );
1331
- const href = router.basePath + logicalHref;
1332
- const isActive = router.currentHref === logicalHrefWithoutHash;
51
+ const isAbsolute =
52
+ logicalHref.startsWith("http://") ||
53
+ logicalHref.startsWith("https://") ||
54
+ logicalHref.startsWith("//");
55
+ const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
56
+ const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
1333
57
  const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1334
58
  const extraProps: React.AnchorHTMLAttributes<HTMLAnchorElement> = {
1335
59
  ...(inactiveProps && !isActive ? inactiveProps() : {}),
@@ -1361,6 +85,8 @@ function LinkInteractive<To extends RouteTo>({
1361
85
  onMouseLeave,
1362
86
  onFocus,
1363
87
  children,
88
+ // @ts-expect-error: defensive strip of accidental href prop passed via spread
89
+ href: _href,
1364
90
  ...anchorProps
1365
91
  }: LinkProps<To>): React.ReactElement {
1366
92
  const router = useRouter();
@@ -1373,7 +99,6 @@ function LinkInteractive<To extends RouteTo>({
1373
99
  { to, search, hash, children, activeProps, inactiveProps },
1374
100
  router
1375
101
  );
1376
-
1377
102
  const effectivePreload = preload ?? router.defaultPreload;
1378
103
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
1379
104
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
@@ -1408,6 +133,18 @@ function LinkInteractive<To extends RouteTo>({
1408
133
  return () => observer.disconnect();
1409
134
  }, [effectivePreload, triggerPrefetch]);
1410
135
 
136
+ // Clear any pending intent prefetch timer on unmount to avoid leaking
137
+ // setTimeout callbacks between test cases (or across re-renders).
138
+ useEffect(
139
+ () => () => {
140
+ if (intentTimerRef.current !== null) {
141
+ clearTimeout(intentTimerRef.current);
142
+ intentTimerRef.current = null;
143
+ }
144
+ },
145
+ []
146
+ );
147
+
1411
148
  const isInternal = (url: string): boolean => {
1412
149
  try {
1413
150
  return new URL(url, window.location.origin).origin === window.location.origin;
@@ -1418,7 +155,11 @@ function LinkInteractive<To extends RouteTo>({
1418
155
 
1419
156
  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
1420
157
  onClick?.(e);
1421
- if (e.defaultPrevented || disabled) {
158
+ if (e.defaultPrevented) {
159
+ return;
160
+ }
161
+ if (disabled) {
162
+ e.preventDefault();
1422
163
  return;
1423
164
  }
1424
165
  // Let browser handle modifier+click (new tab, etc.)
@@ -1465,6 +206,7 @@ function LinkInteractive<To extends RouteTo>({
1465
206
  {
1466
207
  ref: anchorRef,
1467
208
  href,
209
+ "data-furin-link": true,
1468
210
  onClick: handleClick,
1469
211
  onMouseEnter: handleMouseEnter,
1470
212
  onMouseLeave: handleMouseLeave,
@@ -1484,7 +226,8 @@ function LinkInteractive<To extends RouteTo>({
1484
226
  * Static fallback used by Link during SSR when there is no RouterProvider.
1485
227
  * Must not reference `window` — this object is created at module parse time.
1486
228
  */
1487
- const SSR_FALLBACK_ROUTER: RouterContextValue = {
229
+ /** @internal Exported for unit testing only. */
230
+ export const SSR_FALLBACK_ROUTER: RouterContextValue = {
1488
231
  basePath: "",
1489
232
  currentHref: "/",
1490
233
  navigate: () => Promise.resolve(),
@@ -1530,6 +273,8 @@ function renderLinkElement<To extends RouteTo>(
1530
273
  onMouseEnter: _ome,
1531
274
  onMouseLeave: _oml,
1532
275
  onFocus: _of,
276
+ // @ts-expect-error: defensive strip of accidental href prop passed via spread
277
+ href: _href,
1533
278
  ...anchorProps
1534
279
  } = props;
1535
280
 
@@ -1537,6 +282,7 @@ function renderLinkElement<To extends RouteTo>(
1537
282
  "a",
1538
283
  {
1539
284
  href,
285
+ "data-furin-link": true,
1540
286
  ...(isActive ? { "data-status": "active" } : {}),
1541
287
  ...anchorProps,
1542
288
  ...extraProps,