fondu 0.9.5 → 0.10.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.
Files changed (51) hide show
  1. package/README.md +7 -12
  2. package/dist/client/app.d.ts +40 -0
  3. package/dist/client/app.js +162 -0
  4. package/dist/client/navigation.d.ts +35 -0
  5. package/dist/client/navigation.js +210 -0
  6. package/dist/client/progress.d.ts +16 -0
  7. package/dist/client/progress.js +51 -0
  8. package/dist/client.d.ts +4 -15
  9. package/dist/client.js +3 -47
  10. package/dist/index.d.ts +3 -4
  11. package/dist/index.js +3 -4
  12. package/dist/paths.d.ts +10 -7
  13. package/dist/paths.js +15 -15
  14. package/dist/server/app.d.ts +4 -5
  15. package/dist/server/app.js +81 -16
  16. package/dist/server/document.d.ts +3 -3
  17. package/dist/server/document.js +7 -6
  18. package/dist/server/errors.d.ts +4 -2
  19. package/dist/server/errors.js +21 -10
  20. package/dist/server/flash.d.ts +4 -7
  21. package/dist/server/flash.js +9 -14
  22. package/dist/server/handler.d.ts +1 -1
  23. package/dist/server/handler.js +1 -1
  24. package/dist/server/http.d.ts +7 -5
  25. package/dist/server/http.js +15 -6
  26. package/dist/server/prerender.d.ts +1 -1
  27. package/dist/server/prerender.js +6 -6
  28. package/dist/server/protocol.d.ts +22 -35
  29. package/dist/server/protocol.js +65 -195
  30. package/dist/server/routes.d.ts +1 -1
  31. package/dist/server/validate.d.ts +7 -9
  32. package/dist/server/validate.js +8 -21
  33. package/dist/types.d.ts +10 -6
  34. package/dist/virtual.d.ts +3 -5
  35. package/dist/vite/hmr.d.ts +3 -3
  36. package/dist/vite/hmr.js +5 -5
  37. package/dist/vite/index.d.ts +9 -5
  38. package/dist/vite/index.js +158 -79
  39. package/dist/vite/prerender.d.ts +7 -3
  40. package/dist/vite/prerender.js +49 -16
  41. package/dist/vite/strip.d.ts +21 -0
  42. package/dist/vite/strip.js +301 -0
  43. package/dist/vite/typegen.d.ts +3 -2
  44. package/dist/vite/typegen.js +6 -10
  45. package/package.json +2 -9
  46. package/dist/server/props.d.ts +0 -85
  47. package/dist/server/props.js +0 -44
  48. package/dist/vite/layouts.d.ts +0 -10
  49. package/dist/vite/layouts.js +0 -110
  50. package/dist/vite/vitest-cache.d.ts +0 -19
  51. package/dist/vite/vitest-cache.js +0 -30
package/dist/vite/hmr.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { relative, sep } from 'node:path';
2
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) */
3
+ /** the browser's event for "the current page's props may have changed" (the client entry: `reload()`) */
4
4
  export const PROPS_EVENT = 'fondu:props';
5
5
  /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
6
6
  export const PAGE_EXPORTS = '__fondu_pageExports';
7
7
  /**
8
8
  * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
9
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.
10
+ * other than through a route).
11
11
  */
