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

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
@@ -12,10 +12,12 @@ import {
12
12
  useState,
13
13
  } from "react";
14
14
  import type { RuntimeRoute } from "./client";
15
+ import { parseDeferredNdjson } from "./deferred-ndjson";
15
16
  import type { ErrorComponent } from "./error";
16
17
  import type { NotFoundComponent } from "./not-found";
17
18
  import { FurinErrorBoundary, FurinNotFoundBoundary } from "./render/boundaries.tsx";
18
19
  import { DefaultNotFoundScreen } from "./render/default-screens.tsx";
20
+ import { FurinServerError } from "./server-error.ts";
19
21
 
20
22
  // ── Types ─────────────────────────────────────────────────────────────────────
21
23
 
@@ -379,6 +381,15 @@ export interface RouterProviderProps {
379
381
 
380
382
  interface RouterState {
381
383
  data: Record<string, unknown>;
384
+ /**
385
+ * Set when the server's NDJSON payload carried an `__furinError` sentinel
386
+ * (loader threw a non-redirect `Response`, or an `Error`). The provider's
387
+ * render path injects a `<RouteErrorThrower>` in place of the page so the
388
+ * nearest `<FurinErrorBoundary>` catches a `FurinServerError` carrying the
389
+ * server's digest + status. Mirrors the `__furinError` channel that already
390
+ * exists for SSR digest correlation.
391
+ */
392
+ error?: { digest: string; message: string; status: number };
382
393
  /** The canonical href after server-side redirects (e.g. query-default redirect). */
383
394
  finalHref?: string;
384
395
  /**
@@ -425,6 +436,8 @@ export function shouldRefetch(entry: CacheEntry): boolean {
425
436
  }
426
437
 
427
438
  const HASH_FRAGMENT_RE = /#.*$/;
439
+ /** Strips one or more trailing slashes — used by `buildDataEndpoint` in static mode. */
440
+ const TRAILING_SLASHES_RE = /\/+$/;
428
441
 
429
442
  function stripHashFromHref(href: string): string {
430
443
  return href.replace(HASH_FRAGMENT_RE, "");
@@ -458,23 +471,42 @@ function normalizePath(path: string): string {
458
471
  * - `ok` — 2xx response with usable loader data; render normally.
459
472
  * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`; the
460
473
  * caller should render the not-found UI inline (no full-page reload).
461
- * - `bail` — any other non-2xx (5xx, stale-deploy, unparseable payload…);
462
- * the caller falls back to a full-page navigation so the browser picks up
463
- * whatever the server wants to send (could be an error page, redirect, etc.).
474
+ * - `error` — server signalled `__FURIN_DATA__.__furinError` (loader threw a
475
+ * non-redirect `Response` or an `Error`). The caller surfaces this through
476
+ * the nearest `error.tsx` inline by throwing a `FurinServerError` during
477
+ * render so the existing `FurinErrorBoundary` catches it.
478
+ * - `bail` — any other non-2xx without sentinels (stale-deploy, unparseable
479
+ * payload, opaque crash…); the caller falls back to a full-page navigation
480
+ * so the browser shows whatever the server actually sent.
464
481
  *
465
482
  * @internal Exported for unit testing only.
466
483
  */
467
484
  export type SpaResponseKind =
468
485
  | { kind: "ok" }
469
486
  | { kind: "not-found"; error: { data?: unknown; message?: string } }
487
+ | { kind: "error"; error: { digest: string; message: string; status: number } }
470
488
  | { kind: "bail" };
471
489
 
490
+ function isFurinErrorPayload(
491
+ value: unknown
492
+ ): value is { digest: string; message: string; status: number } {
493
+ if (!value || typeof value !== "object") {
494
+ return false;
495
+ }
496
+ const v = value as { digest?: unknown; message?: unknown; status?: unknown };
497
+ return (
498
+ typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number"
499
+ );
500
+ }
501
+
472
502
  /**
473
503
  * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
474
- * already-parsed `__FURIN_DATA__` payload. The 404 signal is trusted over the
475
- * HTTP status (guards against proxies that rewrite status but preserve body),
476
- * while any other non-ok HTTP status triggers a bail even if the payload is
477
- * well-formed.
504
+ * already-parsed `__FURIN_DATA__` payload.
505
+ *
506
+ * Sentinels (`__furinError`, `__furinStatus`) are trusted over the raw HTTP
507
+ * status — proxies / CDNs sometimes rewrite the status code but pass the body
508
+ * through untouched. A non-2xx response without any sentinel triggers a bail
509
+ * so the browser handles it (could be an error page, redirect, etc.).
478
510
  *
479
511
  * @internal Exported for unit testing only.
480
512
  */
@@ -485,6 +517,9 @@ export function classifySpaResponse(
485
517
  if (!data) {
486
518
  return { kind: "bail" };
487
519
  }
520
+ if (isFurinErrorPayload(data.__furinError)) {
521
+ return { kind: "error", error: data.__furinError };
522
+ }
488
523
  if (((status >= 200 && status < 300) || status === 404) && data.__furinStatus === 404) {
489
524
  const notFound = data.__furinNotFound as { data?: unknown; message?: string } | undefined;
490
525
  return { kind: "not-found", error: notFound ?? {} };
@@ -634,19 +669,26 @@ export interface RootBoundaryOptions {
634
669
  /**
635
670
  * Composes the outermost tree produced by `RouterProvider`:
636
671
  *
637
- * <FurinErrorBoundary digest onReset resetKey>
638
- * <RouterContext.Provider value={context}>
672
+ * <RouterContext.Provider value={context}>
673
+ * <FurinErrorBoundary digest onReset resetKey>
639
674
  * {pageElement}
640
- * </RouterContext.Provider>
641
- * </FurinErrorBoundary>
675
+ * </FurinErrorBoundary>
676
+ * </RouterContext.Provider>
642
677
  *
643
- * This top boundary is the LAST line of defence. Per-segment
644
- * `FurinErrorBoundary`s inserted by `buildPageElement` only wrap the page
645
- * subtree BELOW the root layout, so they cannot catch errors thrown in:
678
+ * `RouterContext.Provider` is the OUTERMOST element so that a root-level
679
+ * `error.tsx` rendered by the boundary can still call `useRouter()` / render
680
+ * `<Link>` (the context is in scope above the boundary).
681
+ *
682
+ * The `FurinErrorBoundary` is the LAST line of defence for render errors.
683
+ * Per-segment `FurinErrorBoundary`s inserted by `buildPageElement` only wrap
684
+ * the page subtree BELOW the root layout, so this top boundary is the only one
685
+ * that catches errors thrown in:
646
686
  * - the root layout itself,
647
- * - hydration mismatches (these tear the whole tree before any inner
648
- * boundary is reached),
649
- * - the RouterProvider / page-building scaffolding code.
687
+ * - hydration mismatches within the rendered tree.
688
+ *
689
+ * It does NOT catch errors thrown by `RouterProvider` itself or by the
690
+ * `buildPageElement` / `buildRouterTree` scaffolding — those run before the
691
+ * boundary exists in the tree, so React has no boundary to propagate to.
650
692
  *
651
693
  * We deliberately omit the `fallback` prop so the boundary falls back to its
652
694
  * built-in `DefaultErrorFallback` — if a user-authored fallback crashed
@@ -663,9 +705,9 @@ export function buildRouterTree(
663
705
  options: RootBoundaryOptions
664
706
  ): React.ReactElement {
665
707
  return (
666
- <FurinErrorBoundary {...options}>
667
- <RouterContext.Provider value={context}>{pageElement}</RouterContext.Provider>
668
- </FurinErrorBoundary>
708
+ <RouterContext.Provider value={context}>
709
+ <FurinErrorBoundary {...options}>{pageElement}</FurinErrorBoundary>
710
+ </RouterContext.Provider>
669
711
  );
670
712
  }
671
713
 
@@ -724,14 +766,43 @@ function wrapPageBoundaries(
724
766
  return wrapped;
725
767
  }
726
768
 
769
+ /**
770
+ * Internal helper component that throws a `FurinServerError` during render
771
+ * so the nearest `<FurinErrorBoundary>` catches it and renders the user's
772
+ * `error.tsx` (or the built-in default) — without forcing a full-page reload.
773
+ *
774
+ * Used by `buildPageElement` when the server signalled `__furinError` for the
775
+ * SPA-nav target. The thrown error carries the server's digest + status so:
776
+ * - `FurinErrorBoundary.getDerivedStateFromError` honours the server digest
777
+ * (matches the id the server already logged) instead of recomputing one
778
+ * from a synthetic stack.
779
+ * - The user's `error.tsx` receives `error.status` from the original
780
+ * loader-thrown `Response.status`.
781
+ */
782
+ function RouteErrorThrower({
783
+ error,
784
+ }: {
785
+ error: { digest: string; message: string; status: number };
786
+ }): React.ReactElement {
787
+ throw new FurinServerError(error);
788
+ }
789
+
727
790
  /** @internal Exported for unit testing only. */
728
791
  export function buildPageElement(
729
792
  match: LoadedClientRoute,
730
793
  root: RuntimeRoute | null,
731
794
  data: Record<string, unknown>,
732
- options: BoundaryOptions | undefined
795
+ options: BoundaryOptions | undefined,
796
+ error: { digest: string; message: string; status: number } | undefined
733
797
  ): React.ReactNode {
734
- let element: React.ReactNode = createElement(match.component, data);
798
+ // When the server signalled `__furinError`, the page component's loader
799
+ // failed — there is no real `data` for it. Replace the page with a
800
+ // throw-on-render shim so the deepest `<FurinErrorBoundary>` (set up by
801
+ // wrapPageBoundaries below) catches a `FurinServerError` carrying the
802
+ // server's digest + status.
803
+ let element: React.ReactNode = error
804
+ ? createElement(RouteErrorThrower, { error })
805
+ : createElement(match.component, data);
735
806
 
736
807
  // Collect non-root layouts from the route chain (bottom-up)
737
808
  const allLayouts: React.ComponentType<Record<string, unknown> & { children: React.ReactNode }>[] =
@@ -846,6 +917,59 @@ async function parsePageResponse(
846
917
  return { data, finalHref, title: doc.title };
847
918
  }
848
919
 
920
+ /**
921
+ * Builds the URL the SPA navigation flow uses to fetch a route's loader data.
922
+ *
923
+ * Two transports are supported:
924
+ *
925
+ * • **Runtime (SSR/ISR/dev)** — `${basePath}/_furin/data?path=<logicalHref>`.
926
+ * Served by the Elysia plugin in `createDataEndpoint`, which dynamically
927
+ * re-runs the loader with the requested path/query.
928
+ *
929
+ * • **Static export** — `${basePath}<logicalPathname>/__furin_data.ndjson`.
930
+ * Pre-written next to each `index.html` by `buildStaticTarget`, served
931
+ * verbatim by any file server (GitHub Pages, S3, …). The loader does not
932
+ * execute at request time, so query strings are *intentionally* ignored:
933
+ * a single NDJSON exists per route, computed at build time.
934
+ *
935
+ * `staticMode` is decided once at boot from the `<meta name="furin-mode">`
936
+ * tag injected by `generateProdIndexHtml` — flipping the transport at runtime
937
+ * for the wrong deployment would just produce 404s.
938
+ *
939
+ * @internal Exported for unit testing.
940
+ */
941
+ export function buildDataEndpoint(
942
+ basePath: string,
943
+ logicalHref: string,
944
+ staticMode: boolean
945
+ ): string {
946
+ if (!staticMode) {
947
+ return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
948
+ }
949
+ // Strip query/hash and any trailing slash. In static mode the on-disk file
950
+ // is `<pathname>/__furin_data.ndjson` regardless of search/hash, because
951
+ // the loader payload was frozen at build time.
952
+ const parsed = new URL(logicalHref, "http://x");
953
+ const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
954
+ return `${basePath}${pathname}/__furin_data.ndjson`;
955
+ }
956
+
957
+ /**
958
+ * Reads `<meta name="furin-mode" content="static">` from the document at boot.
959
+ * The static adapter injects this tag (`shell.ts:generateProdIndexHtml`) so the
960
+ * SPA client picks the static-friendly transport. SSR/dev shells omit the tag
961
+ * and the client uses the runtime endpoint.
962
+ *
963
+ * @internal Exported for unit testing.
964
+ */
965
+ export function detectStaticMode(): boolean {
966
+ if (typeof document === "undefined") {
967
+ return false;
968
+ }
969
+ const meta = document.querySelector<HTMLMetaElement>('meta[name="furin-mode"]');
970
+ return meta?.content === "static";
971
+ }
972
+
849
973
  /** Strips basePath prefix from a physical pathname, returning the logical path. */
850
974
  export function toLogical(physicalPathname: string, basePath: string): string {
851
975
  if (
@@ -873,12 +997,6 @@ export function RouterProvider({
873
997
  defaultPreloadStaleTime,
874
998
  prefetchCacheSize,
875
999
  }: RouterProviderProps): React.ReactElement {
876
- const _autoRefresh = autoRefresh ?? true;
877
- const _basePath = basePath ?? "";
878
- const _defaultPreload = defaultPreload ?? "intent";
879
- const _defaultPreloadDelay = defaultPreloadDelay ?? 50;
880
- const _defaultPreloadStaleTime = defaultPreloadStaleTime ?? 30_000;
881
- const _prefetchCacheSize = prefetchCacheSize ?? 50;
882
1000
  // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
883
1001
  // the provider boots into the inline not-found UI (see `initialNotFound` JSDoc).
884
1002
  // `notFoundBoundaries` is left undefined so the render path can fall through to
@@ -895,11 +1013,18 @@ export function RouterProvider({
895
1013
  if (typeof window === "undefined") {
896
1014
  return "/";
897
1015
  }
898
- return normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
1016
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
899
1017
  });
900
1018
  const prefetchCache = useRef(new Map<string, CacheEntry>());
901
1019
  /** Monotonic counter to discard stale navigations (race condition guard). */
902
1020
  const navVersion = useRef(0);
1021
+ /**
1022
+ * AbortController for the current navigation. Cancelled when a newer
1023
+ * navigation starts so any in-flight `parseDeferredNdjson` releases its
1024
+ * pending deferred promises (resolvers reject with `AbortError`) and frees
1025
+ * the underlying stream reader.
1026
+ */
1027
+ const navAbortRef = useRef<AbortController | null>(null);
903
1028
  /**
904
1029
  * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
905
1030
  * This replaces the fragile double-requestAnimationFrame pattern with a render-
@@ -915,6 +1040,13 @@ export function RouterProvider({
915
1040
  * soon as the user navigates away via `navigate()` or the back button.
916
1041
  */
917
1042
  const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
1043
+ /**
1044
+ * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
1045
+ * fetch URL: runtime `/_furin/data` for SSR/ISR/dev, per-route
1046
+ * `__furin_data.ndjson` for static exports. Computed once because the meta
1047
+ * tag is part of the shell — it cannot change without a full reload.
1048
+ */
1049
+ const staticModeRef = useRef<boolean>(detectStaticMode());
918
1050
 
919
1051
  /**
920
1052
  * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
@@ -933,8 +1065,45 @@ export function RouterProvider({
933
1065
  return;
934
1066
  }, [routes]);
935
1067
 
1068
+ /**
1069
+ * Resolves the RouterState when no client-side route matched the URL. The
1070
+ * server's `renderRootNotFound` produced the 404 HTML; we fetch the physical
1071
+ * URL to detect the `__furinStatus: 404` signal and render the 404 UI inline
1072
+ * (rather than triggering a jarring full-page reload). Extracted from
1073
+ * `fetchPageState` to keep that function's complexity under the lint
1074
+ * threshold.
1075
+ */
1076
+ const resolveNoMatchState = useCallback(
1077
+ async (physicalHref: string): Promise<RouterState | null> => {
1078
+ const res = await fetch(physicalHref);
1079
+ if (isStaleDeployResponse(res)) {
1080
+ window.location.href = physicalHref;
1081
+ return null;
1082
+ }
1083
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
1084
+ const kind = classifySpaResponse(res.status, data);
1085
+ if (kind.kind !== "not-found") {
1086
+ return null;
1087
+ }
1088
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
1089
+ return {
1090
+ match: currentMatchRef.current,
1091
+ data: cleanData,
1092
+ title,
1093
+ finalHref,
1094
+ notFound: kind.error,
1095
+ notFoundBoundaries: rootBoundaries,
1096
+ };
1097
+ },
1098
+ [basePath, rootBoundaries]
1099
+ );
1100
+
936
1101
  const fetchPageState = useCallback(
937
- async (rawLogicalHref: string): Promise<RouterState | null> => {
1102
+ async (
1103
+ rawLogicalHref: string,
1104
+ signal: AbortSignal | undefined
1105
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
1106
+ ): Promise<RouterState | null> => {
938
1107
  // Normalize trailing slashes so "/docs/routing/" matches the route
939
1108
  // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
940
1109
  // redirect to or serve URLs with a trailing slash.
@@ -942,46 +1111,23 @@ export function RouterProvider({
942
1111
  try {
943
1112
  // Physical href: what the browser/server actually receives.
944
1113
  // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
945
- const physicalHref = _basePath + logicalHref;
1114
+ const physicalHref = basePath + logicalHref;
946
1115
  const url = new URL(physicalHref, window.location.origin);
947
1116
  // Route matching always uses the LOGICAL pathname (basePath stripped).
948
- const logicalPathname = toLogical(url.pathname, _basePath);
1117
+ const logicalPathname = toLogical(url.pathname, basePath);
949
1118
  const match = routes.find((r) => r.regex.test(logicalPathname));
950
1119
  if (!match) {
951
- // No client-side route matched — the server will call renderRootNotFound.
952
- // Fetch the URL so we can detect the __furinStatus: 404 signal embedded
953
- // by renderRootNotFound and render the 404 UI inline (SPA) instead of
954
- // forcing a jarring full-page reload.
955
- const res = await fetch(physicalHref);
956
- if (isStaleDeployResponse(res)) {
957
- window.location.href = physicalHref;
958
- return null;
959
- }
960
- const { data, finalHref, title } = await parsePageResponse(res, _basePath);
961
- const kind = classifySpaResponse(res.status, data);
962
- if (kind.kind !== "not-found") {
963
- // Non-404 server response for an unmatched URL (e.g. 5xx) — bail to
964
- // full-page navigation so the browser shows whatever the server sent.
965
- return null;
966
- }
967
- // Strip internal signals before surfacing loader data.
968
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
969
- return {
970
- match: currentMatchRef.current,
971
- data: cleanData,
972
- title,
973
- finalHref,
974
- notFound: kind.error,
975
- // Pass only depth-0 boundaries: for an unmatched URL the root
976
- // not-found.tsx is always the right component — no page-specific
977
- // segment context exists.
978
- notFoundBoundaries: rootBoundaries,
979
- };
1120
+ return await resolveNoMatchState(physicalHref);
980
1121
  }
981
1122
 
982
- // Parallelize HTML data fetch + JS chunk load for this route.
983
- // The browser module cache makes match.load() near-instant for already-loaded pages.
984
- const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
1123
+ // ── NDJSON data endpoint + JS chunk load (parallel) ──────────────────
1124
+ // Fetch loader data and load the JS module concurrently. The transport
1125
+ // depends on the deployment mode (see `buildDataEndpoint` JSDoc): the
1126
+ // runtime endpoint for SSR/ISR/dev, a static `__furin_data.ndjson`
1127
+ // file for static exports. Detection happens once at boot to avoid
1128
+ // racing the meta-tag lookup against React StrictMode double-renders.
1129
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
1130
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint), match.load()]);
985
1131
 
986
1132
  // Stale-deploy detection: if the server reports a different buildId, the client
987
1133
  // bundle is outdated and SPA navigation would mount wrong components / stale code.
@@ -991,18 +1137,62 @@ export function RouterProvider({
991
1137
  return null;
992
1138
  }
993
1139
 
994
- // Parse the HTML payload BEFORE deciding whether to bail on !res.ok.
995
- // Slice 8: a 404 response still carries a valid __FURIN_DATA__ with a
996
- // `__furinStatus: 404` signal, which lets us render the not-found UI
997
- // inline instead of doing a jarring full-page reload. Any other
998
- // non-2xx still bails out (see `classifySpaResponse`).
999
- const { data, finalHref, title } = await parsePageResponse(res, _basePath);
1000
-
1001
- const kind = classifySpaResponse(res.status, data);
1002
- if (kind.kind === "bail") {
1003
- log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
1140
+ // Non-2xx without an error sentinel? Bail to full reload. We always
1141
+ // try to parse the body first because non-2xx responses now carry the
1142
+ // `__furinError` NDJSON sentinel for non-redirect Response throws.
1143
+ // Truly opaque non-2xx responses (server crash, proxy interjection)
1144
+ // have no body we can deserialise → bail.
1145
+ const body = res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() });
1146
+ let parsed: {
1147
+ syncData: Record<string, unknown>;
1148
+ deferredPromises: Record<string, Promise<unknown>>;
1149
+ };
1150
+ try {
1151
+ parsed = await parseDeferredNdjson(body, signal);
1152
+ } catch (parseErr) {
1153
+ log.warn({
1154
+ action: "navigate_server_error",
1155
+ href: physicalHref,
1156
+ status: res.status,
1157
+ error: String(parseErr),
1158
+ });
1004
1159
  return null;
1005
1160
  }
1161
+ const { syncData, deferredPromises } = parsed;
1162
+
1163
+ // Special fields injected by the server into syncData:
1164
+ // __furinStatus — 404 signal
1165
+ // __furinNotFound — not-found payload
1166
+ // __furinRedirect — server-side redirect target (logical path)
1167
+ // __furinError — error sentinel (digest, message, status)
1168
+ // __furinTitle — document title resolved server-side from head()
1169
+ const {
1170
+ __furinStatus,
1171
+ __furinNotFound,
1172
+ __furinRedirect,
1173
+ __furinError,
1174
+ __furinTitle,
1175
+ ...cleanSyncData
1176
+ } = syncData as {
1177
+ __furinStatus?: number;
1178
+ __furinNotFound?: { data?: unknown; message?: string };
1179
+ __furinRedirect?: string;
1180
+ __furinError?: { digest: string; message: string; status: number };
1181
+ __furinTitle?: string;
1182
+ [key: string]: unknown;
1183
+ };
1184
+
1185
+ const finalHref: string | undefined =
1186
+ typeof __furinRedirect === "string" ? __furinRedirect : undefined;
1187
+
1188
+ // Merge sync data + deferred Promises. The component receives Promise
1189
+ // values for deferred fields — wrapped in <Await> for suspension.
1190
+ const data = { ...cleanSyncData, ...deferredPromises };
1191
+
1192
+ // Title comes exclusively from the server-resolved head() output
1193
+ // (__furinTitle). A loader returning a plain `title` field no longer
1194
+ // hijacks document.title — head() is the single source of truth.
1195
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
1006
1196
 
1007
1197
  const loadedMatch: LoadedClientRoute = {
1008
1198
  ...match,
@@ -1010,29 +1200,49 @@ export function RouterProvider({
1010
1200
  pageRoute: loadedMod.default._route,
1011
1201
  };
1012
1202
 
1013
- if (kind.kind === "not-found") {
1014
- // Strip the server-injected signals from `data` before handing it to
1015
- // the component — the NotFound payload is surfaced via `state.notFound`
1016
- // instead, and leaking __furinStatus into component props would be
1017
- // noise. The caller (RouterProvider render) ignores `data` when
1018
- // `notFound` is set anyway, but we keep it tidy for devtools.
1019
- const { __furinStatus, __furinNotFound, ...cleanData } = data ?? {};
1203
+ // Loader threw a non-redirect Response (or an Error). Render the
1204
+ // route's segment-level error.tsx inline by surfacing the sentinel
1205
+ // through state.error — RouterProvider's render path injects a
1206
+ // `RouteErrorThrower` at the page slot.
1207
+ if (__furinError) {
1208
+ return {
1209
+ match: loadedMatch,
1210
+ data: {},
1211
+ title,
1212
+ finalHref,
1213
+ error: __furinError,
1214
+ };
1215
+ }
1216
+
1217
+ // Non-2xx without sentinel and not 404 → opaque server error. Bail to
1218
+ // full-page reload so the browser shows whatever the server sent.
1219
+ if (!res.ok && res.status !== 404) {
1220
+ log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
1221
+ return null;
1222
+ }
1223
+
1224
+ if (__furinStatus === 404) {
1020
1225
  return {
1021
1226
  match: loadedMatch,
1022
- data: cleanData,
1227
+ data,
1023
1228
  title,
1024
1229
  finalHref,
1025
- notFound: kind.error,
1230
+ notFound: (__furinNotFound as { data?: unknown; message?: string }) ?? {},
1026
1231
  };
1027
1232
  }
1028
1233
 
1029
- return { match: loadedMatch, data: data ?? {}, title, finalHref };
1234
+ // Server-side redirect: do not mount the pre-redirect route.
1235
+ if (finalHref) {
1236
+ return { match: null, data, title, finalHref };
1237
+ }
1238
+
1239
+ return { match: loadedMatch, data, title, finalHref };
1030
1240
  } catch (err: unknown) {
1031
- log.error({ action: "navigate_failed", href: _basePath + logicalHref, error: String(err) });
1241
+ log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
1032
1242
  return null;
1033
1243
  }
1034
1244
  },
1035
- [routes, _basePath, rootBoundaries]
1245
+ [routes, basePath, resolveNoMatchState]
1036
1246
  );
1037
1247
 
1038
1248
  const invalidatePrefetch = useCallback((path: string, type: "page" | "layout" = "page") => {
@@ -1062,26 +1272,44 @@ export function RouterProvider({
1062
1272
 
1063
1273
  const prefetch = useCallback(
1064
1274
  (href: string, opts?: { staleTime?: number }) => {
1065
- const staleTime = opts?.staleTime ?? _defaultPreloadStaleTime;
1275
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
1066
1276
  const existing = prefetchCache.current.get(href);
1067
1277
  if (existing && !shouldRefetch(existing)) {
1068
1278
  return;
1069
1279
  }
1070
1280
  prefetchCache.current.set(href, {
1071
- promise: fetchPageState(href),
1281
+ promise: fetchPageState(href, undefined),
1072
1282
  createdAt: Date.now(),
1073
1283
  staleTime,
1074
1284
  });
1075
1285
  // Evict the oldest entry when the cap is exceeded
1076
- if (prefetchCache.current.size > _prefetchCacheSize) {
1286
+ if (prefetchCache.current.size > prefetchCacheSize) {
1077
1287
  const oldest = prefetchCache.current.keys().next().value as string;
1078
1288
  prefetchCache.current.delete(oldest);
1079
1289
  }
1080
1290
  },
1081
- [fetchPageState, _defaultPreloadStaleTime, _prefetchCacheSize]
1291
+ [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
1082
1292
  );
1083
1293
 
1294
+ /** Loads the RouterState for a redirect target, respecting the nav version. */
1295
+ async function resolveRedirectState(
1296
+ redirectLogical: string,
1297
+ myVersion: number,
1298
+ signal: AbortSignal | undefined
1299
+ ): Promise<RouterState | null> {
1300
+ const cached = prefetchCache.current.get(redirectLogical);
1301
+ const state =
1302
+ cached && !shouldRefetch(cached)
1303
+ ? await cached.promise
1304
+ : await fetchPageState(redirectLogical, signal);
1305
+ if (navVersion.current !== myVersion) {
1306
+ return null;
1307
+ }
1308
+ return state;
1309
+ }
1310
+
1084
1311
  const navigate = useCallback(
1312
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — redirect follow, history management, and scroll handling require this depth
1085
1313
  async (rawLogicalHref: string, opts?: { replace?: boolean; resetScroll?: boolean }) => {
1086
1314
  // Normalize trailing slashes so the prefetch cache key and route
1087
1315
  // matching stay consistent regardless of how the href was formed.
@@ -1090,9 +1318,15 @@ export function RouterProvider({
1090
1318
  // The prefetch cache is keyed by logical hrefs.
1091
1319
  prefetch(logicalHref);
1092
1320
  const myVersion = ++navVersion.current;
1321
+ // Cancel any in-flight navigation: its parseDeferredNdjson resolvers will
1322
+ // reject with AbortError and the underlying stream reader will be freed.
1323
+ navAbortRef.current?.abort();
1324
+ const navAbort = new AbortController();
1325
+ navAbortRef.current = navAbort;
1326
+ const navSignal = navAbort.signal;
1093
1327
  setIsNavigating(true);
1094
1328
  try {
1095
- const newState = await prefetchCache.current.get(logicalHref)?.promise;
1329
+ let newState = await prefetchCache.current.get(logicalHref)?.promise;
1096
1330
  // Discard if a newer navigation was started while we were waiting
1097
1331
  if (navVersion.current !== myVersion) {
1098
1332
  return;
@@ -1104,18 +1338,43 @@ export function RouterProvider({
1104
1338
  reason: "prefetch_returned_null",
1105
1339
  });
1106
1340
  // Fall back to full-page navigation using the physical URL.
1107
- window.location.href = _basePath + logicalHref;
1341
+ window.location.href = basePath + logicalHref;
1108
1342
  return;
1109
1343
  }
1344
+
1345
+ // Server-side redirect: replace current history entry and load target
1346
+ let redirectLogical: string | undefined;
1347
+ if (newState.finalHref && !newState.match && !newState.notFound) {
1348
+ redirectLogical = normalizeHref(newState.finalHref);
1349
+ const redirectPhysical = basePath + redirectLogical;
1350
+ window.history.replaceState(
1351
+ {
1352
+ ...((history.state as object) ?? {}),
1353
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
1354
+ },
1355
+ "",
1356
+ redirectPhysical
1357
+ );
1358
+ setCurrentHref(redirectLogical);
1359
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
1360
+ if (!redirectState) {
1361
+ if (navVersion.current === myVersion) {
1362
+ window.location.href = redirectPhysical;
1363
+ }
1364
+ return;
1365
+ }
1366
+ newState = redirectState;
1367
+ }
1368
+
1110
1369
  currentMatchRef.current = newState.match;
1111
1370
  setState(newState);
1112
1371
  if (newState.title) {
1113
1372
  document.title = newState.title;
1114
1373
  }
1115
1374
  // effectiveHref is logical (finalHref from fetchPageState is also logical).
1116
- const effectiveLogical = newState.finalHref ?? logicalHref;
1375
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
1117
1376
  // Push the PHYSICAL path to browser history.
1118
- const physicalEffective = _basePath + effectiveLogical;
1377
+ const physicalEffective = basePath + effectiveLogical;
1119
1378
  if (opts?.replace) {
1120
1379
  // Preserve the existing key — same history entry, URL just updated.
1121
1380
  window.history.replaceState(
@@ -1136,7 +1395,7 @@ export function RouterProvider({
1136
1395
  }
1137
1396
  // Store the LOGICAL path in currentHref so Link active-state works.
1138
1397
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
1139
- const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, _basePath));
1398
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
1140
1399
  setCurrentHref(logicalPath + effectiveUrl.search);
1141
1400
  if (opts?.resetScroll ?? true) {
1142
1401
  pendingScrollRef.current = { type: "reset", href: physicalEffective };
@@ -1148,19 +1407,19 @@ export function RouterProvider({
1148
1407
  }
1149
1408
  }
1150
1409
  },
1151
- [prefetch, _basePath]
1410
+ [prefetch, basePath]
1152
1411
  );
1153
1412
 
1154
1413
  const refresh = useCallback(
1155
1414
  async (opts?: { resetScroll?: boolean }) => {
1156
1415
  // Convert the physical browser URL to a logical href before navigating.
1157
- const logicalPath = toLogical(window.location.pathname, _basePath);
1416
+ const logicalPath = toLogical(window.location.pathname, basePath);
1158
1417
  const logicalHref = logicalPath + window.location.search;
1159
1418
  // Bust the cache for this exact logical page so navigate always re-fetches
1160
1419
  invalidatePrefetch(logicalHref, "page");
1161
1420
  await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
1162
1421
  },
1163
- [navigate, invalidatePrefetch, _basePath]
1422
+ [navigate, invalidatePrefetch, basePath]
1164
1423
  );
1165
1424
 
1166
1425
  // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
@@ -1186,11 +1445,18 @@ export function RouterProvider({
1186
1445
  // Convert physical browser URL to logical href for cache lookup + fetchPageState.
1187
1446
  // Normalize trailing slashes so "/docs/routing/" back-button navigations
1188
1447
  // still match the route pattern "/docs/routing".
1189
- const logicalPath = normalizeHref(toLogical(window.location.pathname, _basePath));
1448
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
1190
1449
  const logicalHref = logicalPath + window.location.search;
1191
1450
  const myVersion = ++navVersion.current;
1451
+ // Cancel in-flight nav (same rationale as in `navigate`): release pending
1452
+ // deferred promises and stream readers from the now-stale request.
1453
+ navAbortRef.current?.abort();
1454
+ const navAbort = new AbortController();
1455
+ navAbortRef.current = navAbort;
1456
+ const navSignal = navAbort.signal;
1192
1457
  setIsNavigating(true);
1193
1458
 
1459
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: popstate handler — cache check, redirect follow, and scroll restoration require this depth
1194
1460
  (async () => {
1195
1461
  try {
1196
1462
  // Check prefetch cache before fetching fresh (keyed by logical href)
@@ -1199,7 +1465,7 @@ export function RouterProvider({
1199
1465
  if (cached && !shouldRefetch(cached)) {
1200
1466
  newState = await cached.promise;
1201
1467
  } else {
1202
- newState = await fetchPageState(logicalHref);
1468
+ newState = await fetchPageState(logicalHref, navSignal);
1203
1469
  }
1204
1470
  // Discard if a newer navigation was started while we were waiting
1205
1471
  if (navVersion.current !== myVersion) {
@@ -1214,16 +1480,33 @@ export function RouterProvider({
1214
1480
  window.location.reload();
1215
1481
  return;
1216
1482
  }
1483
+
1484
+ // Server-side redirect: replace history entry and load target
1485
+ let redirectLogical: string | undefined;
1486
+ if (newState.finalHref && !newState.match && !newState.notFound) {
1487
+ redirectLogical = normalizeHref(newState.finalHref);
1488
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
1489
+ setCurrentHref(redirectLogical);
1490
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
1491
+ if (!redirectState) {
1492
+ if (navVersion.current === myVersion) {
1493
+ window.location.reload();
1494
+ }
1495
+ return;
1496
+ }
1497
+ newState = redirectState;
1498
+ }
1499
+
1217
1500
  currentMatchRef.current = newState.match;
1218
1501
  setState(newState);
1219
1502
  if (newState.title) {
1220
1503
  document.title = newState.title;
1221
1504
  }
1222
1505
  // effectiveHref is logical (includes search); push physical to history if server redirected.
1223
- const effectiveLogical = newState.finalHref ?? logicalHref;
1506
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
1224
1507
  if (newState.finalHref) {
1225
1508
  // Preserve _furinKey so scroll restoration still works after a redirect.
1226
- window.history.replaceState(history.state, "", _basePath + effectiveLogical);
1509
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
1227
1510
  }
1228
1511
  // effectiveLogical already contains the search params — no URL round-trip needed.
1229
1512
  setCurrentHref(normalizeHref(effectiveLogical));
@@ -1239,7 +1522,7 @@ export function RouterProvider({
1239
1522
  }
1240
1523
  }
1241
1524
  })();
1242
- }, [fetchPageState, _basePath]);
1525
+ }, [fetchPageState, basePath]);
1243
1526
 
1244
1527
  // Disable native scroll restoration and assign a key to the initial history entry.
1245
1528
  // No cleanup: in an SPA once manual it stays manual for the app lifetime.
@@ -1318,7 +1601,7 @@ export function RouterProvider({
1318
1601
  const logicalHref = shouldInterceptClick(
1319
1602
  anchor,
1320
1603
  e,
1321
- _basePath,
1604
+ basePath,
1322
1605
  window.location.origin,
1323
1606
  window.location.pathname
1324
1607
  );
@@ -1330,7 +1613,7 @@ export function RouterProvider({
1330
1613
  };
1331
1614
  document.addEventListener("click", handler);
1332
1615
  return () => document.removeEventListener("click", handler);
1333
- }, [navigate, _basePath]);
1616
+ }, [navigate, basePath]);
1334
1617
 
1335
1618
  // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
1336
1619
  // This ensures that API routes calling revalidatePath() automatically bust the
@@ -1348,9 +1631,9 @@ export function RouterProvider({
1348
1631
  invalidatePrefetch(path, type);
1349
1632
  invalidated.push({ path, type });
1350
1633
  });
1351
- if (_autoRefresh && invalidated.length > 0) {
1634
+ if (autoRefresh && invalidated.length > 0) {
1352
1635
  const currentLogicalPath =
1353
- normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
1636
+ normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
1354
1637
  if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
1355
1638
  // fire-and-forget: don't block the original fetch caller
1356
1639
  refresh();
@@ -1365,7 +1648,7 @@ export function RouterProvider({
1365
1648
  return () => {
1366
1649
  window.fetch = originalFetch;
1367
1650
  };
1368
- }, [invalidatePrefetch, refresh, _autoRefresh]);
1651
+ }, [invalidatePrefetch, refresh, autoRefresh]);
1369
1652
 
1370
1653
  // Slice 8 — when a prior SPA navigation hit a loader-thrown or catch-all 404,
1371
1654
  // render the bare not-found element (mirrors server's `buildNotFoundElement`).
@@ -1388,16 +1671,25 @@ export function RouterProvider({
1388
1671
  state.notFound ?? {}
1389
1672
  );
1390
1673
  } else {
1391
- pageElement = buildPageElement(state.match, root, state.data, {
1392
- // User's `reset()` prop → clear local boundary state (handled by the
1393
- // boundary itself) → re-run loaders for the current route so transient
1394
- // errors (bad state, expired data) can recover without a full reload.
1395
- onReset: refresh,
1396
- // Auto-clear latched errors when navigating between routes that share
1397
- // a boundary instance — otherwise the new route would render INSIDE
1398
- // the previous route's error fallback.
1399
- resetKey: currentHref,
1400
- });
1674
+ pageElement = buildPageElement(
1675
+ state.match,
1676
+ root,
1677
+ state.data,
1678
+ {
1679
+ // User's `reset()` prop → clear local boundary state (handled by the
1680
+ // boundary itself) → re-run loaders for the current route so transient
1681
+ // errors (bad state, expired data) can recover without a full reload.
1682
+ onReset: refresh,
1683
+ // Auto-clear latched errors when navigating between routes that share
1684
+ // a boundary instance — otherwise the new route would render INSIDE
1685
+ // the previous route's error fallback.
1686
+ resetKey: currentHref,
1687
+ },
1688
+ // Slice 3 — when the server's NDJSON sentinelled `__furinError`, render
1689
+ // the deepest `error.tsx` inline by throwing a `FurinServerError` at
1690
+ // the page slot. The boundaries set up by buildPageElement catch it.
1691
+ state.error
1692
+ );
1401
1693
  }
1402
1694
 
1403
1695
  // Slice 9 + 10 — wrap the entire tree in a root FurinErrorBoundary that
@@ -1407,16 +1699,16 @@ export function RouterProvider({
1407
1699
  // the same id the server already logged.
1408
1700
  return buildRouterTree(
1409
1701
  {
1410
- basePath: _basePath,
1702
+ basePath,
1411
1703
  currentHref,
1412
1704
  navigate,
1413
1705
  prefetch,
1414
1706
  refresh,
1415
1707
  invalidatePrefetch,
1416
1708
  isNavigating,
1417
- defaultPreload: _defaultPreload,
1418
- defaultPreloadDelay: _defaultPreloadDelay,
1419
- defaultPreloadStaleTime: _defaultPreloadStaleTime,
1709
+ defaultPreload,
1710
+ defaultPreloadDelay,
1711
+ defaultPreloadStaleTime,
1420
1712
  },
1421
1713
  pageElement,
1422
1714
  {