fondu 0.17.0 → 0.18.1
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/dist/client/form.d.ts +4 -0
- package/dist/client/form.js +43 -2
- package/dist/client/navigation.js +86 -20
- package/dist/client.d.ts +3 -3
- package/dist/form.d.ts +2 -1
- package/dist/form.js +9 -2
- package/dist/paths.d.ts +5 -0
- package/dist/paths.js +64 -4
- package/dist/server/app.d.ts +3 -2
- package/dist/server/app.js +29 -60
- package/dist/server/document.js +25 -8
- package/dist/server/flash.js +54 -15
- package/dist/server/http.d.ts +26 -2
- package/dist/server/http.js +61 -4
- package/dist/server/prerender.js +19 -2
- package/dist/server/protocol.js +21 -10
- package/dist/server/routes.js +21 -6
- package/dist/server/validate.d.ts +2 -2
- package/dist/server/validate.js +4 -3
- package/dist/virtual.d.ts +2 -0
- package/dist/vite/index.d.ts +8 -1
- package/dist/vite/index.js +96 -54
- package/dist/vite/node-server.d.ts +10 -0
- package/dist/vite/node-server.js +49 -0
- package/dist/vite/options.d.ts +8 -0
- package/dist/vite/options.js +72 -0
- package/dist/vite/prerender.d.ts +13 -2
- package/dist/vite/prerender.js +103 -17
- package/dist/vite/strip.d.ts +1 -1
- package/dist/vite/strip.js +70 -11
- package/package.json +1 -1
package/dist/vite/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Options as ReactOptions } from '@vitejs/plugin-react';
|
|
2
|
-
import { type PluginOption } from 'vite';
|
|
2
|
+
import { type PluginOption, type ResolvedConfig } from 'vite';
|
|
3
3
|
import type { ProgressOptions } from '../client/progress.js';
|
|
4
4
|
/**
|
|
5
5
|
* `vite.config.ts`: `plugins: [fondu({ target: 'node' })]` (or `'bun'`; for Cloudflare: `cloudflare()` and
|
|
@@ -32,3 +32,10 @@ export interface FonduOptions {
|
|
|
32
32
|
/** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
|
|
33
33
|
export declare const HONO: string[];
|
|
34
34
|
export default function fondu(options: FonduOptions): PluginOption[];
|
|
35
|
+
/**
|
|
36
|
+
* the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`),
|
|
37
|
+
* `assetsDir` the client build's (hashed files, which never change: the only ones served as immutable, and only when
|
|
38
|
+
* serveStatic found the file: an app's route under the same URL keeps its own Cache-Control)
|
|
39
|
+
*/
|
|
40
|
+
export declare function entryCode(options: FonduOptions, paths: string[], assetsDir?: string): string;
|
|
41
|
+
export declare function productionAssets(config: ResolvedConfig, options: FonduOptions): string;
|
package/dist/vite/index.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import { builtinModules
|
|
4
|
-
import {
|
|
5
|
-
import { fileURLToPath
|
|
3
|
+
import { builtinModules } from 'node:module';
|
|
4
|
+
import { relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
|
|
7
7
|
import react, {} from '@vitejs/plugin-react';
|
|
8
|
-
import { normalizePath, parseAst, transformWithOxc, } from 'vite';
|
|
8
|
+
import { loadEnv, normalizePath, parseAst, transformWithOxc, } from 'vite';
|
|
9
9
|
import { isPageFile, layoutsOf, pageId } from '../paths.js';
|
|
10
10
|
import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
|
|
11
|
+
import { devServerNodeServer } from './node-server.js';
|
|
12
|
+
import { checkOptions } from './options.js';
|
|
11
13
|
import { nodeServer, prerender, worker } from './prerender.js';
|
|
12
14
|
import { stripRoutes, stripServerCode } from './strip.js';
|
|
13
15
|
import { typegen, walk as walkFiles } from './typegen.js';
|
|
@@ -21,7 +23,6 @@ export const HONO = [
|
|
|
21
23
|
'hono/factory',
|
|
22
24
|
'hono/http-exception',
|
|
23
25
|
'hono/secure-headers',
|
|
24
|
-
'hono/trailing-slash',
|
|
25
26
|
];
|
|
26
27
|
const SERVER = './app/server.ts';
|
|
27
28
|
const DEV_CSS = '/@fondu/dev.css';
|
|
@@ -87,9 +88,10 @@ function scanMdx(config) {
|
|
|
87
88
|
};
|
|
88
89
|
}
|
|
89
90
|
/**
|
|
90
|
-
* The
|
|
91
|
-
* hydrateRoot) at its top: the whole of React's browser renderer
|
|
92
|
-
*
|
|
91
|
+
* The server never mounts or hydrates a page (it renders with react-dom/server), but fondu/client imports
|
|
92
|
+
* `react-dom/client` (createRoot, hydrateRoot) at its top: the whole of React's browser renderer, loaded at every
|
|
93
|
+
* start (about a third of a Worker, and of its start in dev; about 59 ms of a Node server's). On every target, it is
|
|
94
|
+
* a module that says so if called
|
|
93
95
|
*/
|
|
94
96
|
const REACT_DOM_CLIENT = '\0fondu:react-dom-client';
|
|
95
97
|
function serverReactDomClient() {
|
|
@@ -110,6 +112,7 @@ function serverReactDomClient() {
|
|
|
110
112
|
};
|
|
111
113
|
}
|
|
112
114
|
export default function fondu(options) {
|
|
115
|
+
checkOptions(options);
|
|
113
116
|
const node = options.target !== 'cloudflare';
|
|
114
117
|
return [
|
|
115
118
|
// .mdx too: MDX pages and components get Fast Refresh (as MDX's own docs set it up)
|
|
@@ -119,7 +122,8 @@ export default function fondu(options) {
|
|
|
119
122
|
hmr(),
|
|
120
123
|
loadFailure(),
|
|
121
124
|
typegen(),
|
|
122
|
-
...(node ? runtimePlugins(options) : [
|
|
125
|
+
...(node ? runtimePlugins(options) : []),
|
|
126
|
+
serverReactDomClient(),
|
|
123
127
|
];
|
|
124
128
|
}
|
|
125
129
|
/** the app's dependencies stay in node_modules, as with any Node server (native modules cannot be bundled) */
|
|
@@ -131,18 +135,21 @@ function dependencies(root = '') {
|
|
|
131
135
|
* Node / Bun: the server build's entry, dist/server/index.js. The client build's files first (found next to the
|
|
132
136
|
* server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
|
|
133
137
|
* on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
|
|
134
|
-
* serves the default export itself
|
|
138
|
+
* serves the default export itself, on `PORT` (else the option; Bun's own default without one), with the app's
|
|
139
|
+
* `websocket`, if it has one.
|
|
135
140
|
* With `prerender`, the pages the build wrote are served from their files first, with the headers it decided
|
|
136
141
|
* (`prerender.json`, next to this entry).
|
|
137
142
|
*/
|
|
138
143
|
function serverEntry(options) {
|
|
139
144
|
let root = process.cwd();
|
|
145
|
+
let assetsDir = 'assets';
|
|
140
146
|
return {
|
|
141
147
|
name: 'fondu:server-entry',
|
|
142
148
|
apply: 'build',
|
|
143
149
|
applyToEnvironment: (env) => env.name === 'ssr',
|
|
144
150
|
configResolved(c) {
|
|
145
151
|
root = c.root;
|
|
152
|
+
assetsDir = c.environments.client?.build.assetsDir ?? c.build.assetsDir;
|
|
146
153
|
},
|
|
147
154
|
resolveId: { filter: { id: /^virtual:fondu\/server-entry$/ }, handler: (id) => resolved(id) },
|
|
148
155
|
load: {
|
|
@@ -154,58 +161,86 @@ function serverEntry(options) {
|
|
|
154
161
|
.filter((e) => e.name !== '.vite')
|
|
155
162
|
.map((e) => (e.isDirectory() ? `/${e.name}/*` : `/${e.name}`))
|
|
156
163
|
: [];
|
|
157
|
-
|
|
158
|
-
return [
|
|
159
|
-
`import { Hono } from 'hono'`,
|
|
160
|
-
`import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
|
|
161
|
-
`import { fileURLToPath } from 'node:url'`,
|
|
162
|
-
`import app from '${SERVER.slice(1)}'`,
|
|
163
|
-
`const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
|
|
164
|
-
`const main = new Hono()`,
|
|
165
|
-
`main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
|
|
166
|
-
// prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
|
|
167
|
-
// this server was built: not there while the build prerenders, so the app renders them then)
|
|
168
|
-
...(options.prerender
|
|
169
|
-
? [
|
|
170
|
-
`import { existsSync, readFileSync } from 'node:fs'`,
|
|
171
|
-
`import { staticPages } from ${JSON.stringify(staticModule)}`,
|
|
172
|
-
`const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
|
|
173
|
-
`if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
|
|
174
|
-
]
|
|
175
|
-
: []),
|
|
176
|
-
...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
|
|
177
|
-
`main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
|
|
178
|
-
...(bun
|
|
179
|
-
? [
|
|
180
|
-
`export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`,
|
|
181
|
-
]
|
|
182
|
-
: [
|
|
183
|
-
`import { serve } from '@hono/node-server'`,
|
|
184
|
-
`const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
|
|
185
|
-
`const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
|
|
186
|
-
`process.on('SIGINT', shutdown)`,
|
|
187
|
-
`process.on('SIGTERM', shutdown)`,
|
|
188
|
-
`export default main`,
|
|
189
|
-
]),
|
|
190
|
-
].join('\n');
|
|
164
|
+
return entryCode(options, paths, assetsDir);
|
|
191
165
|
},
|
|
192
166
|
},
|
|
193
167
|
};
|
|
194
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`),
|
|
171
|
+
* `assetsDir` the client build's (hashed files, which never change: the only ones served as immutable, and only when
|
|
172
|
+
* serveStatic found the file: an app's route under the same URL keeps its own Cache-Control)
|
|
173
|
+
*/
|
|
174
|
+
export function entryCode(options, paths, assetsDir = 'assets') {
|
|
175
|
+
const bun = options.target === 'bun';
|
|
176
|
+
const hashed = assetsDir ? `/${assetsDir}/*` : undefined;
|
|
177
|
+
return [
|
|
178
|
+
// NODE_ENV first, and the rest imported after it: static imports run before this line, and React picks its
|
|
179
|
+
// production or development build when it is first loaded
|
|
180
|
+
`process.env.NODE_ENV ??= 'production'`,
|
|
181
|
+
`const { Hono } = await import('hono')`,
|
|
182
|
+
`const { serveStatic } = await import('${bun ? 'hono/bun' : '@hono/node-server/serve-static'}')`,
|
|
183
|
+
`const { fileURLToPath } = await import('node:url')`,
|
|
184
|
+
`const { default: app } = await import('${SERVER.slice(1)}')`,
|
|
185
|
+
`const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
|
|
186
|
+
`const main = new Hono()`,
|
|
187
|
+
// prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
|
|
188
|
+
// this server was built: not there while the build prerenders, so the app renders them then)
|
|
189
|
+
...(options.prerender
|
|
190
|
+
? [
|
|
191
|
+
`const { existsSync, readFileSync } = await import('node:fs')`,
|
|
192
|
+
`const { staticPages } = await import(${JSON.stringify(staticModule)})`,
|
|
193
|
+
`const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
|
|
194
|
+
`if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
|
|
195
|
+
]
|
|
196
|
+
: []),
|
|
197
|
+
...(hashed
|
|
198
|
+
? [
|
|
199
|
+
`main.use(${JSON.stringify(hashed)}, serveStatic({ root: clientRoot, onFound: (_path, c) => c.header('Cache-Control', 'public, max-age=31536000, immutable') }))`,
|
|
200
|
+
]
|
|
201
|
+
: []),
|
|
202
|
+
...paths
|
|
203
|
+
.filter((p) => p !== hashed)
|
|
204
|
+
.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
|
|
205
|
+
`main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
|
|
206
|
+
...(bun
|
|
207
|
+
? [
|
|
208
|
+
// Bun serves the default export: its `port` (`PORT` first, as on Node), else Bun's own default (PORT, 3000)
|
|
209
|
+
options.port === undefined
|
|
210
|
+
? `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`
|
|
211
|
+
: `export default { fetch: main.fetch, port: Number(process.env.PORT) || ${Number(options.port)}, ...(app.websocket && { websocket: app.websocket }) }`,
|
|
212
|
+
]
|
|
213
|
+
: [
|
|
214
|
+
`const { serve } = await import('@hono/node-server')`,
|
|
215
|
+
`const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
|
|
216
|
+
`const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
|
|
217
|
+
`process.on('SIGINT', shutdown)`,
|
|
218
|
+
`process.on('SIGTERM', shutdown)`,
|
|
219
|
+
`export default main`,
|
|
220
|
+
]),
|
|
221
|
+
].join('\n');
|
|
222
|
+
}
|
|
195
223
|
function runtimePlugins(options) {
|
|
196
224
|
return [
|
|
225
|
+
{
|
|
226
|
+
// dev: the app's .env files (in Vite's `envDir`: `.env`, `.env.local`, `.env.[mode]`, `.env.[mode].local`) are in `process.env`, as the
|
|
227
|
+
// server code reads them; a variable set already (the shell's, the host's) stays. Vite loads them for
|
|
228
|
+
// `import.meta.env` only, and for the `VITE_` ones. Cloudflare has its own, `.dev.vars`. The production server
|
|
229
|
+
// reads them itself (the template's `start` script)
|
|
230
|
+
name: 'fondu:env',
|
|
231
|
+
apply: 'serve',
|
|
232
|
+
configResolved(config) {
|
|
233
|
+
for (const [key, value] of Object.entries(loadEnv(config.mode, config.envDir, '')))
|
|
234
|
+
process.env[key] ??= value;
|
|
235
|
+
},
|
|
236
|
+
},
|
|
197
237
|
{
|
|
198
238
|
// dev: the same Request / Response globals as the production server (@hono/node-server's), which the dev
|
|
199
239
|
// server's requests are made with: middleware that re-creates the request (hono/body-limit) needs them
|
|
200
240
|
name: 'fondu:node-globals',
|
|
201
241
|
apply: 'serve',
|
|
202
242
|
async configureServer() {
|
|
203
|
-
|
|
204
|
-
const fromDevServer = createRequire(createRequire(import.meta.url).resolve('@hono/vite-dev-server'));
|
|
205
|
-
const dir = dirname(dirname(fromDevServer.resolve('@hono/node-server'))); // …/dist/index.js
|
|
206
|
-
const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
207
|
-
const entry = pkg.exports['.'].import;
|
|
208
|
-
const { getRequestListener } = (await import(pathToFileURL(join(dir, typeof entry === 'string' ? entry : entry.default)).href));
|
|
243
|
+
const { getRequestListener } = await devServerNodeServer();
|
|
209
244
|
getRequestListener(() => new Response());
|
|
210
245
|
},
|
|
211
246
|
},
|
|
@@ -274,7 +309,7 @@ function core(options) {
|
|
|
274
309
|
.replace(/[^a-zA-Z0-9]+/g, '-')
|
|
275
310
|
.replace(/^-|-$/g, '')
|
|
276
311
|
: undefined;
|
|
277
|
-
return
|
|
312
|
+
return `${config.environments.client?.build.assetsDir ?? config.build.assetsDir}/${name || '[name]'}-[hash].js`;
|
|
278
313
|
},
|
|
279
314
|
},
|
|
280
315
|
},
|
|
@@ -435,7 +470,7 @@ function core(options) {
|
|
|
435
470
|
this.emitFile({
|
|
436
471
|
type: 'asset',
|
|
437
472
|
fileName: '_headers',
|
|
438
|
-
source:
|
|
473
|
+
source: `/${this.environment.config.build.assetsDir}/*\n Cache-Control: public, max-age=31536000, immutable\n`,
|
|
439
474
|
});
|
|
440
475
|
},
|
|
441
476
|
// the server render loads a page through the entry's import(), of a module createApp has imported already: in
|
|
@@ -527,7 +562,7 @@ export function assetTags(_component, nonce) {
|
|
|
527
562
|
+ \`<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>\`
|
|
528
563
|
}`;
|
|
529
564
|
}
|
|
530
|
-
function productionAssets(config, options) {
|
|
565
|
+
export function productionAssets(config, options) {
|
|
531
566
|
const outDir = options.target === 'cloudflare'
|
|
532
567
|
? resolve(config.root, config.environments.client?.build.outDir ?? 'dist/client')
|
|
533
568
|
: resolve(config.root, 'dist/client');
|
|
@@ -564,7 +599,14 @@ function productionAssets(config, options) {
|
|
|
564
599
|
.map((dir) => `app/routes/${dir ? `${dir}/` : ''}_layout.tsx`)
|
|
565
600
|
.filter((k) => k in manifest);
|
|
566
601
|
const all = [...around, key].map(tags);
|
|
567
|
-
|
|
602
|
+
// each file once, and not the entry's: assetTags() adds those to every page (the entry's first)
|
|
603
|
+
const own = (files, entryFiles) => [
|
|
604
|
+
...new Set(files.filter((f) => !entryFiles.includes(f))),
|
|
605
|
+
];
|
|
606
|
+
pages[pageId(file)] = {
|
|
607
|
+
css: own(all.flatMap((t) => t.css), entry.css),
|
|
608
|
+
js: own(all.flatMap((t) => t.js), entry.js),
|
|
609
|
+
};
|
|
568
610
|
}
|
|
569
611
|
const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
570
612
|
return `const base = ${JSON.stringify(config.base)}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dev server's own `@hono/node-server`, as an ES module (its CommonJS build would be another class): found
|
|
3
|
+
* through `@hono/vite-dev-server` (its dependency, not the app's), by the path of its main file (`dist/index.js`, a
|
|
4
|
+
* directory below the package) and by the shape of its `exports` (`'.'`: `import`, a path or `{ default }`). That is
|
|
5
|
+
* what this relies on: when it no longer holds, the error says so (test/node-globals.test.ts runs it on the
|
|
6
|
+
* installed version).
|
|
7
|
+
*/
|
|
8
|
+
export declare function devServerNodeServer(devServer?: string): Promise<{
|
|
9
|
+
getRequestListener: (fetch: () => Response) => unknown;
|
|
10
|
+
}>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
/**
|
|
6
|
+
* The dev server's own `@hono/node-server`, as an ES module (its CommonJS build would be another class): found
|
|
7
|
+
* through `@hono/vite-dev-server` (its dependency, not the app's), by the path of its main file (`dist/index.js`, a
|
|
8
|
+
* directory below the package) and by the shape of its `exports` (`'.'`: `import`, a path or `{ default }`). That is
|
|
9
|
+
* what this relies on: when it no longer holds, the error says so (test/node-globals.test.ts runs it on the
|
|
10
|
+
* installed version).
|
|
11
|
+
*/
|
|
12
|
+
export async function devServerNodeServer(devServer = createRequire(import.meta.url).resolve('@hono/vite-dev-server')) {
|
|
13
|
+
let looked = `.../@hono/node-server/dist/index.js (its CommonJS main), resolved from ${devServer}`;
|
|
14
|
+
const fail = (why, cause) => {
|
|
15
|
+
throw new Error(`fondu: @hono/vite-dev-server's own @hono/node-server was not found as expected: ${why}. Fondu looks for ` +
|
|
16
|
+
`${looked}; then ../package.json with exports['.'].import, an ES module with getRequestListener. ` +
|
|
17
|
+
`Report it: https://github.com/fondujs/fondu/issues, with the versions of @hono/vite-dev-server and @hono/node-server.`, { cause });
|
|
18
|
+
};
|
|
19
|
+
let dir = '';
|
|
20
|
+
try {
|
|
21
|
+
dir = dirname(dirname(createRequire(devServer).resolve('@hono/node-server'))); // …/dist/index.js
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
return fail('it cannot be resolved', error);
|
|
25
|
+
}
|
|
26
|
+
looked = `${join(dir, 'package.json')}`;
|
|
27
|
+
let pkg;
|
|
28
|
+
try {
|
|
29
|
+
pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
return fail('its package.json cannot be read', error);
|
|
33
|
+
}
|
|
34
|
+
looked = `${join(dir, 'package.json')} (version ${pkg.version ?? 'unknown'})`;
|
|
35
|
+
const entry = pkg.exports?.['.']?.import;
|
|
36
|
+
const file = typeof entry === 'string' ? entry : entry?.default;
|
|
37
|
+
if (typeof file !== 'string')
|
|
38
|
+
return fail("it has no exports['.'].import");
|
|
39
|
+
let module;
|
|
40
|
+
try {
|
|
41
|
+
module = await import(pathToFileURL(join(dir, file)).href);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
return fail(`${file} cannot be imported`, error);
|
|
45
|
+
}
|
|
46
|
+
if (typeof module.getRequestListener !== 'function')
|
|
47
|
+
return fail(`${file} has no getRequestListener`);
|
|
48
|
+
return module;
|
|
49
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { FonduOptions } from './index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Checks the options of `fondu()` when the plugin is created, so that a wrong one fails at once, with the option's
|
|
4
|
+
* name and what it may be (not as a TypeError, or never). The types say it for TypeScript; a `vite.config.js`, or a
|
|
5
|
+
* cast, has no such check. `react` is the options of @vitejs/plugin-react: its keys as its types define them, and
|
|
6
|
+
* the keys it may get later are its own to refuse.
|
|
7
|
+
*/
|
|
8
|
+
export declare function checkOptions(options: unknown): asserts options is FonduOptions;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const TARGETS = ['node', 'bun', 'cloudflare'];
|
|
2
|
+
const KEYS = ['target', 'port', 'ssr', 'react', 'prerender', 'progress'];
|
|
3
|
+
const PROGRESS_KEYS = ['delay', 'color', 'forms'];
|
|
4
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
5
|
+
const show = (v) => (typeof v === 'string' ? `'${v}'` : String(v));
|
|
6
|
+
/**
|
|
7
|
+
* Checks the options of `fondu()` when the plugin is created, so that a wrong one fails at once, with the option's
|
|
8
|
+
* name and what it may be (not as a TypeError, or never). The types say it for TypeScript; a `vite.config.js`, or a
|
|
9
|
+
* cast, has no such check. `react` is the options of @vitejs/plugin-react: its keys as its types define them, and
|
|
10
|
+
* the keys it may get later are its own to refuse.
|
|
11
|
+
*/
|
|
12
|
+
export function checkOptions(options) {
|
|
13
|
+
const fail = (message) => {
|
|
14
|
+
throw new Error(`fondu(): ${message}`);
|
|
15
|
+
};
|
|
16
|
+
if (options === undefined || options === null)
|
|
17
|
+
fail("the options are required, at least `target`: 'node', 'bun' or 'cloudflare'");
|
|
18
|
+
if (!isObject(options))
|
|
19
|
+
return fail("the options are an object: `fondu({ target: 'node' })`");
|
|
20
|
+
const unknown = (keys, allowed, prefix = '') => {
|
|
21
|
+
const extra = keys.filter((k) => !allowed.includes(k));
|
|
22
|
+
if (extra.length)
|
|
23
|
+
fail(`unknown option${extra.length > 1 ? 's' : ''} ${extra.map((k) => `\`${prefix}${k}\``).join(', ')}. The options are ${allowed.join(', ')}`);
|
|
24
|
+
};
|
|
25
|
+
unknown(Object.keys(options), KEYS);
|
|
26
|
+
const { target, port, ssr, prerender, progress, react } = options;
|
|
27
|
+
if (target === undefined)
|
|
28
|
+
fail("`target` is required: 'node', 'bun' or 'cloudflare'");
|
|
29
|
+
if (!TARGETS.includes(target))
|
|
30
|
+
fail(`\`target\` must be 'node', 'bun' or 'cloudflare', not ${show(target)}`);
|
|
31
|
+
// `port` goes with the option (#249)
|
|
32
|
+
if (port !== undefined) {
|
|
33
|
+
if (target === 'cloudflare')
|
|
34
|
+
fail("`port` is for target 'node' or 'bun': a Worker has no port of its own");
|
|
35
|
+
if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535)
|
|
36
|
+
fail(`\`port\` must be an integer from 1 to 65535, not ${show(port)}`);
|
|
37
|
+
}
|
|
38
|
+
for (const [name, value] of Object.entries({ ssr, prerender }))
|
|
39
|
+
if (value !== undefined && typeof value !== 'boolean')
|
|
40
|
+
fail(`\`${name}\` must be true or false, not ${show(value)}`);
|
|
41
|
+
if (progress !== undefined && progress !== false) {
|
|
42
|
+
if (!isObject(progress))
|
|
43
|
+
fail(`\`progress\` must be false or an object: ${PROGRESS_KEYS.join(', ')}`);
|
|
44
|
+
const p = progress;
|
|
45
|
+
unknown(Object.keys(p), PROGRESS_KEYS, 'progress.');
|
|
46
|
+
if (p.delay !== undefined && (typeof p.delay !== 'number' || !(p.delay >= 0)))
|
|
47
|
+
fail(`\`progress.delay\` must be a number of milliseconds, 0 or more, not ${show(p.delay)}`);
|
|
48
|
+
if (p.color !== undefined && typeof p.color !== 'string')
|
|
49
|
+
fail(`\`progress.color\` must be a CSS color, a string, not ${show(p.color)}`);
|
|
50
|
+
if (p.forms !== undefined && typeof p.forms !== 'boolean')
|
|
51
|
+
fail(`\`progress.forms\` must be true or false, not ${show(p.forms)}`);
|
|
52
|
+
}
|
|
53
|
+
if (react !== undefined) {
|
|
54
|
+
if (!isObject(react))
|
|
55
|
+
fail('`react` must be an object (the options of @vitejs/plugin-react)');
|
|
56
|
+
const r = react;
|
|
57
|
+
if (r.jsxRuntime !== undefined && r.jsxRuntime !== 'automatic' && r.jsxRuntime !== 'classic')
|
|
58
|
+
fail(`\`react.jsxRuntime\` must be 'automatic' or 'classic', not ${show(r.jsxRuntime)}`);
|
|
59
|
+
for (const name of ['jsxImportSource', 'reactRefreshHost'])
|
|
60
|
+
if (r[name] !== undefined && typeof r[name] !== 'string')
|
|
61
|
+
fail(`\`react.${name}\` must be a string, not ${show(r[name])}`);
|
|
62
|
+
for (const name of ['include', 'exclude']) {
|
|
63
|
+
const v = r[name];
|
|
64
|
+
const one = (x) => typeof x === 'string' || x instanceof RegExp;
|
|
65
|
+
if (v !== undefined && !(one(v) || (Array.isArray(v) && v.every(one))))
|
|
66
|
+
fail(`\`react.${name}\` must be a string, a RegExp or an array of them`);
|
|
67
|
+
}
|
|
68
|
+
const compiler = r.compiler;
|
|
69
|
+
if (compiler !== undefined && typeof compiler !== 'boolean' && !isObject(compiler))
|
|
70
|
+
fail(`\`react.compiler\` must be true, false or an object, not ${show(compiler)}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
package/dist/vite/prerender.d.ts
CHANGED
|
@@ -38,6 +38,17 @@ export declare function prerender(start: () => Promise<Server>, clientDir: strin
|
|
|
38
38
|
}): Promise<undefined>;
|
|
39
39
|
/** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
|
|
40
40
|
export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
|
|
41
|
-
/**
|
|
42
|
-
export
|
|
41
|
+
/** how long the built server may take to answer, in ms: to start (a wall-clock deadline), and each request, its body read included */
|
|
42
|
+
export interface Deadlines {
|
|
43
|
+
startup: number;
|
|
44
|
+
request: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
|
|
48
|
+
* until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
|
|
49
|
+
* child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
|
|
50
|
+
*/
|
|
51
|
+
export declare const nodeServer: (root: string, runtime: string, { startup, request }?: Deadlines) => () => Promise<Server>;
|
|
52
|
+
/** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
|
|
53
|
+
export declare function outputProblems(paths: string[], dir: string): string[];
|
|
43
54
|
export {};
|
package/dist/vite/prerender.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
|
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { createServer } from 'node:net';
|
|
6
|
-
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
7
7
|
import { pathToFileURL } from 'node:url';
|
|
8
8
|
import { PAGE_DATA, staticFiles } from '../paths.js';
|
|
9
9
|
/** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
|
|
@@ -101,6 +101,10 @@ export async function prerender(start, clientDir, logger, where) {
|
|
|
101
101
|
logger.warn('fondu: prerender is on, and no route has `export const prerender`');
|
|
102
102
|
return;
|
|
103
103
|
}
|
|
104
|
+
// every file to write, known before the first: all inside the client directory, none two pages' (or a directory)
|
|
105
|
+
const unsafe = outputProblems(paths, clientDir);
|
|
106
|
+
if (unsafe.length)
|
|
107
|
+
return fail(unsafe);
|
|
104
108
|
let security;
|
|
105
109
|
const errors = [];
|
|
106
110
|
for (const path of paths) {
|
|
@@ -145,6 +149,12 @@ export async function prerender(start, clientDir, logger, where) {
|
|
|
145
149
|
writeFileSync(file, withHeaderRules(own, security ?? {}));
|
|
146
150
|
}
|
|
147
151
|
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
// a request, or the read of its body, that did not finish: the deadline of the server's fetch
|
|
154
|
+
if (timedOut(error))
|
|
155
|
+
fail([`the server did not finish an answer in time (${error.message})`]);
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
148
158
|
finally {
|
|
149
159
|
await server.dispose();
|
|
150
160
|
}
|
|
@@ -167,35 +177,56 @@ export const worker = (root, workerConfig) => async () => {
|
|
|
167
177
|
await started.ready;
|
|
168
178
|
return {
|
|
169
179
|
// a Worker that throws as it starts: wrangler logs it, then its requests never answer
|
|
180
|
+
// the signal covers the body's read too, as the Node / Bun server's does (the timer below, its headers only)
|
|
170
181
|
fetch: (path, headers = {}) => {
|
|
171
182
|
let timer;
|
|
172
183
|
const late = new Promise((_, reject) => {
|
|
173
184
|
timer = setTimeout(() => reject(new Error(`the Worker did not answer ${path} (an error above?)`)), 60_000);
|
|
174
185
|
});
|
|
175
186
|
return Promise.race([
|
|
176
|
-
started.fetch(new URL(path, 'http://localhost').href, {
|
|
187
|
+
started.fetch(new URL(path, 'http://localhost').href, {
|
|
188
|
+
headers,
|
|
189
|
+
redirect: 'manual',
|
|
190
|
+
signal: AbortSignal.timeout(60_000),
|
|
191
|
+
}),
|
|
177
192
|
late,
|
|
178
193
|
]).finally(() => clearTimeout(timer));
|
|
179
194
|
},
|
|
180
195
|
dispose: () => started.dispose(),
|
|
181
196
|
};
|
|
182
197
|
};
|
|
183
|
-
/**
|
|
184
|
-
|
|
198
|
+
/** a failed request: the server did not answer in time (the timeout and the abort of a signal are DOMExceptions) */
|
|
199
|
+
const timedOut = (error) => error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError');
|
|
200
|
+
/**
|
|
201
|
+
* Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
|
|
202
|
+
* until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
|
|
203
|
+
* child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
|
|
204
|
+
*/
|
|
205
|
+
export const nodeServer = (root, runtime, { startup, request } = { startup: 30_000, request: 60_000 }) => async () => {
|
|
185
206
|
const port = await freePort();
|
|
186
207
|
const child = spawn(runtime, ['dist/server/index.js'], {
|
|
187
208
|
cwd: root,
|
|
188
209
|
env: { ...process.env, PORT: String(port), FONDU_PRERENDER: '1', NODE_ENV: 'production' },
|
|
189
210
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
190
211
|
});
|
|
212
|
+
// the last of what it wrote: the reason it gives for failing to start, not all of what a long build writes
|
|
191
213
|
let output = '';
|
|
192
|
-
|
|
193
|
-
child.
|
|
214
|
+
const keep = (d) => (output = (output + d).slice(-16_384));
|
|
215
|
+
child.stdout.on('data', keep);
|
|
216
|
+
child.stderr.on('data', keep);
|
|
217
|
+
// a child that cannot be spawned (no such executable) emits `error`, and, unhandled, that ends the build's process
|
|
218
|
+
let spawnError;
|
|
219
|
+
child.on('error', (error) => (spawnError = error));
|
|
194
220
|
const base = `http://127.0.0.1:${port}`;
|
|
221
|
+
const gone = () => child.exitCode !== null || child.signalCode !== null || spawnError;
|
|
195
222
|
const server = {
|
|
196
|
-
fetch: (path, headers = {}) => fetch(base + path, {
|
|
223
|
+
fetch: (path, headers = {}) => fetch(base + path, {
|
|
224
|
+
headers,
|
|
225
|
+
redirect: 'manual',
|
|
226
|
+
signal: AbortSignal.timeout(request),
|
|
227
|
+
}),
|
|
197
228
|
dispose: async () => {
|
|
198
|
-
if (
|
|
229
|
+
if (gone())
|
|
199
230
|
return;
|
|
200
231
|
const exited = new Promise((r) => child.once('exit', r));
|
|
201
232
|
child.kill();
|
|
@@ -204,17 +235,32 @@ export const nodeServer = (root, runtime) => async () => {
|
|
|
204
235
|
clearTimeout(force);
|
|
205
236
|
},
|
|
206
237
|
};
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
238
|
+
try {
|
|
239
|
+
const deadline = Date.now() + startup;
|
|
240
|
+
for (;;) {
|
|
241
|
+
if (spawnError)
|
|
242
|
+
throw new Error(`the server (${runtime} dist/server/index.js) did not start: ${spawnError.message}`);
|
|
243
|
+
if (child.exitCode !== null || child.signalCode !== null || Date.now() >= deadline)
|
|
244
|
+
throw new Error(`the server (${runtime} dist/server/index.js) did not start${gone() ? '' : `: no answer within ${startup / 1000} s`}:\n${output.trim()}`);
|
|
245
|
+
try {
|
|
246
|
+
// an answer, any, or the next try: a server that takes the connection and sends nothing is one try
|
|
247
|
+
const left = Math.max(1, deadline - Date.now());
|
|
248
|
+
const res = await fetch(base + '/__fondu/prerender', {
|
|
249
|
+
redirect: 'manual',
|
|
250
|
+
signal: AbortSignal.timeout(Math.min(2000, left)),
|
|
251
|
+
});
|
|
252
|
+
await res.body?.cancel();
|
|
253
|
+
return server;
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
257
|
+
}
|
|
216
258
|
}
|
|
217
259
|
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
await server.dispose();
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
218
264
|
};
|
|
219
265
|
const freePort = () => new Promise((resolve, reject) => {
|
|
220
266
|
const s = createServer();
|
|
@@ -224,7 +270,47 @@ const freePort = () => new Promise((resolve, reject) => {
|
|
|
224
270
|
s.close(() => resolve(port));
|
|
225
271
|
});
|
|
226
272
|
});
|
|
273
|
+
/** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
|
|
274
|
+
export function outputProblems(paths, dir) {
|
|
275
|
+
const problems = [];
|
|
276
|
+
const owner = new Map();
|
|
277
|
+
for (const path of paths) {
|
|
278
|
+
let files;
|
|
279
|
+
try {
|
|
280
|
+
files = Object.values(staticFiles(path));
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
problems.push(`${path}: not a valid URL path (it does not decode)`);
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
for (const file of files) {
|
|
287
|
+
if (file.includes('\\') || !inside(dir, file)) {
|
|
288
|
+
problems.push(`${path}: its file (${JSON.stringify(file)}) is not inside the build's directory`);
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const other = owner.get(file);
|
|
292
|
+
if (other !== undefined)
|
|
293
|
+
problems.push(`${path} and ${other} are the same file (${file})`);
|
|
294
|
+
else
|
|
295
|
+
owner.set(file, path);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// a page's file that is another's directory (`/a.html` is `a.html.html`, but `/a` is `a.html`: `/a.html/b` its child)
|
|
299
|
+
for (const [file, path] of owner)
|
|
300
|
+
for (let at = file.indexOf('/'); at !== -1; at = file.indexOf('/', at + 1)) {
|
|
301
|
+
const other = owner.get(file.slice(0, at));
|
|
302
|
+
if (other !== undefined)
|
|
303
|
+
problems.push(`${path} needs ${file.slice(0, at)} to be a directory, the file of ${other}`);
|
|
304
|
+
}
|
|
305
|
+
return problems;
|
|
306
|
+
}
|
|
307
|
+
const inside = (dir, file) => {
|
|
308
|
+
const to = resolve(dir, file);
|
|
309
|
+
return to.startsWith(resolve(dir) + sep);
|
|
310
|
+
};
|
|
227
311
|
function write(dir, file, content) {
|
|
312
|
+
if (!inside(dir, file))
|
|
313
|
+
throw new Error(`fondu: ${JSON.stringify(file)} is not inside ${dir}`);
|
|
228
314
|
const to = join(dir, file);
|
|
229
315
|
mkdirSync(dirname(to), { recursive: true });
|
|
230
316
|
writeFileSync(to, content);
|
package/dist/vite/strip.d.ts
CHANGED