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

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 (132) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/bun.d.ts +3 -0
  4. package/dist/adapter/static.d.ts +3 -0
  5. package/dist/build/client.d.ts +25 -0
  6. package/dist/build/compile-entry.d.ts +9 -0
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +38 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +24 -0
  11. package/dist/build/index.d.ts +8 -0
  12. package/dist/build/index.js +8106 -0
  13. package/dist/build/route-types.d.ts +23 -0
  14. package/dist/build/scan-server.d.ts +8 -0
  15. package/dist/build/server-routes-entry.d.ts +13 -0
  16. package/dist/build/server-routes-entry.ts +36 -0
  17. package/dist/build/shared.d.ts +12 -0
  18. package/dist/build/ssg-cache.d.ts +4 -0
  19. package/dist/build/types.d.ts +80 -0
  20. package/dist/cli/config.d.ts +9 -0
  21. package/dist/cli/index.d.ts +2 -0
  22. package/dist/cli/index.js +8097 -0
  23. package/dist/client/boundaries.d.ts +117 -0
  24. package/dist/client/default-screens.d.ts +17 -0
  25. package/dist/client/link.d.ts +22 -0
  26. package/dist/client/link.js +4244 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/types.d.ts +292 -0
  38. package/dist/client/server-error.d.ts +12 -0
  39. package/dist/client/sync.d.ts +25 -0
  40. package/dist/client.d.ts +243 -0
  41. package/dist/client.js +140 -0
  42. package/dist/config.d.ts +57 -0
  43. package/dist/config.js +29 -0
  44. package/dist/env.d.ts +50 -0
  45. package/dist/furin.d.ts +77 -0
  46. package/dist/furin.js +8693 -0
  47. package/dist/plugin/index.d.ts +20 -0
  48. package/dist/plugin/index.js +1500 -0
  49. package/dist/plugin/transform-client.d.ts +10 -0
  50. package/dist/server/auto-invalidate/index.d.ts +4 -0
  51. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  52. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  53. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  54. package/dist/server/auto-invalidate/types.d.ts +12 -0
  55. package/dist/server/cache/dev-loader.d.ts +28 -0
  56. package/dist/server/cache/index.d.ts +10 -0
  57. package/dist/server/cache/invalidation.d.ts +12 -0
  58. package/dist/server/cache/isr-ssg.d.ts +26 -0
  59. package/dist/server/cache/isr.d.ts +6 -0
  60. package/dist/server/cache/registry.d.ts +5 -0
  61. package/dist/server/cache/route-cache.d.ts +26 -0
  62. package/dist/server/cache/ssg.d.ts +5 -0
  63. package/dist/server/context-logger.d.ts +28 -0
  64. package/dist/server/dev-inspector.d.ts +89 -0
  65. package/dist/server/dev-page-plugin.d.ts +112 -0
  66. package/dist/server/internal.d.ts +35 -0
  67. package/dist/server/internal.js +17 -0
  68. package/dist/server/lang-detect.d.ts +5 -0
  69. package/dist/server/render/assemble.d.ts +49 -0
  70. package/dist/server/render/element.d.ts +24 -0
  71. package/dist/server/render/index.d.ts +7 -0
  72. package/dist/server/render/index.ts +22 -0
  73. package/dist/server/render/isr.d.ts +4 -0
  74. package/dist/server/render/loaders.d.ts +64 -0
  75. package/dist/server/render/not-found.d.ts +6 -0
  76. package/dist/server/render/shell.d.ts +39 -0
  77. package/dist/server/render/shell.ts +202 -0
  78. package/dist/server/render/ssg.d.ts +9 -0
  79. package/dist/server/render/ssr.d.ts +108 -0
  80. package/dist/server/render/template.d.ts +6 -0
  81. package/dist/server/router/discovery.d.ts +16 -0
  82. package/dist/server/router/hmr.d.ts +65 -0
  83. package/dist/server/router/index.d.ts +6 -0
  84. package/dist/server/router/index.js +27 -0
  85. package/dist/server/router/index.ts +28 -0
  86. package/dist/server/router/patterns.d.ts +40 -0
  87. package/dist/server/router/plugin.d.ts +21 -0
  88. package/dist/server/router/schemas.d.ts +59 -0
  89. package/dist/server/router/types.d.ts +60 -0
  90. package/dist/server/runtime-env.d.ts +3 -0
  91. package/dist/server/runtime-env.js +10 -0
  92. package/dist/server/sync/config.d.ts +6 -0
  93. package/dist/server/sync/index.d.ts +4 -0
  94. package/dist/server/sync/plugin.d.ts +369 -0
  95. package/dist/server/sync/stream.d.ts +47 -0
  96. package/dist/shared/await.d.ts +67 -0
  97. package/dist/shared/deferred-ndjson.d.ts +32 -0
  98. package/dist/shared/digest.d.ts +16 -0
  99. package/dist/shared/error.d.ts +37 -0
  100. package/dist/shared/not-found.d.ts +19 -0
  101. package/dist/shared/search-params.d.ts +17 -0
  102. package/dist/shared/utils/ast-walk.d.ts +18 -0
  103. package/dist/shared/utils/index.d.ts +13 -0
  104. package/package.json +5 -5
  105. package/src/adapter/README.md +13 -13
  106. package/src/build/client.ts +152 -152
  107. package/src/build/compile-entry.ts +109 -109
  108. package/src/build/entry-template.ts +156 -156
  109. package/src/build/hydrate.ts +340 -337
  110. package/src/build/index.ts +152 -152
  111. package/src/build/route-types.ts +145 -145
  112. package/src/build/scan-server.ts +95 -95
  113. package/src/build/server-routes-entry.ts +36 -36
  114. package/src/build/shared.ts +80 -79
  115. package/src/build/ssg-cache.ts +32 -32
  116. package/src/build/types.ts +89 -89
  117. package/src/client/router/link-utils.ts +184 -177
  118. package/src/client/router/provider.tsx +804 -759
  119. package/src/client/router/types.ts +276 -271
  120. package/src/client/sync.ts +98 -0
  121. package/src/client.ts +369 -355
  122. package/src/furin.ts +465 -444
  123. package/src/server/auto-invalidate/runtime.ts +134 -133
  124. package/src/server/dev-page-plugin.ts +454 -449
  125. package/src/server/render/assemble.ts +160 -133
  126. package/src/server/render/isr.ts +323 -317
  127. package/src/server/render/ssr.ts +585 -583
  128. package/src/server/router/plugin.ts +384 -384
  129. package/src/server/sync/config.ts +29 -0
  130. package/src/server/sync/index.ts +14 -0
  131. package/src/server/sync/plugin.ts +108 -0
  132. package/src/server/sync/stream.ts +144 -0
