fondu 0.12.1 → 0.14.0
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 +1 -1
- package/dist/client/app.d.ts +36 -8
- package/dist/client/app.js +65 -41
- package/dist/client/form.d.ts +3 -1
- package/dist/client/form.js +11 -7
- package/dist/client/navigation.d.ts +4 -1
- package/dist/client/navigation.js +173 -29
- package/dist/client.d.ts +12 -8
- package/dist/client.js +7 -1
- package/dist/form.d.ts +2 -2
- package/dist/form.js +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/paths.d.ts +13 -2
- package/dist/paths.js +18 -7
- package/dist/server/app.d.ts +7 -3
- package/dist/server/app.js +38 -27
- package/dist/server/document.d.ts +10 -2
- package/dist/server/document.js +71 -19
- package/dist/server/errors.d.ts +0 -2
- package/dist/server/errors.js +4 -3
- package/dist/server/flash.d.ts +0 -2
- package/dist/server/flash.js +1 -1
- package/dist/server/http.d.ts +4 -0
- package/dist/server/http.js +5 -0
- package/dist/server/prerender.js +7 -49
- package/dist/server/protocol.d.ts +16 -2
- package/dist/server/protocol.js +95 -15
- package/dist/server/routes.d.ts +4 -1
- package/dist/server/routes.js +9 -1
- package/dist/server/static.d.ts +14 -0
- package/dist/server/static.js +37 -0
- package/dist/server/validate.d.ts +2 -6
- package/dist/virtual.d.ts +5 -1
- package/dist/vite/index.d.ts +4 -1
- package/dist/vite/index.js +33 -25
- package/dist/vite/prerender.d.ts +12 -9
- package/dist/vite/prerender.js +17 -13
- package/dist/vite/strip.d.ts +1 -3
- package/dist/vite/strip.js +3 -15
- package/dist/vite/typegen.d.ts +0 -6
- package/dist/vite/typegen.js +3 -3
- package/package.json +1 -1
package/dist/server/prerender.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData
|
|
2
|
-
import {
|
|
3
|
-
/** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
|
|
4
|
-
const STATIC_FILES = Symbol.for('fondu.staticFiles');
|
|
5
|
-
/** a page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment */
|
|
6
|
-
const isPageFile = (file) => file.split('/').every((s) => s !== '' && !s.startsWith('.'));
|
|
1
|
+
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
|
|
2
|
+
import { isPrerendering } from './http.js';
|
|
7
3
|
/** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
|
|
8
4
|
export async function prerenderPaths(routes) {
|
|
9
5
|
const paths = new Set();
|
|
@@ -46,47 +42,11 @@ export async function prerenderPaths(routes) {
|
|
|
46
42
|
* a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
|
|
47
43
|
*/
|
|
48
44
|
export function prerenderRoutes(app, routes, version) {
|
|
49
|
-
// Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
|
|
50
|
-
// Cloudflare, Workers Static Assets serve the files before the Worker runs). The built server says how to read them.
|
|
51
|
-
app.use(async (c, next) => {
|
|
52
|
-
const read = globalThis[STATIC_FILES];
|
|
53
|
-
if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
|
|
54
|
-
return next();
|
|
55
|
-
const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
|
|
56
|
-
if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
|
|
57
|
-
return next();
|
|
58
|
-
// a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
|
|
59
|
-
if (!data && endsInIndex(c.req.path))
|
|
60
|
-
return next();
|
|
61
|
-
let file;
|
|
62
|
-
try {
|
|
63
|
-
file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
|
|
64
|
-
}
|
|
65
|
-
catch {
|
|
66
|
-
return next(); // not a path a file could have
|
|
67
|
-
}
|
|
68
|
-
if (!isPageFile(file))
|
|
69
|
-
return next();
|
|
70
|
-
const body = await read(file);
|
|
71
|
-
if (!body)
|
|
72
|
-
return next();
|
|
73
|
-
c.header('Cache-Control', 'private, no-cache');
|
|
74
|
-
if (data)
|
|
75
|
-
c.header('X-Fondu', 'true');
|
|
76
|
-
// the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
|
|
77
|
-
// security headers give it a new one
|
|
78
|
-
const nonce = c.get('secureHeadersNonce');
|
|
79
|
-
if (!data && nonce) {
|
|
80
|
-
const html = new TextDecoder()
|
|
81
|
-
.decode(body)
|
|
82
|
-
.replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
|
|
83
|
-
return c.html(html, 200);
|
|
84
|
-
}
|
|
85
|
-
return c.body(body, 200, {
|
|
86
|
-
'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
|
|
87
|
-
});
|
|
88
|
-
});
|
|
89
45
|
app.get(`${PAGE_DATA}/*`, (c) => {
|
|
46
|
+
// a prefetch is for a static page's file only (served before the app, which is not reached): a page without
|
|
47
|
+
// one is asked for at the click, and no loader runs for a page that may not be visited
|
|
48
|
+
if (c.req.header('X-Fondu-Prefetch') === 'true')
|
|
49
|
+
return c.body(null, 204, { 'Cache-Control': 'no-store' });
|
|
90
50
|
const path = pathOfPageData(c.req.path);
|
|
91
51
|
// a page object's own URL is not a page: no page object of a page object (and so on)
|
|
92
52
|
if (!path || path.startsWith('/_fondu/'))
|
|
@@ -104,9 +64,7 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
104
64
|
});
|
|
105
65
|
app.get('/__fondu/prerender', async (c) => {
|
|
106
66
|
// set for the build only: a Worker binding, or the environment of `node` / `bun dist/server/index.js`
|
|
107
|
-
|
|
108
|
-
globalThis.process?.env?.FONDU_PRERENDER;
|
|
109
|
-
if (!env)
|
|
67
|
+
if (!isPrerendering(c))
|
|
110
68
|
return c.notFound();
|
|
111
69
|
return c.json({ version, ...(await prerenderPaths(routes())) });
|
|
112
70
|
});
|
|
@@ -9,6 +9,19 @@ type Shareable<T> = {
|
|
|
9
9
|
};
|
|
10
10
|
/** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
|
|
11
11
|
export declare function share(c: Context, props: Shareable<Shared>): void;
|
|
12
|
+
/** a prop the page gets with a second request: `defer(fn)` in `render()`'s props */
|
|
13
|
+
declare class DeferredProp<T> {
|
|
14
|
+
readonly type?: T;
|
|
15
|
+
readonly load: () => T | PromiseLike<T>;
|
|
16
|
+
constructor(load: () => T | PromiseLike<T>);
|
|
17
|
+
}
|
|
18
|
+
export type { DeferredProp };
|
|
19
|
+
/**
|
|
20
|
+
* A prop of the page that is not sent with it: `render(c, Page, { user, stats: defer(() => loadStats()) })`. The page
|
|
21
|
+
* renders without it (optional in the component's props); the client asks for it once the page is on the screen, and
|
|
22
|
+
* `fn` runs only for that request.
|
|
23
|
+
*/
|
|
24
|
+
export declare function defer<T>(fn: () => T | PromiseLike<T>): DeferredProp<T>;
|
|
12
25
|
/** a page: a component, its props what it receives (a function component, or a class one) */
|
|
13
26
|
type PageComponent<P> = ((props: P) => ReactNode | Promise<ReactNode>) | (new (props: P) => Component<P>);
|
|
14
27
|
/** the props a page names: not an index signature (a page without props takes `Record<string, never>`) */
|
|
@@ -46,8 +59,10 @@ type JsonInput<T> = IsAny<T> extends true ? T : T extends Json | undefined ? T |
|
|
|
46
59
|
type NotJsonError = 'fondu: the page receives this prop as JSON (a Date as a string, a Map as {}): type it as such';
|
|
47
60
|
/** a page's props as `render` takes them: what becomes each as JSON, or an error for a type JSON can't deliver */
|
|
48
61
|
export type Delivered<P> = {
|
|
49
|
-
[K in keyof P]: Arrives<P[K]> extends true ? JsonInput<P[K]> : NotJsonError;
|
|
62
|
+
[K in keyof P]: Arrives<P[K]> extends true ? JsonInput<P[K]> | Deferrable<P, K> : NotJsonError;
|
|
50
63
|
};
|
|
64
|
+
/** `defer()` for a prop the page takes as optional: it renders without it */
|
|
65
|
+
type Deferrable<P, K extends keyof P> = {} extends Pick<P, K> ? DeferredProp<JsonInput<Exclude<P[K], undefined>>> : never;
|
|
51
66
|
type RequiredKeys<T> = {
|
|
52
67
|
[K in keyof T]-?: object extends Pick<T, K> ? never : K;
|
|
53
68
|
}[keyof T];
|
|
@@ -67,4 +82,3 @@ export declare function render<P extends object>(c: Context, page: PageComponent
|
|
|
67
82
|
/** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
|
|
68
83
|
export declare function renderPage(c: Context, id: string, props: Record<string, unknown>, options?: RenderOptions): Promise<Response>;
|
|
69
84
|
export declare const protocol: MiddlewareHandler[];
|
|
70
|
-
export {};
|
package/dist/server/protocol.js
CHANGED
|
@@ -1,12 +1,34 @@
|
|
|
1
1
|
import { version } from 'virtual:fondu/assets';
|
|
2
2
|
import { renderDocument } from './document.js';
|
|
3
3
|
import { flashCookie, takeCarried } from './flash.js';
|
|
4
|
-
import { appendHeader, back, isPageRequest, sameOrigin } from './http.js';
|
|
4
|
+
import { appendHeader, back, isPageRequest, isPrerendering, sameOrigin } from './http.js';
|
|
5
5
|
const shared = new WeakMap();
|
|
6
6
|
/** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
|
|
7
7
|
export function share(c, props) {
|
|
8
8
|
shared.set(c, { ...shared.get(c), ...props });
|
|
9
9
|
}
|
|
10
|
+
// ---- deferred props (`defer`): left out of a page, asked for by a request of their own
|
|
11
|
+
// As Inertia's deferred props, with rescue always on (a function that throws is logged and its prop left out); no groups
|
|
12
|
+
/** a prop the page gets with a second request: `defer(fn)` in `render()`'s props */
|
|
13
|
+
class DeferredProp {
|
|
14
|
+
load;
|
|
15
|
+
constructor(load) {
|
|
16
|
+
this.load = load;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
Object.defineProperty(DeferredProp.prototype, 'toJSON', {
|
|
20
|
+
value() {
|
|
21
|
+
throw new Error('fondu: defer() is for a prop of render(), at the top (not in share(), not inside a prop)');
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* A prop of the page that is not sent with it: `render(c, Page, { user, stats: defer(() => loadStats()) })`. The page
|
|
26
|
+
* renders without it (optional in the component's props); the client asks for it once the page is on the screen, and
|
|
27
|
+
* `fn` runs only for that request.
|
|
28
|
+
*/
|
|
29
|
+
export function defer(fn) {
|
|
30
|
+
return new DeferredProp(fn);
|
|
31
|
+
}
|
|
10
32
|
// the pages of app/routes/ (createApp): a component → its ids; and, per request, the page of the route answering it
|
|
11
33
|
// (the ids: a page may be the default export of several, `export { default } from './index.tsx'`)
|
|
12
34
|
const pageIds = new WeakMap();
|
|
@@ -39,18 +61,56 @@ export function render(c, page, ...[props = {}, options = {}]) {
|
|
|
39
61
|
}
|
|
40
62
|
/** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
|
|
41
63
|
export async function renderPage(c, id, props, options = {}) {
|
|
42
|
-
const
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
64
|
+
const only = askedFor(c, id);
|
|
65
|
+
const deferred = Object.keys(props).filter((k) => props[k] instanceof DeferredProp);
|
|
66
|
+
let page;
|
|
67
|
+
if (only) {
|
|
68
|
+
// a partial request: what was asked for, and nothing the page already has (no shared props, no errors, no flash:
|
|
69
|
+
// the cookie is the next page's)
|
|
70
|
+
const wanted = only.filter((k) => Object.hasOwn(props, k));
|
|
71
|
+
const entries = await Promise.all(wanted.map(async (key) => {
|
|
72
|
+
const value = props[key];
|
|
73
|
+
if (!(value instanceof DeferredProp))
|
|
74
|
+
return [[key, value]];
|
|
75
|
+
try {
|
|
76
|
+
return [[key, await value.load()]];
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
console.error(`[fondu] the deferred prop "${key}" of "${id}" failed:`, error);
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
}));
|
|
83
|
+
page = {
|
|
84
|
+
component: id,
|
|
85
|
+
props: Object.fromEntries(entries.flat()),
|
|
86
|
+
url: pageUrl(c),
|
|
87
|
+
version,
|
|
88
|
+
flash: {},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
const carried = takeCarried(c);
|
|
93
|
+
const fromShared = await Promise.all(Object.entries(shared.get(c) ?? {}).map(async ([key, value]) => [
|
|
94
|
+
key,
|
|
95
|
+
typeof value === 'function' ? await value() : value,
|
|
96
|
+
]));
|
|
97
|
+
// a static page has all its data: what is deferred is awaited
|
|
98
|
+
const now = isPrerendering(c);
|
|
99
|
+
const own = Object.fromEntries(await Promise.all(Object.entries(props)
|
|
100
|
+
.filter(([key]) => now || !deferred.includes(key))
|
|
101
|
+
.map(async ([key, value]) => [
|
|
102
|
+
key,
|
|
103
|
+
value instanceof DeferredProp ? await value.load() : value,
|
|
104
|
+
])));
|
|
105
|
+
page = {
|
|
106
|
+
component: id,
|
|
107
|
+
props: { ...Object.fromEntries(fromShared), ...own, errors: carried.errors },
|
|
108
|
+
url: pageUrl(c),
|
|
109
|
+
version,
|
|
110
|
+
flash: carried.flash,
|
|
111
|
+
...(deferred.length && !now && { deferred }),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
54
114
|
// a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
|
|
55
115
|
if (!c.res.headers.has('Cache-Control'))
|
|
56
116
|
c.header('Cache-Control', 'private, no-cache');
|
|
@@ -58,7 +118,27 @@ export async function renderPage(c, id, props, options = {}) {
|
|
|
58
118
|
c.header('X-Fondu', 'true');
|
|
59
119
|
return c.json(page, (options.status ?? 200));
|
|
60
120
|
}
|
|
61
|
-
|
|
121
|
+
const status = (options.status ?? 200);
|
|
122
|
+
const document = await renderDocument(c, page, isPrerendering(c));
|
|
123
|
+
return typeof document === 'string'
|
|
124
|
+
? c.html(document, status)
|
|
125
|
+
: c.body(document, status, { 'Content-Type': 'text/html; charset=UTF-8' });
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The props a partial request asks for (`X-Fondu-Only: stats,feed`), if it is one: a navigation, a GET, for the
|
|
129
|
+
* component this route renders
|
|
130
|
+
*/
|
|
131
|
+
function askedFor(c, id) {
|
|
132
|
+
const only = c.req.header('x-fondu-only');
|
|
133
|
+
if (!only ||
|
|
134
|
+
c.req.method !== 'GET' ||
|
|
135
|
+
!isPageRequest(c) ||
|
|
136
|
+
c.req.header('x-fondu-component') !== id)
|
|
137
|
+
return;
|
|
138
|
+
return only
|
|
139
|
+
.split(',')
|
|
140
|
+
.map((name) => name.trim())
|
|
141
|
+
.filter(Boolean);
|
|
62
142
|
}
|
|
63
143
|
/** an http(s) URL, as `to` resolves from the request's */
|
|
64
144
|
function webUrl(c, to) {
|
|
@@ -80,7 +160,7 @@ const versionCheck = async (c, next) => {
|
|
|
80
160
|
}
|
|
81
161
|
await next();
|
|
82
162
|
// a URL answers a navigation and a document differently: caches keep them apart
|
|
83
|
-
appendHeader(c, 'Vary', 'X-Fondu');
|
|
163
|
+
appendHeader(c, 'Vary', isPageRequest(c) ? 'X-Fondu, X-Fondu-Only' : 'X-Fondu');
|
|
84
164
|
// an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
|
|
85
165
|
// isn't read to tell (a stream's would be, to its end)
|
|
86
166
|
if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
|
package/dist/server/routes.d.ts
CHANGED
|
@@ -10,9 +10,11 @@ export interface RouteModule {
|
|
|
10
10
|
params?: Params;
|
|
11
11
|
/** a `_middleware.ts`: the middleware; a page: its component */
|
|
12
12
|
default?: Handlers;
|
|
13
|
+
/** a page's route file (`.tsx`): GET, POST, POST `?name` */
|
|
13
14
|
loader?: Handlers;
|
|
14
15
|
action?: Handlers;
|
|
15
16
|
actions?: Record<string, Handlers>;
|
|
17
|
+
/** a `.ts` route file: the HTTP methods */
|
|
16
18
|
GET?: Handlers;
|
|
17
19
|
POST?: Handlers;
|
|
18
20
|
PUT?: Handlers;
|
|
@@ -33,6 +35,7 @@ export interface Route {
|
|
|
33
35
|
* The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
|
|
34
36
|
* by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
|
|
35
37
|
* on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
|
|
36
|
-
* other's middleware), `params` that no route takes or that aren't single segments
|
|
38
|
+
* other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
|
|
39
|
+
* app's, a `.jsx` file that would be a route, a layout or the error page (route files are TypeScript).
|
|
37
40
|
*/
|
|
38
41
|
export declare function routeTable(modules: Record<string, RouteModule>, append: boolean): Route[];
|
package/dist/server/routes.js
CHANGED
|
@@ -5,10 +5,18 @@ const SEGMENT = /^[\w.~-]+$/;
|
|
|
5
5
|
* The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
|
|
6
6
|
* by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
|
|
7
7
|
* on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
|
|
8
|
-
* other's middleware), `params` that no route takes or that aren't single segments
|
|
8
|
+
* other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
|
|
9
|
+
* app's, a `.jsx` file that would be a route, a layout or the error page (route files are TypeScript).
|
|
9
10
|
*/
|
|
10
11
|
export function routeTable(modules, append) {
|
|
11
12
|
const files = Object.keys(modules);
|
|
13
|
+
const jsx = files.find((f) => f.endsWith('.jsx') &&
|
|
14
|
+
(isRouteFile(f.replace(/\.jsx$/, '.tsx')) || /(?:^|\/)_(?:layout|error)\.jsx$/.test(f)));
|
|
15
|
+
if (jsx)
|
|
16
|
+
throw new Error(`fondu: routes/${jsx}: route files are TypeScript; rename it to ${jsx.replace(/\.jsx$/, '.tsx')}`);
|
|
17
|
+
const nested = files.find((f) => f.endsWith('/_error.tsx'));
|
|
18
|
+
if (nested)
|
|
19
|
+
throw new Error(`fondu: routes/${nested} is never shown: the error page is routes/_error.tsx, one for the app`);
|
|
12
20
|
const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
|
|
13
21
|
const used = new Set(); // `${file}:${name}`: a `params` entry that applies to a route
|
|
14
22
|
const routes = [];
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
/** Hono's `serveStatic` of the runtime (`hono/bun`, `@hono/node-server/serve-static`), given by the built server's entry */
|
|
3
|
+
export type ServeStatic = (options: {
|
|
4
|
+
root: string;
|
|
5
|
+
rewriteRequestPath?: (path: string) => string;
|
|
6
|
+
}) => MiddlewareHandler;
|
|
7
|
+
/**
|
|
8
|
+
* Node / Bun: the prerendered pages as files, before the app: a document request (`Accept: text/html`, no `X-Fondu`)
|
|
9
|
+
* for `/docs/intro` is `docs/intro.html`, a page object (`/_fondu/pages/…`) its `.json`, each with the headers the
|
|
10
|
+
* build decided (`headers`: `dist/server/prerender.json`). No file, or no page request: the next handler (the app).
|
|
11
|
+
* A URL ending in `index` is never a document file (it would be its directory's). A path that still has an escaped
|
|
12
|
+
* reserved character (`%2F`…) after decoding is not served from a file: serveStatic refuses it, and the app answers.
|
|
13
|
+
*/
|
|
14
|
+
export declare function staticPages(serveStatic: ServeStatic, clientRoot: string, headers: Record<string, string>): MiddlewareHandler;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { endsInIndex, htmlFile, PAGE_DATA } from '../paths.js';
|
|
2
|
+
import { isPageRequest } from './http.js';
|
|
3
|
+
/** the headers on the response a file was served with (the runtimes differ in when `onFound` could set them) */
|
|
4
|
+
const withHeaders = (res, headers) => {
|
|
5
|
+
for (const [name, value] of Object.entries(headers))
|
|
6
|
+
res.headers.set(name, value);
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Node / Bun: the prerendered pages as files, before the app: a document request (`Accept: text/html`, no `X-Fondu`)
|
|
10
|
+
* for `/docs/intro` is `docs/intro.html`, a page object (`/_fondu/pages/…`) its `.json`, each with the headers the
|
|
11
|
+
* build decided (`headers`: `dist/server/prerender.json`). No file, or no page request: the next handler (the app).
|
|
12
|
+
* A URL ending in `index` is never a document file (it would be its directory's). A path that still has an escaped
|
|
13
|
+
* reserved character (`%2F`…) after decoding is not served from a file: serveStatic refuses it, and the app answers.
|
|
14
|
+
*/
|
|
15
|
+
export function staticPages(serveStatic, clientRoot, headers) {
|
|
16
|
+
const pageObject = serveStatic({ root: clientRoot });
|
|
17
|
+
const document = serveStatic({ root: clientRoot, rewriteRequestPath: htmlFile });
|
|
18
|
+
const serve = (middleware, own) => async (c, next) => {
|
|
19
|
+
const res = await middleware(c, next);
|
|
20
|
+
if (res instanceof Response)
|
|
21
|
+
withHeaders(res, { ...headers, ...own });
|
|
22
|
+
return res;
|
|
23
|
+
};
|
|
24
|
+
const pages = serve(pageObject, { 'Cache-Control': 'private, no-cache', 'X-Fondu': 'true' });
|
|
25
|
+
const documents = serve(document, { 'Cache-Control': 'private, no-cache' });
|
|
26
|
+
return (c, next) => {
|
|
27
|
+
if ((c.req.method !== 'GET' && c.req.method !== 'HEAD') || c.req.path.includes('\0'))
|
|
28
|
+
return next();
|
|
29
|
+
if (c.req.path.startsWith(`${PAGE_DATA}/`))
|
|
30
|
+
return pages(c, next);
|
|
31
|
+
if (isPageRequest(c) ||
|
|
32
|
+
!(c.req.header('accept') ?? '').includes('text/html') ||
|
|
33
|
+
endsInIndex(c.req.path))
|
|
34
|
+
return next();
|
|
35
|
+
return documents(c, next);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { type Issue } from '../form.js';
|
|
2
3
|
/** The Standard Schema interface (zod, valibot, arktype…), the part used here. */
|
|
3
4
|
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
4
5
|
readonly '~standard': {
|
|
@@ -15,12 +16,7 @@ type StandardResult<Output> = {
|
|
|
15
16
|
readonly value: Output;
|
|
16
17
|
readonly issues?: undefined;
|
|
17
18
|
} | {
|
|
18
|
-
readonly issues: ReadonlyArray<
|
|
19
|
-
readonly message: string;
|
|
20
|
-
readonly path?: ReadonlyArray<PropertyKey | {
|
|
21
|
-
readonly key: PropertyKey;
|
|
22
|
-
}>;
|
|
23
|
-
}>;
|
|
19
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
24
20
|
};
|
|
25
21
|
type InferOutput<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
|
|
26
22
|
/**
|
package/dist/virtual.d.ts
CHANGED
|
@@ -10,7 +10,11 @@ declare module 'virtual:fondu/assets' {
|
|
|
10
10
|
declare module 'virtual:fondu/ssr' {
|
|
11
11
|
/** the server render of a page (null: `fondu({ ssr: false })`) */
|
|
12
12
|
export const renderPage:
|
|
13
|
-
| ((
|
|
13
|
+
| ((
|
|
14
|
+
page: import('./client/navigation.js').Page,
|
|
15
|
+
options: { nonce?: string; onError?: (error: unknown) => void },
|
|
16
|
+
after?: import('react').ReactElement,
|
|
17
|
+
) => Promise<import('./client/app.js').Rendered>)
|
|
14
18
|
| null
|
|
15
19
|
/** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
|
|
16
20
|
export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -23,7 +23,10 @@ export interface FonduOptions {
|
|
|
23
23
|
* time, and navigations read them; the server (the Worker) answers the other pages
|
|
24
24
|
*/
|
|
25
25
|
prerender?: boolean;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* the bar at the top of the page while a navigation is on its way: its `delay` (ms), its `color`, and whether forms'
|
|
28
|
+
* submissions show it (`forms`); `false`: none
|
|
29
|
+
*/
|
|
27
30
|
progress?: ProgressOptions | false;
|
|
28
31
|
}
|
|
29
32
|
/** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
|
package/dist/vite/index.js
CHANGED
|
@@ -2,19 +2,19 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { builtinModules, createRequire } from 'node:module';
|
|
4
4
|
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
5
|
-
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
6
|
import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
|
|
7
7
|
import react, {} from '@vitejs/plugin-react';
|
|
8
|
-
import { parseAst, transformWithOxc, } from 'vite';
|
|
8
|
+
import { normalizePath, parseAst, transformWithOxc, } from 'vite';
|
|
9
9
|
import { isPageFile, layoutsOf, pageId } from '../paths.js';
|
|
10
10
|
import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
|
|
11
11
|
import { nodeServer, prerender, worker } from './prerender.js';
|
|
12
12
|
import { stripRoutes, stripServerCode } from './strip.js';
|
|
13
|
-
import { typegen } from './typegen.js';
|
|
14
|
-
import { walk as walkFiles } from './typegen.js';
|
|
13
|
+
import { typegen, walk as walkFiles } from './typegen.js';
|
|
15
14
|
/** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
|
|
16
15
|
export const HONO = [
|
|
17
16
|
'hono',
|
|
17
|
+
'hono/body-limit',
|
|
18
18
|
'hono/combine',
|
|
19
19
|
'hono/cookie',
|
|
20
20
|
'hono/csrf',
|
|
@@ -32,18 +32,20 @@ const V = {
|
|
|
32
32
|
ssr: 'virtual:fondu/ssr',
|
|
33
33
|
serverEntry: 'virtual:fondu/server-entry',
|
|
34
34
|
};
|
|
35
|
+
/** fondu's own `server/static.js`, imported by the built server's entry (by its path: it is not an export of the package) */
|
|
36
|
+
const staticModule = normalizePath(fileURLToPath(new URL('../server/static.js', import.meta.url)));
|
|
35
37
|
const resolved = (id) => '\0' + id;
|
|
36
38
|
/** the pages, for the app's entry: the route files of `app/routes/` that are React, but what isn't a route */
|
|
37
39
|
const PAGES_GLOB = [
|
|
38
|
-
'/app/routes/**/*.{tsx,
|
|
40
|
+
'/app/routes/**/*.{tsx,mdx}',
|
|
39
41
|
'!/app/routes/**/_*',
|
|
40
42
|
'!/app/routes/**/_*/**',
|
|
41
|
-
'!/app/routes/**/*.{test,spec}.
|
|
43
|
+
'!/app/routes/**/*.{test,spec}.tsx',
|
|
42
44
|
];
|
|
43
45
|
/** the error page (`_error.tsx`: a page, though its name says it is no URL) */
|
|
44
|
-
const ERROR_GLOB = '/app/routes/_error.
|
|
46
|
+
const ERROR_GLOB = '/app/routes/_error.tsx';
|
|
45
47
|
/** and the layouts (`_layout.tsx`): the client puts a page in those of its directories */
|
|
46
|
-
const LAYOUTS_GLOB = ['/app/routes/**/_layout.
|
|
48
|
+
const LAYOUTS_GLOB = ['/app/routes/**/_layout.tsx', '!/app/routes/**/_*/**'];
|
|
47
49
|
/**
|
|
48
50
|
* For the dependency scan: a page's route file as the browser gets it, its server code removed. The scan would find
|
|
49
51
|
* the server's dependencies otherwise, and bundle them for the browser.
|
|
@@ -52,13 +54,13 @@ function scanRoutes(root) {
|
|
|
52
54
|
return {
|
|
53
55
|
name: 'fondu:scan-routes',
|
|
54
56
|
load: {
|
|
55
|
-
filter: { id: /\/app\/routes\/.*\.
|
|
57
|
+
filter: { id: /\/app\/routes\/.*\.tsx$/ },
|
|
56
58
|
async handler(id) {
|
|
57
59
|
const file = relative(`${root()}/app/routes`, id).split(sep).join('/');
|
|
58
60
|
if (file.startsWith('..') || !isPageFile(file))
|
|
59
61
|
return;
|
|
60
62
|
const { code } = await transformWithOxc(readFileSync(id, 'utf8'), id, {
|
|
61
|
-
lang:
|
|
63
|
+
lang: 'tsx',
|
|
62
64
|
jsx: { runtime: 'automatic' },
|
|
63
65
|
});
|
|
64
66
|
return {
|
|
@@ -130,6 +132,8 @@ function dependencies(root = '') {
|
|
|
130
132
|
* server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
|
|
131
133
|
* on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
|
|
132
134
|
* serves the default export itself and reads `PORT` (with the app's `websocket`, if it has one).
|
|
135
|
+
* With `prerender`, the pages the build wrote are served from their files first, with the headers it decided
|
|
136
|
+
* (`prerender.json`, next to this entry).
|
|
133
137
|
*/
|
|
134
138
|
function serverEntry(options) {
|
|
135
139
|
let root = process.cwd();
|
|
@@ -159,15 +163,17 @@ function serverEntry(options) {
|
|
|
159
163
|
`const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
|
|
160
164
|
`const main = new Hono()`,
|
|
161
165
|
`main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
|
|
162
|
-
|
|
163
|
-
//
|
|
166
|
+
// prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
|
|
167
|
+
// this server was built: not there while the build prerenders, so the app renders them then)
|
|
164
168
|
...(options.prerender
|
|
165
169
|
? [
|
|
166
|
-
`import {
|
|
167
|
-
`import {
|
|
168
|
-
`
|
|
170
|
+
`import { existsSync, readFileSync } from 'node:fs'`,
|
|
171
|
+
`import { staticPages } from ${JSON.stringify(staticModule)}`,
|
|
172
|
+
`const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
|
|
173
|
+
`if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
|
|
169
174
|
]
|
|
170
175
|
: []),
|
|
176
|
+
...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
|
|
171
177
|
`main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
|
|
172
178
|
...(bun
|
|
173
179
|
? [
|
|
@@ -256,7 +262,7 @@ function core(options) {
|
|
|
256
262
|
isBuild = env.command === 'build';
|
|
257
263
|
const client = {
|
|
258
264
|
manifest: true,
|
|
259
|
-
|
|
265
|
+
rolldownOptions: {
|
|
260
266
|
input: V.entry,
|
|
261
267
|
// a page's or a layout's chunk named after its route file: (site)/users/[id].tsx is site-users-id
|
|
262
268
|
output: {
|
|
@@ -293,7 +299,9 @@ function core(options) {
|
|
|
293
299
|
const wrangler = resolve(config.root, env.config.build.outDir, 'wrangler.json');
|
|
294
300
|
if (options.prerender && existsSync(wrangler)) {
|
|
295
301
|
const clientDir = resolve(config.root, client.config.build.outDir);
|
|
296
|
-
await prerender(worker(config.root, wrangler), clientDir, config.logger,
|
|
302
|
+
await prerender(worker(config.root, wrangler), clientDir, config.logger, {
|
|
303
|
+
headersFile: true,
|
|
304
|
+
});
|
|
297
305
|
workerFirstForIndex(wrangler);
|
|
298
306
|
}
|
|
299
307
|
}
|
|
@@ -316,7 +324,7 @@ function core(options) {
|
|
|
316
324
|
emptyOutDir: true,
|
|
317
325
|
copyPublicDir: false,
|
|
318
326
|
minify: true,
|
|
319
|
-
|
|
327
|
+
rolldownOptions: {
|
|
320
328
|
input: V.serverEntry,
|
|
321
329
|
external: [
|
|
322
330
|
...builtinModules,
|
|
@@ -334,7 +342,7 @@ function core(options) {
|
|
|
334
342
|
await builder.build(builder.environments.client);
|
|
335
343
|
await builder.build(builder.environments.ssr);
|
|
336
344
|
if (options.prerender)
|
|
337
|
-
await prerender(nodeServer(config.root, target), resolve(config.root, 'dist/client'), config.logger,
|
|
345
|
+
await prerender(nodeServer(config.root, target), resolve(config.root, 'dist/client'), config.logger, { serverDir: resolve(config.root, 'dist/server') });
|
|
338
346
|
},
|
|
339
347
|
},
|
|
340
348
|
};
|
|
@@ -343,7 +351,7 @@ function core(options) {
|
|
|
343
351
|
// so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
|
|
344
352
|
// for it by the app's @mdx-js/rollup; the browser's, a page's route file without its server code
|
|
345
353
|
configEnvironment(name, env) {
|
|
346
|
-
const pages = ['app/routes/**/*.{tsx,
|
|
354
|
+
const pages = ['app/routes/**/*.{tsx,mdx}'];
|
|
347
355
|
const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
|
|
348
356
|
if (name === 'client')
|
|
349
357
|
return {
|
|
@@ -388,7 +396,7 @@ function core(options) {
|
|
|
388
396
|
const env = server.environments.client;
|
|
389
397
|
const css = [];
|
|
390
398
|
try {
|
|
391
|
-
const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.
|
|
399
|
+
const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.tsx$/.test(f) &&
|
|
392
400
|
!f
|
|
393
401
|
.split('/')
|
|
394
402
|
.slice(0, -1)
|
|
@@ -463,9 +471,9 @@ function core(options) {
|
|
|
463
471
|
? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
|
|
464
472
|
: [
|
|
465
473
|
`import '${V.entry}'`,
|
|
466
|
-
`import {
|
|
474
|
+
`import { renderToReadableStream, renderToStaticMarkup } from 'react-dom/server'`,
|
|
467
475
|
`import { renderPage as render } from 'fondu/client'`,
|
|
468
|
-
`export const renderPage = (page) => render(page,
|
|
476
|
+
`export const renderPage = (page, options, after) => render(page, (el) => renderToReadableStream(el, options), after)`,
|
|
469
477
|
`export { renderToStaticMarkup as renderMarkup }`,
|
|
470
478
|
].join('\n');
|
|
471
479
|
if (id === resolved(V.assets))
|
|
@@ -549,11 +557,11 @@ function productionAssets(config, options) {
|
|
|
549
557
|
const pages = {};
|
|
550
558
|
for (const key of Object.keys(manifest)) {
|
|
551
559
|
const file = key.startsWith('app/routes/') ? key.slice('app/routes/'.length) : undefined;
|
|
552
|
-
if (!file || !(isPageFile(file) || /^_error\.
|
|
560
|
+
if (!file || !(isPageFile(file) || /^_error\.tsx$/.test(file)))
|
|
553
561
|
continue;
|
|
554
562
|
// the page's chunk, and its layouts' (loaded with it)
|
|
555
563
|
const around = layoutsOf(file)
|
|
556
|
-
.
|
|
564
|
+
.map((dir) => `app/routes/${dir ? `${dir}/` : ''}_layout.tsx`)
|
|
557
565
|
.filter((k) => k in manifest);
|
|
558
566
|
const all = [...around, key].map(tags);
|
|
559
567
|
pages[pageId(file)] = { css: all.flatMap((t) => t.css), js: all.flatMap((t) => t.js) };
|
package/dist/vite/prerender.d.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import type { Logger } from 'vite';
|
|
2
|
-
import { staticFiles } from '../paths.js';
|
|
3
|
-
export { staticFiles };
|
|
4
2
|
/**
|
|
5
|
-
* A static document's own tags: those with the build's nonce (its Content Security Policy's). The
|
|
6
|
-
* document
|
|
7
|
-
*
|
|
8
|
-
* inline scripts.
|
|
3
|
+
* A static document's own tags: those with the build's nonce (its Content Security Policy's). The policy of a static
|
|
4
|
+
* document has no nonce: its inline scripts are allowed by their hashes instead, and only these tags may have had the
|
|
5
|
+
* nonce: a `nonce` the document has otherwise (in a page's markup) is dropped. Then the hashes of these inline scripts.
|
|
9
6
|
*/
|
|
10
7
|
export declare function ownScripts(html: string, policy: string | undefined): {
|
|
11
8
|
html: string;
|
|
@@ -30,11 +27,17 @@ interface Server {
|
|
|
30
27
|
/**
|
|
31
28
|
* After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
|
|
32
29
|
* `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
|
|
33
|
-
* a navigation, and both are written to the client build
|
|
34
|
-
*
|
|
30
|
+
* a navigation, and both are written to the client build, with the security headers the build decided for them: one
|
|
31
|
+
* set, in `_headers` (Cloudflare serves the files before the Worker) or in `prerender.json` next to the built server
|
|
32
|
+
* (Node and Bun: its entry serves the files before the app).
|
|
35
33
|
*/
|
|
36
|
-
export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger,
|
|
34
|
+
export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, where: {
|
|
35
|
+
headersFile: true;
|
|
36
|
+
} | {
|
|
37
|
+
serverDir: string;
|
|
38
|
+
}): Promise<undefined>;
|
|
37
39
|
/** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
|
|
38
40
|
export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
|
|
39
41
|
/** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
|
|
40
42
|
export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;
|
|
43
|
+
export {};
|