@teyik0/furin 0.1.0-alpha.8 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4734 -548
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4713 -549
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +54 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5288 -601
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/server/context-logger.d.ts +28 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -4
  68. package/{src → dist/server}/render/shell.ts +31 -9
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +83 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +83 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/server/context-logger.ts +76 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1173
  163. package/dist/render/assemble.d.ts +0 -13
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -34
  169. package/dist/router.js +0 -830
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1035
  172. package/src/render/assemble.ts +0 -64
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -479
  176. package/src/render/loaders.ts +0 -113
  177. package/src/router.ts +0 -400
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,143 @@
1
+ import type React from "react";
2
+ import { createElement } from "react";
3
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
4
+ import { DefaultNotFoundScreen } from "../default-screens.tsx";
5
+ import { TRAILING_SLASHES_RE, toLogical } from "./link-utils.ts";
6
+ import type { ClientSegmentBoundary, SpaResponseKind } from "./types.ts";
7
+
8
+ function isFurinErrorPayload(
9
+ value: unknown
10
+ ): value is { digest: string; message: string; status: number } {
11
+ if (!value || typeof value !== "object") {
12
+ return false;
13
+ }
14
+ const v = value as { digest?: unknown; message?: unknown; status?: unknown };
15
+ return (
16
+ typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number"
17
+ );
18
+ }
19
+
20
+ /**
21
+ * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
22
+ * already-parsed `__FURIN_DATA__` payload.
23
+ *
24
+ * Sentinels (`__furinError`, `__furinStatus`) are trusted over the raw HTTP
25
+ * status — proxies / CDNs sometimes rewrite the status code but pass the body
26
+ * through untouched. A non-2xx response without any sentinel triggers a bail
27
+ * so the browser handles it (could be an error page, redirect, etc.).
28
+ *
29
+ * @internal Exported for unit testing only.
30
+ */
31
+ export function classifySpaResponse(
32
+ status: number,
33
+ data: Record<string, unknown> | null
34
+ ): SpaResponseKind {
35
+ if (!data) {
36
+ return { kind: "bail" };
37
+ }
38
+ if (isFurinErrorPayload(data.__furinError)) {
39
+ return { kind: "error", error: data.__furinError };
40
+ }
41
+ if (((status >= 200 && status < 300) || status === 404) && data.__furinStatus === 404) {
42
+ const notFound = data.__furinNotFound as { data?: unknown; message?: string } | undefined;
43
+ return { kind: "not-found", error: notFound ?? {} };
44
+ }
45
+ if (status >= 200 && status < 300) {
46
+ return { kind: "ok" };
47
+ }
48
+ return { kind: "bail" };
49
+ }
50
+
51
+ /**
52
+ * Picks the deepest not-found component declared on the match's boundary chain.
53
+ *
54
+ * @internal Exported for unit testing only.
55
+ */
56
+ export function pickDeepestNotFound(
57
+ boundaries: ClientSegmentBoundary[] | undefined
58
+ ): NotFoundComponent | undefined {
59
+ if (!boundaries) {
60
+ return;
61
+ }
62
+ for (let i = boundaries.length - 1; i >= 0; i--) {
63
+ const seg = boundaries[i];
64
+ if (seg?.notFound) {
65
+ return seg.notFound;
66
+ }
67
+ }
68
+ return;
69
+ }
70
+
71
+ const DefaultClientNotFoundFallback: NotFoundComponent = ({ error }) =>
72
+ createElement(DefaultNotFoundScreen, { message: error.message });
73
+
74
+ /**
75
+ * Builds the bare not-found element rendered inline by RouterProvider on SPA
76
+ * navigation when the server signalled a 404.
77
+ *
78
+ * @internal Exported for unit testing only.
79
+ */
80
+ export function buildNotFoundPageElement(
81
+ boundaries: ClientSegmentBoundary[] | undefined,
82
+ error: { data?: unknown; message?: string }
83
+ ): React.ReactNode {
84
+ const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
85
+ return createElement(Fallback, { error });
86
+ }
87
+
88
+ /**
89
+ * Parses the HTML payload of a page response into the pieces `fetchPageState`
90
+ * cares about: the document (for title), the __FURIN_DATA__ loader payload,
91
+ * and the logical `finalHref` after any server-side redirect.
92
+ */
93
+ export async function parsePageResponse(
94
+ res: Response,
95
+ basePath: string
96
+ ): Promise<{ data: Record<string, unknown> | null; finalHref: string | undefined; title: string }> {
97
+ let finalHref: string | undefined;
98
+ if (res.redirected) {
99
+ const final = new URL(res.url);
100
+ finalHref = toLogical(final.pathname, basePath) + final.search;
101
+ }
102
+ const html = await res.text();
103
+ const doc = new DOMParser().parseFromString(html, "text/html");
104
+ const dataEl = doc.getElementById("__FURIN_DATA__");
105
+ const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
106
+ return { data, finalHref, title: doc.title };
107
+ }
108
+
109
+ /**
110
+ * Builds the URL the SPA navigation flow uses to fetch a route's loader data.
111
+ *
112
+ * Two transports are supported:
113
+ *
114
+ * • **Runtime (SSR/ISR/dev)** — `${basePath}/_furin/data?path=<logicalHref>`.
115
+ * • **Static export** — `${basePath}<logicalPathname>/__furin_data.ndjson`.
116
+ *
117
+ * @internal Exported for unit testing.
118
+ */
119
+ export function buildDataEndpoint(
120
+ basePath: string,
121
+ logicalHref: string,
122
+ staticMode: boolean
123
+ ): string {
124
+ if (!staticMode) {
125
+ return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
126
+ }
127
+ const parsed = new URL(logicalHref, "http://x");
128
+ const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
129
+ return `${basePath}${pathname}/__furin_data.ndjson`;
130
+ }
131
+
132
+ /**
133
+ * Reads `<meta name="furin-mode" content="static">` from the document at boot.
134
+ *
135
+ * @internal Exported for unit testing.
136
+ */
137
+ export function detectStaticMode(): boolean {
138
+ if (typeof document === "undefined") {
139
+ return false;
140
+ }
141
+ const meta = document.querySelector<HTMLMetaElement>('meta[name="furin-mode"]');
142
+ return meta?.content === "static";
143
+ }
@@ -0,0 +1,263 @@
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
+
6
+ /**
7
+ * Augment this interface via declaration merging in furin-env.d.ts
8
+ * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
9
+ *
10
+ * @example
11
+ * // furin-env.d.ts (auto-generated by Furin at project root)
12
+ * import "@teyik0/furin/link";
13
+ * declare module "@teyik0/furin/link" {
14
+ * interface RouteManifest {
15
+ * "/blog": { search?: { page?: number; tag?: string } };
16
+ * "/": { search?: never };
17
+ * [key: `/blog/${string}`]: { search?: never };
18
+ * }
19
+ * }
20
+ */
21
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
22
+ export interface RouteManifest {}
23
+
24
+ /**
25
+ * The valid `to` pathname union derived from the augmented RouteManifest.
26
+ * Falls back to `string` when furin-env.d.ts has not been generated yet.
27
+ * When augmented, also includes `https://` and `http://` for external links.
28
+ */
29
+ export type RouteTo = keyof RouteManifest extends never
30
+ ? string
31
+ : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
32
+
33
+ /**
34
+ * The typed search params for a given `to` pathname.
35
+ * Falls back to a permissive record when RouteManifest is not augmented.
36
+ */
37
+ export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
38
+ ? Record<string, string | number | boolean | null | undefined>
39
+ : To extends keyof RouteManifest
40
+ ? RouteManifest[To] extends { search?: infer S }
41
+ ? S
42
+ : undefined
43
+ : undefined;
44
+
45
+ export type PreloadStrategy = false | "intent" | "viewport" | "render";
46
+
47
+ export interface LinkProps<To extends RouteTo = RouteTo>
48
+ extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
49
+ /**
50
+ * Extra props merged onto the anchor when the link is active.
51
+ * `isActive` is also passed so one function can handle both states.
52
+ * Styles and classNames from `activeProps` win over the static props.
53
+ */
54
+ activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
55
+ /** Static children or a render function receiving active state. */
56
+ children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
57
+ /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
58
+ disabled?: boolean;
59
+ /** Optional URL fragment (without the #). */
60
+ hash?: string;
61
+ /**
62
+ * Extra props merged onto the anchor when the link is NOT active.
63
+ * Styles and classNames from `inactiveProps` win over the static props.
64
+ */
65
+ inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
66
+ /** Preload strategy. Default: "intent" (preload on hover/focus). */
67
+ preload?: PreloadStrategy;
68
+ /** Delay in ms before intent preload triggers. Default: 50. */
69
+ preloadDelay?: number;
70
+ /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
71
+ preloadStaleTime?: number;
72
+ /** If true, uses history.replaceState instead of pushState (no new history entry). */
73
+ replace?: boolean;
74
+ /**
75
+ * Whether to scroll after SPA navigation. Default: true.
76
+ * - If the destination href has a `#hash`, scrolls to that element.
77
+ * - Otherwise scrolls to the top of the page.
78
+ * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
79
+ */
80
+ resetScroll?: boolean;
81
+ /** Typed search params for this route. Auto-completed from the route's query schema. */
82
+ search?: RouteSearch<To>;
83
+ to: To;
84
+ }
85
+
86
+ export interface RouterContextValue {
87
+ /**
88
+ * Sub-path prefix for static deployments (e.g. "/furin").
89
+ * Empty string when the site is served from root.
90
+ * Used by `Link` to build correct physical hrefs for the `<a>` element.
91
+ */
92
+ basePath: string;
93
+ /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
94
+ currentHref: string;
95
+ defaultPreload: PreloadStrategy;
96
+ defaultPreloadDelay: number;
97
+ defaultPreloadStaleTime: number;
98
+ /**
99
+ * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
100
+ * made on the server. Called automatically by the `window.fetch` interceptor when
101
+ * the server emits `X-Furin-Revalidate` headers.
102
+ *
103
+ * - `type: 'page'` (default) — exact URL match
104
+ * - `type: 'layout'` — prefix match (path + all nested children)
105
+ */
106
+ invalidatePrefetch: (path: string, type: "page" | "layout") => void;
107
+ isNavigating: boolean;
108
+ navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
109
+ prefetch: (href: string, opts?: { staleTime?: number }) => void;
110
+ /**
111
+ * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
112
+ * loaders, and updates the rendered tree — without adding a history entry or
113
+ * resetting scroll (unless `resetScroll: true` is passed).
114
+ *
115
+ * Prefer this over `navigate(window.location.pathname)` after a mutation.
116
+ */
117
+ refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
118
+ }
119
+
120
+ /**
121
+ * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
122
+ * version this does NOT carry the directory path — it's purely a (depth,
123
+ * fallback) pair because the client never reads files, only renders.
124
+ */
125
+ export interface ClientSegmentBoundary {
126
+ depth: number;
127
+ error?: ErrorComponent;
128
+ notFound?: NotFoundComponent;
129
+ }
130
+
131
+ export interface ClientRoute {
132
+ component?: React.ComponentType<Record<string, unknown>>;
133
+ load: () => Promise<{
134
+ default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
135
+ segmentBoundaries?: ClientSegmentBoundary[];
136
+ }>;
137
+ pageRoute?: RuntimeRoute;
138
+ pattern: string;
139
+ regex: RegExp;
140
+ /**
141
+ * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
142
+ * to the route-chain index used on the server side, so `buildPageElement`
143
+ * can interleave boundaries at the exact same positions that the server
144
+ * used in `buildElement` — guaranteeing hydration consistency.
145
+ */
146
+ segmentBoundaries?: ClientSegmentBoundary[];
147
+ }
148
+
149
+ /**
150
+ * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
151
+ * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
152
+ * on navigation via fetchPageState.
153
+ */
154
+ export type LoadedClientRoute = ClientRoute & {
155
+ component: React.ComponentType<Record<string, unknown>>;
156
+ pageRoute: RuntimeRoute;
157
+ };
158
+
159
+ export interface RouterProviderProps {
160
+ /**
161
+ * When `true` (default), the router automatically re-fetches the current page
162
+ * whenever a server `revalidatePath()` call targets it. The signal is the
163
+ * `X-Furin-Revalidate` header detected on any `window.fetch` response.
164
+ *
165
+ * Set to `false` to opt out and call `router.refresh()` manually instead.
166
+ */
167
+ autoRefresh: boolean;
168
+ /**
169
+ * Sub-path prefix for static deployments (e.g. "/furin").
170
+ * Must start with "/" and have no trailing slash.
171
+ * Default: "" (site served from root).
172
+ */
173
+ basePath: string;
174
+ defaultPreload: PreloadStrategy;
175
+ defaultPreloadDelay: number;
176
+ defaultPreloadStaleTime: number;
177
+ initialData: Record<string, unknown>;
178
+ /**
179
+ * Slice 10 — server-logged error digest threaded from
180
+ * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
181
+ * `FurinErrorBoundary` so that if a client-side error escapes the
182
+ * per-segment boundaries (root layout crash, hydration mismatch, …), the
183
+ * fallback UI surfaces the id a user would find in server logs.
184
+ */
185
+ initialDigest: string | undefined;
186
+ /**
187
+ * The route matched at hydration time. `null` is a valid value ONLY when
188
+ * `initialNotFound` is also provided.
189
+ */
190
+ initialMatch: LoadedClientRoute | null;
191
+ /**
192
+ * When set, the provider boots into the inline not-found state as if a
193
+ * prior SPA navigation hit a 404.
194
+ */
195
+ initialNotFound: { data?: unknown; message?: string } | undefined;
196
+ /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
197
+ prefetchCacheSize: number;
198
+ root: RuntimeRoute | null;
199
+ routes: ClientRoute[];
200
+ }
201
+
202
+ /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
203
+ export interface RouterState {
204
+ data: Record<string, unknown>;
205
+ /**
206
+ * Set when the server's NDJSON payload carried an `__furinError` sentinel.
207
+ */
208
+ error?: { digest: string; message: string; status: number };
209
+ /** The canonical href after server-side redirects (e.g. query-default redirect). */
210
+ finalHref?: string;
211
+ /**
212
+ * The currently rendered route.
213
+ *
214
+ * `null` is a valid value ONLY when `notFound` is also set.
215
+ */
216
+ match: LoadedClientRoute | null;
217
+ /**
218
+ * Slice 8 — set when the matched route's loader threw `notFound()` on the server.
219
+ */
220
+ notFound?: { data?: unknown; message?: string };
221
+ /**
222
+ * Explicit boundary chain to use for the not-found render.
223
+ */
224
+ notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
225
+ title?: string;
226
+ }
227
+
228
+ /** @internal */
229
+ export interface CacheEntry {
230
+ createdAt: number;
231
+ promise: Promise<RouterState | null>;
232
+ staleTime: number;
233
+ }
234
+
235
+ /**
236
+ * Classification of a fetch response during SPA navigation. Returned by the
237
+ * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
238
+ *
239
+ * - `ok` — 2xx response with usable loader data; render normally.
240
+ * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
241
+ * - `error` — server signalled `__FURIN_DATA__.__furinError`.
242
+ * - `bail` — any other non-2xx without sentinels.
243
+ *
244
+ * @internal Exported for unit testing only.
245
+ */
246
+ export type SpaResponseKind =
247
+ | { kind: "ok" }
248
+ | { kind: "not-found"; error: { data?: unknown; message?: string } }
249
+ | { kind: "error"; error: { digest: string; message: string; status: number } }
250
+ | { kind: "bail" };
251
+
252
+ /**
253
+ * Root-level safety-net options forwarded onto the outermost
254
+ * `FurinErrorBoundary` that wraps the entire RouterProvider tree.
255
+ */
256
+ export interface RootBoundaryOptions {
257
+ /**
258
+ * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
259
+ */
260
+ digest?: string;
261
+ onReset?: () => void;
262
+ resetKey?: string | number;
263
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Server-thrown error carrying an HTTP status and a server-computed digest
3
+ * across SSR and SPA navigation.
4
+ *
5
+ * Why a class (not property-stamping):
6
+ * - Mirrors the `FurinNotFoundError` pattern (consistency).
7
+ * - Type-narrowable via `instanceof` and the brand check.
8
+ * - Survives error wrappers (Sentry / monitoring libs that re-throw
9
+ * `new Error(original.message)` would strip property stamps).
10
+ *
11
+ * Used by:
12
+ * - `FurinErrorBoundary.getDerivedStateFromError` — to honour the server's
13
+ * digest instead of recomputing one client-side (the latter would produce a
14
+ * different hash because the public message + synthetic stack differ from the
15
+ * original server-side error).
16
+ * - SPA navigation: `RouterProvider` throws this during render of the route
17
+ * position when `__furinError` was sentinelled into the NDJSON payload, so
18
+ * the nearest error boundary catches it without forcing a full-page reload.
19
+ */
20
+ const SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR" as const;
21
+
22
+ export interface FurinServerErrorPayload {
23
+ digest: string;
24
+ message: string;
25
+ status: number;
26
+ }
27
+
28
+ export class FurinServerError extends Error {
29
+ readonly __furinBrand = SERVER_ERROR_BRAND;
30
+ readonly digest: string;
31
+ readonly status: number;
32
+
33
+ constructor(args: FurinServerErrorPayload) {
34
+ super(args.message);
35
+ this.status = args.status;
36
+ this.digest = args.digest;
37
+ }
38
+ }
39
+
40
+ export function isFurinServerError(err: unknown): err is FurinServerError {
41
+ return (
42
+ err instanceof FurinServerError ||
43
+ (typeof err === "object" &&
44
+ err !== null &&
45
+ (err as { __furinBrand?: unknown }).__furinBrand === SERVER_ERROR_BRAND)
46
+ );
47
+ }
package/src/client.ts CHANGED
@@ -9,6 +9,10 @@
9
9
 
10
10
  import type { Cookie, StatusMap } from "elysia";
11
11
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
12
+ import type { RequestLogger } from "evlog";
13
+
14
+ // biome-ignore lint/performance/noBarrelFile: client.ts is the canonical DX entry for furin/client consumers — not a barrel
15
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
12
16
 
13
17
  declare const UNSET: unique symbol;
14
18
  type Unset = typeof UNSET;
@@ -35,14 +39,22 @@ type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
35
39
  * Transforms each key of a parent-data record into an individual `Promise<T>`.
36
40
  * This is what child loaders see for inherited fields — direct values from
37
41
  * `RouteContext` (request, params, set, …) remain unchanged.
42
+ *
43
+ * `Awaited<T[K]>` mirrors the JS Promise-chaining auto-flatten used by
44
+ * `createLoaderCtx`: when an ancestor wrapped a field with `defer()` (so the
45
+ * raw value is itself a `Promise<U>`), the type collapses to `Promise<U>`
46
+ * instead of `Promise<Promise<U>>`. Otherwise TypeScript would force a
47
+ * redundant `await await ctx.field` dance.
38
48
  */
39
49
  type PromisifyData<T extends Record<string, unknown>> = {
40
- [K in keyof T]: Promise<T[K]>;
50
+ [K in keyof T]: Promise<Awaited<T[K]>>;
41
51
  };
42
52
 
43
53
  export interface RouteContext<TParams = {}, TQuery = {}> {
44
54
  cookie: Record<string, Cookie<unknown>>;
45
55
  headers: Record<string, string | undefined>;
56
+ /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
57
+ log: RequestLogger;
46
58
  params: NormalizeUnset<TParams>;
47
59
  path: string;
48
60
  query: NormalizeUnset<TQuery>;
@@ -66,7 +78,11 @@ type ResolveParent<T> =
66
78
  : { data: {}; params: Unset; query: Unset };
67
79
 
68
80
  interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
69
- data: ToRecord<ResolveParent<TParentRef>["data"] & TLoaderData>;
81
+ // `Omit<TLoaderData, "__isDeferred">` strips the runtime brand that `defer()`
82
+ // attaches to its return value. A layout/route loader wrapped with `defer()`
83
+ // would otherwise leak `__isDeferred: true` into descendant loader contexts
84
+ // and component props.
85
+ data: ToRecord<ResolveParent<TParentRef>["data"] & Omit<TLoaderData, "__isDeferred">>;
70
86
  params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
71
87
  query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
72
88
  }
@@ -107,9 +123,12 @@ export interface HeadOptions {
107
123
  // Extracts the resolved return type from a loader function type.
108
124
  // Using ReturnType + Awaited here means TLoader is inferred as the whole function
109
125
  // first, and then we extract the data — so inference is order-independent.
126
+ // The `__isDeferred` key (DEFERRED_BRAND, see below) is stripped: a `defer()`
127
+ // return carries that runtime marker, but it must never surface as a
128
+ // component / head() prop — it is an internal implementation detail.
110
129
  type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown
111
130
  ? Awaited<ReturnType<TLoader>> extends object
112
- ? ToRecord<Awaited<ReturnType<TLoader>>>
131
+ ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">>
113
132
  : {}
114
133
  : {};
115
134
 
@@ -125,6 +144,7 @@ export interface PageConfig<
125
144
  ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
126
145
  ) => Promise<TPageLoaderData> | TPageLoaderData;
127
146
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
147
+ tags?: string[];
128
148
  }
