@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14
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/await.d.ts +67 -0
- package/dist/build/index.js +2013 -191
- package/dist/cli/index.js +2007 -190
- package/dist/client.d.ts +33 -2
- 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 +3 -0
- package/dist/furin.js +2684 -318
- 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 +247 -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 +63 -0
- package/dist/router.js +2768 -317
- package/dist/router.ts +543 -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/await.tsx +175 -0
- package/src/build/client.ts +4 -8
- package/src/build/hydrate.ts +67 -1
- package/src/build/route-types.ts +5 -1
- package/src/build/scan-server.ts +6 -23
- package/src/client.ts +58 -1
- 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 +12 -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 +7 -0
- package/src/render/default-screens.tsx +4 -11
- package/src/render/element.tsx +26 -3
- package/src/render/index.ts +247 -44
- package/src/render/loaders.ts +221 -18
- package/src/render/shell.ts +27 -12
- package/src/router-provider.tsx +414 -122
- package/src/router.ts +543 -54
- package/src/server-error.ts +47 -0
- package/src/utils.ts +31 -0
|
@@ -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/utils.d.ts
CHANGED
|
@@ -3,4 +3,11 @@ export declare function isFurinPage(value: unknown): value is RuntimePage;
|
|
|
3
3
|
export declare function isFurinRoute(value: unknown): value is RuntimeRoute;
|
|
4
4
|
export declare function collectRouteChainFromRoute(route: RuntimeRoute): RuntimeRoute[];
|
|
5
5
|
export declare function hasCycle(route: RuntimeRoute): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Maps over `items` with a bounded worker pool, preserving input order.
|
|
8
|
+
* Use whenever an `await Promise.all(items.map(...))` would open as many
|
|
9
|
+
* concurrent async operations as there are items — unbounded fan-out can
|
|
10
|
+
* exhaust file descriptors, sockets, or memory on large inputs.
|
|
11
|
+
*/
|
|
12
|
+
export declare function mapWithConcurrency<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
|
|
6
13
|
export declare function validateRouteChain(chain: RuntimeRoute[], root: RuntimeRoute, pagePath?: string): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teyik0/furin",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.14",
|
|
4
4
|
"description": "React meta-framework powered by Elysia and Bun with file-based routing, SSR, SSG, and ISR.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "teyik0",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"module": "./dist/furin.js",
|
|
39
39
|
"types": "./dist/furin.d.ts",
|
|
40
40
|
"bin": {
|
|
41
|
-
"furin": "./
|
|
41
|
+
"furin": "./src/cli/index.ts"
|
|
42
42
|
},
|
|
43
43
|
"exports": {
|
|
44
44
|
".": {
|
|
@@ -91,17 +91,18 @@
|
|
|
91
91
|
"dependencies": {
|
|
92
92
|
"@elysiajs/static": "^1.4.10",
|
|
93
93
|
"magic-string": "^0.30.21",
|
|
94
|
-
"
|
|
94
|
+
"seroval": "^1.5.4",
|
|
95
|
+
"yuku-parser": "^0.5.15"
|
|
95
96
|
},
|
|
96
97
|
"devDependencies": {
|
|
97
|
-
"@types/react": "^19.2.
|
|
98
|
+
"@types/react": "^19.2.15",
|
|
98
99
|
"@types/react-dom": "^19.2.3",
|
|
99
100
|
"expect-type": "^1.3.0"
|
|
100
101
|
},
|
|
101
102
|
"peerDependencies": {
|
|
102
103
|
"elysia": "^1.4.28",
|
|
103
|
-
"evlog": "^2.
|
|
104
|
-
"react": "^19.2.
|
|
105
|
-
"react-dom": "^19.2.
|
|
104
|
+
"evlog": "^2.17.0",
|
|
105
|
+
"react": "^19.2.6",
|
|
106
|
+
"react-dom": "^19.2.6"
|
|
106
107
|
}
|
|
107
108
|
}
|
package/src/adapter/bun.ts
CHANGED
|
@@ -65,7 +65,7 @@ async function createBuildFingerprint(
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
const fileParts = await Promise.all(
|
|
68
|
-
[...fingerprintPaths].
|
|
68
|
+
[...fingerprintPaths].toSorted().map(async (path) => {
|
|
69
69
|
const content = existsSync(path) ? await Bun.file(path).text() : "";
|
|
70
70
|
return `${toPosixPath(path)}:${content}`;
|
|
71
71
|
})
|
|
@@ -77,7 +77,7 @@ async function createBuildFingerprint(
|
|
|
77
77
|
)
|
|
78
78
|
.sort();
|
|
79
79
|
|
|
80
|
-
return [entryChunk, ...[...cssChunks].
|
|
80
|
+
return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join("\n");
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
function buildCompileMetadata(root: RootLayout, routes: ResolvedRoute[]) {
|
|
@@ -150,7 +150,7 @@ export async function buildBunTarget(
|
|
|
150
150
|
const clientDir = join(targetDir, "client");
|
|
151
151
|
writeFileSync(
|
|
152
152
|
join(clientDir, "index.html"),
|
|
153
|
-
generateProdIndexHtml(entryChunk, cssChunks, buildId)
|
|
153
|
+
generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false)
|
|
154
154
|
);
|
|
155
155
|
|
|
156
156
|
const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
|
package/src/adapter/static.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { prerenderSSG } from "../render/index.ts";
|
|
|
9
9
|
import { generateProdIndexHtml } from "../render/shell.ts";
|
|
10
10
|
import { setProductionTemplateContent } from "../render/template.ts";
|
|
11
11
|
import type { ResolvedRoute, RootLayout } from "../router.ts";
|
|
12
|
+
import { mapWithConcurrency } from "../utils.ts";
|
|
12
13
|
|
|
13
14
|
/** Maximum concurrent pre-render calls (mirrors warmSSGCache). */
|
|
14
15
|
const STATIC_CONCURRENCY = 4;
|
|
@@ -22,20 +23,21 @@ const TRAILING_SLASHES_RE = /\/+$/;
|
|
|
22
23
|
// ── Path helpers ──────────────────────────────────────────────────────────────
|
|
23
24
|
|
|
24
25
|
/**
|
|
25
|
-
* Converts a URL path to a filesystem output path.
|
|
26
|
-
* "/" → "outDir/index.html"
|
|
27
|
-
* "/docs/routing" → "outDir/docs/routing/index.html"
|
|
26
|
+
* Converts a URL path to a filesystem output path for the given file name.
|
|
27
|
+
* "/" + "index.html" → "outDir/index.html"
|
|
28
|
+
* "/docs/routing" + "index.html" → "outDir/docs/routing/index.html"
|
|
29
|
+
* "/docs/routing" + "__furin_data.ndjson" → "outDir/docs/routing/__furin_data.ndjson"
|
|
28
30
|
*
|
|
29
31
|
* The resolved path is validated to stay within `outDir` so that `..`
|
|
30
32
|
* segments injected via dynamic `staticParams()` values cannot escape
|
|
31
33
|
* the output directory.
|
|
32
34
|
*/
|
|
33
|
-
function pathToOutputFile(urlPath: string, outDir: string): string {
|
|
35
|
+
function pathToOutputFile(urlPath: string, outDir: string, fileName: string): string {
|
|
34
36
|
const normalizedOutDir = resolve(outDir);
|
|
35
37
|
if (urlPath === "/" || urlPath === "") {
|
|
36
|
-
return join(normalizedOutDir,
|
|
38
|
+
return join(normalizedOutDir, fileName);
|
|
37
39
|
}
|
|
38
|
-
const resolved = resolve(normalizedOutDir, urlPath.slice(1),
|
|
40
|
+
const resolved = resolve(normalizedOutDir, urlPath.slice(1), fileName);
|
|
39
41
|
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
40
42
|
throw new Error(
|
|
41
43
|
`[furin] static: unsafe output path detected for URL "${urlPath}" — path traversal via ".." is not allowed.`
|
|
@@ -56,7 +58,8 @@ async function prerenderAndWrite(
|
|
|
56
58
|
basePath: string
|
|
57
59
|
): Promise<void> {
|
|
58
60
|
const urlPath = resolvePath(route.pattern, params);
|
|
59
|
-
const
|
|
61
|
+
const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
|
|
62
|
+
const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
|
|
60
63
|
|
|
61
64
|
try {
|
|
62
65
|
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
@@ -68,10 +71,14 @@ async function prerenderAndWrite(
|
|
|
68
71
|
return;
|
|
69
72
|
}
|
|
70
73
|
|
|
71
|
-
ensureDir(dirname(
|
|
72
|
-
writeFileSync(
|
|
74
|
+
ensureDir(dirname(htmlOutputFile));
|
|
75
|
+
writeFileSync(htmlOutputFile, entry.html);
|
|
76
|
+
// Persist the loader payload at a static-friendly URL: SPA navigation on
|
|
77
|
+
// file-server deployments (GitHub Pages, S3, …) fetches this file instead
|
|
78
|
+
// of the runtime `/_furin/data?path=…` endpoint, which doesn't exist there.
|
|
79
|
+
writeFileSync(dataOutputFile, entry.ndjson);
|
|
73
80
|
renderedRoutes.push(urlPath);
|
|
74
|
-
console.log(`[furin] static: ${urlPath} → ${toPosixPath(
|
|
81
|
+
console.log(`[furin] static: ${urlPath} → ${toPosixPath(htmlOutputFile)}`);
|
|
75
82
|
} catch (err) {
|
|
76
83
|
console.error(
|
|
77
84
|
`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`,
|
|
@@ -135,32 +142,67 @@ async function buildTaskQueue(
|
|
|
135
142
|
): Promise<Array<() => Promise<void>>> {
|
|
136
143
|
const tasks: Array<() => Promise<void>> = [];
|
|
137
144
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
145
|
+
type StaticParamsResult =
|
|
146
|
+
| { paramSets: Record<string, string>[] | null; route: ResolvedRoute }
|
|
147
|
+
| { error: unknown; paramSets: null; route: ResolvedRoute };
|
|
148
|
+
|
|
149
|
+
const staticParamsResults: StaticParamsResult[] = await mapWithConcurrency(
|
|
150
|
+
ssgRoutes,
|
|
151
|
+
STATIC_CONCURRENCY,
|
|
152
|
+
async (route) => {
|
|
153
|
+
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
154
|
+
return { route, paramSets: [{}] };
|
|
155
|
+
}
|
|
156
|
+
if (!route.page.staticParams) {
|
|
157
|
+
console.warn(
|
|
158
|
+
`[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
|
|
159
|
+
);
|
|
160
|
+
skippedRoutes.push(route.pattern);
|
|
161
|
+
return { route, paramSets: null };
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const paramSets = (await route.page.staticParams()) ?? [];
|
|
165
|
+
return { route, paramSets };
|
|
166
|
+
} catch (err) {
|
|
167
|
+
return { error: err, paramSets: null, route };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
for (const result of staticParamsResults) {
|
|
173
|
+
if ("error" in result) {
|
|
174
|
+
console.error(
|
|
175
|
+
`[furin] static: staticParams() failed for "${result.route.pattern}":`,
|
|
176
|
+
result.error
|
|
142
177
|
);
|
|
178
|
+
skippedRoutes.push(result.route.pattern);
|
|
143
179
|
continue;
|
|
144
180
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
181
|
+
if (result.paramSets === null) {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
// Defend against staticParams() returning a non-array (e.g. a bare object
|
|
185
|
+
// or `null`-after-coercion). Without this guard, a single malformed route
|
|
186
|
+
// would throw out of `for...of` and abort the entire build.
|
|
187
|
+
if (!Array.isArray(result.paramSets)) {
|
|
188
|
+
console.error(
|
|
189
|
+
`[furin] static: staticParams() for "${result.route.pattern}" returned a non-array value; skipping route.`
|
|
149
190
|
);
|
|
150
|
-
skippedRoutes.push(route.pattern);
|
|
191
|
+
skippedRoutes.push(result.route.pattern);
|
|
151
192
|
continue;
|
|
152
193
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
194
|
+
for (const params of result.paramSets) {
|
|
195
|
+
tasks.push(() =>
|
|
196
|
+
prerenderAndWrite(
|
|
197
|
+
result.route,
|
|
198
|
+
params,
|
|
199
|
+
root,
|
|
200
|
+
outDir,
|
|
201
|
+
renderedRoutes,
|
|
202
|
+
skippedRoutes,
|
|
203
|
+
basePath
|
|
204
|
+
)
|
|
205
|
+
);
|
|
164
206
|
}
|
|
165
207
|
}
|
|
166
208
|
|
|
@@ -275,7 +317,7 @@ export async function buildStaticTarget(
|
|
|
275
317
|
// This ensures the browser finds it even when the site is served from a sub-path.
|
|
276
318
|
const publicFavicon = join(rootDir, "public", "favicon.ico");
|
|
277
319
|
const faviconHref = existsSync(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
|
|
278
|
-
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
|
|
320
|
+
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
|
|
279
321
|
|
|
280
322
|
// ── 5. Prime the renderer with the production shell ──────────────────────
|
|
281
323
|
// Must be called before any prerenderSSG invocation.
|
package/src/await.tsx
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Component, createContext, createElement, type ReactNode, use } from "react";
|
|
2
|
+
|
|
3
|
+
// ── Async error context ────────────────────────────────────────────────────────
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Context used to pass the caught error from `AsyncErrorBoundary` down to
|
|
7
|
+
* `errorElement` children so they can read it via `useAsyncError()`.
|
|
8
|
+
*/
|
|
9
|
+
export const AsyncErrorContext = createContext<unknown>(undefined);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Inside an `<Await errorElement={...}>`, returns the error that caused the
|
|
13
|
+
* deferred Promise to reject. Throws outside of an error-boundary subtree.
|
|
14
|
+
*/
|
|
15
|
+
export function useAsyncError(): unknown {
|
|
16
|
+
return use(AsyncErrorContext);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Inside a resolved `<Await>`, returns the resolved value via React 19's
|
|
21
|
+
* `use()`. Can be used as an alternative to the render-prop children API.
|
|
22
|
+
*
|
|
23
|
+
* Must be used inside a component that is rendered as children of `<Await>`.
|
|
24
|
+
*/
|
|
25
|
+
export function useAsyncValue<T>(): T {
|
|
26
|
+
// This hook is intended to be used inside <Await>'s children renderer.
|
|
27
|
+
// The actual value is accessed via the AwaitValueContext.
|
|
28
|
+
const ctx = use(AwaitValueContext) as { promise: Promise<T> } | undefined;
|
|
29
|
+
if (!ctx) {
|
|
30
|
+
throw new Error("useAsyncValue must be used inside <Await> children");
|
|
31
|
+
}
|
|
32
|
+
return use(ctx.promise);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const AwaitValueContext = createContext<{ promise: Promise<unknown> } | undefined>(undefined);
|
|
36
|
+
|
|
37
|
+
// ── Error boundary ─────────────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
interface AsyncErrorBoundaryProps {
|
|
40
|
+
children?: ReactNode;
|
|
41
|
+
errorElement: ReactNode | undefined;
|
|
42
|
+
resolve: Promise<unknown>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface AsyncErrorBoundaryState {
|
|
46
|
+
error: unknown;
|
|
47
|
+
hasError: boolean;
|
|
48
|
+
resolve: Promise<unknown> | undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Class-based error boundary that wraps `<Await>` to catch rejected Promises.
|
|
53
|
+
* When `use(promise)` triggers an unhandled rejection during render, React
|
|
54
|
+
* propagates it to the nearest error boundary — this one catches it and
|
|
55
|
+
* renders the user-provided `errorElement`.
|
|
56
|
+
*
|
|
57
|
+
* NOTE: React error boundaries require `getDerivedStateFromError`, which only
|
|
58
|
+
* exists on class components — this class is intentional and cannot be replaced
|
|
59
|
+
* by a function component.
|
|
60
|
+
*/
|
|
61
|
+
// biome-ignore lint/style/useReactFunctionComponents: error boundaries require getDerivedStateFromError, which has no function-component equivalent
|
|
62
|
+
class AsyncErrorBoundary extends Component<AsyncErrorBoundaryProps, AsyncErrorBoundaryState> {
|
|
63
|
+
constructor(props: AsyncErrorBoundaryProps) {
|
|
64
|
+
super(props);
|
|
65
|
+
this.state = { hasError: false, error: undefined, resolve: props.resolve };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static getDerivedStateFromProps(
|
|
69
|
+
props: AsyncErrorBoundaryProps,
|
|
70
|
+
state: AsyncErrorBoundaryState
|
|
71
|
+
): Partial<AsyncErrorBoundaryState> | null {
|
|
72
|
+
if (props.resolve !== state.resolve) {
|
|
73
|
+
return { hasError: false, error: undefined, resolve: props.resolve };
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
static getDerivedStateFromError(error: unknown): Partial<AsyncErrorBoundaryState> {
|
|
79
|
+
return { hasError: true, error };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
override render(): ReactNode {
|
|
83
|
+
const { hasError, error } = this.state;
|
|
84
|
+
const { children, errorElement } = this.props;
|
|
85
|
+
|
|
86
|
+
if (hasError) {
|
|
87
|
+
if (errorElement === undefined) {
|
|
88
|
+
// No errorElement provided — re-throw so the nearest Suspense/parent boundary handles it
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
// Provide the error via context so useAsyncError() can access it
|
|
92
|
+
return createElement(AsyncErrorContext.Provider, { value: error }, errorElement);
|
|
93
|
+
}
|
|
94
|
+
return children;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ── <Await> component ──────────────────────────────────────────────────────────
|
|
99
|
+
|
|
100
|
+
export interface AwaitProps<T> {
|
|
101
|
+
/**
|
|
102
|
+
* Render-prop children: called with the resolved value once the Promise
|
|
103
|
+
* settles. The returned `ReactNode` is rendered inside a Suspense boundary.
|
|
104
|
+
*
|
|
105
|
+
* Marked optional here so `createElement(Await, props, renderFn)` is
|
|
106
|
+
* accepted by TypeScript — the 3rd argument to `createElement` becomes
|
|
107
|
+
* `children` at runtime and is always required for correct behaviour.
|
|
108
|
+
*/
|
|
109
|
+
children?: (value: T) => ReactNode;
|
|
110
|
+
/**
|
|
111
|
+
* Rendered when the Promise rejects. Inside this subtree, `useAsyncError()`
|
|
112
|
+
* returns the rejection reason. When omitted the error propagates up to the
|
|
113
|
+
* next React error boundary.
|
|
114
|
+
*/
|
|
115
|
+
errorElement?: ReactNode;
|
|
116
|
+
/**
|
|
117
|
+
* The deferred Promise to await. Passed as a prop so React's `use()` can
|
|
118
|
+
* suspend the boundary until it resolves. This is the same Promise object
|
|
119
|
+
* that the loader returned inside `defer()`.
|
|
120
|
+
*/
|
|
121
|
+
resolve: Promise<T>;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Deferred-data boundary component. Uses React 19's `use()` to suspend the
|
|
126
|
+
* render until `resolve` settles, then calls the render-prop `children` with
|
|
127
|
+
* the resolved value.
|
|
128
|
+
*
|
|
129
|
+
* Wrap with `<Suspense fallback={…}>` to show a loading indicator while the
|
|
130
|
+
* Promise is pending.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```tsx
|
|
134
|
+
* export default route.page({
|
|
135
|
+
* loader: () => defer({ board: "x", stats: fetchStats() }),
|
|
136
|
+
* component: ({ board, stats }) => (
|
|
137
|
+
* <div>
|
|
138
|
+
* <h1>{board}</h1>
|
|
139
|
+
* <Suspense fallback={<Spinner />}>
|
|
140
|
+
* <Await resolve={stats}>
|
|
141
|
+
* {(s) => <StatsBar stats={s} />}
|
|
142
|
+
* </Await>
|
|
143
|
+
* </Suspense>
|
|
144
|
+
* </div>
|
|
145
|
+
* ),
|
|
146
|
+
* });
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
export function Await<T>({ resolve, errorElement, children }: AwaitProps<T>): ReactNode {
|
|
150
|
+
return createElement(
|
|
151
|
+
AsyncErrorBoundary,
|
|
152
|
+
{ errorElement, resolve: resolve as Promise<unknown> },
|
|
153
|
+
// react-doctor-disable-next-line react/no-children-prop
|
|
154
|
+
createElement(AwaitInner<T>, { resolve, children })
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface AwaitInnerProps<T> {
|
|
159
|
+
children?: (value: T) => ReactNode;
|
|
160
|
+
resolve: Promise<T>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Inner component that calls `use(resolve)` — this is intentionally a
|
|
165
|
+
* separate component so `AsyncErrorBoundary` above it can catch any errors
|
|
166
|
+
* thrown during the `use()` suspension protocol.
|
|
167
|
+
*/
|
|
168
|
+
function AwaitInner<T>({ resolve, children }: AwaitInnerProps<T>): ReactNode {
|
|
169
|
+
const value = use(resolve);
|
|
170
|
+
return createElement(
|
|
171
|
+
AwaitValueContext.Provider,
|
|
172
|
+
{ value: { promise: resolve as Promise<unknown> } },
|
|
173
|
+
children ? children(value) : null
|
|
174
|
+
);
|
|
175
|
+
}
|
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) {
|
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
|
}
|