fondu 0.8.0 → 0.9.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/dist/client.d.ts CHANGED
@@ -22,4 +22,11 @@ export declare function href<P extends Href>(path: P, ...[params]: Args<P>): str
22
22
  * object of another build reloads the page as a document, as the server's 409 would.
23
23
  */
24
24
  export declare function prerendered(): void;
25
+ /**
26
+ * The build adds this to the client entry: in production, a GET visit answered with something that isn't an Inertia
27
+ * page (a proxy's 502, a CDN's 524) loads the URL as a document, as a site without Inertia would, instead of showing
28
+ * that answer in Inertia's dialog. Fondu's own answers to visits are pages, errors included. Other methods keep the
29
+ * dialog (loading the URL would drop the form); a visit's own `onHttpException` comes first.
30
+ */
31
+ export declare function documentFallback(): void;
25
32
  export {};
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { http } from '@inertiajs/react';
1
+ import { http, router } from '@inertiajs/react';
2
2
  import { fillPattern, pageDataPath } from './paths.js';
3
3
  export function href(path, ...[params]) {
4
4
  return fillPattern(path, params);
@@ -30,3 +30,21 @@ export function prerendered() {
30
30
  };
31
31
  });
32
32
  }
33
+ /**
34
+ * The build adds this to the client entry: in production, a GET visit answered with something that isn't an Inertia
35
+ * page (a proxy's 502, a CDN's 524) loads the URL as a document, as a site without Inertia would, instead of showing
36
+ * that answer in Inertia's dialog. Fondu's own answers to visits are pages, errors included. Other methods keep the
37
+ * dialog (loading the URL would drop the form); a visit's own `onHttpException` comes first.
38
+ */
39
+ export function documentFallback() {
40
+ let visit;
41
+ router.on('start', (event) => {
42
+ visit = event.detail.visit;
43
+ });
44
+ router.on('httpException', (event) => {
45
+ if (event.detail.response.headers['x-inertia'] || visit?.method !== 'get')
46
+ return;
47
+ event.preventDefault();
48
+ window.location.href = visit.url.href;
49
+ });
50
+ }
@@ -4,9 +4,10 @@ import type { PluginOption } from 'vite';
4
4
  * `vite.config.ts`: `plugins: [fondu({ target: 'node' })]` (or `'bun'`; for Cloudflare: `cloudflare()` and
5
5
  * `fondu({ target: 'cloudflare' })`). Composes the packages that do the work:
6
6
  * - `@vitejs/plugin-react`, and `@inertiajs/vite` (pages from `app/pages/`, the server render of `app/app.tsx`)
7
- * - Node / Bun: `@hono/vite-dev-server` (dev) and `@hono/vite-build` (`vite build --mode client && vite build`)
8
- * - Cloudflare: `@cloudflare/vite-plugin` (yours: dev in workerd, one `vite build`)
9
- * and adds what none of them does: the document's asset tags, the generated types, the server-only guard.
7
+ * - Node / Bun: `@hono/vite-dev-server` (dev); the build is Vite's own, of two environments (`serverEntry()`)
8
+ * - 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
11
  */
