@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.
@@ -0,0 +1,26 @@
1
+ export type RevalidateType = "page" | "layout";
2
+ export interface CacheInvalidationResult {
3
+ deleted: boolean;
4
+ purgedPaths: string[];
5
+ }
6
+ export interface Cache<Entry> {
7
+ clear(): void;
8
+ delete(key: string): boolean;
9
+ entries(): IterableIterator<[string, Entry]>;
10
+ get(key: string): Entry | undefined;
11
+ has(key: string): boolean;
12
+ invalidatePath(path: string, type: RevalidateType): CacheInvalidationResult;
13
+ keys(): IterableIterator<string>;
14
+ readonly name: string;
15
+ set(key: string, entry: Entry): void;
16
+ get size(): number;
17
+ readonly store: Map<string, Entry>;
18
+ }
19
+ export interface RouteCacheOptions<Entry> {
20
+ maxSize?: number;
21
+ name: string;
22
+ onDelete?: (key: string, entry: Entry) => void;
23
+ onSet?: (key: string, entry: Entry, previous: Entry | undefined) => void;
24
+ pathFromKey?: (key: string) => string | null;
25
+ }
26
+ export declare function createRouteCache<Entry>(options: RouteCacheOptions<Entry>): Cache<Entry>;
@@ -0,0 +1,187 @@
1
+ import type { HeadOptions, MetaDescriptor } from "../client.ts";
2
+
3
+ export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
+ if (!meta) {
5
+ return;
6
+ }
7
+ for (const entry of meta) {
8
+ if ("title" in entry) {
9
+ return (entry as { title: string }).title;
10
+ }
11
+ }
12
+ return;
13
+ }
14
+
15
+ export function isMetaTag(entry: MetaDescriptor): boolean {
16
+ return !(
17
+ "title" in entry ||
18
+ "charSet" in entry ||
19
+ "script:ld+json" in entry ||
20
+ "tagName" in entry
21
+ );
22
+ }
23
+
24
+ export function escapeHtml(str: string): string {
25
+ return str
26
+ .replace(/&/g, "&amp;")
27
+ .replace(/</g, "&lt;")
28
+ .replace(/>/g, "&gt;")
29
+ .replace(/"/g, "&quot;")
30
+ .replace(/'/g, "&#039;");
31
+ }
32
+
33
+ export function safeJson(value: unknown): string {
34
+ return JSON.stringify(value)
35
+ .replace(/</g, "\\u003c")
36
+ .replace(/>/g, "\\u003e")
37
+ .replace(/\u2028/g, "\\u2028")
38
+ .replace(/\u2029/g, "\\u2029");
39
+ }
40
+
41
+ export function renderAttrs(obj: Record<string, string | undefined>): string {
42
+ return Object.entries(obj)
43
+ .filter(([, v]) => v !== undefined)
44
+ .map(([k, v]) => `${k}="${escapeHtml(String(v))}"`)
45
+ .join(" ");
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Head injection helpers
50
+ // ---------------------------------------------------------------------------
51
+
52
+ export function buildMetaParts(meta: MetaDescriptor[]): string[] {
53
+ const parts: string[] = [];
54
+ const title = extractTitle(meta);
55
+ if (title) {
56
+ parts.push(`<title>${escapeHtml(title)}</title>`);
57
+ }
58
+ for (const m of meta) {
59
+ if (isMetaTag(m)) {
60
+ parts.push(`<meta ${renderAttrs(m as Record<string, string>)} />`);
61
+ }
62
+ if ("script:ld+json" in m) {
63
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
64
+ }
65
+ }
66
+ return parts;
67
+ }
68
+
69
+ export function buildLinkParts(links: NonNullable<HeadOptions["links"]>): string[] {
70
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
71
+ }
72
+
73
+ export function buildScriptParts(scripts: NonNullable<HeadOptions["scripts"]>): string[] {
74
+ return scripts.map((script) => {
75
+ const { children, ...rest } = script;
76
+ const attrs = renderAttrs(rest as Record<string, string | undefined>);
77
+ if (children) {
78
+ return `<script ${attrs}>${children}</script>`;
79
+ }
80
+ return `<script ${attrs}></script>`;
81
+ });
82
+ }
83
+
84
+ export function buildStyleParts(styles: NonNullable<HeadOptions["styles"]>): string[] {
85
+ return styles.map((style) => {
86
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
87
+ return `<style${typeAttr}>${style.children}</style>`;
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Builds the string to inject into the <!--ssr-head--> placeholder.
93
+ * Handles title, meta tags, links, inline scripts, and inline styles from
94
+ * the page's `head()` function. CSS is handled by Bun (imported in user files).
95
+ */
96
+ export function buildHeadInjection(headData: HeadOptions | undefined): string {
97
+ const parts: string[] = [];
98
+
99
+ if (headData?.meta) {
100
+ parts.push(...buildMetaParts(headData.meta));
101
+ }
102
+
103
+ if (headData?.links) {
104
+ parts.push(...buildLinkParts(headData.links));
105
+ }
106
+
107
+ if (headData?.scripts) {
108
+ parts.push(...buildScriptParts(headData.scripts));
109
+ }
110
+
111
+ if (headData?.styles) {
112
+ parts.push(...buildStyleParts(headData.styles));
113
+ }
114
+
115
+ return parts.length > 0 ? `\n ${parts.join("\n ")}\n` : "";
116
+ }
117
+
118
+ /**
119
+ * Inline script that synchronously applies the persisted theme class to <html>
120
+ * before the first paint, preventing a flash of unstyled content (FOUC).
121
+ * Reads the `furin-theme` key from localStorage; defaults to "dark" on error.
122
+ */
123
+ const THEME_INIT_SCRIPT =
124
+ `<script>try{var __t=localStorage.getItem("furin-theme");` +
125
+ `document.documentElement.classList.add(__t==="light"?"light":"dark")}` +
126
+ `catch(e){document.documentElement.classList.add("dark")}</script>`;
127
+
128
+ export function generateIndexHtml(): string {
129
+ return `<!DOCTYPE html>
130
+ <html lang="en">
131
+ <head>
132
+ <meta charset="UTF-8">
133
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
134
+ ${THEME_INIT_SCRIPT}
135
+ <!--ssr-head-->
136
+ </head>
137
+ <body>
138
+ <div id="root"><!--ssr-outlet--></div>
139
+ <script type="module" src="./_hydrate.tsx"></script>
140
+ </body>
141
+ </html>
142
+ `;
143
+ }
144
+
145
+ /**
146
+ * Generates the production SSR template (index.html) with hashed asset paths.
147
+ * Called after Bun.build() completes so we can inject the correct entry chunk
148
+ * and CSS paths derived from result.outputs.
149
+ *
150
+ * @param buildId - Short hash identifying this specific build. Injected as a
151
+ * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
152
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
153
+ * When provided, a `<link rel="icon">` tag is injected so browsers can locate
154
+ * the favicon even when the site is served from a sub-path.
155
+ */
156
+ export function generateProdIndexHtml(
157
+ entryChunk: string,
158
+ cssChunks: string[],
159
+ buildId?: string,
160
+ faviconHref?: string
161
+ ): string {
162
+ const cssLinks = cssChunks
163
+ .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
164
+ .join("\n");
165
+ const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
166
+ const buildIdMeta = buildId
167
+ ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">\n`
168
+ : "";
169
+ const faviconLink = faviconHref
170
+ ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
171
+ : "";
172
+
173
+ return `<!DOCTYPE html>
174
+ <html lang="en">
175
+ <head>
176
+ <meta charset="UTF-8">
177
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
178
+ ${THEME_INIT_SCRIPT}
179
+ ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
180
+ </head>
181
+ <body>
182
+ <div id="root"><!--ssr-outlet--></div>
183
+ ${scriptTag}
184
+ </body>
185
+ </html>
186
+ `;
187
+ }
@@ -0,0 +1,467 @@
1
+ import type React from "react";
2
+ import type { RuntimeRoute } from "./client";
3
+ import type { ErrorComponent } from "./error";
4
+ import type { NotFoundComponent } from "./not-found";
5
+ /**
6
+ * Augment this interface via declaration merging in furin-env.d.ts
7
+ * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
8
+ *
9
+ * @example
10
+ * // furin-env.d.ts (auto-generated by Furin at project root)
11
+ * import "@teyik0/furin/link";
12
+ * declare module "@teyik0/furin/link" {
13
+ * interface RouteManifest {
14
+ * "/blog": { search?: { page?: number; tag?: string } };
15
+ * "/": { search?: never };
16
+ * [key: `/blog/${string}`]: { search?: never };
17
+ * }
18
+ * }
19
+ */
20
+ export interface RouteManifest {
21
+ }
22
+ /**
23
+ * The valid `to` pathname union derived from the augmented RouteManifest.
24
+ * Falls back to `string` when furin-env.d.ts has not been generated yet.
25
+ * When augmented, also includes `https://` and `http://` for external links.
26
+ */
27
+ export type RouteTo = keyof RouteManifest extends never ? string : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
28
+ /**
29
+ * The typed search params for a given `to` pathname.
30
+ * Falls back to a permissive record when RouteManifest is not augmented.
31
+ */
32
+ export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never ? Record<string, string | number | boolean | null | undefined> : To extends keyof RouteManifest ? RouteManifest[To] extends {
33
+ search?: infer S;
34
+ } ? S : undefined : undefined;
35
+ export type PreloadStrategy = false | "intent" | "viewport" | "render";
36
+ export interface LinkProps<To extends RouteTo = RouteTo> extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
37
+ /**
38
+ * Extra props merged onto the anchor when the link is active.
39
+ * `isActive` is also passed so one function can handle both states.
40
+ * Styles and classNames from `activeProps` win over the static props.
41
+ */
42
+ activeProps?: (opts: {
43
+ isActive: boolean;
44
+ }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
45
+ /** Static children or a render function receiving active state. */
46
+ children?: React.ReactNode | ((state: {
47
+ isActive: boolean;
48
+ }) => React.ReactNode);
49
+ /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
50
+ disabled?: boolean;
51
+ /** Optional URL fragment (without the #). */
52
+ hash?: string;
53
+ /**
54
+ * Extra props merged onto the anchor when the link is NOT active.
55
+ * Styles and classNames from `inactiveProps` win over the static props.
56
+ */
57
+ inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
58
+ /** Preload strategy. Default: "intent" (preload on hover/focus). */
59
+ preload?: PreloadStrategy;
60
+ /** Delay in ms before intent preload triggers. Default: 50. */
61
+ preloadDelay?: number;
62
+ /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
63
+ preloadStaleTime?: number;
64
+ /** If true, uses history.replaceState instead of pushState (no new history entry). */
65
+ replace?: boolean;
66
+ /**
67
+ * Whether to scroll after SPA navigation. Default: true.
68
+ * - If the destination href has a `#hash`, scrolls to that element.
69
+ * - Otherwise scrolls to the top of the page.
70
+ * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
71
+ */
72
+ resetScroll?: boolean;
73
+ /** Typed search params for this route. Auto-completed from the route's query schema. */
74
+ search?: RouteSearch<To>;
75
+ to: To;
76
+ }
77
+ /**
78
+ * Builds a full href string from a pathname, optional search params, and optional hash.
79
+ * Null/undefined search values are omitted.
80
+ *
81
+ * @internal Exported for unit testing only.
82
+ */
83
+ export declare function buildHref(to: string, search?: Record<string, unknown> | null, hash?: string): string;
84
+ /**
85
+ * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
86
+ * each path entry. Header format: `"/path1,/path2:layout,/path3"`
87
+ *
88
+ * Intended to be called from a `window.fetch` interceptor or SPA navigation
89
+ * handler so that client-side prefetch caches are busted automatically whenever
90
+ * a server-side `revalidatePath()` call is made within the same request.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * const res = await fetch("/api/publish");
95
+ * applyRevalidateHeader(res.headers, (path, type) => {
96
+ * console.log("invalidate", path, type);
97
+ * });
98
+ * ```
99
+ */
100
+ export declare function applyRevalidateHeader(headers: Headers, invalidate: (path: string, type?: "page" | "layout") => void): void;
101
+ /**
102
+ * Returns `true` when `currentPath` is targeted by at least one invalidation entry,
103
+ * using the same matching rules as `invalidatePrefetch`:
104
+ * - `type: 'page'` — exact pathname match (query string stripped)
105
+ * - `type: 'layout'` — prefix match: the path itself OR any descendant
106
+ *
107
+ * @internal Exported for unit testing only.
108
+ */
109
+ export declare function shouldAutoRefreshPath(currentPath: string, invalidations: ReadonlyArray<{
110
+ path: string;
111
+ type: "page" | "layout";
112
+ }>): boolean;
113
+ export interface RouterContextValue {
114
+ /**
115
+ * Sub-path prefix for static deployments (e.g. "/furin").
116
+ * Empty string when the site is served from root.
117
+ * Used by `Link` to build correct physical hrefs for the `<a>` element.
118
+ */
119
+ basePath: string;
120
+ /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
121
+ currentHref: string;
122
+ defaultPreload: PreloadStrategy;
123
+ defaultPreloadDelay: number;
124
+ defaultPreloadStaleTime: number;
125
+ /**
126
+ * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
127
+ * made on the server. Called automatically by the `window.fetch` interceptor when
128
+ * the server emits `X-Furin-Revalidate` headers.
129
+ *
130
+ * - `type: 'page'` (default) — exact URL match
131
+ * - `type: 'layout'` — prefix match (path + all nested children)
132
+ */
133
+ invalidatePrefetch: (path: string, type?: "page" | "layout") => void;
134
+ isNavigating: boolean;
135
+ navigate: (href: string, opts?: {
136
+ replace?: boolean;
137
+ resetScroll?: boolean;
138
+ }) => Promise<void>;
139
+ prefetch: (href: string, opts?: {
140
+ staleTime?: number;
141
+ }) => void;
142
+ /**
143
+ * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
144
+ * loaders, and updates the rendered tree — without adding a history entry or
145
+ * resetting scroll (unless `resetScroll: true` is passed).
146
+ *
147
+ * Prefer this over `navigate(window.location.pathname)` after a mutation.
148
+ *
149
+ * @example
150
+ * ```tsx
151
+ * const { refresh } = useRouter();
152
+ * await apiClient.api.boards.post({ name });
153
+ * await refresh();
154
+ * ```
155
+ */
156
+ refresh: (opts?: {
157
+ resetScroll?: boolean;
158
+ }) => Promise<void>;
159
+ }
160
+ export declare const RouterContext: React.Context<RouterContextValue | null>;
161
+ /**
162
+ * Returns the current router context.
163
+ * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
164
+ */
165
+ export declare function useRouter(): RouterContextValue;
166
+ /**
167
+ * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
168
+ * version this does NOT carry the directory path — it's purely a (depth,
169
+ * fallback) pair because the client never reads files, only renders.
170
+ *
171
+ * Emitted by `generateHydrateEntry` from the scanned `segmentBoundaries`
172
+ * array: each route's entry lists ONLY the directories on its path that
173
+ * declare a convention file, so routes with no error.tsx / not-found.tsx
174
+ * anywhere carry an empty list (or omit the field entirely).
175
+ */
176
+ export interface ClientSegmentBoundary {
177
+ depth: number;
178
+ error?: ErrorComponent;
179
+ notFound?: NotFoundComponent;
180
+ }
181
+ export interface ClientRoute {
182
+ component?: React.ComponentType<Record<string, unknown>>;
183
+ load: () => Promise<{
184
+ default: {
185
+ component: React.ComponentType<Record<string, unknown>>;
186
+ _route: RuntimeRoute;
187
+ };
188
+ }>;
189
+ pageRoute?: RuntimeRoute;
190
+ pattern: string;
191
+ regex: RegExp;
192
+ /**
193
+ * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
194
+ * to the route-chain index used on the server side, so `buildPageElement`
195
+ * can interleave boundaries at the exact same positions that the server
196
+ * used in `buildElement` — guaranteeing hydration consistency.
197
+ */
198
+ segmentBoundaries?: ClientSegmentBoundary[];
199
+ }
200
+ /**
201
+ * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
202
+ * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
203
+ * on navigation via fetchPageState.
204
+ */
205
+ export type LoadedClientRoute = ClientRoute & {
206
+ component: React.ComponentType<Record<string, unknown>>;
207
+ pageRoute: RuntimeRoute;
208
+ };
209
+ export interface RouterProviderProps {
210
+ /**
211
+ * When `true` (default), the router automatically re-fetches the current page
212
+ * whenever a server `revalidatePath()` call targets it. The signal is the
213
+ * `X-Furin-Revalidate` header detected on any `window.fetch` response.
214
+ *
215
+ * Set to `false` to opt out and call `router.refresh()` manually instead.
216
+ */
217
+ autoRefresh: boolean;
218
+ /**
219
+ * Sub-path prefix for static deployments (e.g. "/furin").
220
+ * Must start with "/" and have no trailing slash.
221
+ * Default: "" (site served from root).
222
+ *
223
+ * When set:
224
+ * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
225
+ * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
226
+ * - `fetch` calls use the physical path `basePath + logicalHref`.
227
+ */
228
+ basePath: string;
229
+ defaultPreload: PreloadStrategy;
230
+ defaultPreloadDelay: number;
231
+ defaultPreloadStaleTime: number;
232
+ initialData: Record<string, unknown>;
233
+ /**
234
+ * Slice 10 — server-logged error digest threaded from
235
+ * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
236
+ * `FurinErrorBoundary` so that if a client-side error escapes the
237
+ * per-segment boundaries (root layout crash, hydration mismatch, …), the
238
+ * fallback UI surfaces the id a user would find in server logs.
239
+ * Undefined when the initial SSR response was successful (no server-side
240
+ * error digest to correlate).
241
+ */
242
+ initialDigest: string | undefined;
243
+ /**
244
+ * The route matched at hydration time. `null` is a valid value ONLY when
245
+ * `initialNotFound` is also provided — it signals the initial URL didn't
246
+ * match any registered route (direct load to an unknown URL). The provider
247
+ * then mounts in a "not-found" state so the root `not-found.tsx` hydrates
248
+ * inside a live RouterContext — critical for Links in the not-found UI to
249
+ * participate in SPA navigation instead of triggering a full-page reload.
250
+ */
251
+ initialMatch: LoadedClientRoute | null;
252
+ /**
253
+ * When set, the provider boots into the inline not-found state as if a
254
+ * prior SPA navigation hit a 404. Callers set this when the server-rendered
255
+ * HTML carries `__FURIN_DATA__.__furinStatus === 404` — either because the
256
+ * loader threw `notFound()` (rare at hydration time) or, more commonly,
257
+ * because the URL didn't match any client route and `initialMatch` is
258
+ * `null`. In the unmatched-URL case the depth-0 `rootBoundaries` are used
259
+ * as the boundary chain, matching the server's `renderRootNotFound` choice.
260
+ */
261
+ initialNotFound: {
262
+ data?: unknown;
263
+ message?: string;
264
+ } | undefined;
265
+ /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
266
+ prefetchCacheSize: number;
267
+ root: RuntimeRoute | null;
268
+ routes: ClientRoute[];
269
+ }
270
+ interface RouterState {
271
+ data: Record<string, unknown>;
272
+ /** The canonical href after server-side redirects (e.g. query-default redirect). */
273
+ finalHref?: string;
274
+ /**
275
+ * The currently rendered route.
276
+ *
277
+ * `null` is a valid value ONLY when `notFound` is also set — it signals the
278
+ * initial URL didn't match any registered route (direct load to an unknown
279
+ * URL). In that case the provider renders the root `not-found.tsx` directly
280
+ * and waits for the next `navigate()` call to populate `match`. Every other
281
+ * state (including loader-triggered `notFound()` on a matched route) keeps a
282
+ * non-null `match`. Render code MUST guard on `notFound` before dereferencing.
283
+ */
284
+ match: LoadedClientRoute | null;
285
+ /**
286
+ * Slice 8 — set when the matched route's loader threw `notFound()` on the
287
+ * server (signalled via `__FURIN_DATA__.__furinStatus === 404`). Triggers
288
+ * inline rendering of the deepest segment-level not-found.tsx instead of
289
+ * the normal layout+page tree, mirroring the server's `buildNotFoundElement`.
290
+ */
291
+ notFound?: {
292
+ data?: unknown;
293
+ message?: string;
294
+ };
295
+ /**
296
+ * Explicit boundary chain to use for the not-found render.
297
+ *
298
+ * - **Set** (typically to depth-0 only) when no client-side route matched the
299
+ * navigation URL — the root `not-found.tsx` is the correct fallback and no
300
+ * page-specific segment context exists.
301
+ * - **Absent** when a matched route's loader called `notFound()`, in which
302
+ * case `match.segmentBoundaries` is used (preserves per-route not-found).
303
+ */
304
+ notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
305
+ title?: string;
306
+ }
307
+ /** @internal */
308
+ export interface CacheEntry {
309
+ createdAt: number;
310
+ promise: Promise<RouterState | null>;
311
+ staleTime: number;
312
+ }
313
+ /** @internal Exported for unit testing only. */
314
+ export declare function shouldRefetch(entry: CacheEntry): boolean;
315
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
316
+ * Query strings and hashes are preserved and re-attached after normalization. */
317
+ export declare function normalizeHref(href: string): string;
318
+ /**
319
+ * Classification of a fetch response during SPA navigation. Returned by the
320
+ * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
321
+ *
322
+ * - `ok` — 2xx response with usable loader data; render normally.
323
+ * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`; the
324
+ * caller should render the not-found UI inline (no full-page reload).
325
+ * - `bail` — any other non-2xx (5xx, stale-deploy, unparseable payload…);
326
+ * the caller falls back to a full-page navigation so the browser picks up
327
+ * whatever the server wants to send (could be an error page, redirect, etc.).
328
+ *
329
+ * @internal Exported for unit testing only.
330
+ */
331
+ export type SpaResponseKind = {
332
+ kind: "ok";
333
+ } | {
334
+ kind: "not-found";
335
+ error: {
336
+ data?: unknown;
337
+ message?: string;
338
+ };
339
+ } | {
340
+ kind: "bail";
341
+ };
342
+ /**
343
+ * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
344
+ * already-parsed `__FURIN_DATA__` payload. The 404 signal is trusted over the
345
+ * HTTP status (guards against proxies that rewrite status but preserve body),
346
+ * while any other non-ok HTTP status triggers a bail even if the payload is
347
+ * well-formed.
348
+ *
349
+ * @internal Exported for unit testing only.
350
+ */
351
+ export declare function classifySpaResponse(status: number, data: Record<string, unknown> | null): SpaResponseKind;
352
+ /**
353
+ * Decides whether a native `<a>` click should be intercepted and converted
354
+ * to an SPA navigation. Returns the logical href to navigate to, or `null`
355
+ * when the browser should handle the click normally.
356
+ *
357
+ * Pure function: all external dependencies (current origin, pathname) are
358
+ * passed as parameters so tests need neither DOM globals nor mocks.
359
+ *
360
+ * @internal Exported for unit testing only.
361
+ */
362
+ export declare function shouldInterceptClick(anchor: {
363
+ href: string;
364
+ target: string;
365
+ hasAttribute(name: string): boolean;
366
+ }, event: {
367
+ metaKey: boolean;
368
+ ctrlKey: boolean;
369
+ shiftKey: boolean;
370
+ altKey: boolean;
371
+ }, basePath: string, currentOrigin: string, currentPathname: string): string | null;
372
+ /**
373
+ * Picks the deepest not-found component declared on the match's boundary
374
+ * chain. Mirrors the server's `route.notFound ?? root.notFound` selection:
375
+ * since `segmentBoundaries` is ordered shallow→deep, the last entry with a
376
+ * `notFound` wins. Returns undefined when no boundary on the chain declares
377
+ * a not-found convention.
378
+ *
379
+ * @internal Exported for unit testing only.
380
+ */
381
+ export declare function pickDeepestNotFound(boundaries: ClientSegmentBoundary[] | undefined): NotFoundComponent | undefined;
382
+ /**
383
+ * Builds the bare not-found element rendered inline by RouterProvider on SPA
384
+ * navigation when the server signalled a 404. Matches the server's
385
+ * `buildNotFoundElement` exactly — NO layouts, NO segment boundaries, just the
386
+ * deepest user-declared `not-found.tsx` (or the built-in default). Preserving
387
+ * layouts on 404 is a deliberate non-goal for this slice: it would diverge
388
+ * from the server's current behaviour and require coordinated changes on both
389
+ * sides.
390
+ *
391
+ * Accepts the boundary chain directly (rather than a full `LoadedClientRoute`)
392
+ * so callers can pass a subset (e.g. depth-0 only for unmatched URLs) without
393
+ * fabricating a synthetic route object.
394
+ *
395
+ * @internal Exported for unit testing only.
396
+ */
397
+ export declare function buildNotFoundPageElement(boundaries: ClientSegmentBoundary[] | undefined, error: {
398
+ data?: unknown;
399
+ message?: string;
400
+ }): React.ReactNode;
401
+ /**
402
+ * Root-level safety-net options forwarded onto the outermost
403
+ * `FurinErrorBoundary` that wraps the entire RouterProvider tree. See
404
+ * `buildRouterTree` for the full rationale.
405
+ */
406
+ export interface RootBoundaryOptions {
407
+ /**
408
+ * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
409
+ * When the server's SSR response carried a digest (loader error or shell
410
+ * recovery) this value lets the client's fallback UI display the SAME id a
411
+ * user would find in the server logs — without having to recompute and
412
+ * potentially produce a different hash from a different error instance.
413
+ */
414
+ digest?: string;
415
+ onReset?: () => void;
416
+ resetKey?: string | number;
417
+ }
418
+ /**
419
+ * Composes the outermost tree produced by `RouterProvider`:
420
+ *
421
+ * <FurinErrorBoundary digest onReset resetKey>
422
+ * <RouterContext.Provider value={context}>
423
+ * {pageElement}
424
+ * </RouterContext.Provider>
425
+ * </FurinErrorBoundary>
426
+ *
427
+ * This top boundary is the LAST line of defence. Per-segment
428
+ * `FurinErrorBoundary`s inserted by `buildPageElement` only wrap the page
429
+ * subtree BELOW the root layout, so they cannot catch errors thrown in:
430
+ * - the root layout itself,
431
+ * - hydration mismatches (these tear the whole tree before any inner
432
+ * boundary is reached),
433
+ * - the RouterProvider / page-building scaffolding code.
434
+ *
435
+ * We deliberately omit the `fallback` prop so the boundary falls back to its
436
+ * built-in `DefaultErrorFallback` — if a user-authored fallback crashed
437
+ * during its own render, we'd still have a guaranteed-to-render UI here.
438
+ * Users who want a custom *branded* global error UI author a root-level
439
+ * `error.tsx`; that convention is already picked up by `segmentBoundaries`
440
+ * at depth 0 and sits inside this top boundary.
441
+ *
442
+ * @internal Exported for unit testing only.
443
+ */
444
+ export declare function buildRouterTree(context: RouterContextValue, pageElement: React.ReactNode, options: RootBoundaryOptions): React.ReactElement;
445
+ /**
446
+ * Options threaded from `RouterProvider` (or a test harness) into each
447
+ * boundary that `buildPageElement` inserts:
448
+ *
449
+ * - `onReset` — invoked by `FurinErrorBoundary.reset` after it clears local
450
+ * error state. RouterProvider wires this to `refresh()` so the user's
451
+ * `reset()` prop re-runs the current route's loaders in addition to
452
+ * remounting the subtree.
453
+ * - `resetKey` — when it changes, both boundary classes clear their latched
454
+ * error. RouterProvider passes `currentHref`, so navigating between
455
+ * sibling routes that share a boundary (e.g. /blog/a → /blog/b) auto-clears
456
+ * any stuck error state even when the boundary instance persists.
457
+ */
458
+ export interface BoundaryOptions {
459
+ onReset?: () => void;
460
+ resetKey?: string | number;
461
+ }
462
+ /** @internal Exported for unit testing only. */
463
+ export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>, options: BoundaryOptions | undefined): React.ReactNode;
464
+ /** Strips basePath prefix from a physical pathname, returning the logical path. */
465
+ export declare function toLogical(physicalPathname: string, basePath: string): string;
466
+ export declare function RouterProvider({ routes, root, initialMatch, initialData, initialDigest, initialNotFound, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
467
+ export {};