fondu 0.9.6 → 0.11.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 +11 -15
- package/dist/client/app.d.ts +40 -0
- package/dist/client/app.js +185 -0
- package/dist/client/navigation.d.ts +36 -0
- package/dist/client/navigation.js +432 -0
- package/dist/client/progress.d.ts +16 -0
- package/dist/client/progress.js +64 -0
- package/dist/client.d.ts +4 -15
- package/dist/client.js +3 -47
- package/dist/index.d.ts +3 -4
- package/dist/index.js +3 -4
- package/dist/paths.d.ts +23 -8
- package/dist/paths.js +52 -21
- package/dist/server/app.d.ts +4 -5
- package/dist/server/app.js +81 -16
- package/dist/server/document.d.ts +3 -3
- package/dist/server/document.js +27 -6
- package/dist/server/errors.d.ts +4 -2
- package/dist/server/errors.js +23 -10
- package/dist/server/flash.d.ts +4 -7
- package/dist/server/flash.js +9 -14
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +1 -1
- package/dist/server/http.d.ts +7 -5
- package/dist/server/http.js +15 -6
- package/dist/server/prerender.d.ts +1 -1
- package/dist/server/prerender.js +18 -10
- package/dist/server/protocol.d.ts +22 -35
- package/dist/server/protocol.js +67 -195
- package/dist/server/routes.d.ts +1 -1
- package/dist/server/validate.d.ts +8 -9
- package/dist/server/validate.js +23 -37
- package/dist/types.d.ts +10 -6
- package/dist/virtual.d.ts +3 -5
- package/dist/vite/hmr.d.ts +3 -3
- package/dist/vite/hmr.js +5 -5
- package/dist/vite/index.d.ts +9 -5
- package/dist/vite/index.js +174 -80
- package/dist/vite/prerender.d.ts +3 -3
- package/dist/vite/prerender.js +17 -12
- package/dist/vite/strip.d.ts +21 -0
- package/dist/vite/strip.js +306 -0
- package/dist/vite/typegen.d.ts +3 -2
- package/dist/vite/typegen.js +6 -10
- package/package.json +2 -9
- package/dist/server/props.d.ts +0 -85
- package/dist/server/props.js +0 -44
- package/dist/vite/layouts.d.ts +0 -10
- package/dist/vite/layouts.js +0 -110
- package/dist/vite/vitest-cache.d.ts +0 -19
- package/dist/vite/vitest-cache.js +0 -30
package/dist/vite/index.js
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } 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 {
|
|
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 {
|
|
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
|
-
*
|
|
37
|
-
*
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
201
|
-
*
|
|
202
|
-
*
|
|
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
|
|
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 (
|
|
231
|
+
if (navigation || req.headers.accept?.includes('text/html'))
|
|
216
232
|
failed = true;
|
|
217
|
-
if (!
|
|
233
|
+
if (!navigation)
|
|
218
234
|
return next(error);
|
|
219
235
|
res.writeHead(409, {
|
|
220
|
-
'X-
|
|
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 = {
|
|
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,13 +286,15 @@ 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
|
-
|
|
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');
|
|
259
294
|
if (options.prerender && existsSync(wrangler)) {
|
|
260
295
|
const clientDir = resolve(config.root, client.config.build.outDir);
|
|
261
296
|
await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
|
|
297
|
+
workerFirstForIndex(wrangler);
|
|
262
298
|
}
|
|
263
299
|
}
|
|
264
300
|
},
|
|
@@ -305,25 +341,37 @@ function core(options) {
|
|
|
305
341
|
},
|
|
306
342
|
// dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
|
|
307
343
|
// 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
|
|
344
|
+
// for it by the app's @mdx-js/rollup; the browser's, a page's route file without its server code
|
|
309
345
|
configEnvironment(name, env) {
|
|
310
|
-
const pages = ['app/
|
|
346
|
+
const pages = ['app/routes/**/*.{tsx,jsx,mdx}'];
|
|
311
347
|
const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
|
|
312
348
|
if (name === 'client')
|
|
313
|
-
return {
|
|
349
|
+
return {
|
|
350
|
+
optimizeDeps: {
|
|
351
|
+
entries: pages,
|
|
352
|
+
...mdx,
|
|
353
|
+
rolldownOptions: {
|
|
354
|
+
plugins: [...mdx.rolldownOptions.plugins, scanRoutes(() => config.root)],
|
|
355
|
+
},
|
|
356
|
+
},
|
|
357
|
+
};
|
|
314
358
|
if (options.target !== 'cloudflare')
|
|
315
359
|
return;
|
|
316
360
|
// 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
|
|
318
|
-
//
|
|
361
|
+
// module), so the scan does not see what it imports (HONO, react, react-dom); nor react-dom/server, imported by
|
|
362
|
+
// the server render (virtual:fondu/ssr). Found late, they would restart the Worker in the middle of requests.
|
|
319
363
|
// The build is minified, as Workers start faster with less code to parse
|
|
320
364
|
return {
|
|
321
365
|
optimizeDeps: {
|
|
322
366
|
exclude: ['fondu'],
|
|
323
|
-
include: [
|
|
324
|
-
|
|
367
|
+
include: [
|
|
368
|
+
...HONO,
|
|
369
|
+
'react',
|
|
370
|
+
'react-dom',
|
|
371
|
+
...(options.ssr === false ? [] : ['react-dom/server']),
|
|
372
|
+
],
|
|
373
|
+
entries: [SERVER.slice(2), 'app/routes/**/*.ts', ...pages],
|
|
325
374
|
...mdx,
|
|
326
|
-
// the pre-bundled @inertiajs/react too
|
|
327
375
|
rolldownOptions: { plugins: [...mdx.rolldownOptions.plugins, serverReactDomClient()] },
|
|
328
376
|
},
|
|
329
377
|
...(env.build?.minify === undefined && { build: { minify: true } }),
|
|
@@ -332,14 +380,20 @@ function core(options) {
|
|
|
332
380
|
configResolved(c) {
|
|
333
381
|
config = c;
|
|
334
382
|
},
|
|
335
|
-
// dev: the CSS the
|
|
336
|
-
// at first paint (Vite would add it only once the
|
|
383
|
+
// dev: the CSS the layouts import (the app's own: `import './styles/app.css'` in routes/_layout.tsx), as a
|
|
384
|
+
// stylesheet in the document, so a server-rendered page is styled at first paint (Vite would add it only once the
|
|
385
|
+
// JS runs); removed by fondu/client once the page's modules (its layouts: their CSS) are loaded
|
|
337
386
|
configureServer(server) {
|
|
338
387
|
server.middlewares.use(DEV_CSS, async (_req, res) => {
|
|
339
388
|
const env = server.environments.client;
|
|
340
389
|
const css = [];
|
|
341
390
|
try {
|
|
342
|
-
|
|
391
|
+
const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.[jt]sx$/.test(f) &&
|
|
392
|
+
!f
|
|
393
|
+
.split('/')
|
|
394
|
+
.slice(0, -1)
|
|
395
|
+
.some((d) => d.startsWith('_')));
|
|
396
|
+
await Promise.all(layouts.map((f) => env.transformRequest(`/app/routes/${f}`)));
|
|
343
397
|
const seen = new Set();
|
|
344
398
|
const walk = (mod) => {
|
|
345
399
|
if (!mod?.id || seen.has(mod.id))
|
|
@@ -350,7 +404,8 @@ function core(options) {
|
|
|
350
404
|
for (const m of mod.importedModules)
|
|
351
405
|
walk(m);
|
|
352
406
|
};
|
|
353
|
-
|
|
407
|
+
for (const f of layouts)
|
|
408
|
+
walk(env.moduleGraph.getModuleById(resolve(config.root, 'app/routes', f)));
|
|
354
409
|
const parts = await Promise.all(css.map(async (url) => (await env.transformRequest(url + (url.includes('?') ? '&' : '?') + 'direct'))
|
|
355
410
|
?.code ?? ''));
|
|
356
411
|
res.setHeader('Content-Type', 'text/css');
|
|
@@ -375,60 +430,93 @@ function core(options) {
|
|
|
375
430
|
source: '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n',
|
|
376
431
|
});
|
|
377
432
|
},
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
433
|
+
// the server render loads a page through the entry's import(), of a module createApp has imported already: in
|
|
434
|
+
// the server's bundle, as it should be
|
|
435
|
+
onLog(_level, log) {
|
|
436
|
+
if (log.code === 'INEFFECTIVE_DYNAMIC_IMPORT' && log.message.includes('virtual:fondu/entry'))
|
|
437
|
+
return false;
|
|
381
438
|
},
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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 };
|
|
439
|
+
resolveId(id, importer) {
|
|
440
|
+
if (id === V.entry || id === V.assets || id === V.ssr)
|
|
441
|
+
return resolved(id);
|
|
442
|
+
// the server-only guard, for fondu's own: `fondu` is the server's, `fondu/client` the browser's
|
|
443
|
+
if (id === 'fondu' && importer && this.environment.config.consumer === 'client')
|
|
444
|
+
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
445
|
},
|
|
401
446
|
load(id) {
|
|
447
|
+
// the app's entry, in the browser and for the server render: the pages and layouts, whether pages are
|
|
448
|
+
// prerendered (navigations read their page objects from the static files), the progress bar; in dev, the
|
|
449
|
+
// page's props asked for again when what its route depends on changed (hmr.ts)
|
|
450
|
+
if (id === resolved(V.entry)) {
|
|
451
|
+
const dev = this.environment.config.consumer === 'client' && !isBuild;
|
|
452
|
+
const settings = { prerender: Boolean(options.prerender), progress: options.progress ?? {} };
|
|
453
|
+
const glob = (pattern) => `import.meta.glob(${JSON.stringify(pattern)})`;
|
|
454
|
+
return [
|
|
455
|
+
`import { __entry${dev ? ', reload' : ''} } from 'fondu/client'`,
|
|
456
|
+
...(dev ? [`import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => reload())`] : []),
|
|
457
|
+
`__entry({ ...${glob(PAGES_GLOB)}, ...${glob(ERROR_GLOB)} }, ${glob(LAYOUTS_GLOB)}, ${JSON.stringify(settings)})`,
|
|
458
|
+
].join('\n');
|
|
459
|
+
}
|
|
402
460
|
// and React's static markup for a JSX document (react-dom/server: the server render's, or loaded for it)
|
|
403
461
|
if (id === resolved(V.ssr))
|
|
404
462
|
return options.ssr === false
|
|
405
463
|
? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
|
|
406
|
-
:
|
|
464
|
+
: [
|
|
465
|
+
`import '${V.entry}'`,
|
|
466
|
+
`import { renderToString, renderToStaticMarkup } from 'react-dom/server'`,
|
|
467
|
+
`import { renderPage as render } from 'fondu/client'`,
|
|
468
|
+
`export const renderPage = (page) => render(page, renderToString)`,
|
|
469
|
+
`export { renderToStaticMarkup as renderMarkup }`,
|
|
470
|
+
].join('\n');
|
|
407
471
|
if (id === resolved(V.assets))
|
|
408
472
|
return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
|
|
409
473
|
`\nexport const prerender = ${Boolean(options.prerender)}`);
|
|
410
474
|
// the server-only guard: browser code must never import server code
|
|
411
475
|
if (this.environment.config.consumer === 'client' && isServerOnly(id, config.root)) {
|
|
412
|
-
this.error(`fondu: ${id.replace(config.root, '')} is server code (routes
|
|
476
|
+
this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/*.ts, server.ts, *.server.ts) and cannot be imported by browser code`);
|
|
413
477
|
}
|
|
478
|
+
// and a page's route file as it is (`?raw`, `?url`…): the browser's copy is the page alone
|
|
479
|
+
const [file, query] = id.split('?');
|
|
480
|
+
if (this.environment.config.consumer === 'client' &&
|
|
481
|
+
query &&
|
|
482
|
+
file.startsWith(`${config.root}/app/routes/`) &&
|
|
483
|
+
isPageFile(file.slice(`${config.root}/app/routes/`.length)) &&
|
|
484
|
+
/(?:^|&)(?:raw|url|inline)(?:&|=|$)/.test(query))
|
|
485
|
+
this.error(`fondu: ${file.replace(config.root, '')} has server code: only its page reaches the browser`);
|
|
414
486
|
},
|
|
415
487
|
};
|
|
416
488
|
}
|
|
417
|
-
/**
|
|
489
|
+
/**
|
|
490
|
+
* `*.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
|
|
491
|
+
* may have them). A page's route file (`.tsx`) reaches the browser without its server code (strip.ts).
|
|
492
|
+
*/
|
|
418
493
|
const isServerOnly = (id, root) => {
|
|
419
494
|
const file = id.split('?')[0];
|
|
420
495
|
return (/\.server\.[cm]?[jt]sx?$/.test(file) ||
|
|
421
|
-
file.startsWith(`${root}/app/routes/`) ||
|
|
496
|
+
(file.startsWith(`${root}/app/routes/`) && file.endsWith('.ts')) ||
|
|
422
497
|
file === `${root}/app/server.ts`);
|
|
423
498
|
};
|
|
499
|
+
/**
|
|
500
|
+
* The built Worker's config: URLs ending in index go to the Worker first. Static assets would answer them with the
|
|
501
|
+
* page of their directory (`/docs/index` → `docs/index.html`, redirected to `/docs/`), while a route (a param's value)
|
|
502
|
+
* may be theirs. Added to the app's own `run_worker_first`, unless it is `true` (every request first) already.
|
|
503
|
+
*/
|
|
504
|
+
function workerFirstForIndex(file) {
|
|
505
|
+
const config = JSON.parse(readFileSync(file, 'utf8'));
|
|
506
|
+
const assets = (config.assets ??= {});
|
|
507
|
+
if (assets.run_worker_first === true)
|
|
508
|
+
return;
|
|
509
|
+
const own = Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
|
|
510
|
+
assets.run_worker_first = [...new Set([...own, '/index', '/*/index'])];
|
|
511
|
+
writeFileSync(file, JSON.stringify(config));
|
|
512
|
+
}
|
|
424
513
|
const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
|
|
425
514
|
function devAssets(base) {
|
|
426
515
|
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
516
|
return `export const version = null
|
|
428
|
-
export const pages = null
|
|
429
517
|
export function assetTags(_component, nonce) {
|
|
430
518
|
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}${
|
|
519
|
+
+ \`<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
520
|
}`;
|
|
433
521
|
}
|
|
434
522
|
function productionAssets(config, options) {
|
|
@@ -456,19 +544,25 @@ function productionAssets(config, options) {
|
|
|
456
544
|
collect(key, css, js);
|
|
457
545
|
return { css: [...css], js: [...js] };
|
|
458
546
|
};
|
|
459
|
-
|
|
547
|
+
// the app's entry: the client build's only one
|
|
548
|
+
const entry = tags(Object.keys(manifest).find((k) => manifest[k].isEntry));
|
|
460
549
|
const pages = {};
|
|
461
550
|
for (const key of Object.keys(manifest)) {
|
|
462
|
-
const
|
|
463
|
-
if (
|
|
464
|
-
|
|
551
|
+
const file = key.startsWith('app/routes/') ? key.slice('app/routes/'.length) : undefined;
|
|
552
|
+
if (!file || !(isPageFile(file) || /^_error\.[jt]sx$/.test(file)))
|
|
553
|
+
continue;
|
|
554
|
+
// the page's chunk, and its layouts' (loaded with it)
|
|
555
|
+
const around = layoutsOf(file)
|
|
556
|
+
.flatMap((dir) => ['tsx', 'jsx'].map((ext) => `app/routes/${dir ? `${dir}/` : ''}_layout.${ext}`))
|
|
557
|
+
.filter((k) => k in manifest);
|
|
558
|
+
const all = [...around, key].map(tags);
|
|
559
|
+
pages[pageId(file)] = { css: all.flatMap((t) => t.css), js: all.flatMap((t) => t.js) };
|
|
465
560
|
}
|
|
466
561
|
const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
467
562
|
return `const base = ${JSON.stringify(config.base)}
|
|
468
563
|
const entry = ${JSON.stringify(entry)}
|
|
469
564
|
const byPage = ${JSON.stringify(pages)}
|
|
470
565
|
export const version = ${JSON.stringify(version)}
|
|
471
|
-
export const pages = ${JSON.stringify(Object.keys(pages))}
|
|
472
566
|
export function assetTags(component, nonce) {
|
|
473
567
|
const page = byPage[component] ?? { css: [], js: [] }
|
|
474
568
|
const css = [...new Set([...entry.css, ...page.css])]
|
package/dist/vite/prerender.d.ts
CHANGED
|
@@ -17,8 +17,8 @@ export declare function ownScripts(html: string, policy: string | undefined): {
|
|
|
17
17
|
*/
|
|
18
18
|
export declare function staticPolicy(policy: string, hashes?: string[]): string;
|
|
19
19
|
/**
|
|
20
|
-
* `_headers` with Fondu's rules in it: the documents' security headers (`/*`), and the page objects' X-
|
|
21
|
-
* (
|
|
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
22
|
* (Workers keep one rule per path: a second `/*` would replace the first); any other, a rule at the end.
|
|
23
23
|
*/
|
|
24
24
|
export declare function withHeaderRules(file: string, headers: Record<string, string>): string;
|
|
@@ -30,7 +30,7 @@ interface Server {
|
|
|
30
30
|
/**
|
|
31
31
|
* After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
|
|
32
32
|
* `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
|
|
33
|
-
* a
|
|
33
|
+
* a navigation, and both are written to the client build. Cloudflare serves them before the Worker, with the security
|
|
34
34
|
* headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
|
|
35
35
|
*/
|
|
36
36
|
export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, headersFile: boolean): Promise<undefined>;
|
package/dist/vite/prerender.js
CHANGED
|
@@ -48,15 +48,15 @@ export function staticPolicy(policy, hashes = []) {
|
|
|
48
48
|
.join('; ');
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
51
|
-
* `_headers` with Fondu's rules in it: the documents' security headers (`/*`), and the page objects' X-
|
|
52
|
-
* (
|
|
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
53
|
* (Workers keep one rule per path: a second `/*` would replace the first); any other, a rule at the end.
|
|
54
54
|
*/
|
|
55
55
|
export function withHeaderRules(file, headers) {
|
|
56
56
|
const lines = file.replace(/\n+$/, '').split('\n');
|
|
57
57
|
const rules = [
|
|
58
58
|
['/*', headers],
|
|
59
|
-
[`${PAGE_DATA}/*`, { 'X-
|
|
59
|
+
[`${PAGE_DATA}/*`, { 'X-Fondu': 'true' }],
|
|
60
60
|
];
|
|
61
61
|
for (const [path, set] of rules) {
|
|
62
62
|
const start = lines.findIndex((line) => line.trimEnd() === path);
|
|
@@ -80,7 +80,7 @@ export function withHeaderRules(file, headers) {
|
|
|
80
80
|
/**
|
|
81
81
|
* After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
|
|
82
82
|
* `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
|
|
83
|
-
* a
|
|
83
|
+
* a navigation, and both are written to the client build. Cloudflare serves them before the Worker, with the security
|
|
84
84
|
* headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
|
|
85
85
|
*/
|
|
86
86
|
export async function prerender(start, clientDir, logger, headersFile) {
|
|
@@ -107,8 +107,8 @@ export async function prerender(start, clientDir, logger, headersFile) {
|
|
|
107
107
|
for (const path of paths) {
|
|
108
108
|
const doc = await get(path, { Accept: 'text/html' });
|
|
109
109
|
const visit = await get(path, {
|
|
110
|
-
'X-
|
|
111
|
-
...(version && { 'X-
|
|
110
|
+
'X-Fondu': 'true',
|
|
111
|
+
...(version && { 'X-Fondu-Version': version }),
|
|
112
112
|
});
|
|
113
113
|
if (doc.status !== 200 || visit.status !== 200) {
|
|
114
114
|
const to = doc.headers.get('location');
|
|
@@ -116,11 +116,6 @@ export async function prerender(start, clientDir, logger, headersFile) {
|
|
|
116
116
|
continue;
|
|
117
117
|
}
|
|
118
118
|
const page = (await visit.json());
|
|
119
|
-
const later = ['deferredProps', 'scrollProps'].filter((key) => page[key]);
|
|
120
|
-
if (later.length) {
|
|
121
|
-
errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
|
|
122
|
-
continue;
|
|
123
|
-
}
|
|
124
119
|
const { html, hashes } = ownScripts(await doc.text(), doc.headers.get('content-security-policy') ?? undefined);
|
|
125
120
|
const headers = Object.fromEntries([...doc.headers]
|
|
126
121
|
.filter(([name]) => SECURITY_HEADERS.test(name))
|
|
@@ -167,7 +162,17 @@ export const worker = (root, workerConfig) => async () => {
|
|
|
167
162
|
});
|
|
168
163
|
await started.ready;
|
|
169
164
|
return {
|
|
170
|
-
|
|
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
|
+
},
|
|
171
176
|
dispose: () => started.dispose(),
|
|
172
177
|
};
|
|
173
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: the imports and top-level declarations the code kept doesn't reach. 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 {};
|