11
12
  export interface FonduOptions {
12
13
  target: 'node' | 'bun' | 'cloudflare';
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
3
- import { createRequire } from 'node:module';
3
+ import { builtinModules, createRequire } from 'node:module';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
@@ -25,7 +25,11 @@ export const HONO = [
25
25
  ];
26
26
  const SERVER = './app/server.ts';
27
27
  const DEV_CSS = '/@fondu/dev.css';
28
- const V = { assets: 'virtual:fondu/assets', ssr: 'virtual:fondu/ssr' };
28
+ const V = {
29
+ assets: 'virtual:fondu/assets',
30
+ ssr: 'virtual:fondu/ssr',
31
+ serverEntry: 'virtual:fondu/server-entry',
32
+ };
29
33
  const resolved = (id) => '\0' + id;
30
34
  /**
31
35
  * `@inertiajs/vite` wraps `createInertiaApp(...)` for the server; its React template also starts a standalone
@@ -97,48 +101,47 @@ export default function fondu(options) {
97
101
  ...(node ? runtimePlugins(options) : [serverReactDomClient()]),
98
102
  ];
99
103
  }
100
- async function buildPlugin(options) {
101
- const { default: build } = options.target === 'bun'
102
- ? await import('@hono/vite-build/bun')
103
- : await import('@hono/vite-build/node');
104
- // the app's dependencies stay in node_modules (as with any Node server: native modules cannot be bundled)
105
- const pkg = JSON.parse(readFileSync(resolve('package.json'), 'utf8'));
106
- const external = Object.keys(pkg.dependencies ?? {}).filter((d) => d !== 'fondu');
107
- const plugin = build({
108
- entry: SERVER,
109
- external,
110
- outputDir: './dist/server', // next to dist/client, as the client build writes it
111
- emptyOutDir: true, // dist/server is the server build's own
112
- // Node: @hono/node-server's serve() on `PORT` (else the option), saying where it listens, with a graceful
113
- // shutdown on SIGTERM / SIGINT (10 s). Bun serves the default export itself and reads `PORT`.
114
- ...(options.target === 'node' && {
115
- entryContentAfterHooks: [
116
- (app) => [
117
- `import { serve } from '@hono/node-server'`,
118
- `const server = serve({ fetch: ${app}.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
119
- `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
120
- `process.on('SIGINT', shutdown)`,
121
- `process.on('SIGTERM', shutdown)`,
122
- ].join('\n'),
123
- ],
124
- }),
125
- // the client build's files (dist/client), found next to the server bundle wherever it runs from; hashed files
126
- // never change
127
- entryContentBeforeHooks: [
128
- (app) => {
129
- const dir = resolve('dist/client'); // vite runs in the project root
104
+ /** the app's dependencies stay in node_modules, as with any Node server (native modules cannot be bundled) */
105
+ function dependencies(root = '') {
106
+ const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
107
+ return Object.keys(pkg.dependencies ?? {}).filter((d) => d !== 'fondu');
108
+ }
109
+ /**
110
+ * Node / Bun: the server build's entry, dist/server/index.js. The client build's files first (found next to the
111
+ * server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
112
+ * on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
113
+ * serves the default export itself and reads `PORT` (with the app's `websocket`, if it has one).
114
+ */
115
+ function serverEntry(options) {
116
+ let root = process.cwd();
117
+ return {
118
+ name: 'fondu:server-entry',
119
+ apply: 'build',
120
+ applyToEnvironment: (env) => env.name === 'ssr',
121
+ configResolved(c) {
122
+ root = c.root;
123
+ },
124
+ resolveId: { filter: { id: /^virtual:fondu\/server-entry$/ }, handler: (id) => resolved(id) },
125
+ load: {
126
+ filter: { id: /^\0virtual:fondu\/server-entry$/ },
127
+ handler() {
128
+ const dir = resolve(root, 'dist/client');
130
129
  const paths = existsSync(dir)
131
130
  ? readdirSync(dir, { withFileTypes: true })
132
131
  .filter((e) => e.name !== '.vite')
133
132
  .map((e) => (e.isDirectory() ? `/${e.name}/*` : `/${e.name}`))
134
133
  : [];
134
+ const bun = options.target === 'bun';
135
135
  return [
136
- `import { serveStatic } from '${options.target === 'bun' ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
136
+ `import { Hono } from 'hono'`,
137
+ `import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
137
138
  `import { fileURLToPath } from 'node:url'`,
139
+ `import app from '${SERVER.slice(1)}'`,
138
140
  `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
139
- `${app}.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
140
- ...paths.map((p) => `${app}.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
141
- // prerender: how the app reads the prerendered pages (fondu's server/prerender.ts), in the client build
141
+ `const main = new Hono()`,
142
+ `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
143
+ ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
144
+ // prerender: how the app reads the prerendered pages (fondu's server/prerender.ts)
142
145
  ...(options.prerender
143
146
  ? [
144
147
  `import { readFile } from 'node:fs/promises'`,
@@ -146,11 +149,23 @@ async function buildPlugin(options) {
146
149
  `globalThis[Symbol.for('fondu.staticFiles')] = (file) => { const to = joinPath(clientRoot, file); return to.startsWith(clientRoot + sep) ? readFile(to).catch(() => null) : Promise.resolve(null) }`,
147
150
  ]
148
151
  : []),
152
+ `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
153
+ ...(bun
154
+ ? [
155
+ `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`,
156
+ ]
157
+ : [
158
+ `import { serve } from '@hono/node-server'`,
159
+ `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
160
+ `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
161
+ `process.on('SIGINT', shutdown)`,
162
+ `process.on('SIGTERM', shutdown)`,
163
+ `export default main`,
164
+ ]),
149
165
  ].join('\n');
150
166
  },
151
- ],
152
- });
153
- return plugin;
167
+ },
168
+ };
154
169
  }
155
170
  function runtimePlugins(options) {
156
171
  return [
@@ -176,7 +191,7 @@ function runtimePlugins(options) {
176
191
  exclude: devServerDefaults.exclude,
177
192
  handleHotUpdate: () => { }, // fondu's plugin does it, for every target
178
193
  }),
179
- buildPlugin(options),
194
+ serverEntry(options),
180
195
  ];
181
196
  }
182
197
  /**
@@ -216,13 +231,11 @@ function loadFailure() {
216
231
  function core(options) {
217
232
  let config;
218
233
  let isBuild = false;
219
- let serverBuild = false; // Node / Bun: `vite build`, after `vite build --mode client`
220
234
  return {
221
235
  name: 'fondu',
222
236
  enforce: 'pre',
223
- config(_user, env) {
237
+ config(user, env) {
224
238
  isBuild = env.command === 'build';
225
- serverBuild = isBuild && options.target !== 'cloudflare' && env.mode !== 'client';
226
239
  const client = { manifest: true, rollupOptions: { input: ENTRY } };
227
240
  if (options.target === 'cloudflare') {
228
241
  return {
@@ -251,16 +264,42 @@ function core(options) {
251
264
  ssr: { noExternal: ['fondu'] },
252
265
  };
253
266
  }
254
- // Node / Bun: `vite build --mode client` builds the client into dist/client, `vite build` the server
255
- return env.mode === 'client'
256
- ? { build: { ...client, outDir: 'dist/client', emptyOutDir: true } }
257
- : {
258
- ssr: { noExternal: ['fondu'] },
259
- build: {
260
- copyPublicDir: false,
261
- rollupOptions: { output: { chunkFileNames: '[name]-[hash].js' } },
267
+ // Node / Bun: the client into dist/client, then the server into dist/server (index.js: serverEntry()), then the
268
+ // pages to prerender. The server bundles all but the app's dependencies, and is minified
269
+ const target = options.target;
270
+ const external = isBuild ? dependencies(user.root) : [];
271
+ return {
272
+ ssr: isBuild ? { noExternal: true, external, target: 'node' } : { noExternal: ['fondu'] },
273
+ environments: {
274
+ client: { build: { ...client, outDir: 'dist/client', emptyOutDir: true } },
275
+ ssr: {
276
+ build: {
277
+ outDir: 'dist/server',
278
+ emptyOutDir: true,
279
+ copyPublicDir: false,
280
+ minify: true,
281
+ rollupOptions: {
282
+ input: V.serverEntry,
283
+ external: [
284
+ ...builtinModules,
285
+ /^node:/,
286
+ ...(target === 'bun' ? ['bun'] : []),
287
+ ...external,
288
+ ],
289
+ output: { entryFileNames: 'index.js', chunkFileNames: '[name]-[hash].js' },
290
+ },
291
+ },
262
292
  },
263
- };
293
+ },
294
+ builder: {
295
+ async buildApp(builder) {
296
+ await builder.build(builder.environments.client);
297
+ await builder.build(builder.environments.ssr);
298
+ if (options.prerender)
299
+ await prerender(nodeServer(config.root, target), resolve(config.root, 'dist/client'), config.logger, false);
300
+ },
301
+ },
302
+ };
264
303
  },
265
304
  // dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
266
305
  // so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
@@ -291,14 +330,6 @@ function core(options) {
291
330
  configResolved(c) {
292
331
  config = c;
293
332
  },
294
- // Node / Bun: the server built, its pages to prerender written next to the client build's files
295
- async closeBundle() {
296
- if (!options.prerender || !serverBuild || options.target === 'cloudflare')
297
- return;
298
- serverBuild = false; // once
299
- const clientDir = resolve(config.root, 'dist/client');
300
- await prerender(nodeServer(config.root, options.target), clientDir, config.logger, false);
301
- },
302
333
  // dev: the CSS the client entry imports, as a stylesheet in the document, so a server-rendered page is styled
303
334
  // at first paint (Vite would add it only once the JS runs); removed once the entry has run
304
335
  configureServer(server) {
@@ -347,14 +378,16 @@ function core(options) {
347
378
  return resolved(id);
348
379
  },
349
380
  // the client entry: with prerender, page objects read from the prerendered files (fondu/client's `prerendered`);
350
- // in dev, the page's props asked for again when what its route depends on changed (hmr.ts)
381
+ // in production, an answer to a visit that isn't a page loaded as a document (`documentFallback`); in dev,
382
+ // Inertia's dialog (the error report is shown there), and the page's props asked for again when what its route
383
+ // depends on changed (hmr.ts)
351
384
  transform(code, id) {
352
385
  if (this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
353
386
  return;
354
387
  const before = [
355
388
  ...(options.prerender ? [`import { prerendered } from 'fondu/client';prerendered();`] : []),
356
389
  ...(isBuild
357
- ? []
390
+ ? [`import { documentFallback } from 'fondu/client';documentFallback();`]
358
391
  : [
359
392
  `import { router as __fondu_router } from '@inertiajs/react';`,
360
393
  `import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => __fondu_router.reload());`,
@@ -402,7 +435,7 @@ function productionAssets(config, options) {
402
435
  : resolve(config.root, 'dist/client');
403
436
  const file = resolve(outDir, '.vite/manifest.json');
404
437
  if (!existsSync(file))
405
- throw new Error(`fondu: the client manifest (${file}) is missing: build the client first (\`vite build --mode client\`)`);
438
+ throw new Error(`fondu: the client manifest (${file}) is missing: the client is built first (\`vite build\`)`);
406
439
  const text = readFileSync(file, 'utf8');
407
440
  const manifest = JSON.parse(text);
408
441
  const collect = (key, css, js, seen = new Set()) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",
@@ -49,7 +49,6 @@
49
49
  "typecheck": "tsc -p tsconfig.json"
50
50
  },
51
51
  "dependencies": {
52
- "@hono/vite-build": "^1.11.1",
53
52
  "@hono/vite-dev-server": "^0.26.1",
54
53
  "@inertiajs/vite": "^3.9.1",
55
54
  "@vitejs/plugin-react": "^6.1.2"