129
149
 
130
150
  export interface RuntimeRoute {
@@ -136,6 +156,7 @@ export interface RuntimeRoute {
136
156
  parent?: RuntimeRoute;
137
157
  query?: unknown;
138
158
  revalidate?: number;
159
+ tags?: string[];
139
160
  }
140
161
 
141
162
  export interface RuntimePage {
@@ -145,6 +166,7 @@ export interface RuntimePage {
145
166
  head?(ctx: Record<string, unknown>): HeadOptions;
146
167
  loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
147
168
  staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
169
+ tags?: string[];
148
170
  }
149
171
 
150
172
  export interface RouteRef<
@@ -169,6 +191,7 @@ interface PageResult<
169
191
  loader?: (
170
192
  ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
171
193
  ) => Promise<TPageLoaderData> | TPageLoaderData;
194
+ tags?: string[];
172
195
  }
173
196
 
174
197
  export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
@@ -191,6 +214,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
191
214
  mode?: "ssr" | "ssg" | "isr";
192
215
  revalidate?: number;
193
216
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
217
+ tags?: string[];
194
218
  component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
195
219
  head?: (
196
220
  ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>
@@ -202,6 +226,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
202
226
  mode?: "ssr" | "ssg" | "isr";
203
227
  revalidate?: number;
204
228
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
229
+ tags?: string[];
205
230
  component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
206
231
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
207
232
  }): PageResult<TParentData, TParams, TQuery, {}>;