@@ -1,271 +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
-
210
- /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
211
- export interface RouterState {
212
- data: Record<string, unknown>;
213
- /**
214
- * Set when the server's NDJSON payload carried an `__furinError` sentinel.
215
- */
216
- error?: { digest: string; message: string; status: number };
217
- /** The canonical href after server-side redirects (e.g. query-default redirect). */
218
- finalHref?: string;
219
- /**
220
- * The currently rendered route.
221
- *
222
- * `null` is a valid value ONLY when `notFound` is also set.
223
- */
224
- match: LoadedClientRoute | null;
225
- /**
226
- * Slice 8 — set when the matched route's loader threw `notFound()` on the server.
227
- */
228
- notFound?: { data?: unknown; message?: string };
229
- /**
230
- * Explicit boundary chain to use for the not-found render.
231
- */
232
- notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
233
- title?: string;
234
- }
235
-
236
- /** @internal */
237
- export interface CacheEntry {
238
- createdAt: number;
239
- promise: Promise<RouterState | null>;
240
- staleTime: number;
241
- }
242
-
243
- /**
244
- * Classification of a fetch response during SPA navigation. Returned by the
245
- * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
246
- *
247
- * - `ok` — 2xx response with usable loader data; render normally.
248
- * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
249
- * - `error` — server signalled `__FURIN_DATA__.__furinError`.
250
- * - `bail` — any other non-2xx without sentinels.
251
- *
252
- * @internal Exported for unit testing only.
253
- */
254
- export type SpaResponseKind =
255
- | { kind: "ok" }
256
- | { kind: "not-found"; error: { data?: unknown; message?: string } }
257
- | { kind: "error"; error: { digest: string; message: string; status: number } }
258
- | { kind: "bail" };
259
-
260
- /**
261
- * Root-level safety-net options forwarded onto the outermost
262
- * `FurinErrorBoundary` that wraps the entire RouterProvider tree.
263
- */
264
- export interface RootBoundaryOptions {
265
- /**
266
- * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
267
- */
268
- digest?: string;
269
- onReset?: () => void;
270
- resetKey?: string | number;
271
- }
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
+ }
@@ -0,0 +1,98 @@
1
+ import { useCallback } from "react";
2
+
3
+ export interface SyncMutationHeaders {
4
+ "Idempotency-Key": string;
5
+ }
6
+
7
+ export interface SyncMutationOptions {
8
+ headers: SyncMutationHeaders;
9
+ }
10
+
11
+ export interface SyncMutationContext<TInput> {
12
+ idempotencyKey: string;
13
+ input: TInput;
14
+ }
15
+
16
+ export interface SyncMutationSuccessContext<TInput, TResult> extends SyncMutationContext<TInput> {
17
+ result: TResult;
18
+ }
19
+
20
+ export interface SyncMutationErrorContext<TInput, TResult> extends SyncMutationContext<TInput> {
21
+ error: unknown;
22
+ result?: TResult;
23
+ }
24
+
25
+ export interface UseSyncOptions<TInput, TResult> {
26
+ onError?: (ctx: SyncMutationErrorContext<TInput, TResult>) => Promise<void> | void;
27
+ onSuccess?: (ctx: SyncMutationSuccessContext<TInput, TResult>) => Promise<void> | void;
28
+ optimistic?: (ctx: SyncMutationContext<TInput>) => (() => void) | undefined;
29
+ }
30
+
31
+ export type SyncMutation<TInput, TResult> = (
32
+ input: TInput,
33
+ options: SyncMutationOptions
34
+ ) => Promise<TResult>;
35
+
36
+ export type SyncMutationRunner<TInput, TResult> = undefined extends TInput
37
+ ? (input?: TInput) => Promise<TResult>
38
+ : (input: TInput) => Promise<TResult>;
39
+
40
+ interface EdenErrorResult {
41
+ error?: unknown;
42
+ }
43
+
44
+ function createIdempotencyKey(): string {
45
+ if (typeof globalThis.crypto?.randomUUID === "function") {
46
+ return globalThis.crypto.randomUUID();
47
+ }
48
+ return `${Date.now()}-${Math.random()}`;
49
+ }
50
+
51
+ function getResolvedError(result: unknown): unknown | undefined {
52
+ if (!(typeof result === "object" && result !== null && "error" in result)) {
53
+ return;
54
+ }
55
+
56
+ const error = (result as EdenErrorResult).error;
57
+ return error == null ? undefined : error;
58
+ }
59
+
60
+ export function useSync<TInput, TResult>(
61
+ mutation: SyncMutation<TInput, TResult>,
62
+ options?: UseSyncOptions<TInput, TResult>
63
+ ): SyncMutationRunner<TInput, TResult> {
64
+ const optimistic = options?.optimistic;
65
+ const onError = options?.onError;
66
+ const onSuccess = options?.onSuccess;
67
+
68
+ const run = useCallback(
69
+ async (input: TInput) => {
70
+ const idempotencyKey = createIdempotencyKey();
71
+ const rollback = optimistic?.({ idempotencyKey, input });
72
+
73
+ let result: TResult;
74
+ try {
75
+ result = await mutation(input, {
76
+ headers: { "Idempotency-Key": idempotencyKey },
77
+ });
78
+ } catch (error) {
79
+ rollback?.();
80
+ await onError?.({ error, idempotencyKey, input });
81
+ throw error;
82
+ }
83
+
84
+ const resolvedError = getResolvedError(result);
85
+ if (resolvedError !== undefined) {
86
+ rollback?.();
87
+ await onError?.({ error: resolvedError, idempotencyKey, input, result });
88
+ return result;
89
+ }
90
+
91
+ await onSuccess?.({ idempotencyKey, input, result });
92
+ return result;
93
+ },
94
+ [mutation, optimistic, onError, onSuccess]
95
+ );
96
+
97
+ return run as SyncMutationRunner<TInput, TResult>;
98
+ }