@teyik0/furin 0.1.0-alpha.9 → 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 +4027 -685
  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 +4007 -687
  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 +51 -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 +5291 -662
  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/{context-logger.d.ts → server/context-logger.d.ts} +2 -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 -7
  68. package/{src → dist/server}/render/shell.ts +28 -13
  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 +79 -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 +80 -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/{context-logger.ts → server/context-logger.ts} +5 -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 -1232
  163. package/dist/render/assemble.d.ts +0 -15
  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 -45
  169. package/dist/router.js +0 -1671
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1120
  172. package/src/render/assemble.ts +0 -66
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -483
  176. package/src/render/loaders.ts +0 -117
  177. package/src/router.ts +0 -439
  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,26 @@
1
+ import type React from "react";
2
+ import type { RuntimeRoute } from "../../client.ts";
3
+ import { type BoundaryOptions } from "../boundaries.tsx";
4
+ import type { LoadedClientRoute, RootBoundaryOptions, RouterContextValue } from "./types.ts";
5
+ /**
6
+ * Composes the outermost tree produced by `RouterProvider`:
7
+ *
8
+ * <RouterContext.Provider value={context}>
9
+ * <FurinErrorBoundary digest onReset resetKey>
10
+ * {pageElement}
11
+ * </FurinErrorBoundary>
12
+ * </RouterContext.Provider>
13
+ *
14
+ * `RouterContext.Provider` is the OUTERMOST element so that a root-level
15
+ * `error.tsx` rendered by the boundary can still call `useRouter()` / render
16
+ * `<Link>` (the context is in scope above the boundary).
17
+ *
18
+ * @internal Exported for unit testing only.
19
+ */
20
+ export declare function buildRouterTree(context: RouterContextValue, pageElement: React.ReactNode, options: RootBoundaryOptions): React.ReactElement;
21
+ /** @internal Exported for unit testing only. */
22
+ export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>, options: BoundaryOptions | undefined, error: {
23
+ digest: string;
24
+ message: string;
25
+ status: number;
26
+ } | undefined): React.ReactNode;
@@ -0,0 +1,8 @@
1
+ import type { RouterContextValue } from "./types.ts";
2
+ export declare const RouterContext: import("react").Context<RouterContextValue | null>;
3
+ export declare const CLIENT_FALLBACK_ROUTER: RouterContextValue;
4
+ /**
5
+ * Returns the current router context.
6
+ * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
7
+ */
8
+ export declare function useRouter(): RouterContextValue;
@@ -0,0 +1,9 @@
1
+ export declare const SCROLL_STORAGE_KEY = "__furin_scroll__";
2
+ export declare function getHistoryKey(state: unknown): string | undefined;
3
+ export declare function generateHistoryKey(): string;
4
+ export declare function saveScrollPosition(key: string): void;
5
+ /**
6
+ * Returns `true` when the server reports a different build-id from the one
7
+ * embedded in the initial HTML (`<meta name="furin-build-id">`).
8
+ */
9
+ export declare function isStaleDeployResponse(res: Response): boolean;
@@ -0,0 +1,7 @@
1
+ export { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
2
+ export { CLIENT_FALLBACK_ROUTER, RouterContext, useRouter } from "./context.ts";
3
+ export { generateHistoryKey, getHistoryKey, isStaleDeployResponse, SCROLL_STORAGE_KEY, saveScrollPosition, } from "./history.ts";
4
+ export { applyRevalidateHeader, buildHref, normalizeHref, normalizePath, shouldAutoRefreshPath, shouldInterceptClick, shouldRefetch, stripHashFromHref, TRAILING_SLASHES_RE, toLogical, } from "./link-utils.ts";
5
+ export { RouterProvider } from "./provider.tsx";
6
+ export { buildDataEndpoint, buildNotFoundPageElement, classifySpaResponse, detectStaticMode, parsePageResponse, pickDeepestNotFound, } from "./spa-response.ts";
7
+ export type { CacheEntry, ClientRoute, ClientSegmentBoundary, LinkProps, LoadedClientRoute, PreloadStrategy, RootBoundaryOptions, RouteManifest, RouterContextValue, RouterProviderProps, RouterState, RouteSearch, RouteTo, SpaResponseKind, } from "./types.ts";
@@ -0,0 +1,51 @@
1
+ import type { CacheEntry } from "./types.ts";
2
+ /** Strips one or more trailing slashes — used by `buildDataEndpoint` in static mode. */
3
+ export declare const TRAILING_SLASHES_RE: RegExp;
4
+ /**
5
+ * Builds a full href string from a pathname, optional search params, and optional hash.
6
+ * Null/undefined search values are omitted.
7
+ *
8
+ * @internal Exported for unit testing only.
9
+ */
10
+ export declare function buildHref(to: string, search: Record<string, unknown> | null | undefined, hash: string | undefined): string;
11
+ /**
12
+ * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
13
+ * each path entry. Header format: `"/path1,/path2:layout,/path3"`
14
+ */
15
+ export declare function applyRevalidateHeader(headers: Headers, invalidate: (path: string, type: "page" | "layout" | undefined) => void): void;
16
+ /**
17
+ * Returns `true` when `currentPath` is targeted by at least one invalidation entry.
18
+ *
19
+ * @internal Exported for unit testing only.
20
+ */
21
+ export declare function shouldAutoRefreshPath(currentPath: string, invalidations: ReadonlyArray<{
22
+ path: string;
23
+ type: "page" | "layout";
24
+ }>): boolean;
25
+ export declare function stripHashFromHref(href: string): string;
26
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
27
+ * Query strings and hashes are preserved and re-attached after normalization. */
28
+ export declare function normalizeHref(href: string): string;
29
+ /** Strips a single trailing slash from a pathname. Root `/` and empty string are preserved. */
30
+ export declare function normalizePath(path: string): string;
31
+ /** @internal Exported for unit testing only. */
32
+ export declare function shouldRefetch(entry: CacheEntry): boolean;
33
+ /**
34
+ * Decides whether a native `<a>` click should be intercepted and converted
35
+ * to an SPA navigation. Returns the logical href to navigate to, or `null`
36
+ * when the browser should handle the click normally.
37
+ *
38
+ * @internal Exported for unit testing only.
39
+ */
40
+ export declare function shouldInterceptClick(anchor: {
41
+ href: string;
42
+ target: string;
43
+ hasAttribute(name: string): boolean;
44
+ }, event: {
45
+ metaKey: boolean;
46
+ ctrlKey: boolean;
47
+ shiftKey: boolean;
48
+ altKey: boolean;
49
+ }, basePath: string, currentOrigin: string, currentPathname: string): string | null;
50
+ /** Strips basePath prefix from a physical pathname, returning the logical path. */
51
+ export declare function toLogical(physicalPathname: string, basePath: string): string;
@@ -0,0 +1,4 @@
1
+ import type React from "react";
2
+ import type { CacheEntry, RouterProviderProps } from "./types.ts";
3
+ export declare function setPrefetchCacheEntry(cache: Map<string, CacheEntry>, href: string, entry: CacheEntry, maxSize: number): void;
4
+ export declare function RouterProvider({ routes, root, initialMatch, initialData, initialDigest, initialNotFound, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
@@ -0,0 +1,58 @@
1
+ import type React from "react";
2
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
3
+ import type { ClientSegmentBoundary, SpaResponseKind } from "./types.ts";
4
+ /**
5
+ * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
6
+ * already-parsed `__FURIN_DATA__` payload.
7
+ *
8
+ * Sentinels (`__furinError`, `__furinStatus`) are trusted over the raw HTTP
9
+ * status — proxies / CDNs sometimes rewrite the status code but pass the body
10
+ * through untouched. A non-2xx response without any sentinel triggers a bail
11
+ * so the browser handles it (could be an error page, redirect, etc.).
12
+ *
13
+ * @internal Exported for unit testing only.
14
+ */
15
+ export declare function classifySpaResponse(status: number, data: Record<string, unknown> | null): SpaResponseKind;
16
+ /**
17
+ * Picks the deepest not-found component declared on the match's boundary chain.
18
+ *
19
+ * @internal Exported for unit testing only.
20
+ */
21
+ export declare function pickDeepestNotFound(boundaries: ClientSegmentBoundary[] | undefined): NotFoundComponent | undefined;
22
+ /**
23
+ * Builds the bare not-found element rendered inline by RouterProvider on SPA
24
+ * navigation when the server signalled a 404.
25
+ *
26
+ * @internal Exported for unit testing only.
27
+ */
28
+ export declare function buildNotFoundPageElement(boundaries: ClientSegmentBoundary[] | undefined, error: {
29
+ data?: unknown;
30
+ message?: string;
31
+ }): React.ReactNode;
32
+ /**
33
+ * Parses the HTML payload of a page response into the pieces `fetchPageState`
34
+ * cares about: the document (for title), the __FURIN_DATA__ loader payload,
35
+ * and the logical `finalHref` after any server-side redirect.
36
+ */
37
+ export declare function parsePageResponse(res: Response, basePath: string): Promise<{
38
+ data: Record<string, unknown> | null;
39
+ finalHref: string | undefined;
40
+ title: string;
41
+ }>;
42
+ /**
43
+ * Builds the URL the SPA navigation flow uses to fetch a route's loader data.
44
+ *
45
+ * Two transports are supported:
46
+ *
47
+ * • **Runtime (SSR/ISR/dev)** — `${basePath}/_furin/data?path=<logicalHref>`.
48
+ * • **Static export** — `${basePath}<logicalPathname>/__furin_data.ndjson`.
49
+ *
50
+ * @internal Exported for unit testing.
51
+ */
52
+ export declare function buildDataEndpoint(basePath: string, logicalHref: string, staticMode: boolean): string;
53
+ /**
54
+ * Reads `<meta name="furin-mode" content="static">` from the document at boot.
55
+ *
56
+ * @internal Exported for unit testing.
57
+ */
58
+ export declare function detectStaticMode(): boolean;
@@ -1,5 +1,7 @@
1
1
  import type React from "react";
2
- import type { RuntimeRoute } from "./client";
2
+ import type { RuntimeRoute } from "../../client.ts";
3
+ import type { ErrorComponent } from "../../shared/error.ts";
4
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
3
5
  /**
4
6
  * Augment this interface via declaration merging in furin-env.d.ts
5
7
  * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
@@ -22,7 +24,7 @@ export interface RouteManifest {
22
24
  * Falls back to `string` when furin-env.d.ts has not been generated yet.
23
25
  * When augmented, also includes `https://` and `http://` for external links.
24
26
  */
25
- export type RouteTo = keyof RouteManifest extends never ? string : keyof RouteManifest | `https://${string}` | `http://${string}`;
27
+ export type RouteTo = keyof RouteManifest extends never ? string : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
26
28
  /**
27
29
  * The typed search params for a given `to` pathname.
28
30
  * Falls back to a permissive record when RouteManifest is not augmented.
@@ -72,42 +74,6 @@ export interface LinkProps<To extends RouteTo = RouteTo> extends Omit<React.Anch
72
74
  search?: RouteSearch<To>;
73
75
  to: To;
74
76
  }
75
- /**
76
- * Builds a full href string from a pathname, optional search params, and optional hash.
77
- * Null/undefined search values are omitted.
78
- *
79
- * @internal Exported for unit testing only.
80
- */
81
- export declare function buildHref(to: string, search?: Record<string, unknown> | null, hash?: string): string;
82
- /**
83
- * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
84
- * each path entry. Header format: `"/path1,/path2:layout,/path3"`
85
- *
86
- * Intended to be called from a `window.fetch` interceptor or SPA navigation
87
- * handler so that client-side prefetch caches are busted automatically whenever
88
- * a server-side `revalidatePath()` call is made within the same request.
89
- *
90
- * @example
91
- * ```ts
92
- * const res = await fetch("/api/publish");
93
- * applyRevalidateHeader(res.headers, (path, type) => {
94
- * console.log("invalidate", path, type);
95
- * });
96
- * ```
97
- */
98
- export declare function applyRevalidateHeader(headers: Headers, invalidate: (path: string, type?: "page" | "layout") => void): void;
99
- /**
100
- * Returns `true` when `currentPath` is targeted by at least one invalidation entry,
101
- * using the same matching rules as `invalidatePrefetch`:
102
- * - `type: 'page'` — exact pathname match (query string stripped)
103
- * - `type: 'layout'` — prefix match: the path itself OR any descendant
104
- *
105
- * @internal Exported for unit testing only.
106
- */
107
- export declare function shouldAutoRefreshPath(currentPath: string, invalidations: ReadonlyArray<{
108
- path: string;
109
- type: "page" | "layout";
110
- }>): boolean;
111
77
  export interface RouterContextValue {
112
78
  /**
113
79
  * Sub-path prefix for static deployments (e.g. "/furin").
@@ -128,7 +94,7 @@ export interface RouterContextValue {
128
94
  * - `type: 'page'` (default) — exact URL match
129
95
  * - `type: 'layout'` — prefix match (path + all nested children)
130
96
  */
131
- invalidatePrefetch: (path: string, type?: "page" | "layout") => void;
97
+ invalidatePrefetch: (path: string, type: "page" | "layout") => void;
132
98
  isNavigating: boolean;
133
99
  navigate: (href: string, opts?: {
134
100
  replace?: boolean;
@@ -143,24 +109,21 @@ export interface RouterContextValue {
143
109
  * resetting scroll (unless `resetScroll: true` is passed).
144
110
  *
145
111
  * Prefer this over `navigate(window.location.pathname)` after a mutation.
146
- *
147
- * @example
148
- * ```tsx
149
- * const { refresh } = useRouter();
150
- * await apiClient.api.boards.post({ name });
151
- * await refresh();
152
- * ```
153
112
  */
154
113
  refresh: (opts?: {
155
114
  resetScroll?: boolean;
156
115
  }) => Promise<void>;
157
116
  }
158
- export declare const RouterContext: React.Context<RouterContextValue | null>;
159
117
  /**
160
- * Returns the current router context.
161
- * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
118
+ * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
119
+ * version this does NOT carry the directory path — it's purely a (depth,
120
+ * fallback) pair because the client never reads files, only renders.
162
121
  */
163
- export declare function useRouter(): RouterContextValue;
122
+ export interface ClientSegmentBoundary {
123
+ depth: number;
124
+ error?: ErrorComponent;
125
+ notFound?: NotFoundComponent;
126
+ }
164
127
  export interface ClientRoute {
165
128
  component?: React.ComponentType<Record<string, unknown>>;
166
129
  load: () => Promise<{
@@ -168,10 +131,18 @@ export interface ClientRoute {
168
131
  component: React.ComponentType<Record<string, unknown>>;
169
132
  _route: RuntimeRoute;
170
133
  };
134
+ segmentBoundaries?: ClientSegmentBoundary[];
171
135
  }>;
172
136
  pageRoute?: RuntimeRoute;
173
137
  pattern: string;
174
138
  regex: RegExp;
139
+ /**
140
+ * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
141
+ * to the route-chain index used on the server side, so `buildPageElement`
142
+ * can interleave boundaries at the exact same positions that the server
143
+ * used in `buildElement` — guaranteeing hydration consistency.
144
+ */
145
+ segmentBoundaries?: ClientSegmentBoundary[];
175
146
  }
176
147
  /**
177
148
  * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
@@ -190,33 +161,73 @@ export interface RouterProviderProps {
190
161
  *
191
162
  * Set to `false` to opt out and call `router.refresh()` manually instead.
192
163
  */
193
- autoRefresh?: boolean;
164
+ autoRefresh: boolean;
194
165
  /**
195
166
  * Sub-path prefix for static deployments (e.g. "/furin").
196
167
  * Must start with "/" and have no trailing slash.
197
168
  * Default: "" (site served from root).
198
- *
199
- * When set:
200
- * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
201
- * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
202
- * - `fetch` calls use the physical path `basePath + logicalHref`.
203
- */
204
- basePath?: string;
205
- defaultPreload?: PreloadStrategy;
206
- defaultPreloadDelay?: number;
207
- defaultPreloadStaleTime?: number;
169
+ */
170
+ basePath: string;
171
+ defaultPreload: PreloadStrategy;
172
+ defaultPreloadDelay: number;
173
+ defaultPreloadStaleTime: number;
208
174
  initialData: Record<string, unknown>;
209
- initialMatch: LoadedClientRoute;
175
+ /**
176
+ * Slice 10 — server-logged error digest threaded from
177
+ * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
178
+ * `FurinErrorBoundary` so that if a client-side error escapes the
179
+ * per-segment boundaries (root layout crash, hydration mismatch, …), the
180
+ * fallback UI surfaces the id a user would find in server logs.
181
+ */
182
+ initialDigest: string | undefined;
183
+ /**
184
+ * The route matched at hydration time. `null` is a valid value ONLY when
185
+ * `initialNotFound` is also provided.
186
+ */
187
+ initialMatch: LoadedClientRoute | null;
188
+ /**
189
+ * When set, the provider boots into the inline not-found state as if a
190
+ * prior SPA navigation hit a 404.
191
+ */
192
+ initialNotFound: {
193
+ data?: unknown;
194
+ message?: string;
195
+ } | undefined;
210
196
  /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
211
- prefetchCacheSize?: number;
197
+ prefetchCacheSize: number;
212
198
  root: RuntimeRoute | null;
213
199
  routes: ClientRoute[];
214
200
  }
215
- interface RouterState {
201
+ /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
202
+ export interface RouterState {
216
203
  data: Record<string, unknown>;
204
+ /**
205
+ * Set when the server's NDJSON payload carried an `__furinError` sentinel.
206
+ */
207
+ error?: {
208
+ digest: string;
209
+ message: string;
210
+ status: number;
211
+ };
217
212
  /** The canonical href after server-side redirects (e.g. query-default redirect). */
218
213
  finalHref?: string;
219
- match: LoadedClientRoute;
214
+ /**
215
+ * The currently rendered route.
216
+ *
217
+ * `null` is a valid value ONLY when `notFound` is also set.
218
+ */
219
+ match: LoadedClientRoute | null;
220
+ /**
221
+ * Slice 8 — set when the matched route's loader threw `notFound()` on the server.
222
+ */
223
+ notFound?: {
224
+ data?: unknown;
225
+ message?: string;
226
+ };
227
+ /**
228
+ * Explicit boundary chain to use for the not-found render.
229
+ */
230
+ notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
220
231
  title?: string;
221
232
  }
222
233
  /** @internal */
@@ -225,21 +236,44 @@ export interface CacheEntry {
225
236
  promise: Promise<RouterState | null>;
226
237
  staleTime: number;
227
238
  }
228
- /** @internal Exported for unit testing only. */
229
- export declare function shouldRefetch(entry: CacheEntry): boolean;
230
- /** @internal Exported for unit testing only. */
231
- export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>): React.ReactNode;
232
- export declare function RouterProvider({ routes, root, initialMatch, initialData, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
233
239
  /**
234
- * SSR-aware Link component.
240
+ * Classification of a fetch response during SPA navigation. Returned by the
241
+ * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
235
242
  *
236
- * - **Server (SSR):** uses `RouterContext.Consumer` (a render-prop, not a hook)
237
- * to read basePath / currentHref from any enclosing RouterProvider, then
238
- * falls back to `SSR_FALLBACK_ROUTER` when no provider is present.
239
- * `Context.Consumer` bypasses `ReactCurrentDispatcher` entirely, so it is
240
- * safe even when two React instances coexist in the module graph (Bun HMR).
241
- * - **Client:** delegates to `LinkInteractive` which adds preloading, SPA
242
- * navigation, active-state tracking and all other interactive features.
243
+ * - `ok` — 2xx response with usable loader data; render normally.
244
+ * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
245
+ * - `error` — server signalled `__FURIN_DATA__.__furinError`.
246
+ * - `bail` — any other non-2xx without sentinels.
247
+ *
248
+ * @internal Exported for unit testing only.
243
249
  */
244
- export declare function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactElement;
245
- export {};
250
+ export type SpaResponseKind = {
251
+ kind: "ok";
252
+ } | {
253
+ kind: "not-found";
254
+ error: {
255
+ data?: unknown;
256
+ message?: string;
257
+ };
258
+ } | {
259
+ kind: "error";
260
+ error: {
261
+ digest: string;
262
+ message: string;
263
+ status: number;
264
+ };
265
+ } | {
266
+ kind: "bail";
267
+ };
268
+ /**
269
+ * Root-level safety-net options forwarded onto the outermost
270
+ * `FurinErrorBoundary` that wraps the entire RouterProvider tree.
271
+ */
272
+ export interface RootBoundaryOptions {
273
+ /**
274
+ * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
275
+ */
276
+ digest?: string;
277
+ onReset?: () => void;
278
+ resetKey?: string | number;
279
+ }
@@ -0,0 +1,12 @@
1
+ export interface FurinServerErrorPayload {
2
+ digest: string;
3
+ message: string;
4
+ status: number;
5
+ }
6
+ export declare class FurinServerError extends Error {
7
+ readonly __furinBrand: "FURIN_SERVER_ERROR";
8
+ readonly digest: string;
9
+ readonly status: number;
10
+ constructor(args: FurinServerErrorPayload);
11
+ }
12
+ export declare function isFurinServerError(err: unknown): err is FurinServerError;
package/dist/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Cookie, StatusMap } from "elysia";
2
2
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
3
3
  import type { RequestLogger } from "evlog";
4
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
4
5
  declare const UNSET: unique symbol;
5
6
  type Unset = typeof UNSET;
6
7
  type ToRecord<T> = {
@@ -13,9 +14,15 @@ type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
13
14
  * Transforms each key of a parent-data record into an individual `Promise<T>`.
14
15
  * This is what child loaders see for inherited fields — direct values from
15
16
  * `RouteContext` (request, params, set, …) remain unchanged.
17
+ *
18
+ * `Awaited<T[K]>` mirrors the JS Promise-chaining auto-flatten used by
19
+ * `createLoaderCtx`: when an ancestor wrapped a field with `defer()` (so the
20
+ * raw value is itself a `Promise<U>`), the type collapses to `Promise<U>`
21
+ * instead of `Promise<Promise<U>>`. Otherwise TypeScript would force a
22
+ * redundant `await await ctx.field` dance.
16
23
  */
17
24
  type PromisifyData<T extends Record<string, unknown>> = {
18
- [K in keyof T]: Promise<T[K]>;
25
+ [K in keyof T]: Promise<Awaited<T[K]>>;
19
26
  };
20
27
  export interface RouteContext<TParams = {}, TQuery = {}> {
21
28
  cookie: Record<string, Cookie<unknown>>;
@@ -47,7 +54,7 @@ type ResolveParent<T> = T extends RouteRef<infer D, infer P, infer Q> ? {
47
54
  query: Unset;
48
55
  };
49
56
  interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
50
- data: ToRecord<ResolveParent<TParentRef>["data"] & TLoaderData>;
57
+ data: ToRecord<ResolveParent<TParentRef>["data"] & Omit<TLoaderData, "__isDeferred">>;
51
58
  params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
52
59
  query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
53
60
  }
@@ -100,12 +107,13 @@ export interface HeadOptions {
100
107
  children: string;
101
108
  }>;
102
109
  }
103
- type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown ? Awaited<ReturnType<TLoader>> extends object ? ToRecord<Awaited<ReturnType<TLoader>>> : {} : {};
110
+ type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown ? Awaited<ReturnType<TLoader>> extends object ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">> : {} : {};
104
111
  export interface PageConfig<TParentData extends Record<string, unknown>, TParams, TQuery, TPageLoaderData extends object = {}> {
105
112
  component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
106
113
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
107
114
  loader?: (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => Promise<TPageLoaderData> | TPageLoaderData;
108
115
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
116
+ tags?: string[];
109
117
  }
110
118
  export interface RuntimeRoute {
111
119
  __type: "FURIN_ROUTE";
@@ -118,6 +126,7 @@ export interface RuntimeRoute {
118
126
  parent?: RuntimeRoute;
119
127
  query?: unknown;
120
128
  revalidate?: number;
129
+ tags?: string[];
121
130
  }
122
131
  export interface RuntimePage {
123
132
  __type: "FURIN_PAGE";
@@ -126,6 +135,7 @@ export interface RuntimePage {
126
135
  head?(ctx: Record<string, unknown>): HeadOptions;
127
136
  loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
128
137
  staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
138
+ tags?: string[];
129
139
  }
130
140
  export interface RouteRef<TData extends Record<string, unknown> = Record<string, unknown>, TParams = unknown, TQuery = unknown> {
131
141
  readonly __brand: "FURIN_ROUTE_REF";
@@ -141,6 +151,7 @@ interface PageResult<TData extends Record<string, unknown>, TParams, TQuery, TPa
141
151
  component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
142
152
  head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
143
153
  loader?: (ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>) => Promise<TPageLoaderData> | TPageLoaderData;
154
+ tags?: string[];
144
155
  }
145
156
  export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
146
157
  __type: "FURIN_ROUTE";
@@ -154,6 +165,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
154
165
  mode?: "ssr" | "ssg" | "isr";
155
166
  revalidate?: number;
156
167
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
168
+ tags?: string[];
157
169
  component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
158
170
  head?: (ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>) => HeadOptions;
159
171
  }): PageResult<TParentData, TParams, TQuery, TPageLoaderData>;
@@ -161,6 +173,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
161
173
  mode?: "ssr" | "ssg" | "isr";
162
174
  revalidate?: number;
163
175
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
176
+ tags?: string[];
164
177
  component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
165
178
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
166
179
  }): PageResult<TParentData, TParams, TQuery, {}>;
@@ -170,6 +183,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
170
183
  /** Branded ref for type inference when used as a parent. */
171
184
  ref: RouteRef<TParentData, TParams, TQuery>;
172
185
  revalidate?: number;
186
+ tags?: string[];
173
187
  }
174
188
  export declare function createRoute<TParentRef extends RouteRef | undefined = undefined, TParamsSchema extends AnySchema | Unset = Unset, TQuerySchema extends AnySchema | Unset = Unset, TLoaderData extends object = {}>(config?: {
175
189
  parent?: {
@@ -181,6 +195,7 @@ export declare function createRoute<TParentRef extends RouteRef | undefined = un
181
195
  revalidate?: number;
182
196
  params?: TParamsSchema;
183
197
  query?: TQuerySchema;
198
+ tags?: string[];
184
199
  loader?: (ctx: RouteContext<Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"], Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]> & PromisifyData<ResolveParent<TParentRef>["data"]>) => Promise<TLoaderData> | TLoaderData;
185
200
  layout?: React.FC<Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
186
201
  children: React.ReactNode;
@@ -192,4 +207,36 @@ export type InferProps<T> = T extends {
192
207
  } ? P : T extends Route<infer D, infer P, infer Q> ? D & {
193
208
  children: React.ReactNode;
194
209
  } & ComponentProps<P, Q> : never;
195
- export {};
210
+ /**
211
+ * Brand key that marks an object as deferred. Using a `const` string avoids
212
+ * a `unique symbol` that would complicate cross-module inference.
213
+ */
214
+ declare const DEFERRED_BRAND: "__isDeferred";
215
+ /**
216
+ * A loader return value that contains a mix of synchronous scalar fields and
217
+ * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
218
+ * shell; Promise fields are streamed as late `<script>` resolution chunks.
219
+ *
220
+ * @example
221
+ * loader: () => defer({
222
+ * title: "My Board", // synchronous — available immediately
223
+ * stats: fetchStats(), // Promise — streamed when it resolves
224
+ * })
225
+ */
226
+ export type DeferredData<T extends Record<string, unknown>> = T & {
227
+ readonly [DEFERRED_BRAND]: true;
228
+ };
229
+ /**
230
+ * Wraps loader data so that Promise-valued fields are streamed lazily while
231
+ * scalar fields are embedded in the initial HTML shell immediately.
232
+ *
233
+ * Use in any loader — page (`route.page({ loader })`) or route/layout
234
+ * (`createRoute({ loader })`). Promise-valued fields are streamed lazily;
235
+ * scalar fields are embedded in the initial HTML shell.
236
+ */
237
+ export declare function defer<T extends Record<string, unknown>>(data: T): DeferredData<T>;
238
+ /**
239
+ * Type guard for DeferredData. Used by the render pipeline to distinguish a
240
+ * plain loader return from a deferred one.
241
+ */
242
+ export declare function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>>;