@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.15
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.
- package/README.md +14 -232
- package/dist/auto-invalidate/index.d.ts +4 -0
- package/dist/auto-invalidate/plugin.d.ts +38 -0
- package/dist/auto-invalidate/registry.d.ts +9 -0
- package/dist/auto-invalidate/runtime.d.ts +9 -0
- package/dist/auto-invalidate/types.d.ts +12 -0
- package/dist/await.d.ts +67 -0
- package/dist/build/index.js +2095 -185
- package/dist/cli/index.js +2070 -182
- package/dist/client.d.ts +51 -4
- package/dist/client.js +65 -1
- package/dist/deferred-ndjson.d.ts +32 -0
- package/dist/error.d.ts +14 -0
- package/dist/furin.d.ts +8 -0
- package/dist/furin.js +2927 -319
- package/dist/lang-detect.d.ts +5 -0
- package/dist/link.d.ts +1 -0
- package/dist/link.js +1453 -95
- package/dist/plugin/index.js +96 -25
- package/dist/plugin/transform-client.d.ts +2 -1
- package/dist/render/assemble.d.ts +32 -0
- package/dist/render/cache.d.ts +7 -0
- package/dist/render/element.d.ts +17 -1
- package/dist/render/index.d.ts +10 -1
- package/dist/render/index.ts +250 -44
- package/dist/render/loaders.d.ts +46 -3
- package/dist/render/shell.d.ts +16 -6
- package/dist/render/shell.ts +27 -12
- package/dist/router-provider.d.ts +86 -18
- package/dist/router.d.ts +66 -0
- package/dist/router.js +2909 -374
- package/dist/router.ts +586 -54
- package/dist/server-error.d.ts +12 -0
- package/dist/utils.d.ts +7 -0
- package/package.json +8 -7
- package/src/adapter/bun.ts +3 -3
- package/src/adapter/static.ts +73 -31
- package/src/auto-invalidate/index.ts +10 -0
- package/src/auto-invalidate/plugin.ts +25 -0
- package/src/auto-invalidate/registry.ts +60 -0
- package/src/auto-invalidate/runtime.ts +133 -0
- package/src/auto-invalidate/types.ts +16 -0
- package/src/await.tsx +175 -0
- package/src/build/client.ts +4 -8
- package/src/build/hydrate.ts +67 -1
- package/src/build/route-types.ts +29 -3
- package/src/build/scan-server.ts +6 -23
- package/src/client.ts +80 -3
- package/src/deferred-ndjson.ts +212 -0
- package/src/dev-page-plugin.ts +2 -0
- package/src/error.ts +18 -1
- package/src/furin.ts +19 -2
- package/src/lang-detect.ts +46 -0
- package/src/link.tsx +16 -3
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +108 -39
- package/src/render/assemble.ts +67 -0
- package/src/render/boundaries.tsx +23 -5
- package/src/render/cache.ts +14 -0
- package/src/render/default-screens.tsx +4 -11
- package/src/render/dev-cache.ts +5 -0
- package/src/render/element.tsx +26 -3
- package/src/render/index.ts +250 -44
- package/src/render/loaders.ts +219 -18
- package/src/render/shell.ts +27 -12
- package/src/router-provider.tsx +414 -122
- package/src/router.ts +586 -54
- package/src/server-error.ts +47 -0
- package/src/utils.ts +31 -0
package/src/build/client.ts
CHANGED
|
@@ -7,7 +7,6 @@ import { CLIENT_MODULE_PATH, LINK_MODULE_PATH } from "./shared";
|
|
|
7
7
|
import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
|
|
8
8
|
|
|
9
9
|
const TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
10
|
-
const REACT_IMPORT_RE = /import\s+React\b/;
|
|
11
10
|
|
|
12
11
|
export interface BuildClientResult {
|
|
13
12
|
/** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
|
|
@@ -63,13 +62,10 @@ export async function buildClient(
|
|
|
63
62
|
const code = await Bun.file(path).text();
|
|
64
63
|
try {
|
|
65
64
|
const result = transformForClient(code, path);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
transformed = transformed
|
|
65
|
+
// transformForClient now emits TS/TSX directly (no pre-transpile),
|
|
66
|
+
// so JSX → React handling is delegated to Bun.build's loader, which
|
|
67
|
+
// applies the project tsconfig's automatic runtime by default.
|
|
68
|
+
const transformed = result.code
|
|
73
69
|
.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
|
|
74
70
|
.replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
|
|
75
71
|
.replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
|
package/src/build/hydrate.ts
CHANGED
|
@@ -107,6 +107,8 @@ import { createElement } from "react";
|
|
|
107
107
|
import { initLogger, log } from "evlog";
|
|
108
108
|
import { createHttpLogDrain } from "evlog/http";
|
|
109
109
|
import { RouterProvider } from "@teyik0/furin/link";
|
|
110
|
+
import { fromCrossJSON } from "@teyik0/furin/link";
|
|
111
|
+
import type { SerovalNode } from "seroval";
|
|
110
112
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
|
|
111
113
|
|
|
112
114
|
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
@@ -127,6 +129,70 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
127
129
|
// former does not — so the two cases fork on _match below.
|
|
128
130
|
const dataEl = document.getElementById("__FURIN_DATA__");
|
|
129
131
|
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
132
|
+
|
|
133
|
+
// ── Deferred data hydration ─────────────────────────────────────────────────
|
|
134
|
+
// window.__FURIN_DEFERRED__ is injected by the server when a loader returns
|
|
135
|
+
// defer(). It carries:
|
|
136
|
+
// - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
|
|
137
|
+
// We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
|
|
138
|
+
// components receive a proper resolved Promise instead of the raw CrossJSON node.
|
|
139
|
+
// Sync loader fields live exclusively in __FURIN_DATA__ (read above).
|
|
140
|
+
interface FurinDeferredRegistry {
|
|
141
|
+
_chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
|
|
142
|
+
_deferredKeys: string[];
|
|
143
|
+
_resolvers: Record<string, {
|
|
144
|
+
promise: Promise<unknown>;
|
|
145
|
+
reject: (reason: unknown) => void;
|
|
146
|
+
resolve: (value: unknown) => void;
|
|
147
|
+
}>;
|
|
148
|
+
getPromise: (key: string) => Promise<unknown>;
|
|
149
|
+
reject: (key: string, chunk: SerovalNode) => void;
|
|
150
|
+
resolve: (key: string, chunk: SerovalNode) => void;
|
|
151
|
+
}
|
|
152
|
+
const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
|
|
153
|
+
.__FURIN_DEFERRED__;
|
|
154
|
+
const deferredData: Record<string, Promise<unknown>> = {};
|
|
155
|
+
if (__deferred && __deferred._chunks) {
|
|
156
|
+
// Patch resolve/reject so any chunks that arrive AFTER this entry has run
|
|
157
|
+
// settle immediately. The previous version stored late chunks in _chunks
|
|
158
|
+
// when no resolver was registered yet, but the drain loop below only runs
|
|
159
|
+
// ONCE at hydrate time — so any chunk landing after the drain would stay
|
|
160
|
+
// orphaned and the corresponding Await would hang forever. Eagerly creating
|
|
161
|
+
// the resolver via getPromise() fixes the race.
|
|
162
|
+
__deferred.resolve = (key: string, chunk: SerovalNode) => {
|
|
163
|
+
__deferred.getPromise(key);
|
|
164
|
+
__deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
|
|
165
|
+
};
|
|
166
|
+
__deferred.reject = (key: string, chunk: SerovalNode) => {
|
|
167
|
+
__deferred.getPromise(key);
|
|
168
|
+
__deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
|
|
169
|
+
};
|
|
170
|
+
for (const key of Object.keys(__deferred._chunks)) {
|
|
171
|
+
const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
|
|
172
|
+
const p = __deferred.getPromise(key) as Promise<unknown>;
|
|
173
|
+
const resolver = __deferred._resolvers[key];
|
|
174
|
+
const value = fromCrossJSON(entry.v, {});
|
|
175
|
+
if (entry.a === 0) {
|
|
176
|
+
resolver.resolve(value);
|
|
177
|
+
} else {
|
|
178
|
+
resolver.reject(value);
|
|
179
|
+
}
|
|
180
|
+
deferredData[key] = p;
|
|
181
|
+
}
|
|
182
|
+
for (const key of __deferred._deferredKeys ?? []) {
|
|
183
|
+
if (!(key in deferredData)) {
|
|
184
|
+
deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// Keys that have a resolver (getPromise was called by <Await>) but no
|
|
188
|
+
// chunk yet (the late <script> hasn't arrived) still need a Promise entry
|
|
189
|
+
// so the hydration data record is complete.
|
|
190
|
+
for (const key of Object.keys(__deferred._resolvers ?? {})) {
|
|
191
|
+
if (!(key in deferredData)) {
|
|
192
|
+
deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
130
196
|
const rootEl = document.getElementById("root") as HTMLElement;
|
|
131
197
|
|
|
132
198
|
// Eagerly load only the current page module for initial hydration.
|
|
@@ -145,7 +211,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
|
|
|
145
211
|
routes,
|
|
146
212
|
root,
|
|
147
213
|
initialMatch: match,
|
|
148
|
-
initialData: loaderData,
|
|
214
|
+
initialData: { ...loaderData, ...deferredData },
|
|
149
215
|
initialDigest: loaderData.__furinError?.digest,
|
|
150
216
|
initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
|
|
151
217
|
} as any);
|
package/src/build/route-types.ts
CHANGED
|
@@ -22,7 +22,11 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
22
22
|
}
|
|
23
23
|
const s = schema as Record<string, unknown>;
|
|
24
24
|
if (s.anyOf && Array.isArray(s.anyOf)) {
|
|
25
|
-
const parts =
|
|
25
|
+
const parts: string[] = [];
|
|
26
|
+
for (const item of s.anyOf as unknown[]) {
|
|
27
|
+
const t = schemaToTypeString(item);
|
|
28
|
+
if (t !== "null") parts.push(t);
|
|
29
|
+
}
|
|
26
30
|
return parts.join(" | ") || "unknown";
|
|
27
31
|
}
|
|
28
32
|
switch (s.type) {
|
|
@@ -50,6 +54,19 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
50
54
|
}
|
|
51
55
|
}
|
|
52
56
|
|
|
57
|
+
function tagKeyToPropertyName(tag: string): string {
|
|
58
|
+
return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function tagToStringLiteral(tag: string): string {
|
|
62
|
+
// Use JSON.stringify for robust escaping of control chars, unicode
|
|
63
|
+
// separators, backslashes and quotes, then convert double quotes to single.
|
|
64
|
+
const json = JSON.stringify(tag);
|
|
65
|
+
// json is double-quoted; convert to single-quoted literal by escaping
|
|
66
|
+
// any contained single quotes and swapping the outer quotes.
|
|
67
|
+
return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
|
|
68
|
+
}
|
|
69
|
+
|
|
53
70
|
/**
|
|
54
71
|
* Generates furin-env.d.ts at the project root — augments RouteManifest
|
|
55
72
|
* in furin/link so that <Link to="..."> has type-safe autocompletion and
|
|
@@ -60,7 +77,8 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
60
77
|
*/
|
|
61
78
|
/** @internal Exported for unit testing only. */
|
|
62
79
|
export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): void {
|
|
63
|
-
const
|
|
80
|
+
const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
|
|
81
|
+
const entries = sortedRoutes.map((r) => {
|
|
64
82
|
const typeKey = patternToTypeString(r.pattern);
|
|
65
83
|
const isDynamic = typeKey.startsWith("`");
|
|
66
84
|
const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
|
|
@@ -70,6 +88,14 @@ export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): v
|
|
|
70
88
|
: ` ${typeKey}: { search?: ${searchType} }`;
|
|
71
89
|
});
|
|
72
90
|
|
|
91
|
+
const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
|
|
92
|
+
const tagBlock =
|
|
93
|
+
sortedTags.length > 0
|
|
94
|
+
? `\n\ndeclare module "@teyik0/furin" {\n interface FurinCacheTags {\n${sortedTags
|
|
95
|
+
.map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`)
|
|
96
|
+
.join("\n")}\n }\n}`
|
|
97
|
+
: "";
|
|
98
|
+
|
|
73
99
|
const content = `// Auto-generated by Furin. Do not edit manually.
|
|
74
100
|
/// <reference types="@teyik0/furin/env" />
|
|
75
101
|
import "@teyik0/furin/link";
|
|
@@ -78,7 +104,7 @@ declare module "@teyik0/furin/link" {
|
|
|
78
104
|
interface RouteManifest {
|
|
79
105
|
${entries.join(";\n")};
|
|
80
106
|
}
|
|
81
|
-
}
|
|
107
|
+
}${tagBlock}
|
|
82
108
|
`;
|
|
83
109
|
|
|
84
110
|
const typesPath = join(projectRoot, "furin-env.d.ts");
|
package/src/build/scan-server.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { parse } from "yuku-parser";
|
|
3
|
+
import { detectLangFromPath, unwrapTSExpression } from "../lang-detect";
|
|
3
4
|
|
|
4
5
|
// Minimal AST node shapes — just what we need
|
|
5
6
|
interface AstNode {
|
|
@@ -7,19 +8,6 @@ interface AstNode {
|
|
|
7
8
|
[key: string]: unknown;
|
|
8
9
|
}
|
|
9
10
|
|
|
10
|
-
function detectLangFromPath(filePath: string): "js" | "ts" | "jsx" | "tsx" | "dts" {
|
|
11
|
-
if (filePath.endsWith(".d.ts")) {
|
|
12
|
-
return "dts";
|
|
13
|
-
}
|
|
14
|
-
const ext = filePath.split(".").pop()?.toLowerCase();
|
|
15
|
-
switch (ext) {
|
|
16
|
-
case "ts": return "ts";
|
|
17
|
-
case "tsx": return "tsx";
|
|
18
|
-
case "jsx": return "jsx";
|
|
19
|
-
default: return "js";
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
11
|
/**
|
|
24
12
|
* Statically scans a server entry file and returns all `pagesDir` string
|
|
25
13
|
* literal values found inside `furin({ pagesDir: "..." })` call expressions.
|
|
@@ -29,21 +17,14 @@ function detectLangFromPath(filePath: string): "js" | "ts" | "jsx" | "tsx" | "dt
|
|
|
29
17
|
*/
|
|
30
18
|
export function scanFurinInstances(serverEntryPath: string): string[] {
|
|
31
19
|
const code = readFileSync(serverEntryPath, "utf8");
|
|
32
|
-
|
|
20
|
+
const lang = detectLangFromPath(serverEntryPath);
|
|
33
21
|
|
|
34
22
|
// Declaration files contain no runtime code — skip parsing.
|
|
35
23
|
if (lang === "dts") {
|
|
36
24
|
return [];
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
|
|
40
|
-
if (lang === "ts" || lang === "tsx") {
|
|
41
|
-
const transpiler = new Bun.Transpiler({ loader: lang });
|
|
42
|
-
parseInput = transpiler.transformSync(code);
|
|
43
|
-
lang = "js";
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const { program, diagnostics } = parse(parseInput, { sourceType: "module", lang });
|
|
27
|
+
const { program, diagnostics } = parse(code, { sourceType: "module", lang });
|
|
47
28
|
const firstError = diagnostics.find((d) => d.severity === "error");
|
|
48
29
|
if (firstError) {
|
|
49
30
|
console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
|
|
@@ -68,7 +49,9 @@ function checkFurinCall(node: AstNode, out: string[]): void {
|
|
|
68
49
|
return;
|
|
69
50
|
}
|
|
70
51
|
|
|
71
|
-
|
|
52
|
+
// Unwrap TS expression wrappers like `furin({...} as Config)` or
|
|
53
|
+
// `furin({...} satisfies Options)` so we still see the ObjectExpression.
|
|
54
|
+
const firstArg = unwrapTSExpression(args[0] as AstNode);
|
|
72
55
|
if (firstArg?.type !== "ObjectExpression") {
|
|
73
56
|
return;
|
|
74
57
|
}
|
package/src/client.ts
CHANGED
|
@@ -11,6 +11,9 @@ import type { Cookie, StatusMap } from "elysia";
|
|
|
11
11
|
import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
|
|
12
12
|
import type { RequestLogger } from "evlog";
|
|
13
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 "./await.tsx";
|
|
16
|
+
|
|
14
17
|
declare const UNSET: unique symbol;
|
|
15
18
|
type Unset = typeof UNSET;
|
|
16
19
|
|
|
@@ -36,9 +39,15 @@ type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
|
|
|
36
39
|
* Transforms each key of a parent-data record into an individual `Promise<T>`.
|
|
37
40
|
* This is what child loaders see for inherited fields — direct values from
|
|
38
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.
|
|
39
48
|
*/
|
|
40
49
|
type PromisifyData<T extends Record<string, unknown>> = {
|
|
41
|
-
[K in keyof T]: Promise<T[K]
|
|
50
|
+
[K in keyof T]: Promise<Awaited<T[K]>>;
|
|
42
51
|
};
|
|
43
52
|
|
|
44
53
|
export interface RouteContext<TParams = {}, TQuery = {}> {
|
|
@@ -69,7 +78,11 @@ type ResolveParent<T> =
|
|
|
69
78
|
: { data: {}; params: Unset; query: Unset };
|
|
70
79
|
|
|
71
80
|
interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
|
|
72
|
-
|
|
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">>;
|
|
73
86
|
params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
|
|
74
87
|
query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
|
|
75
88
|
}
|
|
@@ -110,9 +123,12 @@ export interface HeadOptions {
|
|
|
110
123
|
// Extracts the resolved return type from a loader function type.
|
|
111
124
|
// Using ReturnType + Awaited here means TLoader is inferred as the whole function
|
|
112
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.
|
|
113
129
|
type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown
|
|
114
130
|
? Awaited<ReturnType<TLoader>> extends object
|
|
115
|
-
? ToRecord<Awaited<ReturnType<TLoader
|
|
131
|
+
? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">>
|
|
116
132
|
: {}
|
|
117
133
|
: {};
|
|
118
134
|
|
|
@@ -128,6 +144,7 @@ export interface PageConfig<
|
|
|
128
144
|
ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
|
|
129
145
|
) => Promise<TPageLoaderData> | TPageLoaderData;
|
|
130
146
|
staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
|
|
147
|
+
tags?: string[];
|
|
131
148
|
}
|
|
132
149
|
|
|
133
150
|
export interface RuntimeRoute {
|
|
@@ -139,6 +156,7 @@ export interface RuntimeRoute {
|
|
|
139
156
|
parent?: RuntimeRoute;
|
|
140
157
|
query?: unknown;
|
|
141
158
|
revalidate?: number;
|
|
159
|
+
tags?: string[];
|
|
142
160
|
}
|
|
143
161
|
|
|
144
162
|
export interface RuntimePage {
|
|
@@ -148,6 +166,7 @@ export interface RuntimePage {
|
|
|
148
166
|
head?(ctx: Record<string, unknown>): HeadOptions;
|
|
149
167
|
loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
|
|
150
168
|
staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
|
|
169
|
+
tags?: string[];
|
|
151
170
|
}
|
|
152
171
|
|
|
153
172
|
export interface RouteRef<
|
|
@@ -172,6 +191,7 @@ interface PageResult<
|
|
|
172
191
|
loader?: (
|
|
173
192
|
ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
|
|
174
193
|
) => Promise<TPageLoaderData> | TPageLoaderData;
|
|
194
|
+
tags?: string[];
|
|
175
195
|
}
|
|
176
196
|
|
|
177
197
|
export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
|
|
@@ -194,6 +214,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
|
|
|
194
214
|
mode?: "ssr" | "ssg" | "isr";
|
|
195
215
|
revalidate?: number;
|
|
196
216
|
staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
|
|
217
|
+
tags?: string[];
|
|
197
218
|
component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
|
|
198
219
|
head?: (
|
|
199
220
|
ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>
|
|
@@ -205,6 +226,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
|
|
|
205
226
|
mode?: "ssr" | "ssg" | "isr";
|
|
206
227
|
revalidate?: number;
|
|
207
228
|
staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
|
|
229
|
+
tags?: string[];
|
|
208
230
|
component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
|
|
209
231
|
head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
|
|
210
232
|
}): PageResult<TParentData, TParams, TQuery, {}>;
|
|
@@ -216,6 +238,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
|
|
|
216
238
|
/** Branded ref for type inference when used as a parent. */
|
|
217
239
|
ref: RouteRef<TParentData, TParams, TQuery>;
|
|
218
240
|
revalidate?: number;
|
|
241
|
+
tags?: string[];
|
|
219
242
|
}
|
|
220
243
|
|
|
221
244
|
export function createRoute<
|
|
@@ -229,6 +252,7 @@ export function createRoute<
|
|
|
229
252
|
revalidate?: number;
|
|
230
253
|
params?: TParamsSchema;
|
|
231
254
|
query?: TQuerySchema;
|
|
255
|
+
tags?: string[];
|
|
232
256
|
loader?: (
|
|
233
257
|
ctx: RouteContext<
|
|
234
258
|
Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
|
|
@@ -276,3 +300,56 @@ export type InferProps<T> = T extends {
|
|
|
276
300
|
: T extends Route<infer D, infer P, infer Q>
|
|
277
301
|
? D & { children: React.ReactNode } & ComponentProps<P, Q>
|
|
278
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
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import type { SerovalNode } from "seroval";
|
|
2
|
+
import { fromCrossJSON } from "seroval";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Result returned by `parseDeferredNdjson`.
|
|
6
|
+
*/
|
|
7
|
+
export interface DeferredNdjsonResult {
|
|
8
|
+
/**
|
|
9
|
+
* Deferred promises keyed by their field name. Each Promise resolves (or
|
|
10
|
+
* rejects) once the corresponding data is available. In the SSR case the
|
|
11
|
+
* promises are already settled (serialised by `toCrossJSONAsync`). For
|
|
12
|
+
* streaming endpoints they will settle as the server flushes resolution
|
|
13
|
+
* chunks.
|
|
14
|
+
*/
|
|
15
|
+
deferredPromises: Record<string, Promise<unknown>>;
|
|
16
|
+
/** Scalar/sync values from the loader — available immediately. */
|
|
17
|
+
syncData: Record<string, unknown>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function makeAbortError(reason: unknown): Error {
|
|
21
|
+
const message =
|
|
22
|
+
reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
|
|
23
|
+
const err = new Error(message);
|
|
24
|
+
err.name = "AbortError";
|
|
25
|
+
return err;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Parses an NDJSON stream produced by `/_furin/data`.
|
|
30
|
+
*
|
|
31
|
+
* Protocol (v1 — single-line, all-resolved):
|
|
32
|
+
* Line 0 — `JSON.stringify(await toCrossJSONAsync(loaderData))`
|
|
33
|
+
*
|
|
34
|
+
* The CrossJSON node is deserialised with `fromCrossJSON`. Values that are
|
|
35
|
+
* Promises (seroval type 12) land in `deferredPromises`; everything else
|
|
36
|
+
* lands in `syncData`.
|
|
37
|
+
*
|
|
38
|
+
* @param stream - A `ReadableStream<Uint8Array>` from `fetch().body`.
|
|
39
|
+
* @param signal - AbortSignal that, when aborted, cancels the reader and
|
|
40
|
+
* rejects every still-pending deferred promise with an
|
|
41
|
+
* `AbortError`. Pass `undefined` to opt out (no implicit
|
|
42
|
+
* default — see CLAUDE.md).
|
|
43
|
+
*/
|
|
44
|
+
export async function parseDeferredNdjson(
|
|
45
|
+
stream: ReadableStream<Uint8Array>,
|
|
46
|
+
signal: AbortSignal | undefined
|
|
47
|
+
): Promise<DeferredNdjsonResult> {
|
|
48
|
+
const reader = stream.getReader();
|
|
49
|
+
const decoder = new TextDecoder();
|
|
50
|
+
let buffer = "";
|
|
51
|
+
|
|
52
|
+
async function readLine(): Promise<string | undefined> {
|
|
53
|
+
for (;;) {
|
|
54
|
+
// react-doctor-disable-next-line react-doctor/js-set-map-lookups
|
|
55
|
+
const newlineIndex = buffer.indexOf("\n");
|
|
56
|
+
if (newlineIndex >= 0) {
|
|
57
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
58
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
59
|
+
if (line.length > 0) {
|
|
60
|
+
return line;
|
|
61
|
+
}
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const { done, value } = await reader.read();
|
|
66
|
+
if (done) {
|
|
67
|
+
buffer += decoder.decode();
|
|
68
|
+
const line = buffer.trim();
|
|
69
|
+
buffer = "";
|
|
70
|
+
return line.length > 0 ? line : undefined;
|
|
71
|
+
}
|
|
72
|
+
buffer += decoder.decode(value, { stream: true });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const firstLine = await readLine();
|
|
77
|
+
if (!firstLine) {
|
|
78
|
+
try {
|
|
79
|
+
reader.releaseLock();
|
|
80
|
+
} catch {
|
|
81
|
+
/* already released */
|
|
82
|
+
}
|
|
83
|
+
return { syncData: {}, deferredPromises: {} };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const node = JSON.parse(firstLine) as SerovalNode;
|
|
87
|
+
const deserialized = fromCrossJSON(node, {}) as Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
const syncData: Record<string, unknown> = {};
|
|
90
|
+
const deferredPromises: Record<string, Promise<unknown>> = {};
|
|
91
|
+
const resolvers: Record<
|
|
92
|
+
string,
|
|
93
|
+
{ reject: (reason: unknown) => void; resolve: (value: unknown) => void }
|
|
94
|
+
> = {};
|
|
95
|
+
const deferredKeys = Array.isArray(deserialized.__furinDeferredKeys)
|
|
96
|
+
? (deserialized.__furinDeferredKeys.filter((key) => typeof key === "string") as string[])
|
|
97
|
+
: [];
|
|
98
|
+
|
|
99
|
+
for (const [key, value] of Object.entries(deserialized)) {
|
|
100
|
+
if (key === "__furinDeferredKeys") {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (value instanceof Promise) {
|
|
104
|
+
deferredPromises[key] = value;
|
|
105
|
+
} else {
|
|
106
|
+
syncData[key] = value;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for (const key of deferredKeys) {
|
|
111
|
+
if (!(key in deferredPromises)) {
|
|
112
|
+
deferredPromises[key] = new Promise((resolve, reject) => {
|
|
113
|
+
resolvers[key] = { resolve, reject };
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (deferredKeys.length === 0) {
|
|
119
|
+
try {
|
|
120
|
+
reader.releaseLock();
|
|
121
|
+
} catch {
|
|
122
|
+
/* already released */
|
|
123
|
+
}
|
|
124
|
+
return { syncData, deferredPromises };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Reject every still-pending resolver and cancel the underlying reader. Used
|
|
128
|
+
// both by the AbortSignal listener and by the readDeferredLines error path.
|
|
129
|
+
const rejectAllPending = (reason: unknown): void => {
|
|
130
|
+
for (const key of Object.keys(resolvers)) {
|
|
131
|
+
resolvers[key]?.reject(reason);
|
|
132
|
+
delete resolvers[key];
|
|
133
|
+
}
|
|
134
|
+
reader.cancel(reason).catch(() => {
|
|
135
|
+
/* reader may already be closed */
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
if (signal !== undefined) {
|
|
140
|
+
if (signal.aborted) {
|
|
141
|
+
rejectAllPending(makeAbortError(signal.reason));
|
|
142
|
+
return { syncData, deferredPromises };
|
|
143
|
+
}
|
|
144
|
+
signal.addEventListener(
|
|
145
|
+
"abort",
|
|
146
|
+
() => {
|
|
147
|
+
rejectAllPending(makeAbortError(signal.reason));
|
|
148
|
+
},
|
|
149
|
+
{ once: true }
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
readDeferredLines(readLine, resolvers)
|
|
154
|
+
.then(() => {
|
|
155
|
+
// Stream ended normally. Any resolver that never received its chunk is
|
|
156
|
+
// dropped without a settle event — surface a rejection so consumers
|
|
157
|
+
// (e.g. <Await>) don't hang forever.
|
|
158
|
+
for (const key of Object.keys(resolvers)) {
|
|
159
|
+
const err = new Error(`[furin] deferred stream closed before "${key}" was resolved`);
|
|
160
|
+
resolvers[key]?.reject(err);
|
|
161
|
+
delete resolvers[key];
|
|
162
|
+
}
|
|
163
|
+
})
|
|
164
|
+
.catch((err) => {
|
|
165
|
+
for (const resolver of Object.values(resolvers)) {
|
|
166
|
+
resolver.reject(err);
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
.finally(() => {
|
|
170
|
+
try {
|
|
171
|
+
reader.releaseLock();
|
|
172
|
+
} catch {
|
|
173
|
+
/* already released via reader.cancel() in the abort path */
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
return { syncData, deferredPromises };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function readDeferredLines(
|
|
181
|
+
readLine: () => Promise<string | undefined>,
|
|
182
|
+
resolvers: Record<
|
|
183
|
+
string,
|
|
184
|
+
{ reject: (reason: unknown) => void; resolve: (value: unknown) => void }
|
|
185
|
+
>
|
|
186
|
+
): Promise<void> {
|
|
187
|
+
for (;;) {
|
|
188
|
+
const line = await readLine();
|
|
189
|
+
if (!line) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const entry = JSON.parse(line) as {
|
|
193
|
+
action?: "reject" | "resolve";
|
|
194
|
+
key?: string;
|
|
195
|
+
value?: SerovalNode;
|
|
196
|
+
};
|
|
197
|
+
if (typeof entry.key !== "string" || !entry.value) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const resolver = resolvers[entry.key];
|
|
201
|
+
if (!resolver) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const value = fromCrossJSON(entry.value, {});
|
|
205
|
+
if (entry.action === "reject") {
|
|
206
|
+
resolver.reject(value);
|
|
207
|
+
} else {
|
|
208
|
+
resolver.resolve(value);
|
|
209
|
+
}
|
|
210
|
+
delete resolvers[entry.key];
|
|
211
|
+
}
|
|
212
|
+
}
|
package/src/dev-page-plugin.ts
CHANGED
|
@@ -119,6 +119,7 @@ function escapeRegExp(s: string): string {
|
|
|
119
119
|
export function rewriteSingletonImports(source: string): string {
|
|
120
120
|
let result = source;
|
|
121
121
|
for (const [pkg, absPath] of SINGLETON_PATHS) {
|
|
122
|
+
// react-doctor-disable-next-line react-doctor/js-hoist-regexp
|
|
122
123
|
const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
|
|
123
124
|
result = result.replace(re, (_, g1: string) => `${g1}"${absPath}"`);
|
|
124
125
|
}
|
|
@@ -280,6 +281,7 @@ export function rewriteBareImports(source: string, transpiled: string, dir: stri
|
|
|
280
281
|
// that both import and re-export from the same package. The regex only
|
|
281
282
|
// matches when the specifier is preceded by `from` or `import` so string
|
|
282
283
|
// literals in non-import positions are left untouched.
|
|
284
|
+
// react-doctor-disable-next-line react-doctor/js-hoist-regexp
|
|
283
285
|
const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
|
|
284
286
|
result = result.replace(re, (_, g1: string) => `${g1}"${resolved}"`);
|
|
285
287
|
}
|
package/src/error.ts
CHANGED
|
@@ -11,6 +11,20 @@ export interface ErrorProps {
|
|
|
11
11
|
* without leaking stack traces to the browser.
|
|
12
12
|
*/
|
|
13
13
|
digest: string;
|
|
14
|
+
/**
|
|
15
|
+
* HTTP status associated with the error.
|
|
16
|
+
* - For thrown `Response` objects with a 4xx/5xx status: the response's
|
|
17
|
+
* status (e.g. 401, 403, 404, 500).
|
|
18
|
+
* - For all other errors (thrown `Error`, non-Error throws, shell-render
|
|
19
|
+
* crashes): always `500`.
|
|
20
|
+
*
|
|
21
|
+
* Always present so consumers never need a `?? 500` fallback. Note that
|
|
22
|
+
* `prepared.status` is honoured ONLY for loader-time errors. If a Suspense
|
|
23
|
+
* boundary throws AFTER the SSR shell has flushed (i.e. during streaming),
|
|
24
|
+
* the HTTP status cannot be changed and the user-visible status here may
|
|
25
|
+
* differ from the actual response code.
|
|
26
|
+
*/
|
|
27
|
+
status: number;
|
|
14
28
|
};
|
|
15
29
|
/**
|
|
16
30
|
* Clears the nearest FurinErrorBoundary's error state, remounting its
|
|
@@ -25,7 +39,10 @@ export type ErrorComponent = FC<ErrorProps>;
|
|
|
25
39
|
|
|
26
40
|
export function getPublicErrorMessage(error: Error | unknown): string {
|
|
27
41
|
const branded = error as { __furinBrand?: string } | undefined;
|
|
28
|
-
if (
|
|
42
|
+
if (
|
|
43
|
+
branded?.__furinBrand === "FURIN_NOT_FOUND" ||
|
|
44
|
+
branded?.__furinBrand === "FURIN_SERVER_ERROR"
|
|
45
|
+
) {
|
|
29
46
|
return (error as Error).message;
|
|
30
47
|
}
|
|
31
48
|
return "Something went wrong";
|