fondu 0.2.0 → 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 CHANGED
@@ -1,12 +1,13 @@
1
1
  # Fondu
2
2
 
3
- **A small meta-framework for full-stack React apps.** It stands on the shoulders of giants: built on Hono, Vite and
4
- Inertia.
3
+ **Server routes. React pages. No API in between.**
4
+
5
+ Fondu is a small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare
6
+ Workers and Node.
5
7
 
6
8
  Routes are Hono handlers in `app/routes/`; pages are React components in `app/pages/`. A route renders a page with its
7
9
  props, and Inertia does the rest in the browser: visits without full reloads, forms with validation, deferred and
8
- merged props, all without an API to write or a client-side router to keep in sync. The same app runs on **Node, Bun and
9
- Cloudflare Workers**.
10
+ merged props, all without an API to write or a client-side router to keep in sync.
10
11
 
11
12
  Fondu writes as little of its own as it can: the server side of Inertia's protocol, file routes, typed pages and
12
13
  URLs, the document and error pages. Everything else is Hono's, Vite's and Inertia's.
@@ -19,22 +20,22 @@ cd my-app
19
20
  bun dev
20
21
  ```
21
22
 
22
- It asks where the app runs (Node, Bun or Cloudflare Workers; or `--target node|bun|cloudflare`) and writes a small
23
+ It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cloudflare|node`) and writes a small
23
24
  app: a route, its page, the error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents.
24
25
 
25
- [demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](apps/demo)) shows every Inertia feature, one page each, on
26
+ [demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo)) shows every Inertia feature, one page each, on
26
27
  Cloudflare Workers with D1 and Better Auth.
27
28
 
28
29
  ## Docs
29
30
 
