fondu 0.13.0 → 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 +39 -16
- package/dist/client/form.d.ts +3 -1
- package/dist/client/form.js +10 -4
- package/dist/client/navigation.d.ts +4 -1
- package/dist/client/navigation.js +171 -27
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/paths.d.ts +7 -2
- package/dist/paths.js +13 -6
- package/dist/server/app.d.ts +7 -3
- package/dist/server/app.js +37 -23
- package/dist/server/document.d.ts +10 -2
- package/dist/server/document.js +69 -18
- package/dist/server/errors.js +1 -0
- package/dist/server/http.d.ts +2 -0
- package/dist/server/http.js +3 -0
- package/dist/server/prerender.js +7 -52
- package/dist/server/protocol.d.ts +16 -2
- package/dist/server/protocol.js +95 -15
- package/dist/server/routes.d.ts +3 -1
- package/dist/server/routes.js +6 -2
- package/dist/server/static.d.ts +14 -0
- package/dist/server/static.js +37 -0
- package/dist/virtual.d.ts +5 -1
- package/dist/vite/index.js +30 -21
- package/dist/vite/prerender.d.ts +11 -7
- package/dist/vite/prerender.js +13 -10
- package/dist/vite/strip.d.ts +1 -1
- package/dist/vite/strip.js +1 -1
- package/dist/vite/typegen.js +1 -1
- package/package.json +1 -1
package/dist/paths.js
CHANGED
|
@@ -33,23 +33,23 @@ export function routePatterns(file) {
|
|
|
33
33
|
.join('/');
|
|
34
34
|
return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
|
|
35
35
|
}
|
|
36
|
-
const ROUTE_EXTENSION = /\.(?:
|
|
36
|
+
const ROUTE_EXTENSION = /\.(?:tsx?|mdx)$/;
|
|
37
37
|
/**
|
|
38
|
-
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.
|
|
38
|
+
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
|
|
39
39
|
* tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
|
|
40
40
|
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
41
41
|
*/
|
|
42
42
|
export function isRouteFile(file) {
|
|
43
43
|
return (ROUTE_EXTENSION.test(file) &&
|
|
44
44
|
!file.endsWith('.d.ts') &&
|
|
45
|
-
!/\.(?:test|spec)\.
|
|
45
|
+
!/\.(?:test|spec)\.tsx?$/.test(file) &&
|
|
46
46
|
!file.split('/').some((s) => s.startsWith('_')));
|
|
47
47
|
}
|
|
48
48
|
/** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
|
|
49
49
|
export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
50
50
|
export const HANDLERS = ['loader', 'action', 'actions'];
|
|
51
51
|
export const CONFIG = ['prerender', 'params'];
|
|
52
|
-
/** a route file that is a page (React: `.tsx`, `.
|
|
52
|
+
/** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
|
|
53
53
|
export const isPageFile = (file) => isRouteFile(file) && !file.endsWith('.ts');
|
|
54
54
|
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
55
55
|
export const pageId = (file) => file.replace(ROUTE_EXTENSION, '');
|
|
@@ -122,8 +122,15 @@ export function pathOfPageData(pathname) {
|
|
|
122
122
|
return null;
|
|
123
123
|
return m[1].replace(/(?<=\/)index$/, '').replace(/(?<=\/)~(~*index)$/, '$1');
|
|
124
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
|
|
127
|
+
* `/docs/` → `docs/index.html`
|
|
128
|
+
*/
|
|
129
|
+
export const htmlFile = (decodedPath) => (decodedPath.endsWith('/') ? `${decodedPath}index.html` : `${decodedPath}.html`).slice(1);
|
|
125
130
|
/** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
|
|
126
131
|
export function staticFiles(path) {
|
|
127
|
-
|
|
128
|
-
|
|
132
|
+
return {
|
|
133
|
+
html: htmlFile(decodeURIComponent(path)),
|
|
134
|
+
json: decodeURIComponent(pageDataPath(path)).slice(1),
|
|
135
|
+
};
|
|
129
136
|
}
|
package/dist/server/app.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export interface CreateAppOptions {
|
|
|
9
9
|
trailingSlash?: 'trim' | 'append';
|
|
10
10
|
/** `hono/csrf`'s options; `false`: off */
|
|
11
11
|
csrf?: Parameters<typeof csrf>[0] | false;
|
|
12
|
+
/** the largest request body, in bytes (default: 10 MB), then 413: `hono/body-limit`; `false`: no limit */
|
|
13
|
+
bodyLimit?: number | false;
|
|
12
14
|
/**
|
|
13
15
|
* `hono/secure-headers`' options; `false`: off. Defaults: `referrerPolicy: 'same-origin'` (which `back()` needs) and
|
|
14
16
|
* a Content Security Policy whose directives yours replace one by one; `contentSecurityPolicy: false`: none
|
|
@@ -18,13 +20,15 @@ export interface CreateAppOptions {
|
|
|
18
20
|
}) | false;
|
|
19
21
|
}
|
|
20
22
|
type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
|
|
23
|
+
export declare function checkExports(file: string, mod: Record<string, unknown>): void;
|
|
21
24
|
/**
|
|
22
25
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
23
26
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
24
|
-
* own), `action` (POST) or `actions` (POST `?name`)
|
|
25
|
-
* - server code, `.ts`:
|
|
27
|
+
* own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
|
|
28
|
+
* - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
|
|
29
|
+
* `action`, `actions`: those are a page's)
|
|
26
30
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
27
|
-
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
31
|
+
* Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
|
|
28
32
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
29
33
|
*/
|
|
30
34
|
export declare function createApp(options?: CreateAppOptions): Hono;
|
package/dist/server/app.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
2
3
|
import { every } from 'hono/combine';
|
|
3
4
|
import { csrf } from 'hono/csrf';
|
|
4
5
|
import { HTTPException } from 'hono/http-exception';
|
|
@@ -24,14 +25,15 @@ const CSP = {
|
|
|
24
25
|
};
|
|
25
26
|
const ROOT = '/app/routes/';
|
|
26
27
|
/**
|
|
27
|
-
* What a file of `app/routes/` may export, and what to do with anything else:
|
|
28
|
-
*
|
|
28
|
+
* What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
|
|
29
|
+
* page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
|
|
30
|
+
* HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
|
|
29
31
|
*/
|
|
30
32
|
function exportsOf(file) {
|
|
31
33
|
const name = file.split('/').at(-1);
|
|
32
34
|
if (name === '_middleware.ts')
|
|
33
35
|
return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
|
|
34
|
-
if (/^_(?:layout|error)\.
|
|
36
|
+
if (/^_(?:layout|error)\.tsx$/.test(name))
|
|
35
37
|
return { allowed: ['default'], hint: 'its component only (default)' };
|
|
36
38
|
if (file.endsWith('.mdx'))
|
|
37
39
|
return {
|
|
@@ -40,21 +42,32 @@ function exportsOf(file) {
|
|
|
40
42
|
};
|
|
41
43
|
if (file.endsWith('.ts'))
|
|
42
44
|
return {
|
|
43
|
-
allowed: [...
|
|
44
|
-
hint: '
|
|
45
|
+
allowed: [...METHODS, ...CONFIG],
|
|
46
|
+
hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
|
|
45
47
|
};
|
|
46
48
|
return {
|
|
47
49
|
allowed: ['default', ...HANDLERS, ...CONFIG],
|
|
48
50
|
hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
|
|
49
51
|
};
|
|
50
52
|
}
|
|
51
|
-
|
|
53
|
+
/** what a page's handler is called in a `.ts` file */
|
|
54
|
+
const INSTEAD = {
|
|
55
|
+
loader: 'in a .ts file it is `GET`',
|
|
56
|
+
action: 'in a .ts file it is `POST`',
|
|
57
|
+
actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
|
|
58
|
+
};
|
|
59
|
+
export function checkExports(file, mod) {
|
|
52
60
|
const { allowed, hint } = exportsOf(file);
|
|
53
61
|
const mdx = file.endsWith('.mdx');
|
|
54
62
|
const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
|
|
55
|
-
if (extra.length)
|
|
56
|
-
|
|
57
|
-
|
|
63
|
+
if (extra.length) {
|
|
64
|
+
const renamed = file.endsWith('.ts')
|
|
65
|
+
? extra.filter((k) => k in INSTEAD)
|
|
66
|
+
: [];
|
|
67
|
+
throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
|
|
68
|
+
(renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
|
|
69
|
+
}
|
|
70
|
+
if (/\.(?:tsx|mdx)$/.test(file) && typeof mod.default !== 'function')
|
|
58
71
|
throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
|
|
59
72
|
}
|
|
60
73
|
/** a thrown `ValidationError` becomes the page it came from with its errors (or 422 for an API client) */
|
|
@@ -77,10 +90,11 @@ function actionName(url) {
|
|
|
77
90
|
/**
|
|
78
91
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
79
92
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
80
|
-
* own), `action` (POST) or `actions` (POST `?name`)
|
|
81
|
-
* - server code, `.ts`:
|
|
93
|
+
* own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
|
|
94
|
+
* - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
|
|
95
|
+
* `action`, `actions`: those are a page's)
|
|
82
96
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
83
|
-
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
97
|
+
* Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
|
|
84
98
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
85
99
|
*/
|
|
86
100
|
export function createApp(options = {}) {
|
|
@@ -88,14 +102,13 @@ export function createApp(options = {}) {
|
|
|
88
102
|
const modules = Object.fromEntries(Object.entries(
|
|
89
103
|
// without a type argument: Vitest's module cache leaves out a module with `import.meta.glob(` only
|
|
90
104
|
import.meta.glob([
|
|
91
|
-
'/app/routes/**/*.{ts,tsx,jsx,mdx}',
|
|
105
|
+
'/app/routes/**/*.{ts,tsx,jsx,mdx}', // a .jsx file is found to be refused (routeTable)
|
|
92
106
|
'!/app/routes/**/*.d.ts',
|
|
93
107
|
'!/app/routes/**/*.{test,spec}.{ts,tsx,jsx}', // test files aren't the app's
|
|
94
108
|
'!/app/routes/**/_*/**', // nor what a directory keeps beside its routes
|
|
95
109
|
], { eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
|
|
96
110
|
for (const [file, mod] of Object.entries(modules)) {
|
|
97
|
-
if (!isRouteFile(file) &&
|
|
98
|
-
!/(?:^|\/)_(?:middleware\.ts|layout\.[jt]sx|error\.[jt]sx)$/.test(file))
|
|
111
|
+
if (!isRouteFile(file) && !/(?:^|\/)_(?:middleware\.ts|layout\.tsx|error\.tsx)$/.test(file))
|
|
99
112
|
continue; // a file of a directory's own (`_badge.tsx`)
|
|
100
113
|
checkExports(file, mod);
|
|
101
114
|
if (isPageFile(file))
|
|
@@ -103,7 +116,7 @@ export function createApp(options = {}) {
|
|
|
103
116
|
}
|
|
104
117
|
const own = {
|
|
105
118
|
document: options.document,
|
|
106
|
-
errorPage: Boolean(modules['_error.tsx']
|
|
119
|
+
errorPage: Boolean(modules['_error.tsx']),
|
|
107
120
|
};
|
|
108
121
|
const append = options.trailingSlash === 'append';
|
|
109
122
|
app.use(async (c, next) => {
|
|
@@ -120,6 +133,14 @@ export function createApp(options = {}) {
|
|
|
120
133
|
}
|
|
121
134
|
if (options.csrf !== false)
|
|
122
135
|
app.use(csrf(options.csrf));
|
|
136
|
+
if (options.bodyLimit !== false)
|
|
137
|
+
app.use(bodyLimit({
|
|
138
|
+
maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
|
|
139
|
+
// Fondu's own answer: the error page for a visitor, the status alone for an API client
|
|
140
|
+
onError: () => {
|
|
141
|
+
throw new HTTPException(413);
|
|
142
|
+
},
|
|
143
|
+
}));
|
|
123
144
|
const prerendered = [];
|
|
124
145
|
if (prerender)
|
|
125
146
|
prerenderRoutes(app, () => prerendered, version);
|
|
@@ -152,13 +173,6 @@ export function createApp(options = {}) {
|
|
|
152
173
|
...METHODS.filter((m) => m !== 'GET' && m !== 'POST' && mod[m]),
|
|
153
174
|
],
|
|
154
175
|
});
|
|
155
|
-
const conflict = (a, b) => {
|
|
156
|
-
if (mod[a] && mod[b])
|
|
157
|
-
throw new Error(`fondu: routes/${file} exports both \`${a}\` and \`${b}\`, which handle the same requests`);
|
|
158
|
-
};
|
|
159
|
-
conflict('loader', 'GET');
|
|
160
|
-
conflict('action', 'POST');
|
|
161
|
-
conflict('actions', 'POST');
|
|
162
176
|
if (mod.action && mod.actions)
|
|
163
177
|
throw new Error(`fondu: routes/${file} exports both \`action\` and \`actions\`: one form posts to \`action\`, several each to one of \`actions\` (?name)`);
|
|
164
178
|
const add = (method, handlers) => app.on(method, pattern, ...handlers);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
-
import type
|
|
2
|
+
import { type ReactElement } from 'react';
|
|
3
3
|
import type { Page } from '../client/navigation.js';
|
|
4
4
|
/**
|
|
5
5
|
* The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
|
|
@@ -28,4 +28,12 @@ export declare const settings: WeakMap<Context<any, any, {}>, {
|
|
|
28
28
|
* `fondu({ ssr: false })`.
|
|
29
29
|
*/
|
|
30
30
|
export declare const withoutSsr: () => MiddlewareHandler;
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
|
|
33
|
+
* (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
|
|
34
|
+
* boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
|
|
35
|
+
* first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
|
|
36
|
+
* `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
|
|
37
|
+
* `renderToString` gave).
|
|
38
|
+
*/
|
|
39
|
+
export declare function renderDocument(c: Context, page: Page, whole?: boolean): Promise<string | ReadableStream<Uint8Array>>;
|
package/dist/server/document.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createElement } from 'react';
|
|
1
2
|
import { assetTags } from 'virtual:fondu/assets';
|
|
2
3
|
import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
|
|
3
4
|
import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
|
|
@@ -23,7 +24,7 @@ const pageScript = (page) => `<script data-page="app" type="application/json">${
|
|
|
23
24
|
* their own until then (to the #fragment, WebKit and Firefox), fondu/client keeping their restoration off. Not once
|
|
24
25
|
* the visitor has scrolled, typed or clicked: their own scrolling wins.
|
|
25
26
|
*/
|
|
26
|
-
const restoreScroll =
|
|
27
|
+
const restoreScroll = `try{var k=history.state&&history.state[${JSON.stringify(SCROLL_KEY)}],p=k&&JSON.parse(sessionStorage.getItem(${JSON.stringify(SCROLL_STORAGE)}+k));if(p){var go=function(){scrollTo(+p.x||0,+p.y||0)},off=function(){go=0};go();["wheel","touchstart","keydown","mousedown"].forEach(function(t){addEventListener(t,off,{once:!0,passive:!0})});addEventListener("load",function(){setTimeout(function(){go&&go()})})}}catch(e){}`;
|
|
27
28
|
// where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
|
|
28
29
|
// never read as one
|
|
29
30
|
const HEAD = 'fondu:document-head';
|
|
@@ -41,13 +42,43 @@ async function shell(template, c, nonce) {
|
|
|
41
42
|
return html;
|
|
42
43
|
return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
|
|
43
44
|
}
|
|
44
|
-
|
|
45
|
+
/**
|
|
46
|
+
* The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
|
|
47
|
+
* (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
|
|
48
|
+
* boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
|
|
49
|
+
* first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
|
|
50
|
+
* `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
|
|
51
|
+
* `renderToString` gave).
|
|
52
|
+
*/
|
|
53
|
+
export async function renderDocument(c, page, whole = false) {
|
|
45
54
|
const nonce = nonceOf(c);
|
|
55
|
+
// the template first: one that is wrong fails before anything renders (no stream left running)
|
|
56
|
+
const template = settings.get(c)?.document ?? defaultTemplate;
|
|
57
|
+
const html = await shell(template, c, nonce);
|
|
58
|
+
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
59
|
+
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
60
|
+
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
46
61
|
let ssr = null;
|
|
62
|
+
// what fails in a boundary is for the browser to render, and is logged. The shell's failure is logged below, once:
|
|
63
|
+
// React reports it to `onError` too, so what it reports is held until the shell is known to be there
|
|
64
|
+
const pending = [];
|
|
65
|
+
let live = false;
|
|
66
|
+
const late = (error) => console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
|
|
47
67
|
try {
|
|
48
|
-
//
|
|
49
|
-
if (renderPage && !browserOnly.has(c))
|
|
50
|
-
|
|
68
|
+
// a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
|
|
69
|
+
if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
|
|
70
|
+
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
|
|
71
|
+
const stream = await renderPage(JSON.parse(JSON.stringify(page)), { nonce, onError: (error) => (live ? late(error) : void pending.push(error)) },
|
|
72
|
+
// the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
|
|
73
|
+
// shell, right after the page, before what the boundaries add
|
|
74
|
+
createElement('script', { nonce, dangerouslySetInnerHTML: { __html: restoreScroll } }));
|
|
75
|
+
if (whole)
|
|
76
|
+
await stream.allReady;
|
|
77
|
+
ssr = stream.pipeThrough(new TextDecoderStream());
|
|
78
|
+
for (const error of pending)
|
|
79
|
+
late(error);
|
|
80
|
+
live = true;
|
|
81
|
+
}
|
|
51
82
|
}
|
|
52
83
|
catch (error) {
|
|
53
84
|
// like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
|
|
@@ -55,13 +86,7 @@ export async function renderDocument(c, page) {
|
|
|
55
86
|
}
|
|
56
87
|
// the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
|
|
57
88
|
// content can come before it
|
|
58
|
-
|
|
59
|
-
const body = pageScript(page) + (ssr ? ssr.body + restoreScroll(nonce) : '<div id="app"></div>');
|
|
60
|
-
const template = settings.get(c)?.document ?? defaultTemplate;
|
|
61
|
-
const html = await shell(template, c, nonce);
|
|
62
|
-
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
63
|
-
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
64
|
-
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
89
|
+
const data = pageScript(page);
|
|
65
90
|
// the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
|
|
66
91
|
// document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
|
|
67
92
|
// the page out early (Firefox's, with its tools open) has them sooner
|
|
@@ -69,10 +94,36 @@ export async function renderDocument(c, page) {
|
|
|
69
94
|
const css = tags.match(/<link rel="stylesheet"[^>]*>/g)?.join('') ?? '';
|
|
70
95
|
const charset = /<meta charset=[^>]*>/i;
|
|
71
96
|
const top = css && charset.test(before) ? before.replace(charset, (meta) => meta + css) : before + css;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
97
|
+
const start = top + tags.replace(/<link rel="stylesheet"[^>]*>/g, '');
|
|
98
|
+
if (!ssr)
|
|
99
|
+
return start + between + data + '<div id="app"></div>' + after;
|
|
100
|
+
// React's own: the tags the page hoists, then the page (`<div id="app"`), found across chunks
|
|
101
|
+
const reader = ssr.getReader();
|
|
102
|
+
let text = '';
|
|
103
|
+
let at = -1;
|
|
104
|
+
while (at < 0) {
|
|
105
|
+
const { done, value } = await reader.read();
|
|
106
|
+
if (done)
|
|
107
|
+
break;
|
|
108
|
+
text += value;
|
|
109
|
+
at = text.indexOf('<div id="app"');
|
|
110
|
+
}
|
|
111
|
+
const out = new TextEncoder();
|
|
112
|
+
return new ReadableStream({
|
|
113
|
+
start(controller) {
|
|
114
|
+
controller.enqueue(out.encode(start + text.slice(0, at) + between + data + text.slice(at)));
|
|
115
|
+
},
|
|
116
|
+
async pull(controller) {
|
|
117
|
+
const { done, value } = await reader.read();
|
|
118
|
+
if (!done)
|
|
119
|
+
return controller.enqueue(out.encode(value));
|
|
120
|
+
controller.enqueue(out.encode(after));
|
|
121
|
+
controller.close();
|
|
122
|
+
},
|
|
123
|
+
// the visitor left: React stops (its abort reaches `onError`: not an error of the page)
|
|
124
|
+
cancel(reason) {
|
|
125
|
+
live = false;
|
|
126
|
+
return reader.cancel(reason);
|
|
127
|
+
},
|
|
128
|
+
});
|
|
78
129
|
}
|
package/dist/server/errors.js
CHANGED
package/dist/server/http.d.ts
CHANGED
|
@@ -15,3 +15,5 @@ export declare const back: (c: Context, fallback?: string) => Response & import(
|
|
|
15
15
|
* unless they can't change (a `fetch()`'s): the copy.
|
|
16
16
|
*/
|
|
17
17
|
export declare function appendHeader(c: Context, name: string, value: string): void;
|
|
18
|
+
/** the build is prerendering (`FONDU_PRERENDER`: a Worker binding, or the environment of `node` / `bun dist/server/index.js`) */
|
|
19
|
+
export declare const isPrerendering: (c: Context) => boolean;
|
package/dist/server/http.js
CHANGED
|
@@ -34,3 +34,6 @@ export function appendHeader(c, name, value) {
|
|
|
34
34
|
c.header(name, value, { append: true });
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
+
/** the build is prerendering (`FONDU_PRERENDER`: a Worker binding, or the environment of `node` / `bun dist/server/index.js`) */
|
|
38
|
+
export const isPrerendering = (c) => Boolean(c.env?.FONDU_PRERENDER ??
|
|
39
|
+
globalThis.process?.env?.FONDU_PRERENDER);
|
package/dist/server/prerender.js
CHANGED
|
@@ -1,12 +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
|
-
/**
|
|
6
|
-
* a prerendered page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment; `\\`
|
|
7
|
-
* separates segments too (Windows)
|
|
8
|
-
*/
|
|
9
|
-
const isStaticFile = (file) => file.split(/[\\/]/).every((s) => s !== '' && !s.startsWith('.'));
|
|
1
|
+
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
|
|
2
|
+
import { isPrerendering } from './http.js';
|
|
10
3
|
/** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
|
|
11
4
|
export async function prerenderPaths(routes) {
|
|
12
5
|
const paths = new Set();
|
|
@@ -49,47 +42,11 @@ export async function prerenderPaths(routes) {
|
|
|
49
42
|
* a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
|
|
50
43
|
*/
|
|
51
44
|
export function prerenderRoutes(app, routes, version) {
|
|
52
|
-
// Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
|
|
53
|
-
// Cloudflare, Workers Static Assets serve the files before the Worker runs). The built server says how to read them.
|
|
54
|
-
app.use(async (c, next) => {
|
|
55
|
-
const read = globalThis[STATIC_FILES];
|
|
56
|
-
if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
|
|
57
|
-
return next();
|
|
58
|
-
const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
|
|
59
|
-
if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
|
|
60
|
-
return next();
|
|
61
|
-
// a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
|
|
62
|
-
if (!data && endsInIndex(c.req.path))
|
|
63
|
-
return next();
|
|
64
|
-
let file;
|
|
65
|
-
try {
|
|
66
|
-
file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
|
|
67
|
-
}
|
|
68
|
-
catch {
|
|
69
|
-
return next(); // not a path a file could have
|
|
70
|
-
}
|
|
71
|
-
if (!isStaticFile(file))
|
|
72
|
-
return next();
|
|
73
|
-
const body = await read(file);
|
|
74
|
-
if (!body)
|
|
75
|
-
return next();
|
|
76
|
-
c.header('Cache-Control', 'private, no-cache');
|
|
77
|
-
if (data)
|
|
78
|
-
c.header('X-Fondu', 'true');
|
|
79
|
-
// the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
|
|
80
|
-
// security headers give it a new one
|
|
81
|
-
const nonce = nonceOf(c);
|
|
82
|
-
if (!data && nonce) {
|
|
83
|
-
const html = new TextDecoder()
|
|
84
|
-
.decode(body)
|
|
85
|
-
.replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
|
|
86
|
-
return c.html(html, 200);
|
|
87
|
-
}
|
|
88
|
-
return c.body(body, 200, {
|
|
89
|
-
'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
|
|
90
|
-
});
|
|
91
|
-
});
|
|
92
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' });
|
|
93
50
|
const path = pathOfPageData(c.req.path);
|
|
94
51
|
// a page object's own URL is not a page: no page object of a page object (and so on)
|
|
95
52
|
if (!path || path.startsWith('/_fondu/'))
|
|
@@ -107,9 +64,7 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
107
64
|
});
|
|
108
65
|
app.get('/__fondu/prerender', async (c) => {
|
|
109
66
|
// set for the build only: a Worker binding, or the environment of `node` / `bun dist/server/index.js`
|
|
110
|
-
|
|
111
|
-
globalThis.process?.env?.FONDU_PRERENDER;
|
|
112
|
-
if (!env)
|
|
67
|
+
if (!isPrerendering(c))
|
|
113
68
|
return c.notFound();
|
|
114
69
|
return c.json({ version, ...(await prerenderPaths(routes())) });
|
|
115
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)
|