@@ -213,6 +238,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
213
238
  /** Branded ref for type inference when used as a parent. */
214
239
  ref: RouteRef<TParentData, TParams, TQuery>;
215
240
  revalidate?: number;
241
+ tags?: string[];
216
242
  }
217
243
 
218
244
  export function createRoute<
@@ -226,6 +252,7 @@ export function createRoute<
226
252
  revalidate?: number;
227
253
  params?: TParamsSchema;
228
254
  query?: TQuerySchema;
255
+ tags?: string[];
229
256
  loader?: (
230
257
  ctx: RouteContext<
231
258
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
@@ -273,3 +300,56 @@ export type InferProps<T> = T extends {
273
300
  : T extends Route<infer D, infer P, infer Q>
274
301
  ? D & { children: React.ReactNode } & ComponentProps<P, Q>
275
302
  : never;
303
+
304
+ // ── Deferred data ──────────────────────────────────────────────────────────────
305
+
306
+ /**
307
+ * Brand key that marks an object as deferred. Using a `const` string avoids
308
+ * a `unique symbol` that would complicate cross-module inference.
309
+ */
310
+ const DEFERRED_BRAND = "__isDeferred" as const;
311
+
312
+ /**
313
+ * A loader return value that contains a mix of synchronous scalar fields and
314
+ * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
315
+ * shell; Promise fields are streamed as late `<script>` resolution chunks.
316
+ *
317
+ * @example
318
+ * loader: () => defer({
319
+ * title: "My Board", // synchronous — available immediately
320
+ * stats: fetchStats(), // Promise — streamed when it resolves
321
+ * })
322
+ */
323
+ export type DeferredData<T extends Record<string, unknown>> = T & {
324
+ readonly [DEFERRED_BRAND]: true;
325
+ };
326
+
327
+ /**
328
+ * Wraps loader data so that Promise-valued fields are streamed lazily while
329
+ * scalar fields are embedded in the initial HTML shell immediately.
330
+ *
331
+ * Use in any loader — page (`route.page({ loader })`) or route/layout
332
+ * (`createRoute({ loader })`). Promise-valued fields are streamed lazily;
333
+ * scalar fields are embedded in the initial HTML shell.
334
+ */
335
+ export function defer<T extends Record<string, unknown>>(data: T): DeferredData<T> {
336
+ if (Object.hasOwn(data, DEFERRED_BRAND)) {
337
+ throw new Error(
338
+ `[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`
339
+ );
340
+ }
341
+ return { ...data, [DEFERRED_BRAND]: true } as DeferredData<T>;
342
+ }
343
+
344
+ /**
345
+ * Type guard for DeferredData. Used by the render pipeline to distinguish a
346
+ * plain loader return from a deferred one.
347
+ */
348
+ export function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>> {
349
+ return (
350
+ typeof v === "object" &&
351
+ v !== null &&
352
+ Object.hasOwn(v, DEFERRED_BRAND) &&
353
+ (v as Record<typeof DEFERRED_BRAND, unknown>)[DEFERRED_BRAND] === true
354
+ );
355
+ }
package/src/config.ts CHANGED
@@ -1,5 +1,4 @@
1
- export type { BunPlugin } from "bun";
2
-
1
+ import type { BunPlugin } from "bun";
3
2
  import { t } from "elysia";
4
3
 
5
4
  export const BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"] as const;
@@ -39,6 +38,13 @@ export const configSchema = t.Object({
39
38
  rootDir: t.Optional(t.String()),
40
39
  pagesDir: t.Optional(t.String()),
41
40
  serverEntry: t.Optional(t.String()),
41
+ /**
42
+ * Initialize the browser HTTP log drain in the hydration entry. Off by
43
+ * default — enabling it adds `evlog/http` drain setup and points browser
44
+ * events at `/_furin/ingest`. Server-side logging is unaffected (configured
45
+ * via the `furin({ logger })` plugin option).
46
+ */
47
+ clientLogging: t.Optional(t.Boolean()),
42
48
  targets: t.Optional(t.Array(buildTargetSchema)),
43
49
  bun: t.Optional(
44
50
  t.Object({
@@ -55,8 +61,10 @@ export const configSchema = t.Object({
55
61
  // plugins omitted : TypeBox can't validate Bun.BunPlugin[] (functions)
56
62
  });
57
63
 
64
+ export type FurinPlugin = BunPlugin & { buildOnly?: boolean };
65
+
58
66
  export type FurinConfig = (typeof configSchema)["static"] & {
59
- plugins?: Bun.BunPlugin[];
67
+ plugins?: FurinPlugin[];
60
68
  static?: StaticExportConfig;
61
69
  };
62
70
 
package/src/env.d.ts CHANGED
@@ -44,6 +44,7 @@ declare module "*.woff2" {
44
44
  }
45
45
  declare module "*.mdx" {
46
46
  import type { ComponentType } from "react";
47
+
47
48
  const MDXComponent: ComponentType;
48
49
  export default MDXComponent;
49
50
  }