fondu 0.1.3 → 0.3.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 +27 -154
- package/dist/client.d.ts +6 -0
- package/dist/client.js +25 -1
- package/dist/paths.d.ts +15 -0
- package/dist/paths.js +25 -0
- package/dist/server/app.js +19 -2
- package/dist/server/document.d.ts +7 -2
- package/dist/server/document.js +20 -2
- package/dist/server/prerender.d.ts +23 -0
- package/dist/server/prerender.js +96 -0
- package/dist/server/protocol.d.ts +1 -1
- package/dist/server/protocol.js +6 -3
- package/dist/virtual.d.ts +4 -0
- package/dist/vite/hmr.d.ts +28 -0
- package/dist/vite/hmr.js +106 -0
- package/dist/vite/index.d.ts +7 -0
- package/dist/vite/index.js +128 -29
- package/dist/vite/layouts.d.ts +8 -0
- package/dist/vite/layouts.js +77 -0
- package/dist/vite/prerender.d.ts +28 -0
- package/dist/vite/prerender.js +180 -0
- package/dist/vite/typegen.d.ts +4 -1
- package/dist/vite/typegen.js +7 -6
- package/package.json +18 -3
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { createServer } from 'node:net';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { PAGE_DATA, staticFiles } from '../paths.js';
|
|
9
|
+
export { staticFiles };
|
|
10
|
+
/** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
|
|
11
|
+
const SECURITY_HEADERS = /^(content-security-policy(-report-only)?|strict-transport-security|referrer-policy|permissions-policy|x-content-type-options|x-frame-options|x-xss-protection|x-dns-prefetch-control|x-download-options|x-permitted-cross-domain-policies|origin-agent-cluster|cross-origin-(opener|embedder|resource)-policy)$/i;
|
|
12
|
+
/** the hashes of a document's inline scripts that have the nonce (the document's own, as Fondu gave it) */
|
|
13
|
+
export function nonceScriptHashes(html) {
|
|
14
|
+
const hashes = new Set();
|
|
15
|
+
for (const [, attrs, code] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi))
|
|
16
|
+
if (/\snonce=/i.test(attrs) && !/\ssrc=/i.test(attrs))
|
|
17
|
+
hashes.add(`'sha256-${createHash('sha256').update(code).digest('base64')}'`);
|
|
18
|
+
return [...hashes];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A Content Security Policy for a static document: no nonce (one for every visitor is none); the scripts that had it
|
|
22
|
+
* allowed by their hashes instead, and `'self'` scripts
|
|
23
|
+
*/
|
|
24
|
+
export function staticPolicy(policy, hashes = []) {
|
|
25
|
+
return policy
|
|
26
|
+
.split(';')
|
|
27
|
+
.map((directive) => {
|
|
28
|
+
const [name, ...sources] = directive.trim().split(/\s+/);
|
|
29
|
+
if (!name)
|
|
30
|
+
return '';
|
|
31
|
+
const kept = sources.filter((s) => !s.startsWith("'nonce-"));
|
|
32
|
+
if (kept.length < sources.length && /^script-src(-elem)?$/i.test(name))
|
|
33
|
+
kept.push(...hashes);
|
|
34
|
+
if (/^script-src(-elem)?$/i.test(name) && kept.length === 0)
|
|
35
|
+
kept.push("'self'");
|
|
36
|
+
return [name, ...kept].join(' ');
|
|
37
|
+
})
|
|
38
|
+
.filter(Boolean)
|
|
39
|
+
.join('; ');
|
|
40
|
+
}
|
|
41
|
+
/** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
|
|
42
|
+
export function headerRules(headers) {
|
|
43
|
+
const lines = Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`);
|
|
44
|
+
return `\n/*\n${lines.join('\n')}\n${PAGE_DATA}/*\n X-Inertia: true\n`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* After the build: the built server (the Worker in wrangler, or `node` / `bun dist/index.js`), started with
|
|
48
|
+
* `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
|
|
49
|
+
* a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
|
|
50
|
+
* headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
|
|
51
|
+
*/
|
|
52
|
+
export async function prerender(start, clientDir, logger, headersFile) {
|
|
53
|
+
const fail = (lines) => {
|
|
54
|
+
for (const line of lines)
|
|
55
|
+
logger.error(`fondu: ${line}`);
|
|
56
|
+
throw new Error(`fondu: prerendering failed (${lines.length === 1 ? lines[0] : `${lines.length} problems, above`})`);
|
|
57
|
+
};
|
|
58
|
+
const server = await start().catch((error) => fail([error.message]));
|
|
59
|
+
try {
|
|
60
|
+
const get = server.fetch;
|
|
61
|
+
const listing = await get('/__fondu/prerender');
|
|
62
|
+
if (!listing.ok)
|
|
63
|
+
return fail([`the server did not list the pages (${listing.status})`]);
|
|
64
|
+
const { version, paths, problems } = (await listing.json());
|
|
65
|
+
if (problems.length)
|
|
66
|
+
return fail(problems);
|
|
67
|
+
if (paths.length === 0) {
|
|
68
|
+
logger.warn('fondu: prerender is on, and no route has `export const prerender`');
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
let security;
|
|
72
|
+
const errors = [];
|
|
73
|
+
for (const path of paths) {
|
|
74
|
+
const doc = await get(path, { Accept: 'text/html' });
|
|
75
|
+
const visit = await get(path, { 'X-Inertia': 'true', ...(version && { 'X-Inertia-Version': version }) });
|
|
76
|
+
if (doc.status !== 200 || visit.status !== 200) {
|
|
77
|
+
const to = doc.headers.get('location');
|
|
78
|
+
errors.push(`${path}: ${doc.status}${to ? ` → ${to}` : ''} (a prerendered page must answer 200 to anyone)`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const page = (await visit.json());
|
|
82
|
+
const later = ['deferredProps', 'scrollProps'].filter((key) => page[key]);
|
|
83
|
+
if (later.length) {
|
|
84
|
+
errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const html = await doc.text();
|
|
88
|
+
const hashes = nonceScriptHashes(html);
|
|
89
|
+
const headers = Object.fromEntries([...doc.headers]
|
|
90
|
+
.filter(([name]) => SECURITY_HEADERS.test(name))
|
|
91
|
+
.map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value, hashes) : value]));
|
|
92
|
+
if (headersFile && security && JSON.stringify(headers) !== JSON.stringify(security)) {
|
|
93
|
+
errors.push(`${path}: its security headers differ from ${paths[0]}'s; one set is written for all`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
security = headers;
|
|
97
|
+
const files = staticFiles(path);
|
|
98
|
+
write(clientDir, files.html, html);
|
|
99
|
+
write(clientDir, files.json, JSON.stringify(page));
|
|
100
|
+
logger.info(`fondu: prerendered ${path}`);
|
|
101
|
+
}
|
|
102
|
+
if (errors.length)
|
|
103
|
+
return fail(errors);
|
|
104
|
+
if (headersFile)
|
|
105
|
+
appendFileSync(join(clientDir, '_headers'), headerRules(security ?? {}));
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
await server.dispose();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
|
|
112
|
+
export const worker = (root, workerConfig) => async () => {
|
|
113
|
+
let wrangler;
|
|
114
|
+
try {
|
|
115
|
+
const entry = createRequire(resolve(root, 'package.json')).resolve('wrangler');
|
|
116
|
+
wrangler = (await import(pathToFileURL(entry).href));
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
throw new Error('wrangler is not installed: `npm install -D wrangler` (or bun / pnpm / yarn)');
|
|
120
|
+
}
|
|
121
|
+
const started = await wrangler.unstable_startWorker({
|
|
122
|
+
config: workerConfig,
|
|
123
|
+
bindings: { FONDU_PRERENDER: { type: 'plain_text', value: '1' } },
|
|
124
|
+
dev: { server: { port: 0 }, inspector: false, logLevel: 'error' },
|
|
125
|
+
});
|
|
126
|
+
await started.ready;
|
|
127
|
+
return {
|
|
128
|
+
fetch: (path, headers = {}) => started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
|
|
129
|
+
dispose: () => started.dispose(),
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
/** Node / Bun: `node dist/index.js` (or `bun`), on a free port, until it answers */
|
|
133
|
+
export const nodeServer = (root, runtime) => async () => {
|
|
134
|
+
const port = await freePort();
|
|
135
|
+
const child = spawn(runtime, ['dist/index.js'], {
|
|
136
|
+
cwd: root,
|
|
137
|
+
env: { ...process.env, PORT: String(port), FONDU_PRERENDER: '1', NODE_ENV: 'production' },
|
|
138
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
139
|
+
});
|
|
140
|
+
let output = '';
|
|
141
|
+
child.stdout.on('data', (d) => (output += d));
|
|
142
|
+
child.stderr.on('data', (d) => (output += d));
|
|
143
|
+
const base = `http://127.0.0.1:${port}`;
|
|
144
|
+
const server = {
|
|
145
|
+
fetch: (path, headers = {}) => fetch(base + path, { headers, redirect: 'manual' }),
|
|
146
|
+
dispose: async () => {
|
|
147
|
+
if (child.exitCode !== null)
|
|
148
|
+
return;
|
|
149
|
+
const exited = new Promise((r) => child.once('exit', r));
|
|
150
|
+
child.kill();
|
|
151
|
+
const force = setTimeout(() => child.kill('SIGKILL'), 3000);
|
|
152
|
+
await exited;
|
|
153
|
+
clearTimeout(force);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
for (let tries = 0;; tries++) {
|
|
157
|
+
if (child.exitCode !== null || tries === 200)
|
|
158
|
+
throw new Error(`the server (${runtime} dist/index.js) did not start:\n${output.trim()}`);
|
|
159
|
+
try {
|
|
160
|
+
await fetch(base + '/__fondu/prerender');
|
|
161
|
+
return server;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const freePort = () => new Promise((resolve, reject) => {
|
|
169
|
+
const s = createServer();
|
|
170
|
+
s.on('error', reject);
|
|
171
|
+
s.listen(0, '127.0.0.1', () => {
|
|
172
|
+
const { port } = s.address();
|
|
173
|
+
s.close(() => resolve(port));
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
function write(dir, file, content) {
|
|
177
|
+
const to = join(dir, file);
|
|
178
|
+
mkdirSync(dirname(to), { recursive: true });
|
|
179
|
+
writeFileSync(to, content);
|
|
180
|
+
}
|
package/dist/vite/typegen.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { Plugin } from 'vite';
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
|
|
4
|
+
* MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
|
|
5
|
+
*/
|
|
3
6
|
export declare function generateTypes(root: string): string;
|
|
4
7
|
export declare function writeTypes(root: string): void;
|
|
5
8
|
export declare function typegen(): Plugin;
|
package/dist/vite/typegen.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { join, relative, sep } from 'node:path';
|
|
3
|
-
import { isRouteFile, routePattern } from '../paths.js';
|
|
3
|
+
import { isPageFile, isRouteFile, routePattern } from '../paths.js';
|
|
4
4
|
const OUT = 'app/fondu.gen.d.ts';
|
|
5
5
|
function walk(dir, out = [], base = dir) {
|
|
6
6
|
if (!existsSync(dir))
|
|
@@ -14,18 +14,19 @@ function walk(dir, out = [], base = dir) {
|
|
|
14
14
|
}
|
|
15
15
|
return out;
|
|
16
16
|
}
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
|
|
19
|
+
* MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
|
|
20
|
+
*/
|
|
18
21
|
export function generateTypes(root) {
|
|
19
|
-
const pages = walk(join(root, 'app/pages'))
|
|
20
|
-
.filter((f) => /\.[jt]sx$/.test(f))
|
|
21
|
-
.sort();
|
|
22
|
+
const pages = walk(join(root, 'app/pages')).filter(isPageFile).sort();
|
|
22
23
|
const routes = walk(join(root, 'app/routes')).filter(isRouteFile).sort();
|
|
23
24
|
const line = (key, path) => ` ${JSON.stringify(key)}: typeof import(${JSON.stringify(path)})`;
|
|
24
25
|
return `// Generated by fondu (vite dev / vite build). Commit it; do not edit.
|
|
25
26
|
declare module 'fondu' {
|
|
26
27
|
interface Register {
|
|
27
28
|
pages: {
|
|
28
|
-
${pages.map((f) => line(f.replace(/\.[jt]sx$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
|
|
29
|
+
${pages.map((f) => line(f.replace(/\.(?:[jt]sx|mdx)$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
|
|
29
30
|
}
|
|
30
31
|
routes: {
|
|
31
32
|
${routes.map((f) => line(routePattern(f), `./routes/${f.replace(/\.ts$/, '')}`)).join('\n')}
|
package/package.json
CHANGED
|
@@ -1,8 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fondu",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare Workers and Node.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"bun",
|
|
7
|
+
"cloudflare-workers",
|
|
8
|
+
"fondujs",
|
|
9
|
+
"hono",
|
|
10
|
+
"honojs",
|
|
11
|
+
"inertia",
|
|
12
|
+
"inertiajs",
|
|
13
|
+
"nodejs",
|
|
14
|
+
"react",
|
|
15
|
+
"ssr",
|
|
16
|
+
"vite"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://fondu.dev",
|
|
6
19
|
"bugs": "https://github.com/fondujs/fondu/issues",
|
|
7
20
|
"license": "MIT",
|
|
8
21
|
"repository": {
|
|
@@ -45,6 +58,8 @@
|
|
|
45
58
|
"@inertiajs/core": "3.9.1",
|
|
46
59
|
"@inertiajs/react": "3.9.1",
|
|
47
60
|
"@types/node": "26.6.4",
|
|
61
|
+
"@types/react": "19.3.0",
|
|
62
|
+
"@types/react-dom": "19.3.0",
|
|
48
63
|
"hono": "4.13.13",
|
|
49
64
|
"typescript": "7.0.2",
|
|
50
65
|
"vite": "8.3.4",
|