30
- **[fondu.dev](https://fondu.dev/docs)**: routes, pages and props, forms and validation, type safety, server-side
31
- rendering, static pages, MDX pages, deploying, and the API. Every page is also Markdown for coding agents
31
+ **[fondu.dev](https://fondu.dev/docs)**: routes, pages and props, layouts, forms and validation, type safety,
32
+ server-side rendering, static pages, MDX pages, deploying, and the API. Every page is also Markdown for coding agents
32
33
  ([llms.txt](https://fondu.dev/llms.txt)).
33
34
 
34
35
  ## Contributing
35
36
 
36
37
  ```
37
- packages/fondu the package (≈1,100 lines)
38
+ packages/fondu the package
38
39
  packages/create-fondu `bun create fondu`
39
40
  apps/demo every Inertia feature, one page each — Workers, D1, Better Auth, coss ui
40
41
  apps/site fondu.dev: the docs, MDX and static pages on Workers
@@ -49,13 +50,14 @@ bun run dev # rebuild packages/fondu on change
49
50
  ```
50
51
 
51
52
  Commits follow [Conventional Commits](https://www.conventionalcommits.org) (lefthook runs commitlint, and formats and
52
- lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI publishes the tag to npm
53
- (trusted publishing, with provenance) and writes the GitHub Release from the commits.
53
+ lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI stages it on npm (trusted
54
+ publishing, with provenance), a maintainer approves it, and CI writes the GitHub Release from the commits.
54
55
 
55
56
  `apps/demo`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
56
57
 
57
- See [CONTRIBUTING.md](CONTRIBUTING.md) for the details, and [SECURITY.md](SECURITY.md) to report a vulnerability.
58
+ See [CONTRIBUTING.md](https://github.com/fondujs/fondu/blob/main/CONTRIBUTING.md) for the details, and [SECURITY.md](https://github.com/fondujs/fondu/blob/main/SECURITY.md) to report a
59
+ vulnerability.
58
60
 
59
61
  ## License
60
62
 
61
- Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
63
+ Distributed under the MIT License. See [LICENSE](https://github.com/fondujs/fondu/blob/main/LICENSE) for more information.
@@ -1,6 +1,10 @@
1
1
  import type { Page } from '@inertiajs/core';
2
2
  import type { Context, MiddlewareHandler } from 'hono';
3
- /** The HTML document around a page. */
3
+ import type { ReactElement } from 'react';
4
+ /**
5
+ * The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
6
+ * An inline `<script>` of the document gets the request's nonce, so the Content Security Policy runs it.
7
+ */
4
8
  export interface DocumentParts {
5
9
  /** the page's `<Head>` tags (server render), then the client's styles and scripts */
6
10
  head: string;
@@ -8,7 +12,8 @@ export interface DocumentParts {
8
12
  body: string;
9
13
  c: Context;
10
14
  }
11
- export type DocumentTemplate = (parts: DocumentParts) => string;
15
+ /** the document as JSX (`<html>…</html>`), or as an HTML string */
16
+ export type DocumentTemplate = (parts: DocumentParts) => ReactElement | string;
12
17
  /** the options of the app (`createApp`) a request belongs to */
13
18
  export declare const settings: WeakMap<Context<any, any, {}>, {
14
19
  document?: DocumentTemplate;
@@ -1,5 +1,5 @@
1
1
  import { assetTags } from 'virtual:fondu/assets';
2
- import { renderPage } from 'virtual:fondu/ssr';
2
+ import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
3
3
  const defaultTemplate = ({ head, body }) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}</head><body>${body}</body></html>`;
4
4
  /** the options of the app (`createApp`) a request belongs to */
5
5
  export const settings = new WeakMap();
@@ -15,6 +15,20 @@ export const withoutSsr = () => async (c, next) => {
15
15
  };
16
16
  /** Inertia's own encoding of the page data (`buildSSRBody`): `/` and `<` escaped, no HTML entities. */
17
17
  const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
18
+ // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
19
+ // never read as one
20
+ const HEAD = 'fondu:document-head';
21
+ const BODY = 'fondu:document-body';
22
+ /** the document's own markup: JSX rendered (no whitespace between tags), its inline scripts given the nonce */
23
+ async function shell(template, c, nonce) {
24
+ const out = template({ head: HEAD, body: BODY, c });
25
+ let html = out;
26
+ if (typeof out !== 'string')
27
+ html = `<!doctype html>${await renderMarkup(out)}`;
28
+ if (!nonce)
29
+ return html;
30
+ return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
31
+ }
18
32
  export async function renderDocument(c, page) {
19
33
  const nonce = c.get('secureHeadersNonce');
20
34
  let ssr = null;
@@ -30,5 +44,9 @@ export async function renderDocument(c, page) {
30
44
  // nothing in the page's content can come before it
31
45
  const body = ssr?.body ?? `${pageScript(page)}<div id="app"></div>`;
32
46
  const template = settings.get(c)?.document ?? defaultTemplate;
33
- return template({ head: (ssr?.head.join('') ?? '') + assetTags(page.component, nonce), body, c });
47
+ const html = await shell(template, c, nonce);
48
+ const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
49
+ if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
50
+ throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
51
+ return before + (ssr?.head.join('') ?? '') + assetTags(page.component, nonce) + between + body + after;
34
52
  }
@@ -61,6 +61,12 @@ export function prerenderRoutes(app, routes, version) {
61
61
  c.header('Cache-Control', 'private, no-cache');
62
62
  if (data)
63
63
  c.header('X-Inertia', 'true');
64
+ // the document's scripts had the build's nonce: this response's, as the security headers give it a new one
65
+ const nonce = c.get('secureHeadersNonce');
66
+ if (!data && nonce) {
67
+ const html = new TextDecoder().decode(body).replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
68
+ return c.html(html, 200);
69
+ }
64
70
  return c.body(body, 200, {
65
71
  'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
66
72
  });
@@ -2,7 +2,7 @@ import type { SharedPageProps } from '@inertiajs/core';
2
2
  import type { Context, MiddlewareHandler } from 'hono';
3
3
  import type { Pages } from '../types.js';
4
4
  /**
5
- * The server side of the Inertia v3 protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
5
+ * The server side of Inertia's protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
6
6
  * The client is `@inertiajs/react`, unchanged.
7
7
  */
8
8
  type Shareable<T> = {
package/dist/virtual.d.ts CHANGED
@@ -12,4 +12,6 @@ declare module 'virtual:fondu/assets' {
12
12
  declare module 'virtual:fondu/ssr' {
13
13
  /** the app's `createInertiaApp(...)` rendering a page on the server (null: `fondu({ ssr: false })`) */
14
14
  export const renderPage: ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>) | null
15
+ /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
16
+ export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
15
17
  }
@@ -0,0 +1,28 @@
1
+ import type { Plugin } from 'vite';
2
+ /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
3
+ export declare const PROPS_EVENT = "fondu:props";
4
+ /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
5
+ export declare const PAGE_EXPORTS = "__fondu_pageExports";
6
+ type Node = {
7
+ file: string | null;
8
+ importers: Set<Node>;
9
+ };
10
+ /**
11
+ * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
12
+ * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
13
+ * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
14
+ */
15
+ export declare function reach(start: Iterable<Node>, root: string): {
16
+ routes: boolean;
17
+ document: boolean;
18
+ };
19
+ /**
20
+ * Dev: a change updates what it changes, without reloading the page where it can.
21
+ * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
22
+ * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
23
+ * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
24
+ * and scroll kept, as React Router's "Hot Data Revalidation".
25
+ * - The document (`server.ts` and what only it imports): the page reloads.
26
+ */
27
+ export declare function hmr(): Plugin;
28
+ export {};
@@ -0,0 +1,106 @@
1
+ import { relative, sep } from 'node:path';
2
+ import { isPageFile } from '../paths.js';
3
+ /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
4
+ export const PROPS_EVENT = 'fondu:props';
5
+ /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
6
+ export const PAGE_EXPORTS = '__fondu_pageExports';
7
+ /**
8
+ * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
9
+ * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
10
+ * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
11
+ */
12
+ export function reach(start, root) {
13
+ const found = { routes: false, document: false };
14
+ const seen = new Set();
15
+ const queue = [...start];
16
+ while (queue.length) {
17
+ const mod = queue.shift();
18
+ if (seen.has(mod) || !mod.file)
19
+ continue;
20
+ seen.add(mod);
21
+ const rel = relative(root, mod.file).split(sep).join('/');
22
+ if (rel.startsWith('..') || rel.includes('node_modules/') || !rel.startsWith('app/'))
23
+ continue;
24
+ if (rel.startsWith('app/routes/'))
25
+ found.routes = true;
26
+ else if (rel === 'app/server.ts')
27
+ found.document = true;
28
+ else if (rel !== 'app/app.tsx')
29
+ queue.push(...mod.importers);
30
+ }
31
+ return found;
32
+ }
33
+ /**
34
+ * Dev: a change updates what it changes, without reloading the page where it can.
35
+ * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
36
+ * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
37
+ * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
38
+ * and scroll kept, as React Router's "Hot Data Revalidation".
39
+ * - The document (`server.ts` and what only it imports): the page reloads.
40
+ */
41
+ export function hmr() {
42
+ let root = process.cwd();
43
+ return {
44
+ name: 'fondu:hmr',
45
+ apply: 'serve',
46
+ configResolved(c) {
47
+ root = c.root;
48
+ },
49
+ // the named exports of a page module, for the dev preamble's `__getReactRefreshIgnoredExports`
50
+ transform: {
51
+ order: 'post',
52
+ handler(code, id) {
53
+ if (this.environment.config.consumer !== 'client')
54
+ return;
55
+ const file = id.split('?')[0];
56
+ const rel = relative(`${root}/app/pages`, file).split(sep).join('/');
57
+ if (rel.startsWith('..') || !isPageFile(rel))
58
+ return;
59
+ const names = namedExports(this.parse(code));
60
+ if (!names.length)
61
+ return;
62
+ return {
63
+ code: `${code}\n;(window.${PAGE_EXPORTS} ??= {})[${JSON.stringify(file)}] = ${JSON.stringify(names)};\n`,
64
+ map: null,
65
+ };
66
+ },
67
+ },
68
+ hotUpdate({ file, server }) {
69
+ if (this.environment.name !== 'client')
70
+ return;
71
+ const servers = Object.values(server.environments).filter((env) => env.name !== 'client');
72
+ const onServer = servers.flatMap((env) => [...(env.moduleGraph.getModulesByFile(file) ?? [])]);
73
+ if (!onServer.length)
74
+ return; // the browser's only (or a file a stylesheet watches, as Tailwind's sources)
75
+ const { routes, document } = reach(onServer, root);
76
+ const client = this.environment;
77
+ if (document) {
78
+ client.hot.send({ type: 'full-reload' });
79
+ return [];
80
+ }
81
+ // once the server's modules are updated (they are, in this same update, after the browser's)
82
+ if (routes)
83
+ setTimeout(() => client.hot.send(PROPS_EVENT, {}));
84
+ const inBrowser = [...(client.moduleGraph.getModulesByFile(file) ?? [])].some((m) => m.type === 'js');
85
+ if (!inBrowser)
86
+ return [];
87
+ },
88
+ };
89
+ }
90
+ /** the names a module exports other than `default` */
91
+ function namedExports(program) {
92
+ const names = [];
93
+ for (const node of program.body) {
94
+ if (node.type !== 'ExportNamedDeclaration')
95
+ continue;
96
+ const declaration = node.declaration;
97
+ if (declaration?.id)
98
+ names.push(declaration.id.name);
99
+ for (const d of declaration?.declarations ?? [])
100
+ if (d.id.type === 'Identifier')
101
+ names.push(d.id.name);
102
+ for (const s of node.specifiers ?? [])
103
+ names.push(s.exported.name ?? s.exported.value);
104
+ }
105
+ return names.filter((n) => n !== 'default');
106
+ }
@@ -7,6 +7,7 @@ import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-s
7
7
  import inertia from '@inertiajs/vite';
8
8
  import react, {} from '@vitejs/plugin-react';
9
9
  import { isPageFile } from '../paths.js';
10
+ import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
10
11
  import { layouts } from './layouts.js';
11
12
  import { nodeServer, prerender, worker } from './prerender.js';
12
13
  import { typegen } from './typegen.js';
@@ -58,16 +59,41 @@ function scanMdx(config) {
58
59
  },
59
60
  };
60
61
  }
62
+ /**
63
+ * The Worker never mounts or hydrates a page, but @inertiajs/react imports `react-dom/client` (createRoot,
64
+ * hydrateRoot) at its top: the whole of React's browser renderer in the Worker, evaluated at every start. There, it
65
+ * is a module that says so if called (about a third of the Worker, and of its start in dev)
66
+ */
67
+ const REACT_DOM_CLIENT = '\0fondu:react-dom-client';
68
+ function serverReactDomClient() {
69
+ return {
70
+ name: 'fondu:server-react-dom-client',
71
+ enforce: 'pre',
72
+ applyToEnvironment: (env) => env.config.consumer === 'server',
73
+ resolveId: { filter: { id: /^react-dom\/client$/ }, handler: () => REACT_DOM_CLIENT },
74
+ load: {
75
+ filter: { id: /^\0fondu:react-dom-client$/ },
76
+ handler: () => [
77
+ `const browserOnly = (name) => () => { throw new Error('fondu: react-dom/client ' + name + '() runs in the browser, not in the server') }`,
78
+ `export const createRoot = browserOnly('createRoot')`,
79
+ `export const hydrateRoot = browserOnly('hydrateRoot')`,
80
+ `export const version = ''`,
81
+ ].join('\n'),
82
+ },
83
+ };
84
+ }
61
85
  export default function fondu(options) {
62
86
  const node = options.target !== 'cloudflare';
63
87
  return [
64
- react(options.react),
88
+ // .mdx too: MDX pages and components get Fast Refresh (as MDX's own docs set it up)
89
+ react({ include: /\.(?:[jt]sx?|mdx)$/, ...options.react }),
65
90
  // `ssr: {}`: the server transform without an entry, so without @inertiajs/vite's dev SSR endpoint (Laravel's model)
66
91
  inertia({ ssr: options.ssr === false ? false : {}, frameworks: inertiaInProcess }),
67
92
  core(options),
68
93
  layouts(),
94
+ hmr(),
69
95
  typegen(),
70
- ...(node ? runtimePlugins(options) : []),
96
+ ...(node ? runtimePlugins(options) : [serverReactDomClient()]),
71
97
  ];
72
98
  }
73
99
  async function buildPlugin(options) {
@@ -215,6 +241,8 @@ function core(options) {
215
241
  include: [...HONO, ...(options.ssr === false ? [] : ['react-dom/server'])],
216
242
  entries: [SERVER.slice(2), 'app/routes/**/*.ts', ENTRY, ...pages],
217
243
  ...mdx,
244
+ // the pre-bundled @inertiajs/react too
245
+ rolldownOptions: { plugins: [...mdx.rolldownOptions.plugins, serverReactDomClient()] },
218
246
  },
219
247
  ...(env.build?.minify === undefined && { build: { minify: true } }),
220
248
  };
@@ -230,18 +258,6 @@ function core(options) {
230
258
  const clientDir = resolve(config.root, 'dist/client');
231
259
  await prerender(nodeServer(config.root, options.target), clientDir, config.logger, false);
232
260
  },
233
- // dev: server code changed (a module of the server only: routes/, *.server.ts…): reload the page; a page component:
234
- // React Fast Refresh (the client's HMR)
235
- handleHotUpdate({ server, file }) {
236
- const modules = (env) => [...(server.environments[env]?.moduleGraph.getModulesByFile(file) ?? [])];
237
- // the browser's code (not a file a stylesheet only watches, as Tailwind's sources), or no server's: leave it
238
- if (modules('client').some((m) => m.type === 'js'))
239
- return;
240
- if (!Object.keys(server.environments).some((env) => env !== 'client' && modules(env).length))
241
- return;
242
- server.hot.send({ type: 'full-reload' });
243
- return [];
244
- },
245
261
  // dev: the CSS the client entry imports, as a stylesheet in the document, so a server-rendered page is styled
246
262
  // at first paint (Vite would add it only once the JS runs); removed once the entry has run
247
263
  configureServer(server) {
@@ -288,17 +304,29 @@ function core(options) {
288
304
  if (id === V.assets || id === V.ssr)
289
305
  return resolved(id);
290
306
  },
291
- // prerender: the client entry reads page objects from the prerendered files (fondu/client's `prerendered`)
307
+ // the client entry: with prerender, page objects read from the prerendered files (fondu/client's `prerendered`);
308
+ // in dev, the page's props asked for again when what its route depends on changed (hmr.ts)
292
309
  transform(code, id) {
293
- if (!options.prerender || this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
310
+ if (this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
294
311
  return;
295
- return { code: `import { prerendered } from 'fondu/client';prerendered();${code}`, map: null };
312
+ const before = [
313
+ ...(options.prerender ? [`import { prerendered } from 'fondu/client';prerendered();`] : []),
314
+ ...(isBuild
315
+ ? []
316
+ : [
317
+ `import { router as __fondu_router } from '@inertiajs/react';`,
318
+ `import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => __fondu_router.reload());`,
319
+ ]),
320
+ ];
321
+ if (before.length)
322
+ return { code: before.join('') + code, map: null };
296
323
  },
297
324
  load(id) {
325
+ // and React's static markup for a JSX document (react-dom/server: the server render's, or loaded for it)
298
326
  if (id === resolved(V.ssr))
299
327
  return options.ssr === false
300
- ? 'export const renderPage = null'
301
- : `export { default as renderPage } from '/${ENTRY}'`;
328
+ ? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
329
+ : `export { default as renderPage } from '/${ENTRY}'\nexport { renderToStaticMarkup as renderMarkup } from 'react-dom/server'`;
302
330
  if (id === resolved(V.assets))
303
331
  return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
304
332
  `\nexport const prerender = ${Boolean(options.prerender)}`);
@@ -312,7 +340,7 @@ function core(options) {
312
340
  const isServerOnly = (id) => /\.server\.[cm]?[jt]sx?(\?.*)?$/.test(id) || /\/app\/(routes\/|server\.ts)/.test(id);
313
341
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
314
342
  function devAssets(base) {
315
- const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true`;
343
+ const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true;window.__getReactRefreshIgnoredExports=({id})=>window.${PAGE_EXPORTS}?.[id]??[]`;
316
344
  return `export const version = null
317
345
  export const pages = null
318
346
  export function assetTags(_component, nonce) {
@@ -1,8 +1,13 @@
1
1
  import type { Logger } from 'vite';
2
2
  import { staticFiles } from '../paths.js';
3
3
  export { staticFiles };
4
- /** a Content Security Policy for a static document: no nonce (one for every visitor is none), `'self'` scripts */
5
- export declare function staticPolicy(policy: string): string;
4
+ /** the hashes of a document's inline scripts that have the nonce (the document's own, as Fondu gave it) */
5
+ export declare function nonceScriptHashes(html: string): string[];
6
+ /**
7
+ * A Content Security Policy for a static document: no nonce (one for every visitor is none); the scripts that had it
8
+ * allowed by their hashes instead, and `'self'` scripts
9
+ */
10
+ export declare function staticPolicy(policy: string, hashes?: string[]): string;
6
11
  /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
7
12
  export declare function headerRules(headers: Record<string, string>): string;
8
13
  /** the built server, running for the prerender: fetch a path of it, stop it */
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
2
3
  import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
3
4
  import { createRequire } from 'node:module';
4
5
  import { createServer } from 'node:net';
@@ -8,8 +9,19 @@ import { PAGE_DATA, staticFiles } from '../paths.js';
8
9
  export { staticFiles };
9
10
  /** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
10
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;
11
- /** a Content Security Policy for a static document: no nonce (one for every visitor is none), `'self'` scripts */
12
- export function staticPolicy(policy) {
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 = []) {
13
25
  return policy
14
26
  .split(';')
15
27
  .map((directive) => {
@@ -17,6 +29,8 @@ export function staticPolicy(policy) {
17
29
  if (!name)
18
30
  return '';
19
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);
20
34
  if (/^script-src(-elem)?$/i.test(name) && kept.length === 0)
21
35
  kept.push("'self'");
22
36
  return [name, ...kept].join(' ');
@@ -70,16 +84,18 @@ export async function prerender(start, clientDir, logger, headersFile) {
70
84
  errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
71
85
  continue;
72
86
  }
87
+ const html = await doc.text();
88
+ const hashes = nonceScriptHashes(html);
73
89
  const headers = Object.fromEntries([...doc.headers]
74
90
  .filter(([name]) => SECURITY_HEADERS.test(name))
75
- .map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value) : value]));
91
+ .map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value, hashes) : value]));
76
92
  if (headersFile && security && JSON.stringify(headers) !== JSON.stringify(security)) {
77
93
  errors.push(`${path}: its security headers differ from ${paths[0]}'s; one set is written for all`);
78
94
  continue;
79
95
  }
80
96
  security = headers;
81
97
  const files = staticFiles(path);
82
- write(clientDir, files.html, await doc.text());
98
+ write(clientDir, files.html, html);
83
99
  write(clientDir, files.json, JSON.stringify(page));
84
100
  logger.info(`fondu: prerendered ${path}`);
85
101
  }
package/package.json CHANGED
@@ -1,7 +1,20 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.2.0",
4
- "description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. Node, Bun and Cloudflare Workers.",
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
+ ],
5
18
  "homepage": "https://fondu.dev",
6
19
  "bugs": "https://github.com/fondujs/fondu/issues",
7
20
  "license": "MIT",
@@ -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",