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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -0,0 +1,113 @@
1
+ export interface SyncChangePayload {
2
+ cursor: string;
3
+ invalidations: readonly string[];
4
+ }
5
+
6
+ export interface SyncChangePagePayload {
7
+ changes: readonly SyncChangePayload[];
8
+ cursor: string;
9
+ hasMore: boolean;
10
+ reset: boolean;
11
+ }
12
+
13
+ interface SyncCatchUpOptions {
14
+ fetchPage: (after: string | undefined) => Promise<SyncChangePagePayload>;
15
+ onInvalidations: (invalidations: readonly string[]) => void;
16
+ }
17
+
18
+ export interface SyncCatchUp {
19
+ catchUp(): Promise<void>;
20
+ cursor(): string | undefined;
21
+ initialize(): Promise<void>;
22
+ }
23
+
24
+ interface InvalidationRefreshOptions {
25
+ onError: (error: unknown) => void;
26
+ refresh: () => Promise<void>;
27
+ }
28
+
29
+ export interface InvalidationRefresh {
30
+ run(): Promise<void>;
31
+ }
32
+
33
+ export function createInvalidationRefresh(
34
+ options: InvalidationRefreshOptions
35
+ ): InvalidationRefresh {
36
+ let running: Promise<void> | undefined;
37
+ let requested = false;
38
+
39
+ const refreshUntilCurrent = async (): Promise<void> => {
40
+ do {
41
+ requested = false;
42
+ try {
43
+ await options.refresh();
44
+ } catch (error) {
45
+ if (!isAbortError(error)) {
46
+ throw error;
47
+ }
48
+ }
49
+ } while (requested);
50
+ };
51
+
52
+ return {
53
+ run() {
54
+ requested = true;
55
+ if (!running) {
56
+ running = refreshUntilCurrent()
57
+ .catch((error: unknown) => {
58
+ if (!isAbortError(error)) {
59
+ options.onError(error);
60
+ }
61
+ })
62
+ .finally(() => {
63
+ running = undefined;
64
+ });
65
+ }
66
+ return running;
67
+ },
68
+ };
69
+ }
70
+
71
+ export function createSyncCatchUp(options: SyncCatchUpOptions): SyncCatchUp {
72
+ let currentCursor: string | undefined;
73
+ let running: Promise<void> | undefined;
74
+ let requested = false;
75
+
76
+ const readUntilCurrent = async (): Promise<void> => {
77
+ do {
78
+ requested = false;
79
+ let page: SyncChangePagePayload;
80
+ do {
81
+ page = await options.fetchPage(currentCursor ?? "0");
82
+ if (page.reset) {
83
+ options.onInvalidations(["/:layout"]);
84
+ currentCursor = page.cursor;
85
+ break;
86
+ }
87
+ for (const change of page.changes) {
88
+ options.onInvalidations(change.invalidations);
89
+ }
90
+ currentCursor = page.cursor;
91
+ } while (page.hasMore);
92
+ } while (requested);
93
+ };
94
+
95
+ return {
96
+ async initialize() {
97
+ const page = await options.fetchPage(undefined);
98
+ currentCursor = page.cursor;
99
+ },
100
+ catchUp() {
101
+ requested = true;
102
+ if (!running) {
103
+ running = readUntilCurrent().finally(() => {
104
+ running = undefined;
105
+ });
106
+ }
107
+ return running;
108
+ },
109
+ cursor: () => currentCursor,
110
+ };
111
+ }
112
+
113
+ import { isAbortError } from "./abort.ts";
@@ -1,276 +1,276 @@
1
- import type React from "react";
2
- import type { RuntimeRoute } from "../../client.ts";
3
- import type { ErrorComponent } from "../../shared/error.ts";
4
- import type { NotFoundComponent } from "../../shared/not-found.ts";
5
- import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
-
7
- /**
8
- * Augment this interface via declaration merging in furin-env.d.ts
9
- * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
10
- *
11
- * @example
12
- * // furin-env.d.ts (auto-generated by Furin at project root)
13
- * import "@teyik0/furin/link";
14
- * declare module "@teyik0/furin/link" {
15
- * interface RouteManifest {
16
- * "/blog": { search?: { page?: number; tag?: string } };
17
- * "/": { search?: never };
18
- * [key: `/blog/${string}`]: { search?: never };
19
- * }
20
- * }
21
- */
22
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
23
- export interface RouteManifest {}
24
-
25
- /**
26
- * The valid `to` pathname union derived from the augmented RouteManifest.
27
- * Falls back to `string` when furin-env.d.ts has not been generated yet.
28
- * When augmented, also includes `https://` and `http://` for external links.
29
- */
30
- export type RouteTo = keyof RouteManifest extends never
31
- ? string
32
- : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
33
-
34
- /**
35
- * The typed search params for a given `to` pathname.
36
- * Falls back to a permissive record when RouteManifest is not augmented.
37
- */
38
- export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
39
- ? SearchParamsInput
40
- : To extends keyof RouteManifest
41
- ? RouteManifest[To] extends { searchInput?: infer I }
42
- ? I
43
- : RouteManifest[To] extends { search?: infer S }
44
- ? S
45
- : undefined
46
- : undefined;
47
-
48
- export type PreloadStrategy = false | "intent" | "viewport" | "render";
49
-
50
- export interface LinkProps<To extends RouteTo = RouteTo>
51
- extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
52
- /**
53
- * Extra props merged onto the anchor when the link is active.
54
- * `isActive` is also passed so one function can handle both states.
55
- * Styles and classNames from `activeProps` win over the static props.
56
- */
57
- activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
58
- /** Static children or a render function receiving active state. */
59
- children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
60
- /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
61
- disabled?: boolean;
62
- /** Optional URL fragment (without the #). */
63
- hash?: string;
64
- /**
65
- * Extra props merged onto the anchor when the link is NOT active.
66
- * Styles and classNames from `inactiveProps` win over the static props.
67
- */
68
- inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
69
- /** Preload strategy. Default: "intent" (preload on hover/focus). */
70
- preload?: PreloadStrategy;
71
- /** Delay in ms before intent preload triggers. Default: 50. */
72
- preloadDelay?: number;
73
- /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
74
- preloadStaleTime?: number;
75
- /** If true, uses history.replaceState instead of pushState (no new history entry). */
76
- replace?: boolean;
77
- /**
78
- * Whether to scroll after SPA navigation. Default: true.
79
- * - If the destination href has a `#hash`, scrolls to that element.
80
- * - Otherwise scrolls to the top of the page.
81
- * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
82
- */
83
- resetScroll?: boolean;
84
- /** Typed search params for this route. Auto-completed from the route's query schema. */
85
- search?: RouteSearch<To>;
86
- to: To;
87
- }
88
-
89
- export interface RouterContextValue {
90
- /**
91
- * Sub-path prefix for static deployments (e.g. "/furin").
92
- * Empty string when the site is served from root.
93
- * Used by `Link` to build correct physical hrefs for the `<a>` element.
94
- */
95
- basePath: string;
96
- /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
97
- currentHref: string;
98
- defaultPreload: PreloadStrategy;
99
- defaultPreloadDelay: number;
100
- defaultPreloadStaleTime: number;
101
- /**
102
- * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
103
- * made on the server. Called automatically by the `window.fetch` interceptor when
104
- * the server emits `X-Furin-Revalidate` headers.
105
- *
106
- * - `type: 'page'` (default) — exact URL match
107
- * - `type: 'layout'` — prefix match (path + all nested children)
108
- */
109
- invalidatePrefetch: (path: string, type: "page" | "layout") => void;
110
- isNavigating: boolean;
111
- navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
112
- prefetch: (href: string, opts?: { staleTime?: number }) => void;
113
- /**
114
- * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
115
- * loaders, and updates the rendered tree — without adding a history entry or
116
- * resetting scroll (unless `resetScroll: true` is passed).
117
- *
118
- * Prefer this over `navigate(window.location.pathname)` after a mutation.
119
- */
120
- refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
121
- /** Current server-resolved query params for the rendered route. */
122
- search: SearchParamsInput;
123
- /** Route-level search defaults used to build clean hrefs without default params. */
124
- searchRoutes: SearchRouteMetadata[];
125
- }
126
-
127
- /**
128
- * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
129
- * version this does NOT carry the directory path — it's purely a (depth,
130
- * fallback) pair because the client never reads files, only renders.
131
- */
132
- export interface ClientSegmentBoundary {
133
- depth: number;
134
- error?: ErrorComponent;
135
- notFound?: NotFoundComponent;
136
- }
137
-
138
- export interface ClientRoute {
139
- component?: React.ComponentType<Record<string, unknown>>;
140
- load: () => Promise<{
141
- default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
142
- segmentBoundaries?: ClientSegmentBoundary[];
143
- }>;
144
- pageRoute?: RuntimeRoute;
145
- pattern: string;
146
- regex: RegExp;
147
- searchDefaults?: SearchParamsInput;
148
- /**
149
- * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
150
- * to the route-chain index used on the server side, so `buildPageElement`
151
- * can interleave boundaries at the exact same positions that the server
152
- * used in `buildElement` — guaranteeing hydration consistency.
153
- */
154
- segmentBoundaries?: ClientSegmentBoundary[];
155
- }
156
-
157
- /**
158
- * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
159
- * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
160
- * on navigation via fetchPageState.
161
- */
162
- export type LoadedClientRoute = ClientRoute & {
163
- component: React.ComponentType<Record<string, unknown>>;
164
- pageRoute: RuntimeRoute;
165
- };
166
-
167
- export interface RouterProviderProps {
168
- /**
169
- * When `true` (default), the router automatically re-fetches the current page
170
- * whenever a server `revalidatePath()` call targets it. The signal is the
171
- * `X-Furin-Revalidate` header detected on any `window.fetch` response.
172
- *
173
- * Set to `false` to opt out and call `router.refresh()` manually instead.
174
- */
175
- autoRefresh: boolean;
176
- /**
177
- * Sub-path prefix for static deployments (e.g. "/furin").
178
- * Must start with "/" and have no trailing slash.
179
- * Default: "" (site served from root).
180
- */
181
- basePath: string;
182
- defaultPreload: PreloadStrategy;
183
- defaultPreloadDelay: number;
184
- defaultPreloadStaleTime: number;
185
- initialData: Record<string, unknown>;
186
- /**
187
- * Slice 10 — server-logged error digest threaded from
188
- * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
189
- * `FurinErrorBoundary` so that if a client-side error escapes the
190
- * per-segment boundaries (root layout crash, hydration mismatch, …), the
191
- * fallback UI surfaces the id a user would find in server logs.
192
- */
193
- initialDigest: string | undefined;
194
- /**
195
- * The route matched at hydration time. `null` is a valid value ONLY when
196
- * `initialNotFound` is also provided.
197
- */
198
- initialMatch: LoadedClientRoute | null;
199
- /**
200
- * When set, the provider boots into the inline not-found state as if a
201
- * prior SPA navigation hit a 404.
202
- */
203
- initialNotFound: { data?: unknown; message?: string } | undefined;
204
- /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
205
- prefetchCacheSize: number;
206
- root: RuntimeRoute | null;
207
- routes: ClientRoute[];
208
- /**
209
- * Optional internal SSE endpoint emitted by `furin({ sync: true })`.
210
- * When present, RouterProvider listens for cross-client invalidations.
211
- */
212
- syncStream?: string | undefined;
213
- }
214
-
215
- /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
216
- export interface RouterState {
217
- data: Record<string, unknown>;
218
- /**
219
- * Set when the server's NDJSON payload carried an `__furinError` sentinel.
220
- */
221
- error?: { digest: string; message: string; status: number };
222
- /** The canonical href after server-side redirects (e.g. query-default redirect). */
223
- finalHref?: string;
224
- /**
225
- * The currently rendered route.
226
- *
227
- * `null` is a valid value ONLY when `notFound` is also set.
228
- */
229
- match: LoadedClientRoute | null;
230
- /**
231
- * Slice 8 — set when the matched route's loader threw `notFound()` on the server.
232
- */
233
- notFound?: { data?: unknown; message?: string };
234
- /**
235
- * Explicit boundary chain to use for the not-found render.
236
- */
237
- notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
238
- title?: string;
239
- }
240
-
241
- /** @internal */
242
- export interface CacheEntry {
243
- createdAt: number;
244
- promise: Promise<RouterState | null>;
245
- staleTime: number;
246
- }
247
-
248
- /**
249
- * Classification of a fetch response during SPA navigation. Returned by the
250
- * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
251
- *
252
- * - `ok` — 2xx response with usable loader data; render normally.
253
- * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
254
- * - `error` — server signalled `__FURIN_DATA__.__furinError`.
255
- * - `bail` — any other non-2xx without sentinels.
256
- *
257
- * @internal Exported for unit testing only.
258
- */
259
- export type SpaResponseKind =
260
- | { kind: "ok" }
261
- | { kind: "not-found"; error: { data?: unknown; message?: string } }
262
- | { kind: "error"; error: { digest: string; message: string; status: number } }
263
- | { kind: "bail" };
264
-
265
- /**
266
- * Root-level safety-net options forwarded onto the outermost
267
- * `FurinErrorBoundary` that wraps the entire RouterProvider tree.
268
- */
269
- export interface RootBoundaryOptions {
270
- /**
271
- * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
272
- */
273
- digest?: string;
274
- onReset?: () => void;
275
- resetKey?: string | number;
276
- }
1
+ import type React from "react";
2
+ import type { RuntimeRoute } from "../../client.ts";
3
+ import type { ErrorComponent } from "../../shared/error.ts";
4
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
5
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
+
7
+ /**
8
+ * Augment this interface via declaration merging in furin-env.d.ts
9
+ * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
10
+ *
11
+ * @example
12
+ * // furin-env.d.ts (auto-generated by Furin at project root)
13
+ * import "@teyik0/furin/link";
14
+ * declare module "@teyik0/furin/link" {
15
+ * interface RouteManifest {
16
+ * "/blog": { search?: { page?: number; tag?: string } };
17
+ * "/": { search?: never };
18
+ * [key: `/blog/${string}`]: { search?: never };
19
+ * }
20
+ * }
21
+ */
22
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
23
+ export interface RouteManifest {}
24
+
25
+ /**
26
+ * The valid `to` pathname union derived from the augmented RouteManifest.
27
+ * Falls back to `string` when furin-env.d.ts has not been generated yet.
28
+ * When augmented, also includes `https://` and `http://` for external links.
29
+ */
30
+ export type RouteTo = keyof RouteManifest extends never
31
+ ? string
32
+ : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
33
+
34
+ /**
35
+ * The typed search params for a given `to` pathname.
36
+ * Falls back to a permissive record when RouteManifest is not augmented.
37
+ */
38
+ export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
39
+ ? SearchParamsInput
40
+ : To extends keyof RouteManifest
41
+ ? RouteManifest[To] extends { searchInput?: infer I }
42
+ ? I
43
+ : RouteManifest[To] extends { search?: infer S }
44
+ ? S
45
+ : undefined
46
+ : undefined;
47
+
48
+ export type PreloadStrategy = false | "intent" | "viewport" | "render";
49
+
50
+ export interface LinkProps<To extends RouteTo = RouteTo>
51
+ extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
52
+ /**
53
+ * Extra props merged onto the anchor when the link is active.
54
+ * `isActive` is also passed so one function can handle both states.
55
+ * Styles and classNames from `activeProps` win over the static props.
56
+ */
57
+ activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
58
+ /** Static children or a render function receiving active state. */
59
+ children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
60
+ /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
61
+ disabled?: boolean;
62
+ /** Optional URL fragment (without the #). */
63
+ hash?: string;
64
+ /**
65
+ * Extra props merged onto the anchor when the link is NOT active.
66
+ * Styles and classNames from `inactiveProps` win over the static props.
67
+ */
68
+ inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
69
+ /** Preload strategy. Default: "intent" (preload on hover/focus). */
70
+ preload?: PreloadStrategy;
71
+ /** Delay in ms before intent preload triggers. Default: 50. */
72
+ preloadDelay?: number;
73
+ /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
74
+ preloadStaleTime?: number;
75
+ /** If true, uses history.replaceState instead of pushState (no new history entry). */
76
+ replace?: boolean;
77
+ /**
78
+ * Whether to scroll after SPA navigation. Default: true.
79
+ * - If the destination href has a `#hash`, scrolls to that element.
80
+ * - Otherwise scrolls to the top of the page.
81
+ * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
82
+ */
83
+ resetScroll?: boolean;
84
+ /** Typed search params for this route. Auto-completed from the route's query schema. */
85
+ search?: RouteSearch<To>;
86
+ to: To;
87
+ }
88
+
89
+ export interface RouterContextValue {
90
+ /**
91
+ * Sub-path prefix for static deployments (e.g. "/furin").
92
+ * Empty string when the site is served from root.
93
+ * Used by `Link` to build correct physical hrefs for the `<a>` element.
94
+ */
95
+ basePath: string;
96
+ /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
97
+ currentHref: string;
98
+ defaultPreload: PreloadStrategy;
99
+ defaultPreloadDelay: number;
100
+ defaultPreloadStaleTime: number;
101
+ /**
102
+ * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
103
+ * made on the server. Called automatically by the `window.fetch` interceptor when
104
+ * the server emits `X-Furin-Revalidate` headers.
105
+ *
106
+ * - `type: 'page'` (default) — exact URL match
107
+ * - `type: 'layout'` — prefix match (path + all nested children)
108
+ */
109
+ invalidatePrefetch: (path: string, type: "page" | "layout") => void;
110
+ isNavigating: boolean;
111
+ navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
112
+ prefetch: (href: string, opts?: { staleTime?: number }) => void;
113
+ /**
114
+ * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
115
+ * loaders, and updates the rendered tree — without adding a history entry or
116
+ * resetting scroll (unless `resetScroll: true` is passed).
117
+ *
118
+ * Prefer this over `navigate(window.location.pathname)` after a mutation.
119
+ */
120
+ refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
121
+ /** Current server-resolved query params for the rendered route. */
122
+ search: SearchParamsInput;
123
+ /** Route-level search defaults used to build clean hrefs without default params. */
124
+ searchRoutes: SearchRouteMetadata[];
125
+ }
126
+
127
+ /**
128
+ * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
129
+ * version this does NOT carry the directory path — it's purely a (depth,
130
+ * fallback) pair because the client never reads files, only renders.
131
+ */
132
+ export interface ClientSegmentBoundary {
133
+ depth: number;
134
+ error?: ErrorComponent;
135
+ notFound?: NotFoundComponent;
136
+ }
137
+
138
+ export interface ClientRoute {
139
+ component?: React.ComponentType<Record<string, unknown>>;
140
+ load: () => Promise<{
141
+ default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
142
+ segmentBoundaries?: ClientSegmentBoundary[];
143
+ }>;
144
+ pageRoute?: RuntimeRoute;
145
+ pattern: string;
146
+ regex: RegExp;
147
+ searchDefaults?: SearchParamsInput;
148
+ /**
149
+ * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
150
+ * to the route-chain index used on the server side, so `buildPageElement`
151
+ * can interleave boundaries at the exact same positions that the server
152
+ * used in `buildElement` — guaranteeing hydration consistency.
153
+ */
154
+ segmentBoundaries?: ClientSegmentBoundary[];
155
+ }
156
+
157
+ /**
158
+ * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
159
+ * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
160
+ * on navigation via fetchPageState.
161
+ */
162
+ export type LoadedClientRoute = ClientRoute & {
163
+ component: React.ComponentType<Record<string, unknown>>;
164
+ pageRoute: RuntimeRoute;
165
+ };
166
+
167
+ export interface RouterProviderProps {
168
+ /**
169
+ * When `true` (default), the router automatically re-fetches the current page
170
+ * whenever a server `revalidatePath()` call targets it. The signal is the
171
+ * `X-Furin-Revalidate` header detected on any `window.fetch` response.
172
+ *
173
+ * Set to `false` to opt out and call `router.refresh()` manually instead.
174
+ */
175
+ autoRefresh: boolean;
176
+ /**
177
+ * Sub-path prefix for static deployments (e.g. "/furin").
178
+ * Must start with "/" and have no trailing slash.
179
+ * Default: "" (site served from root).
180
+ */
181
+ basePath: string;
182
+ defaultPreload: PreloadStrategy;
183
+ defaultPreloadDelay: number;
184
+ defaultPreloadStaleTime: number;
185
+ initialData: Record<string, unknown>;
186
+ /**
187
+ * Slice 10 — server-logged error digest threaded from
188
+ * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
189
+ * `FurinErrorBoundary` so that if a client-side error escapes the
190
+ * per-segment boundaries (root layout crash, hydration mismatch, …), the
191
+ * fallback UI surfaces the id a user would find in server logs.
192
+ */
193
+ initialDigest: string | undefined;
194
+ /**
195
+ * The route matched at hydration time. `null` is a valid value ONLY when
196
+ * `initialNotFound` is also provided.
197
+ */
198
+ initialMatch: LoadedClientRoute | null;
199
+ /**
200
+ * When set, the provider boots into the inline not-found state as if a
201
+ * prior SPA navigation hit a 404.
202
+ */
203
+ initialNotFound: { data?: unknown; message?: string } | undefined;
204
+ /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
205
+ prefetchCacheSize: number;
206
+ root: RuntimeRoute | null;
207
+ routes: ClientRoute[];
208
+ /**
209
+ * Optional internal SSE endpoint emitted by `furin({ sync: true })`.
210
+ * When present, RouterProvider listens for cross-client invalidations.
211
+ */
212
+ syncStream?: string | undefined;
213
+ }
214
+
215
+ /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
216
+ export interface RouterState {
217
+ data: Record<string, unknown>;
218
+ /**
219
+ * Set when the server's NDJSON payload carried an `__furinError` sentinel.
220
+ */
221
+ error?: { digest: string; message: string; status: number };
222
+ /** The canonical href after server-side redirects (e.g. query-default redirect). */
223
+ finalHref?: string;
224
+ /**
225
+ * The currently rendered route.
226
+ *
227
+ * `null` is a valid value ONLY when `notFound` is also set.
228
+ */
229
+ match: LoadedClientRoute | null;
230
+ /**
231
+ * Slice 8 — set when the matched route's loader threw `notFound()` on the server.
232
+ */
233
+ notFound?: { data?: unknown; message?: string };
234
+ /**
235
+ * Explicit boundary chain to use for the not-found render.
236
+ */
237
+ notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
238
+ title?: string;
239
+ }
240
+
241
+ /** @internal */
242
+ export interface CacheEntry {
243
+ createdAt: number;
244
+ promise: Promise<RouterState | null>;
245
+ staleTime: number;
246
+ }
247
+
248
+ /**
249
+ * Classification of a fetch response during SPA navigation. Returned by the
250
+ * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
251
+ *
252
+ * - `ok` — 2xx response with usable loader data; render normally.
253
+ * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
254
+ * - `error` — server signalled `__FURIN_DATA__.__furinError`.
255
+ * - `bail` — any other non-2xx without sentinels.
256
+ *
257
+ * @internal Exported for unit testing only.
258
+ */
259
+ export type SpaResponseKind =
260
+ | { kind: "ok" }
261
+ | { kind: "not-found"; error: { data?: unknown; message?: string } }
262
+ | { kind: "error"; error: { digest: string; message: string; status: number } }
263
+ | { kind: "bail" };
264
+
265
+ /**
266
+ * Root-level safety-net options forwarded onto the outermost
267
+ * `FurinErrorBoundary` that wraps the entire RouterProvider tree.
268
+ */
269
+ export interface RootBoundaryOptions {
270
+ /**
271
+ * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
272
+ */
273
+ digest?: string;
274
+ onReset?: () => void;
275
+ resetKey?: string | number;
276
+ }