12
12
  export function reach(start, root) {
13
13
  const found = { routes: false, document: false };
@@ -25,7 +25,7 @@ export function reach(start, root) {
25
25
  found.routes = true;
26
26
  else if (rel === 'app/server.ts')
27
27
  found.document = true;
28
- else if (rel !== 'app/app.tsx')
28
+ else
29
29
  queue.push(...mod.importers);
30
30
  }
31
31
  return found;
@@ -34,7 +34,7 @@ export function reach(start, root) {
34
34
  * Dev: a change updates what it changes, without reloading the page where it can.
35
35
  * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
36
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
37
+ * - What a route depends on: the browser asks for the page's props again (fondu/client's `reload()`), its state
38
38
  * and scroll kept, as React Router's "Hot Data Revalidation".
39
39
  * - The document (`server.ts` and what only it imports): the page reloads.
40
40
  */
@@ -53,7 +53,7 @@ export function hmr() {
53
53
  if (this.environment.config.consumer !== 'client')
54
54
  return;
55
55
  const file = id.split('?')[0];
56
- const rel = relative(`${root}/app/pages`, file).split(sep).join('/');
56
+ const rel = relative(`${root}/app/routes`, file).split(sep).join('/');
57
57
  if (rel.startsWith('..') || !isPageFile(rel))
58
58
  return;
59
59
  const names = namedExports(this.parse(code));
@@ -1,13 +1,15 @@
1
1
  import { type Options as ReactOptions } from '@vitejs/plugin-react';
2
- import type { PluginOption } from 'vite';
2
+ import { type PluginOption } from 'vite';
3
+ import type { ProgressOptions } from '../client/progress.js';
3
4
  /**
4
5
  * `vite.config.ts`: `plugins: [fondu({ target: 'node' })]` (or `'bun'`; for Cloudflare: `cloudflare()` and
5
6
  * `fondu({ target: 'cloudflare' })`). Composes the packages that do the work:
6
- * - `@vitejs/plugin-react`, and `@inertiajs/vite` (pages from `app/pages/`, the server render of `app/app.tsx`)
7
+ * - `@vitejs/plugin-react`
7
8
  * - Node / Bun: `@hono/vite-dev-server` (dev); the build is Vite's own, of two environments (`serverEntry()`)
8
9
  * - Cloudflare: `@cloudflare/vite-plugin` (yours: dev in workerd, the Worker's build)
9
- * and adds what none of them does: the document's asset tags, the generated types, the server-only guard. One
10
- * `vite build` builds the client, then the server, then the pages to prerender.
10
+ * and adds what none of them does: the app's entry (its pages and layouts, from `app/routes/`), the browser's copy of
11
+ * a page's route file (its server code removed), the document's asset tags, the generated types, the server-only
12
+ * guard. One `vite build` builds the client, then the server, then the pages to prerender.
11
13
  */
12
14
  export interface FonduOptions {
13
15
  target: 'node' | 'bun' | 'cloudflare';
@@ -18,9 +20,11 @@ export interface FonduOptions {
18
20
  react?: ReactOptions;
19
21
  /**
20
22
  * Routes with `export const prerender` (or under a `_middleware.ts` with it) are written as static files at build
21
- * time, and visits read them; the server (the Worker) answers the other pages
23
+ * time, and navigations read them; the server (the Worker) answers the other pages
22
24
  */
23
25
  prerender?: boolean;
26
+ /** the bar at the top of the page while a navigation is on its way: its `delay` (ms) and `color`; `false`: none */
27
+ progress?: ProgressOptions | false;
24
28
  }
25
29
  /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
26
30
  export declare const HONO: string[];
@@ -1,18 +1,17 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
3
3
  import { builtinModules, createRequire } from 'node:module';
4
- import { dirname, join, resolve } from 'node:path';
4
+ import { dirname, join, relative, resolve, sep } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
7
- import inertia from '@inertiajs/vite';
8
7
  import react, {} from '@vitejs/plugin-react';
9
- import { isPageFile } from '../paths.js';
8
+ import { parseAst, transformWithOxc, } from 'vite';
9
+ import { isPageFile, layoutsOf, pageId } from '../paths.js';
10
10
  import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
11
- import { layouts } from './layouts.js';
12
11
  import { nodeServer, prerender, worker } from './prerender.js';
12
+ import { stripRoutes, stripServerCode } from './strip.js';
13
13
  import { typegen } from './typegen.js';
14
- import { vitestCache } from './vitest-cache.js';
15
- const ENTRY = 'app/app.tsx';
14
+ import { walk as walkFiles } from './typegen.js';
16
15
  /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
17
16
  export const HONO = [
18
17
  'hono',
@@ -27,28 +26,49 @@ export const HONO = [
27
26
  const SERVER = './app/server.ts';
28
27
  const DEV_CSS = '/@fondu/dev.css';
29
28
  const V = {
29
+ /** the app's entry: the browser's, and the server render's */
30
+ entry: 'virtual:fondu/entry',
30
31
  assets: 'virtual:fondu/assets',
31
32
  ssr: 'virtual:fondu/ssr',
32
33
  serverEntry: 'virtual:fondu/server-entry',
33
34
  };
34
35
  const resolved = (id) => '\0' + id;
36
+ /** the pages, for the app's entry: the route files of `app/routes/` that are React, but what isn't a route */
37
+ const PAGES_GLOB = [
38
+ '/app/routes/**/*.{tsx,jsx,mdx}',
39
+ '!/app/routes/**/_*',
40
+ '!/app/routes/**/_*/**',
41
+ '!/app/routes/**/*.{test,spec}.{tsx,jsx}',
42
+ ];
43
+ /** the error page (`_error.tsx`: a page, though its name says it is no URL) */
44
+ const ERROR_GLOB = '/app/routes/_error.{tsx,jsx}';
45
+ /** and the layouts (`_layout.tsx`): the client puts a page in those of its directories */
46
+ const LAYOUTS_GLOB = ['/app/routes/**/_layout.{tsx,jsx}', '!/app/routes/**/_*/**'];
35
47
  /**
36
- * `@inertiajs/vite` wraps `createInertiaApp(...)` for the server; its React template also starts a standalone
37
- * SSR server (Laravel's model). Same wrap, rendering in this process: the template only exports the render.
48
+ * For the dependency scan: a page's route file as the browser gets it, its server code removed. The scan would find
49
+ * the server's dependencies otherwise, and bundle them for the browser.
38
50
  */
39
- const inertiaInProcess = {
40
- package: '@inertiajs/react',
41
- extensions: ['.tsx', '.jsx', '.mdx'],
42
- extractDefault: true,
43
- ssr: (configureCall) => `
44
- import { renderToString } from 'react-dom/server'
45
- const renderPromise = ${configureCall}
46
- renderPromise.catch((error) => console.error(error))
47
- export default async function renderPage(page) {
48
- return (await renderPromise)(page, renderToString)
51
+ function scanRoutes(root) {
52
+ return {
53
+ name: 'fondu:scan-routes',
54
+ load: {
55
+ filter: { id: /\/app\/routes\/.*\.[jt]sx$/ },
56
+ async handler(id) {
57
+ const file = relative(`${root()}/app/routes`, id).split(sep).join('/');
58
+ if (file.startsWith('..') || !isPageFile(file))
59
+ return;
60
+ const { code } = await transformWithOxc(readFileSync(id, 'utf8'), id, {
61
+ lang: id.endsWith('.jsx') ? 'jsx' : 'tsx',
62
+ jsx: { runtime: 'automatic' },
63
+ });
64
+ return {
65
+ code: stripServerCode(code, parseAst(code), file),
66
+ moduleType: 'js',
67
+ };
68
+ },
69
+ },
70
+ };
49
71
  }
50
- `,
51
- };
52
72
  /** For the dependency scan: an MDX page as the JavaScript @mdx-js/rollup makes of it (nothing without it) */
53
73
  function scanMdx(config) {
54
74
  return {
@@ -65,7 +85,7 @@ function scanMdx(config) {
65
85
  };
66
86
  }
67
87
  /**
68
- * The Worker never mounts or hydrates a page, but @inertiajs/react imports `react-dom/client` (createRoot,
88
+ * The Worker never mounts or hydrates a page, but fondu/client imports `react-dom/client` (createRoot,
69
89
  * hydrateRoot) at its top: the whole of React's browser renderer in the Worker, evaluated at every start. There, it
70
90
  * is a module that says so if called (about a third of the Worker, and of its start in dev)
71
91
  */
@@ -92,11 +112,8 @@ export default function fondu(options) {
92
112
  return [
93
113
  // .mdx too: MDX pages and components get Fast Refresh (as MDX's own docs set it up)
94
114
  react({ include: /\.(?:[jt]sx?|mdx)$/, ...options.react }),
95
- // `ssr: {}`: the server transform without an entry, so without @inertiajs/vite's dev SSR endpoint (Laravel's model)
96
- inertia({ ssr: options.ssr === false ? false : {}, frameworks: inertiaInProcess }),
97
115
  core(options),
98
- layouts(),
99
- vitestCache(ENTRY),
116
+ stripRoutes(),
100
117
  hmr(),
101
118
  loadFailure(),
102
119
  typegen(),
@@ -197,10 +214,9 @@ function runtimePlugins(options) {
197
214
  ];
198
215
  }
199
216
  /**
200
- * Dev: the app that fails to load (a route that throws as it is imported) is Vite's error page, which an Inertia
201
- * visit can't show: its dialog's frame keeps the page's Content Security Policy, which stops the page's script. The
202
- * visit loads the URL as a whole page instead (Inertia's 409), where Vite's overlay shows the error; the next change
203
- * reloads it.
217
+ * Dev: the app that fails to load (a route that throws as it is imported) is Vite's error page, which a navigation
218
+ * can't show as a page: it loads the URL as a document instead (409), where Vite's overlay shows the error; the next
219
+ * change reloads it.
204
220
  */
205
221
  function loadFailure() {
206
222
  let failed = false;
@@ -210,14 +226,14 @@ function loadFailure() {
210
226
  configureServer(server) {
211
227
  // after the dev server (the Cloudflare plugin's too), before Vite's error page
212
228
  return () => server.middlewares.use((error, req, res, next) => {
213
- const visit = Boolean(req.headers['x-inertia']);
229
+ const navigation = req.headers['x-fondu'] === 'true';
214
230
  // a page failed (not a module of the browser's): the next change reloads it
215
- if (visit || req.headers.accept?.includes('text/html'))
231
+ if (navigation || req.headers.accept?.includes('text/html'))
216
232
  failed = true;
217
- if (!visit)
233
+ if (!navigation)
218
234
  return next(error);
219
235
  res.writeHead(409, {
220
- 'X-Inertia-Location': req.originalUrl ?? req.url,
236
+ 'X-Fondu-Location': req.originalUrl ?? req.url,
221
237
  });
222
238
  res.end();
223
239
  });
@@ -238,7 +254,25 @@ function core(options) {
238
254
  enforce: 'pre',
239
255
  config(user, env) {
240
256
  isBuild = env.command === 'build';
241
- const client = { manifest: true, rollupOptions: { input: ENTRY } };
257
+ const client = {
258
+ manifest: true,
259
+ rollupOptions: {
260
+ input: V.entry,
261
+ // a page's or a layout's chunk named after its route file: (site)/users/[id].tsx is site-users-id
262
+ output: {
263
+ chunkFileNames: (chunk) => {
264
+ const file = chunk.facadeModuleId?.split('?')[0];
265
+ const routes = `${config.root}/app/routes/`;
266
+ const name = file?.startsWith(routes)
267
+ ? pageId(file.slice(routes.length))
268
+ .replace(/[^a-zA-Z0-9]+/g, '-')
269
+ .replace(/^-|-$/g, '')
270
+ : undefined;
271
+ return `assets/${name || '[name]'}-[hash].js`;
272
+ },
273
+ },
274
+ },
275
+ };
242
276
  if (options.target === 'cloudflare') {
243
277
  return {
244
278
  environments: { client: { build: client } },
@@ -252,7 +286,8 @@ function core(options) {
252
286
  if (existsSync(ignore))
253
287
  appendFileSync(ignore, '.vite\n');
254
288
  for (const env of Object.values(builder.environments)) {
255
- if (env.name === 'client')
289
+ // the Workers (@cloudflare/vite-plugin's environments, an input each), not Vite's own `ssr`, unused
290
+ if (env.name === 'client' || !env.config.build.rolldownOptions?.input)
256
291
  continue;
257
292
  await builder.build(env);
258
293
  const wrangler = resolve(config.root, env.config.build.outDir, 'wrangler.json');
@@ -305,25 +340,37 @@ function core(options) {
305
340
  },
306
341
  // dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
307
342
  // so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
308
- // for it by the app's @mdx-js/rollup
343
+ // for it by the app's @mdx-js/rollup; the browser's, a page's route file without its server code
309
344
  configEnvironment(name, env) {
310
- const pages = ['app/pages/**/*.{tsx,jsx,mdx}'];
345
+ const pages = ['app/routes/**/*.{tsx,jsx,mdx}'];
311
346
  const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
312
347
  if (name === 'client')
313
- return { optimizeDeps: { entries: [ENTRY, ...pages], ...mdx } };
348
+ return {
349
+ optimizeDeps: {
350
+ entries: pages,
351
+ ...mdx,
352
+ rolldownOptions: {
353
+ plugins: [...mdx.rolldownOptions.plugins, scanRoutes(() => config.root)],
354
+ },
355
+ },
356
+ };
314
357
  if (options.target !== 'cloudflare')
315
358
  return;
316
359
  // the Worker: fondu is not pre-bundled (its routes import it back: a bundle would hand them a half-loaded
317
- // module), so the scan does not see what it imports (HONO); nor react-dom/server, imported by @inertiajs/vite's
318
- // generated render. Found late, they would restart the Worker in the middle of requests.
360
+ // module), so the scan does not see what it imports (HONO, react, react-dom); nor react-dom/server, imported by
361
+ // the server render (virtual:fondu/ssr). Found late, they would restart the Worker in the middle of requests.
319
362
  // The build is minified, as Workers start faster with less code to parse
320
363
  return {
321
364
  optimizeDeps: {
322
365
  exclude: ['fondu'],
323
- include: [...HONO, ...(options.ssr === false ? [] : ['react-dom/server'])],
324
- entries: [SERVER.slice(2), 'app/routes/**/*.ts', ENTRY, ...pages],
366
+ include: [
367
+ ...HONO,
368
+ 'react',
369
+ 'react-dom',
370
+ ...(options.ssr === false ? [] : ['react-dom/server']),
371
+ ],
372
+ entries: [SERVER.slice(2), 'app/routes/**/*.ts', ...pages],
325
373
  ...mdx,
326
- // the pre-bundled @inertiajs/react too
327
374
  rolldownOptions: { plugins: [...mdx.rolldownOptions.plugins, serverReactDomClient()] },
328
375
  },
329
376
  ...(env.build?.minify === undefined && { build: { minify: true } }),
@@ -332,14 +379,20 @@ function core(options) {
332
379
  configResolved(c) {
333
380
  config = c;
334
381
  },
335
- // dev: the CSS the client entry imports, as a stylesheet in the document, so a server-rendered page is styled
336
- // at first paint (Vite would add it only once the JS runs); removed once the entry has run
382
+ // dev: the CSS the layouts import (the app's own: `import './styles/app.css'` in routes/_layout.tsx), as a
383
+ // stylesheet in the document, so a server-rendered page is styled at first paint (Vite would add it only once the
384
+ // JS runs); removed by fondu/client once the page's modules (its layouts: their CSS) are loaded
337
385
  configureServer(server) {
338
386
  server.middlewares.use(DEV_CSS, async (_req, res) => {
339
387
  const env = server.environments.client;
340
388
  const css = [];
341
389
  try {
342
- await env.transformRequest('/' + ENTRY);
390
+ const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.[jt]sx$/.test(f) &&
391
+ !f
392
+ .split('/')
393
+ .slice(0, -1)
394
+ .some((d) => d.startsWith('_')));
395
+ await Promise.all(layouts.map((f) => env.transformRequest(`/app/routes/${f}`)));
343
396
  const seen = new Set();
344
397
  const walk = (mod) => {
345
398
  if (!mod?.id || seen.has(mod.id))
@@ -350,7 +403,8 @@ function core(options) {
350
403
  for (const m of mod.importedModules)
351
404
  walk(m);
352
405
  };
353
- walk(env.moduleGraph.getModuleById(resolve(config.root, ENTRY)));
406
+ for (const f of layouts)
407
+ walk(env.moduleGraph.getModuleById(resolve(config.root, 'app/routes', f)));
354
408
  const parts = await Promise.all(css.map(async (url) => (await env.transformRequest(url + (url.includes('?') ? '&' : '?') + 'direct'))
355
409
  ?.code ?? ''));
356
410
  res.setHeader('Content-Type', 'text/css');
@@ -375,60 +429,79 @@ function core(options) {
375
429
  source: '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n',
376
430
  });
377
431
  },
378
- resolveId(id) {
379
- if (id === V.assets || id === V.ssr)
380
- return resolved(id);
432
+ // the server render loads a page through the entry's import(), of a module createApp has imported already: in
433
+ // the server's bundle, as it should be
434
+ onLog(_level, log) {
435
+ if (log.code === 'INEFFECTIVE_DYNAMIC_IMPORT' && log.message.includes('virtual:fondu/entry'))
436
+ return false;
381
437
  },
382
- // the client entry: with prerender, page objects read from the prerendered files (fondu/client's `prerendered`);
383
- // in production, an answer to a visit that isn't a page loaded as a document (`documentFallback`); in dev,
384
- // Inertia's dialog (the error report is shown there), and the page's props asked for again when what its route
385
- // depends on changed (hmr.ts)
386
- transform(code, id) {
387
- if (this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
388
- return;
389
- const before = [
390
- ...(options.prerender ? [`import { prerendered } from 'fondu/client';prerendered();`] : []),
391
- ...(isBuild
392
- ? [`import { documentFallback } from 'fondu/client';documentFallback();`]
393
- : [
394
- `import { router as __fondu_router } from '@inertiajs/react';`,
395
- `import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => __fondu_router.reload());`,
396
- ]),
397
- ];
398
- if (before.length)
399
- return { code: before.join('') + code, map: null };
438
+ resolveId(id, importer) {
439
+ if (id === V.entry || id === V.assets || id === V.ssr)
440
+ return resolved(id);
441
+ // the server-only guard, for fondu's own: `fondu` is the server's, `fondu/client` the browser's
442
+ if (id === 'fondu' && importer && this.environment.config.consumer === 'client')
443
+ this.error(`fondu: ${importer.replace(config.root, '')} imports 'fondu', server code that cannot be imported by browser code: the browser's is 'fondu/client'`);
400
444
  },
401
445
  load(id) {
446
+ // the app's entry, in the browser and for the server render: the pages and layouts, whether pages are
447
+ // prerendered (navigations read their page objects from the static files), the progress bar; in dev, the
448
+ // page's props asked for again when what its route depends on changed (hmr.ts)
449
+ if (id === resolved(V.entry)) {
450
+ const dev = this.environment.config.consumer === 'client' && !isBuild;
451
+ const settings = { prerender: Boolean(options.prerender), progress: options.progress ?? {} };
452
+ const glob = (pattern) => `import.meta.glob(${JSON.stringify(pattern)})`;
453
+ return [
454
+ `import { __entry${dev ? ', reload' : ''} } from 'fondu/client'`,
455
+ ...(dev ? [`import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => reload())`] : []),
456
+ `__entry({ ...${glob(PAGES_GLOB)}, ...${glob(ERROR_GLOB)} }, ${glob(LAYOUTS_GLOB)}, ${JSON.stringify(settings)})`,
457
+ ].join('\n');
458
+ }
402
459
  // and React's static markup for a JSX document (react-dom/server: the server render's, or loaded for it)
403
460
  if (id === resolved(V.ssr))
404
461
  return options.ssr === false
405
462
  ? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
406
- : `export { default as renderPage } from '/${ENTRY}'\nexport { renderToStaticMarkup as renderMarkup } from 'react-dom/server'`;
463
+ : [
464
+ `import '${V.entry}'`,
465
+ `import { renderToString, renderToStaticMarkup } from 'react-dom/server'`,
466
+ `import { renderPage as render } from 'fondu/client'`,
467
+ `export const renderPage = (page) => render(page, renderToString)`,
468
+ `export { renderToStaticMarkup as renderMarkup }`,
469
+ ].join('\n');
407
470
  if (id === resolved(V.assets))
408
471
  return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
409
472
  `\nexport const prerender = ${Boolean(options.prerender)}`);
410
473
  // the server-only guard: browser code must never import server code
411
474
  if (this.environment.config.consumer === 'client' && isServerOnly(id, config.root)) {
412
- this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/, server.ts, *.server.ts) and cannot be imported by browser code`);
475
+ this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/*.ts, server.ts, *.server.ts) and cannot be imported by browser code`);
413
476
  }
477
+ // and a page's route file as it is (`?raw`, `?url`…): the browser's copy is the page alone
478
+ const [file, query] = id.split('?');
479
+ if (this.environment.config.consumer === 'client' &&
480
+ query &&
481
+ file.startsWith(`${config.root}/app/routes/`) &&
482
+ isPageFile(file.slice(`${config.root}/app/routes/`.length)) &&
483
+ /(?:^|&)(?:raw|url|inline)(?:&|=|$)/.test(query))
484
+ this.error(`fondu: ${file.replace(config.root, '')} has server code: only its page reaches the browser`);
414
485
  },
415
486
  };
416
487
  }
417
- /** `*.server.ts`, or the app's `routes/` and `server.ts` (the root's: a path above it or in a package may have them) */
488
+ /**
489
+ * `*.server.ts`, or the app's `server.ts` and the `.ts` files of `routes/` (the root's: a path above it or in a package
490
+ * may have them). A page's route file (`.tsx`) reaches the browser without its server code (strip.ts).
491
+ */
418
492
  const isServerOnly = (id, root) => {
419
493
  const file = id.split('?')[0];
420
494
  return (/\.server\.[cm]?[jt]sx?$/.test(file) ||
421
- file.startsWith(`${root}/app/routes/`) ||
495
+ (file.startsWith(`${root}/app/routes/`) && file.endsWith('.ts')) ||
422
496
  file === `${root}/app/server.ts`);
423
497
  };
424
498
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
425
499
  function devAssets(base) {
426
500
  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]??[]`;
427
501
  return `export const version = null
428
- export const pages = null
429
502
  export function assetTags(_component, nonce) {
430
503
  return '<link rel="stylesheet" href="${base}${DEV_CSS.slice(1)}" data-fondu-dev-css>'
431
- + \`<script type="module"${nonceAttr}>${preamble}</script><script type="module" src="${base}@vite/client"${nonceAttr}></script><script type="module" src="${base}${ENTRY}"${nonceAttr}></script><script type="module"${nonceAttr}>document.querySelector('[data-fondu-dev-css]')?.remove()</script>\`
504
+ + \`<script type="module"${nonceAttr}>${preamble}</script><script type="module" src="${base}@vite/client"${nonceAttr}></script><script type="module" src="${base}@id/__x00__${V.entry}"${nonceAttr}></script>\`
432
505
  }`;
433
506
  }
434
507
  function productionAssets(config, options) {
@@ -456,19 +529,25 @@ function productionAssets(config, options) {
456
529
  collect(key, css, js);
457
530
  return { css: [...css], js: [...js] };
458
531
  };
459
- const entry = tags(ENTRY);
532
+ // the app's entry: the client build's only one
533
+ const entry = tags(Object.keys(manifest).find((k) => manifest[k].isEntry));
460
534
  const pages = {};
461
535
  for (const key of Object.keys(manifest)) {
462
- const m = key.match(/^app\/pages\/(.+)\.(?:[jt]sx|mdx)$/);
463
- if (m && isPageFile(key))
464
- pages[m[1]] = tags(key);
536
+ const file = key.startsWith('app/routes/') ? key.slice('app/routes/'.length) : undefined;
537
+ if (!file || !(isPageFile(file) || /^_error\.[jt]sx$/.test(file)))
538
+ continue;
539
+ // the page's chunk, and its layouts' (loaded with it)
540
+ const around = layoutsOf(file)
541
+ .flatMap((dir) => ['tsx', 'jsx'].map((ext) => `app/routes/${dir ? `${dir}/` : ''}_layout.${ext}`))
542
+ .filter((k) => k in manifest);
543
+ const all = [...around, key].map(tags);
544
+ pages[pageId(file)] = { css: all.flatMap((t) => t.css), js: all.flatMap((t) => t.js) };
465
545
  }
466
546
  const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
467
547
  return `const base = ${JSON.stringify(config.base)}
468
548
  const entry = ${JSON.stringify(entry)}
469
549
  const byPage = ${JSON.stringify(pages)}
470
550
  export const version = ${JSON.stringify(version)}
471
- export const pages = ${JSON.stringify(Object.keys(pages))}
472
551
  export function assetTags(component, nonce) {
473
552
  const page = byPage[component] ?? { css: [], js: [] }
474
553
  const css = [...new Set([...entry.css, ...page.css])]
@@ -16,8 +16,12 @@ export declare function ownScripts(html: string, policy: string | undefined): {
16
16
  * allowed by their hashes instead, and `'self'` scripts
17
17
  */
18
18
  export declare function staticPolicy(policy: string, hashes?: string[]): string;
19
- /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
20
- export declare function headerRules(headers: Record<string, string>): string;
19
+ /**
20
+ * `_headers` with Fondu's rules in it: the documents' security headers (`/*`), and the page objects' X-Fondu
21
+ * (the client reads a page by it). A path the file has a rule for gets the headers it doesn't set there, so the app's own stay
22
+ * (Workers keep one rule per path: a second `/*` would replace the first); any other, a rule at the end.
23
+ */
24
+ export declare function withHeaderRules(file: string, headers: Record<string, string>): string;
21
25
  /** the built server, running for the prerender: fetch a path of it, stop it */
22
26
  interface Server {
23
27
  fetch(path: string, headers?: Record<string, string>): Promise<Response>;
@@ -26,7 +30,7 @@ interface Server {
26
30
  /**
27
31
  * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
28
32
  * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
29
- * a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
33
+ * a navigation, and both are written to the client build. Cloudflare serves them before the Worker, with the security
30
34
  * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
31
35
  */
32
36
  export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, headersFile: boolean): Promise<undefined>;
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { createServer } from 'node:net';
6
6
  import { dirname, join, resolve } from 'node:path';
@@ -47,15 +47,40 @@ export function staticPolicy(policy, hashes = []) {
47
47
  .filter(Boolean)
48
48
  .join('; ');
49
49
  }
50
- /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
51
- export function headerRules(headers) {
52
- const lines = Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`);
53
- return `\n/*\n${lines.join('\n')}\n${PAGE_DATA}/*\n X-Inertia: true\n`;
50
+ /**
51
+ * `_headers` with Fondu's rules in it: the documents' security headers (`/*`), and the page objects' X-Fondu
52
+ * (the client reads a page by it). A path the file has a rule for gets the headers it doesn't set there, so the app's own stay
53
+ * (Workers keep one rule per path: a second `/*` would replace the first); any other, a rule at the end.
54
+ */
55
+ export function withHeaderRules(file, headers) {
56
+ const lines = file.replace(/\n+$/, '').split('\n');
57
+ const rules = [
58
+ ['/*', headers],
59
+ [`${PAGE_DATA}/*`, { 'X-Fondu': 'true' }],
60
+ ];
61
+ for (const [path, set] of rules) {
62
+ const start = lines.findIndex((line) => line.trimEnd() === path);
63
+ let end = start + 1;
64
+ while (start !== -1 && /^\s+\S/.test(lines[end] ?? ''))
65
+ end++;
66
+ // the names set or removed (`! name`) there
67
+ const own = new Set(lines
68
+ .slice(start + 1, end)
69
+ .map((l) => l.trim().replace(/^!\s*/, '').split(':')[0].toLowerCase()));
70
+ const added = Object.entries(set)
71
+ .filter(([name]) => start === -1 || !own.has(name.toLowerCase()))
72
+ .map(([name, value]) => ` ${name}: ${value}`);
73
+ if (start === -1)
74
+ lines.push(...(lines.at(-1) ? [''] : []), path, ...added);
75
+ else
76
+ lines.splice(end, 0, ...added);
77
+ }
78
+ return `${lines.join('\n')}\n`;
54
79
  }
55
80
  /**
56
81
  * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
57
82
  * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
58
- * a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
83
+ * a navigation, and both are written to the client build. Cloudflare serves them before the Worker, with the security
59
84
  * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
60
85
  */
61
86
  export async function prerender(start, clientDir, logger, headersFile) {
@@ -82,8 +107,8 @@ export async function prerender(start, clientDir, logger, headersFile) {
82
107
  for (const path of paths) {
83
108
  const doc = await get(path, { Accept: 'text/html' });
84
109
  const visit = await get(path, {
85
- 'X-Inertia': 'true',
86
- ...(version && { 'X-Inertia-Version': version }),
110
+ 'X-Fondu': 'true',
111
+ ...(version && { 'X-Fondu-Version': version }),
87
112
  });
88
113
  if (doc.status !== 200 || visit.status !== 200) {
89
114
  const to = doc.headers.get('location');
@@ -91,11 +116,6 @@ export async function prerender(start, clientDir, logger, headersFile) {
91
116
  continue;
92
117
  }
93
118
  const page = (await visit.json());
94
- const later = ['deferredProps', 'scrollProps'].filter((key) => page[key]);
95
- if (later.length) {
96
- errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
97
- continue;
98
- }
99
119
  const { html, hashes } = ownScripts(await doc.text(), doc.headers.get('content-security-policy') ?? undefined);
100
120
  const headers = Object.fromEntries([...doc.headers]
101
121
  .filter(([name]) => SECURITY_HEADERS.test(name))
@@ -115,8 +135,11 @@ export async function prerender(start, clientDir, logger, headersFile) {
115
135
  }
116
136
  if (errors.length)
117
137
  return fail(errors);
118
- if (headersFile)
119
- appendFileSync(join(clientDir, '_headers'), headerRules(security ?? {}));
138
+ if (headersFile) {
139
+ const file = join(clientDir, '_headers');
140
+ const own = existsSync(file) ? readFileSync(file, 'utf8') : '';
141
+ writeFileSync(file, withHeaderRules(own, security ?? {}));
142
+ }
120
143
  }
121
144
  finally {
122
145
  await server.dispose();
@@ -139,7 +162,17 @@ export const worker = (root, workerConfig) => async () => {
139
162
  });
140
163
  await started.ready;
141
164
  return {
142
- fetch: (path, headers = {}) => started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
165
+ // a Worker that throws as it starts: wrangler logs it, then its requests never answer
166
+ fetch: (path, headers = {}) => {
167
+ let timer;
168
+ const late = new Promise((_, reject) => {
169
+ timer = setTimeout(() => reject(new Error(`the Worker did not answer ${path} (an error above?)`)), 60_000);
170
+ });
171
+ return Promise.race([
172
+ started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
173
+ late,
174
+ ]).finally(() => clearTimeout(timer));
175
+ },
143
176
  dispose: () => started.dispose(),
144
177
  };
145
178
  };
@@ -0,0 +1,21 @@
1
+ import type { Plugin } from 'vite';
2
+ /** the exports of a page's route file that are server code: the browser gets the page (default) alone */
3
+ export declare const SERVER_EXPORTS: Set<string>;
4
+ type Node = {
5
+ type: string;
6
+ start: number;
7
+ end: number;
8
+ [key: string]: unknown;
9
+ };
10
+ /**
11
+ * The browser's copy of a page's route file: its server exports removed (`loader`, `action`, `actions`…), then
12
+ * what only they used: imports and top-level declarations no other code names, until none is left. Conservative: a
13
+ * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
14
+ * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
15
+ */
16
+ export declare function stripServerCode(code: string, program: {
17
+ body: Node[];
18
+ }, file: string): string;
19
+ /** The browser's copy of every page's route file (`.tsx`, `.jsx` in `app/routes/`): its server code removed */
20
+ export declare function stripRoutes(): Plugin;
21
+ export {};