fondu 0.18.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.
@@ -77,7 +77,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
77
77
  return;
78
78
  const answer = (async () => {
79
79
  try {
80
- const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
80
+ const response = await fetch(key, {
81
+ headers: { ...headers(), 'X-Fondu-Prefetch': 'true' },
82
+ // not in the way of the page's own requests
83
+ priority: 'low',
84
+ });
81
85
  if (response.status === 200 && response.headers.has('X-Fondu'))
82
86
  return { body: await response.text(), headers: response.headers };
83
87
  }
@@ -382,7 +386,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
382
386
  const link = target?.closest?.('a[href]');
383
387
  if (!(link instanceof HTMLAnchorElement))
384
388
  return;
385
- if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
389
+ // its own `target`, else the document's `<base target>`; SVG `<a>` and `<area>` are not matched: the browser's
390
+ const into = link.target || document.querySelector('base[target]')?.target;
391
+ if ((into && into !== '_self') || link.hasAttribute('download'))
386
392
  return;
387
393
  const url = new URL(link.href);
388
394
  if (url.origin !== location.origin || !isWebUrl(url.href))
@@ -459,6 +465,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
459
465
  const url = new URL(attr('action', 'formaction') || location.href, location.href);
460
466
  if (url.origin !== location.origin || !isWebUrl(url.href))
461
467
  return;
468
+ // a GET to a URL that is none of the app's pages (a `.ts` route): the browser's, as for a link; asking first would
469
+ // run its handler twice
470
+ if (method === 'get' && !isPage(url.pathname))
471
+ return;
462
472
  event.preventDefault();
463
473
  const data = new FormData(form, submitter);
464
474
  // as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
@@ -749,6 +759,11 @@ const isWebUrl = (url) => {
749
759
  return false;
750
760
  }
751
761
  };
762
+ /** `javascript:` is never handed to `location`: the page's CSP would be all that stops it (the URL parser drops leading space, lowers the scheme) */
763
+ function refuseScript(url) {
764
+ if (url.protocol === 'javascript:')
765
+ throw new Error('fondu: refusing to load a javascript: URL');
766
+ }
752
767
  /** a Content-Disposition's file name: `filename*=UTF-8''…` (RFC 6266), else `filename="…"`; '' for none */
753
768
  function fileName(disposition) {
754
769
  const encoded = /filename\*\s*=\s*UTF-8''([^;\s]+)/i.exec(disposition)?.[1];
@@ -765,6 +780,7 @@ function fileName(disposition) {
765
780
  * can't change in place (`<html lang>`: another language).
766
781
  */
767
782
  export function loadDocument(href) {
783
+ refuseScript(new URL(href, location.href));
768
784
  location.assign(href);
769
785
  }
770
786
  /**
@@ -786,6 +802,7 @@ export function navigate(href, options = {}) {
786
802
  const shown = shownUrl?.();
787
803
  // a shallow navigation is relative to the page on the screen, whose URL `location` may have left
788
804
  const url = new URL(href, shallow ? (shown ?? location.href) : location.href);
805
+ refuseScript(url);
789
806
  if (shallow) {
790
807
  if (url.origin !== location.origin || url.pathname !== (shown ?? location).pathname)
791
808
  throw new Error(`fondu: a shallow navigation stays on this page (its query, its #fragment); ${url.origin === location.origin ? url.pathname : url.href} is another page: leave out \`shallow\``);
package/dist/form.d.ts CHANGED
@@ -12,7 +12,8 @@ export declare const crlf: (text: string) => string;
12
12
  * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
13
13
  * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
14
14
  * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
15
- * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
15
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32) and for more than 10,000 entries
16
+ * (files and empty file inputs count).
16
17
  */
17
18
  export declare function formObject(entries: Iterable<Entry>): Record<string, unknown>;
18
19
  /** A Standard Schema's issue, the part used here */
package/dist/form.js CHANGED
@@ -4,6 +4,8 @@
4
4
  */
5
5
  /** how deep form field names nest (`a[b][c]`: 3) */
6
6
  const DEPTH = 32;
7
+ /** how many entries (fields, files, empty file inputs too) a form may have */
8
+ const ENTRIES = 10_000;
7
9
  /** a body that can't be one object: a 400 on the server */
8
10
  export class MalformedForm extends Error {
9
11
  }
@@ -13,17 +15,22 @@ export const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
13
15
  * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
14
16
  * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
15
17
  * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
16
- * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
18
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32) and for more than 10,000 entries
19
+ * (files and empty file inputs count).
17
20
  */
18
21
  export function formObject(entries) {
19
22
  const body = Object.create(null);
20
23
  // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
21
24
  const next = new WeakMap();
22
25
  const isObject = (v) => typeof v === 'object' && !isFile(v) && !Array.isArray(v);
26
+ let count = 0;
23
27
  for (const [key, value] of entries) {
28
+ if (++count > ENTRIES)
29
+ throw new MalformedForm(`more than ${ENTRIES} fields`);
24
30
  if (typeof value !== 'string' && value.size === 0 && value.name === '')
25
31
  continue;
26
- const path = key.replace(/\]/g, '').split('[');
32
+ // a limit: a name that is too deep is known from its first parts, the rest is not split
33
+ const path = key.replace(/\]/g, '').split('[', DEPTH + 1);
27
34
  if (path.length > DEPTH)
28
35
  throw new MalformedForm(`a field name nests deeper than ${DEPTH}`);
29
36
  if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
package/dist/paths.d.ts CHANGED
@@ -59,3 +59,8 @@ export declare function staticFiles(path: string): {
59
59
  html: string;
60
60
  json: string;
61
61
  };
62
+ /**
63
+ * Throws if a route file (`file`, relative to `routes/`) exports a name it may not. The server checks it at startup
64
+ * (the exports of the loaded module), the build too (the names in the source): one message.
65
+ */
66
+ export declare function checkExportNames(file: string, names: readonly string[]): void;
package/dist/paths.js CHANGED
@@ -146,3 +146,51 @@ export function staticFiles(path) {
146
146
  json: decodeURIComponent(pageDataPath(path)).slice(1),
147
147
  };
148
148
  }
149
+ /**
150
+ * What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
151
+ * page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
152
+ * HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
153
+ */
154
+ function exportsOf(file) {
155
+ const name = file.split('/').at(-1);
156
+ if (name === '_middleware.ts')
157
+ return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
158
+ if (/^_(?:layout|error)\.tsx$/.test(name))
159
+ return { allowed: ['default'], hint: 'its component only (default)' };
160
+ if (file.endsWith('.mdx'))
161
+ return {
162
+ allowed: [],
163
+ hint: "its content: an MDX page has no handlers (a _middleware.ts's prerender, params)",
164
+ };
165
+ if (file.endsWith('.ts'))
166
+ return {
167
+ allowed: [...METHODS, ...CONFIG],
168
+ hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
169
+ };
170
+ return {
171
+ allowed: ['default', ...HANDLERS, ...CONFIG],
172
+ hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
173
+ };
174
+ }
175
+ /** what a page's handler is called in a `.ts` file */
176
+ const INSTEAD = {
177
+ loader: 'in a .ts file it is `GET`',
178
+ action: 'in a .ts file it is `POST`',
179
+ actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
180
+ };
181
+ /**
182
+ * Throws if a route file (`file`, relative to `routes/`) exports a name it may not. The server checks it at startup
183
+ * (the exports of the loaded module), the build too (the names in the source): one message.
184
+ */
185
+ export function checkExportNames(file, names) {
186
+ const { allowed, hint } = exportsOf(file);
187
+ const mdx = file.endsWith('.mdx');
188
+ const extra = names.filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
189
+ if (!extra.length)
190
+ return;
191
+ const renamed = file.endsWith('.ts')
192
+ ? extra.filter((k) => k in INSTEAD)
193
+ : [];
194
+ throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
195
+ (renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
196
+ }
@@ -5,7 +5,7 @@ import { type DocumentTemplate } from './document.js';
5
5
  export interface CreateAppOptions {
6
6
  /** the HTML document around pages (default: a minimal one) */
7
7
  document?: DocumentTemplate;
8
- /** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): Hono's trailing-slash middleware */
8
+ /** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): a 301 to a relative URL */
9
9
  trailingSlash?: 'trim' | 'append';
10
10
  /** `hono/csrf`'s options; `false`: off */
11
11
  csrf?: Parameters<typeof csrf>[0] | false;
@@ -33,7 +33,8 @@ export declare function checkExports(file: string, mod: Record<string, unknown>)
33
33
  * `action`, `actions`: those are a page's)
34
34
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
35
35
  * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page, and a request body
36
- * limit (413, after the root `_middleware.ts`, so its error page has the shared props; CSRF's 403 is plain text).
36
+ * limit (413, in each route that takes a body, after its directories' `_middleware.ts`, so its error page has the
37
+ * shared props; CSRF's 403 is plain text).
37
38
  * Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
38
39
  */
39
40
  export declare function createApp(options?: CreateAppOptions): Hono;
@@ -4,11 +4,11 @@ import { every } from 'hono/combine';
4
4
  import { csrf } from 'hono/csrf';
5
5
  import { HTTPException } from 'hono/http-exception';
6
6
  import { NONCE, secureHeaders } from 'hono/secure-headers';
7
- import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
8
7
  import { prerender, version } from 'virtual:fondu/assets';
9
- import { CONFIG, HANDLERS, isPageFile, isRouteFile, METHODS, pageId } from '../paths.js';
8
+ import { checkExportNames, isPageFile, isRouteFile, METHODS, pageId } from '../paths.js';
10
9
  import { settings } from './document.js';
11
10
  import { errorResponse } from './errors.js';
11
+ import { csrfOrigin, trailingSlash } from './http.js';
12
12
  import { prerenderRoutes } from './prerender.js';
13
13
  import { protocol, registerPage, renderPage, routePage } from './protocol.js';
14
14
  import { routeTable } from './routes.js';
@@ -24,49 +24,8 @@ const CSP = {
24
24
  baseUri: ["'self'"],
25
25
  };
26
26
  const ROOT = '/app/routes/';
27
- /**
28
- * What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
29
- * page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
30
- * HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
31
- */
32
- function exportsOf(file) {
33
- const name = file.split('/').at(-1);
34
- if (name === '_middleware.ts')
35
- return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
36
- if (/^_(?:layout|error)\.tsx$/.test(name))
37
- return { allowed: ['default'], hint: 'its component only (default)' };
38
- if (file.endsWith('.mdx'))
39
- return {
40
- allowed: [],
41
- hint: "its content: an MDX page has no handlers (a _middleware.ts's prerender, params)",
42
- };
43
- if (file.endsWith('.ts'))
44
- return {
45
- allowed: [...METHODS, ...CONFIG],
46
- hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
47
- };
48
- return {
49
- allowed: ['default', ...HANDLERS, ...CONFIG],
50
- hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
51
- };
52
- }
53
- /** what a page's handler is called in a `.ts` file */
54
- const INSTEAD = {
55
- loader: 'in a .ts file it is `GET`',
56
- action: 'in a .ts file it is `POST`',
57
- actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
58
- };
59
27
  export function checkExports(file, mod) {
60
- const { allowed, hint } = exportsOf(file);
61
- const mdx = file.endsWith('.mdx');
62
- const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
63
- if (extra.length) {
64
- const renamed = file.endsWith('.ts')
65
- ? extra.filter((k) => k in INSTEAD)
66
- : [];
67
- throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
68
- (renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
69
- }
28
+ checkExportNames(file, Object.keys(mod));
70
29
  if (/\.(?:tsx|mdx)$/.test(file) && typeof mod.default !== 'function')
71
30
  throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
72
31
  }
@@ -95,7 +54,8 @@ function actionName(url) {
95
54
  * `action`, `actions`: those are a page's)
96
55
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
97
56
  * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page, and a request body
98
- * limit (413, after the root `_middleware.ts`, so its error page has the shared props; CSRF's 403 is plain text).
57
+ * limit (413, in each route that takes a body, after its directories' `_middleware.ts`, so its error page has the
58
+ * shared props; CSRF's 403 is plain text).
99
59
  * Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
100
60
  */
101
61
  export function createApp(options = {}) {
@@ -133,13 +93,17 @@ export function createApp(options = {}) {
133
93
  }));
134
94
  }
135
95
  if (options.csrf !== false)
136
- app.use(csrf(options.csrf));
96
+ app.use(csrf({ ...options.csrf, origin: options.csrf?.origin ?? csrfOrigin }));
137
97
  const prerendered = [];
138
98
  if (prerender)
139
99
  prerenderRoutes(app, () => prerendered, version);
140
- app.use(append ? appendTrailingSlash() : trimTrailingSlash(), ...protocol);
100
+ app.use(trailingSlash(append), ...protocol);
141
101
  app.notFound((c) => errorResponse(c, 404));
142
102
  app.onError((error, c) => {
103
+ // the client left (a body cut off mid-upload, a handler that read it): nobody is there to answer, so no 500 is
104
+ // logged. Recognised by the request's own signal, not by the error's type or message (they differ by runtime)
105
+ if (!(error instanceof HTTPException) && c.req.raw.signal.aborted)
106
+ return new Response(null, { status: 499 });
143
107
  if (error instanceof HTTPException && error.res)
144
108
  return error.getResponse();
145
109
  return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
@@ -148,18 +112,22 @@ export function createApp(options = {}) {
148
112
  const rootMiddleware = modules['_middleware.ts']?.default;
149
113
  if (rootMiddleware)
150
114
  app.use(...chain(rootMiddleware));
151
- // After the root middleware, so the error page of a 413 has the shared props it set (a layout reads them). The limit
152
- // still runs before any body is read: with a Content-Length the header is checked, without one the body is counted
153
- // as it is read. A root middleware must not read the body itself. CSRF stays above: Hono's 403 has its own plain
154
- // response, so no page is rendered for it.
155
- if (options.bodyLimit !== false)
156
- app.use(bodyLimit({
157
- maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
158
- // Fondu's own answer: the error page for a visitor, the status alone for an API client
159
- onError: () => {
160
- throw new HTTPException(413);
161
- },
162
- }));
115
+ // One limit, in the chain of each route for the methods that take a body, after its directories' middleware (so a 413
116
+ // has their shared props, and a request they refuse is not read) and before its handler. Not for a GET, a HEAD or a
117
+ // URL that is no route: none of them reads a body. With a Content-Length the header is checked, without one the body
118
+ // is counted as it is read. A directory's middleware must not read the body itself. CSRF stays above: Hono's 403 has
119
+ // its own plain response, so no page is rendered for it.
120
+ const limit = options.bodyLimit === false
121
+ ? []
122
+ : [
123
+ bodyLimit({
124
+ maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
125
+ // Fondu's own answer: the error page for a visitor, the status alone for an API client
126
+ onError: () => {
127
+ throw new HTTPException(413);
128
+ },
129
+ }),
130
+ ];
163
131
  for (const { file, pattern, path, middleware } of routeTable(modules, append)) {
164
132
  const mod = modules[file];
165
133
  const page = isPageFile(file) ? pageId(file) : undefined;
@@ -191,6 +159,7 @@ export function createApp(options = {}) {
191
159
  const actions = mod.actions ?? {};
192
160
  add('POST', [
193
161
  ...mws,
162
+ ...limit,
194
163
  async (c, next) => {
195
164
  const name = actionName(c.req.url);
196
165
  // actions: the one named (?name), else none; otherwise the one action
@@ -210,7 +179,7 @@ export function createApp(options = {}) {
210
179
  continue;
211
180
  const h = mod[method];
212
181
  if (h)
213
- add(method, [...mws, ...chain(h)]);
182
+ add(method, [...mws, ...(method === 'OPTIONS' ? [] : limit), ...chain(h)]);
214
183
  }
215
184
  }
216
185
  return app;
@@ -15,8 +15,12 @@ export const withoutSsr = () => async (c, next) => {
15
15
  browserOnly.add(c);
16
16
  await next();
17
17
  };
18
- /** the page data, `/` and `<` escaped (no `</script>` in it), no HTML entities */
19
- const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
18
+ /**
19
+ * The page data as the document carries it, from the JSON of the page: `<` escaped, so nothing in it is `</script>` or
20
+ * `<!--` (the only ways out of a script's data); no HTML entities. U+2028 and U+2029 are fine in JSON, and the data is
21
+ * not run as JavaScript.
22
+ */
23
+ const pageScript = (json) => `<script data-page="app" type="application/json">${json.replace(/</g, '\\u003c')}</script>`;
20
24
  /**
21
25
  * A reload, Back to a page of another site: this entry's position, where fondu/client left it, before the first
22
26
  * paint (the stylesheets are in: the page is laid out), and again once the page has loaded: browsers scroll on
@@ -65,6 +69,8 @@ export async function renderDocument(c, page, whole = false) {
65
69
  const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
66
70
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
67
71
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
72
+ // the page once as JSON: the document's data, and what the render gets a fresh copy of
73
+ const json = JSON.stringify(page);
68
74
  let ssr = null;
69
75
  // per request: nothing the page renders can be it
70
76
  const marker = crypto.randomUUID();
@@ -72,13 +78,22 @@ export async function renderDocument(c, page, whole = false) {
72
78
  // React reports it to `onError` too, so what it reports is held until the shell is known to be there
73
79
  const pending = [];
74
80
  let live = false;
75
- const late = (error) => console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
81
+ // The client left: React is given the request's signal, stops, and reports the signal's reason to `onError` (what
82
+ // `abort()` was given: an AbortError, or Node's string). That is not an error of the page, and nothing else is left out
83
+ const { signal } = c.req.raw;
84
+ const clientLeft = (error) => signal.aborted && error === signal.reason;
85
+ const late = (error) => {
86
+ if (!clientLeft(error))
87
+ console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
88
+ };
76
89
  try {
77
90
  // a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
78
91
  if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
79
- // the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
80
- const stream = await renderPage(JSON.parse(JSON.stringify(page)), {
92
+ // the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides. A copy
93
+ // of its own: what the render changes in its props is not in the page data
94
+ const stream = await renderPage(JSON.parse(json), {
81
95
  nonce,
96
+ signal,
82
97
  onError: (error) => (live ? late(error) : void pending.push(error)),
83
98
  // React writes this as a script right after the shell, before what the boundaries add: where `restoreScroll`
84
99
  // goes. Not as React's own script (it adds an `id`, and follows its `$RT` one), and not as a sibling of the
@@ -98,12 +113,14 @@ export async function renderDocument(c, page, whole = false) {
98
113
  // same props and most likely fail again, and a visitor without JavaScript would get nothing)
99
114
  if (page.component === '_error')
100
115
  throw error;
101
- // like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
102
- console.error(`[fondu] server render of "${page.component}" failed, sending it to render in the browser:`, error);
116
+ // like Laravel: a page that fails to render on the server is still sent, and rendered in the browser. Not logged if
117
+ // the client left before the shell was there
118
+ if (!clientLeft(error))
119
+ console.error(`[fondu] server render of "${page.component}" failed, sending it to render in the browser:`, error);
103
120
  }
104
121
  // the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
105
122
  // content can come before it
106
- const data = pageScript(page);
123
+ const data = pageScript(json);
107
124
  // the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
108
125
  // document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
109
126
  // the page out early (Firefox's, with its tools open) has them sooner
@@ -1,5 +1,47 @@
1
1
  import { generateCookie, getCookie } from 'hono/cookie';
2
- import { appendHeader } from './http.js';
2
+ import { appendHeader, isSecure } from './http.js';
3
+ /** what fits in a cookie (browsers drop one over ~4 KB, name and attributes included, without a word) */
4
+ const COOKIE_LIMIT = 4000;
5
+ const cookieSize = (value) => encodeURIComponent(JSON.stringify(value)).length;
6
+ const isPlain = (value) => typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;
7
+ /**
8
+ * The cookie comes back from the client: anyone can write it. What is not `{ flash?, errors? }` is ignored: `flash` a
9
+ * plain object (its values any JSON: an app's flash data can be an object), `errors` a plain object of strings
10
+ * (`ValidationError`'s).
11
+ */
12
+ function parseCarried(raw) {
13
+ try {
14
+ const value = JSON.parse(raw ?? 'null');
15
+ if (!isPlain(value))
16
+ return undefined;
17
+ const { flash, errors } = value;
18
+ return (flash === undefined || isPlain(flash)) &&
19
+ (errors === undefined ||
20
+ (isPlain(errors) && Object.values(errors).every((v) => typeof v === 'string')))
21
+ ? { flash, errors }
22
+ : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /** `outgoing` as a cookie's value: whole if it fits, else without the flash data, else the errors that fit, in order */
29
+ function fit(outgoing) {
30
+ const whole = JSON.stringify(outgoing);
31
+ if (encodeURIComponent(whole).length <= COOKIE_LIMIT)
32
+ return { value: whole };
33
+ const errors = {};
34
+ for (const [key, message] of Object.entries(outgoing.errors ?? {}))
35
+ if (cookieSize({ errors: { ...errors, [key]: message } }) <= COOKIE_LIMIT)
36
+ errors[key] = message;
37
+ const kept = Object.keys(errors).length;
38
+ const all = Object.keys(outgoing.errors ?? {}).length;
39
+ const dropped = [
40
+ ...(outgoing.flash ? ['the flash data'] : []),
41
+ ...(kept < all ? [`${all - kept} of ${all} errors`] : []),
42
+ ];
43
+ return { value: kept ? JSON.stringify({ errors }) : undefined, dropped: dropped.join(' and ') };
44
+ }
3
45
  const states = new WeakMap();
4
46
  const state = (c) => {
5
47
  let s = states.get(c);
@@ -7,9 +49,6 @@ const state = (c) => {
7
49
  states.set(c, (s = { outgoing: {}, incoming: undefined, read: false }));
8
50
  return s;
9
51
  };
10
- /** https, directly or behind a proxy that says so */
11
- const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
12
- c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
13
52
  const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
14
53
  /** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
15
54
  export function flash(c, data) {
@@ -25,12 +64,7 @@ export function takeCarried(c) {
25
64
  const s = state(c);
26
65
  if (!s.read) {
27
66
  s.read = true;
28
- try {
29
- s.incoming = JSON.parse(getCookie(c, cookieName(c)) ?? 'null') ?? undefined;
30
- }
31
- catch {
32
- s.incoming = undefined;
33
- }
67
+ s.incoming = parseCarried(getCookie(c, cookieName(c)));
34
68
  }
35
69
  const carried = {
36
70
  flash: { ...s.incoming?.flash, ...s.outgoing.flash },
@@ -45,15 +79,20 @@ export const flashCookie = async (c, next) => {
45
79
  const s = states.get(c);
46
80
  if (!s)
47
81
  return;
82
+ // a HEAD request is a GET's headers: it leaves the flash for the page the browser asks for
83
+ if (c.req.method === 'HEAD')
84
+ return;
48
85
  const name = cookieName(c);
49
86
  const options = { path: '/', httpOnly: true, sameSite: 'Lax', secure: isSecure(c) };
87
+ let value;
50
88
  if (s.outgoing.flash || s.outgoing.errors) {
51
- const value = JSON.stringify(s.outgoing);
52
- // browsers drop a cookie over ~4 KB without a word: the next page would show no errors, no flash
53
- if (encodeURIComponent(value).length > 4000)
54
- console.error(`[fondu] flash data and errors are too large for a cookie (${encodeURIComponent(value).length} bytes, about 4000 fit): the browser will drop them`);
55
- appendHeader(c, 'Set-Cookie', generateCookie(name, value, { ...options, maxAge: 60 }));
89
+ const result = fit(s.outgoing);
90
+ value = result.value;
91
+ if (result.dropped)
92
+ console.warn(`[fondu] flash data and errors are too large for a cookie (about ${COOKIE_LIMIT} bytes fit, the browser drops more): dropped ${result.dropped}`);
56
93
  }
94
+ if (value)
95
+ appendHeader(c, 'Set-Cookie', generateCookie(name, value, { ...options, maxAge: 60 }));
57
96
  else if (s.read && s.incoming)
58
97
  appendHeader(c, 'Set-Cookie', generateCookie(name, '', { ...options, maxAge: 0 }));
59
98
  };
@@ -1,14 +1,38 @@
1
- import type { Context } from 'hono';
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
2
  /** a navigation of fondu/client: it wants the page as JSON */
3
3
  export declare const isPageRequest: (c: Context) => boolean;
4
4
  /** a navigation or a document load (gets a page), not an API client (gets data) */
5
5
  export declare const wantsPage: (c: Context) => boolean;
6
6
  /** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
7
7
  export declare const nonceOf: (c: Context) => string | undefined;
8
- /** `url` as a URL of this site, or null (another site, unparsable) */
8
+ /** https, directly or behind a proxy that says so (`X-Forwarded-Proto`; the proxy's word is read, never `X-Forwarded-Host`) */
9
+ export declare const isSecure: (c: Context) => boolean;
10
+ /** the path and query of a URL, as a redirect to this site: one leading slash (`//evil.com` is another site's) */
11
+ export declare const pathAndQuery: (url: URL) => string;
12
+ /**
13
+ * `url` as a URL of this site, or null (another site, unparsable). Hosts are compared, not origins: behind a proxy
14
+ * that terminates TLS the request's URL is `http://` while the browser's `Referer` is `https://`.
15
+ */
9
16
  export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
17
+ /**
18
+ * The page the request came from (its `Referer`) as a URL: only its path and query are ever used. A request the
19
+ * browser says is `Sec-Fetch-Site: same-origin` came from a page of this site; else its host must be this site's.
20
+ */
21
+ export declare function referer(c: Context): URL | null;
10
22
  /** Back to the page the request came from (303), or `fallback` when there is none on this site. */
11
23
  export declare const back: (c: Context, fallback?: string) => Response & import("hono").TypedResponse<undefined, 303, "redirect">;
24
+ /**
25
+ * The trailing-slash redirect, for a GET or HEAD no route answered (404): a 301 to the path with its slash taken off
26
+ * (`'trim'`) or put on (`'append'`). Its Location is relative, the path as it was asked (encoded) and the query:
27
+ * behind a proxy the request's URL has another scheme than the browser's. One leading slash (`//evil.com/` is
28
+ * `/evil.com`, never another site).
29
+ */
30
+ export declare const trailingSlash: (append: boolean) => MiddlewareHandler;
31
+ /**
32
+ * `hono/csrf`'s fallback for a browser without `Sec-Fetch-Site`: an `Origin` with this request's `Host`, and its scheme
33
+ * (`https` too when a proxy says so). Hono compares it with the request's URL, `http://` behind a proxy.
34
+ */
35
+ export declare const csrfOrigin: (origin: string, c: Context) => boolean;
12
36
  /**
13
37
  * A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
14
38
  * the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
@@ -4,13 +4,38 @@ export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
4
4
  export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
5
5
  /** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
6
6
  export const nonceOf = (c) => c.get('secureHeadersNonce');
7
- /** `url` as a URL of this site, or null (another site, unparsable) */
7
+ /** https, directly or behind a proxy that says so (`X-Forwarded-Proto`; the proxy's word is read, never `X-Forwarded-Host`) */
8
+ export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
9
+ c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
10
+ /** the `Host` the browser asked for: behind a proxy that terminates TLS, the request's URL has the scheme of the hop */
11
+ const hostOf = (c) => (c.req.header('host') ?? new URL(c.req.url).host).toLowerCase();
12
+ /** the path and query of a URL, as a redirect to this site: one leading slash (`//evil.com` is another site's) */
13
+ export const pathAndQuery = (url) => url.pathname.replace(/^\/+/, '/') + url.search;
14
+ /**
15
+ * `url` as a URL of this site, or null (another site, unparsable). Hosts are compared, not origins: behind a proxy
16
+ * that terminates TLS the request's URL is `http://` while the browser's `Referer` is `https://`.
17
+ */
8
18
  export function sameOrigin(c, url) {
9
19
  if (!url)
10
20
  return null;
11
21
  try {
12
22
  const parsed = new URL(url, c.req.url);
13
- return parsed.origin === new URL(c.req.url).origin ? parsed : null;
23
+ return parsed.host === new URL(c.req.url).host || parsed.host === hostOf(c) ? parsed : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /**
30
+ * The page the request came from (its `Referer`) as a URL: only its path and query are ever used. A request the
31
+ * browser says is `Sec-Fetch-Site: same-origin` came from a page of this site; else its host must be this site's.
32
+ */
33
+ export function referer(c) {
34
+ const url = c.req.header('referer');
35
+ if (c.req.header('sec-fetch-site') !== 'same-origin')
36
+ return sameOrigin(c, url);
37
+ try {
38
+ return url ? new URL(url, c.req.url) : null;
14
39
  }
15
40
  catch {
16
41
  return null;
@@ -18,8 +43,40 @@ export function sameOrigin(c, url) {
18
43
  }
19
44
  /** Back to the page the request came from (303), or `fallback` when there is none on this site. */
20
45
  export const back = (c, fallback = '/') => {
21
- const from = sameOrigin(c, c.req.header('referer'));
22
- return c.redirect(from ? from.pathname.replace(/^\/+/, '/') + from.search : fallback, 303);
46
+ const from = referer(c);
47
+ return c.redirect(from ? pathAndQuery(from) : fallback, 303);
48
+ };
49
+ /**
50
+ * The trailing-slash redirect, for a GET or HEAD no route answered (404): a 301 to the path with its slash taken off
51
+ * (`'trim'`) or put on (`'append'`). Its Location is relative, the path as it was asked (encoded) and the query:
52
+ * behind a proxy the request's URL has another scheme than the browser's. One leading slash (`//evil.com/` is
53
+ * `/evil.com`, never another site).
54
+ */
55
+ export const trailingSlash = (append) => async (c, next) => {
56
+ await next();
57
+ if (c.res.status !== 404 || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
58
+ return;
59
+ const url = new URL(c.req.url);
60
+ if (url.pathname === '/' || url.pathname.endsWith('/') === append)
61
+ return;
62
+ url.pathname = append ? `${url.pathname}/` : url.pathname.slice(0, -1);
63
+ c.res = c.redirect(pathAndQuery(url), 301);
64
+ };
65
+ /**
66
+ * `hono/csrf`'s fallback for a browser without `Sec-Fetch-Site`: an `Origin` with this request's `Host`, and its scheme
67
+ * (`https` too when a proxy says so). Hono compares it with the request's URL, `http://` behind a proxy.
68
+ */
69
+ export const csrfOrigin = (origin, c) => {
70
+ try {
71
+ const parsed = new URL(origin);
72
+ return (parsed.origin === origin &&
73
+ parsed.host === hostOf(c) &&
74
+ (parsed.protocol === new URL(c.req.url).protocol ||
75
+ (parsed.protocol === 'https:' && isSecure(c))));
76
+ }
77
+ catch {
78
+ return false;
79
+ }
23
80
  };
24
81
  /**
25
82
  * A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
@@ -1,7 +1,7 @@
1
1
  import { version } from 'virtual:fondu/assets';
2
2
  import { renderDocument } from './document.js';
3
3
  import { flashCookie, takeCarried } from './flash.js';
4
- import { appendHeader, back, isPageRequest, isPrerendering, sameOrigin } from './http.js';
4
+ import { appendHeader, back, isPageRequest, isPrerendering, pathAndQuery, referer, sameOrigin, } from './http.js';
5
5
  const shared = new WeakMap();
6
6
  /** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
7
7
  export function share(c, props) {
@@ -44,8 +44,8 @@ export const routePage = (id) => async (c, next) => {
44
44
  /** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
45
45
  function pageUrl(c) {
46
46
  const here = new URL(c.req.url);
47
- const from = c.req.method === 'GET' ? here : (sameOrigin(c, c.req.header('referer')) ?? here);
48
- return from.pathname.replace(/^\/+/, '/') + from.search;
47
+ const from = c.req.method === 'GET' ? here : (referer(c) ?? here);
48
+ return pathAndQuery(from);
49
49
  }
50
50
  /**
51
51
  * The route file's page (its default export) with these props: JSON for a navigation, the HTML document
@@ -164,7 +164,10 @@ const versionCheck = async (c, next) => {
164
164
  c.req.method === 'GET' &&
165
165
  isPageRequest(c) &&
166
166
  c.req.header('x-fondu-version') !== version) {
167
- return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: NAVIGATION_VARY });
167
+ return c.body(null, 409, {
168
+ 'X-Fondu-Location': pathAndQuery(new URL(c.req.url)),
169
+ Vary: NAVIGATION_VARY,
170
+ });
168
171
  }
169
172
  await next();
170
173
  // a URL answers a navigation and a document differently: caches keep them apart
@@ -186,7 +189,7 @@ const versionCheck = async (c, next) => {
186
189
  // this site's root (a relative Location is the request's, not the page's on the screen)
187
190
  else if (to.includes('#'))
188
191
  c.res = c.body(null, 200, {
189
- 'X-Fondu-Redirect': here.pathname.replace(/^\/+/, '/') + here.search + here.hash,
192
+ 'X-Fondu-Redirect': pathAndQuery(here) + here.hash,
190
193
  });
191
194
  }
192
195
  };
@@ -31,8 +31,8 @@ export declare class ValidationError extends Error {
31
31
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
32
32
  /**
33
33
  * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
34
- * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
35
- * 400.
34
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32, more than 10,000
35
+ * entries) is a 400.
36
36
  */
37
37
  export declare function readBody(c: Context): Promise<unknown>;
38
38
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -23,13 +23,14 @@ export function validationErrorResponse(c, error) {
23
23
  }
24
24
  /**
25
25
  * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
26
- * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
27
- * 400.
26
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32, more than 10,000
27
+ * entries) is a 400.
28
28
  */
29
29
  export async function readBody(c) {
30
30
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
31
31
  const type = (c.req.header('content-type') ?? '').toLowerCase();
32
- if (type.includes('application/json'))
32
+ // `application/json`, and any `application/*+json` (`merge-patch+json`, `vnd.api+json`), as the client reads an answer
33
+ if (type.includes('application/json') || /^application\/[^;\s]+\+json\s*(?:;|$)/.test(type))
33
34
  return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
34
35
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
35
36
  return {};
package/dist/virtual.d.ts CHANGED
@@ -14,6 +14,8 @@ declare module 'virtual:fondu/ssr' {
14
14
  page: import('./client/navigation.js').Page,
15
15
  options: {
16
16
  nonce?: string
17
+ /** the request's: React stops rendering when it aborts */
18
+ signal?: AbortSignal
17
19
  onError?: (error: unknown) => void
18
20
  bootstrapScriptContent?: string
19
21
  },
@@ -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,5 +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
- /** the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`) */
36
- export declare function entryCode(options: FonduOptions, paths: string[]): string;
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;
@@ -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, createRequire } from 'node:module';
4
- import { dirname, join, relative, resolve, sep } from 'node:path';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
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 Worker never mounts or hydrates a page, but fondu/client imports `react-dom/client` (createRoot,
91
- * hydrateRoot) at its top: the whole of React's browser renderer in the Worker, evaluated at every start. There, it
92
- * is a module that says so if called (about a third of the Worker, and of its start in dev)
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) : [serverReactDomClient()]),
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) */
@@ -138,12 +142,14 @@ function dependencies(root = '') {
138
142
  */
139
143
  function serverEntry(options) {
140
144
  let root = process.cwd();
145
+ let assetsDir = 'assets';
141
146
  return {
142
147
  name: 'fondu:server-entry',
143
148
  apply: 'build',
144
149
  applyToEnvironment: (env) => env.name === 'ssr',
145
150
  configResolved(c) {
146
151
  root = c.root;
152
+ assetsDir = c.environments.client?.build.assetsDir ?? c.build.assetsDir;
147
153
  },
148
154
  resolveId: { filter: { id: /^virtual:fondu\/server-entry$/ }, handler: (id) => resolved(id) },
149
155
  load: {
@@ -155,33 +161,47 @@ function serverEntry(options) {
155
161
  .filter((e) => e.name !== '.vite')
156
162
  .map((e) => (e.isDirectory() ? `/${e.name}/*` : `/${e.name}`))
157
163
  : [];
158
- return entryCode(options, paths);
164
+ return entryCode(options, paths, assetsDir);
159
165
  },
160
166
  },
161
167
  };
162
168
  }
163
- /** the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`) */
164
- export function entryCode(options, paths) {
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') {
165
175
  const bun = options.target === 'bun';
176
+ const hashed = assetsDir ? `/${assetsDir}/*` : undefined;
166
177
  return [
167
- `import { Hono } from 'hono'`,
168
- `import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
169
- `import { fileURLToPath } from 'node:url'`,
170
- `import app from '${SERVER.slice(1)}'`,
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)}')`,
171
185
  `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
172
186
  `const main = new Hono()`,
173
- `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
174
187
  // prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
175
188
  // this server was built: not there while the build prerenders, so the app renders them then)
176
189
  ...(options.prerender
177
190
  ? [
178
- `import { existsSync, readFileSync } from 'node:fs'`,
179
- `import { staticPages } from ${JSON.stringify(staticModule)}`,
191
+ `const { existsSync, readFileSync } = await import('node:fs')`,
192
+ `const { staticPages } = await import(${JSON.stringify(staticModule)})`,
180
193
  `const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
181
194
  `if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
182
195
  ]
183
196
  : []),
184
- ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
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 }))`),
185
205
  `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
186
206
  ...(bun
187
207
  ? [
@@ -191,7 +211,7 @@ export function entryCode(options, paths) {
191
211
  : `export default { fetch: main.fetch, port: Number(process.env.PORT) || ${Number(options.port)}, ...(app.websocket && { websocket: app.websocket }) }`,
192
212
  ]
193
213
  : [
194
- `import { serve } from '@hono/node-server'`,
214
+ `const { serve } = await import('@hono/node-server')`,
195
215
  `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
196
216
  `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
197
217
  `process.on('SIGINT', shutdown)`,
@@ -202,18 +222,25 @@ export function entryCode(options, paths) {
202
222
  }
203
223
  function runtimePlugins(options) {
204
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
+ },
205
237
  {
206
238
  // dev: the same Request / Response globals as the production server (@hono/node-server's), which the dev
207
239
  // server's requests are made with: middleware that re-creates the request (hono/body-limit) needs them
208
240
  name: 'fondu:node-globals',
209
241
  apply: 'serve',
210
242
  async configureServer() {
211
- // the dev server's own copy, as an ES module (its CommonJS build would be another class)
212
- const fromDevServer = createRequire(createRequire(import.meta.url).resolve('@hono/vite-dev-server'));
213
- const dir = dirname(dirname(fromDevServer.resolve('@hono/node-server'))); // …/dist/index.js
214
- const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
215
- const entry = pkg.exports['.'].import;
216
- const { getRequestListener } = (await import(pathToFileURL(join(dir, typeof entry === 'string' ? entry : entry.default)).href));
243
+ const { getRequestListener } = await devServerNodeServer();
217
244
  getRequestListener(() => new Response());
218
245
  },
219
246
  },
@@ -282,7 +309,7 @@ function core(options) {
282
309
  .replace(/[^a-zA-Z0-9]+/g, '-')
283
310
  .replace(/^-|-$/g, '')
284
311
  : undefined;
285
- return `assets/${name || '[name]'}-[hash].js`;
312
+ return `${config.environments.client?.build.assetsDir ?? config.build.assetsDir}/${name || '[name]'}-[hash].js`;
286
313
  },
287
314
  },
288
315
  },
@@ -443,7 +470,7 @@ function core(options) {
443
470
  this.emitFile({
444
471
  type: 'asset',
445
472
  fileName: '_headers',
446
- source: '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n',
473
+ source: `/${this.environment.config.build.assetsDir}/*\n Cache-Control: public, max-age=31536000, immutable\n`,
447
474
  });
448
475
  },
449
476
  // the server render loads a page through the entry's import(), of a module createApp has imported already: in
@@ -535,7 +562,7 @@ export function assetTags(_component, nonce) {
535
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>\`
536
563
  }`;
537
564
  }
538
- function productionAssets(config, options) {
565
+ export function productionAssets(config, options) {
539
566
  const outDir = options.target === 'cloudflare'
540
567
  ? resolve(config.root, config.environments.client?.build.outDir ?? 'dist/client')
541
568
  : resolve(config.root, 'dist/client');
@@ -572,7 +599,14 @@ function productionAssets(config, options) {
572
599
  .map((dir) => `app/routes/${dir ? `${dir}/` : ''}_layout.tsx`)
573
600
  .filter((k) => k in manifest);
574
601
  const all = [...around, key].map(tags);
575
- pages[pageId(file)] = { css: all.flatMap((t) => t.css), js: all.flatMap((t) => t.js) };
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
+ };
576
610
  }
577
611
  const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
578
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
+ }
@@ -1,4 +1,4 @@
1
- import type { Plugin } from 'vite';
1
+ import { type Plugin } from 'vite';
2
2
  type Node = {
3
3
  type: string;
4
4
  start: number;
@@ -1,5 +1,6 @@
1
- import { relative, sep } from 'node:path';
2
- import { CONFIG, HANDLERS, isPageFile, METHODS } from '../paths.js';
1
+ import { dirname, relative, resolve, sep } from 'node:path';
2
+ import { normalizePath } from 'vite';
3
+ import { CONFIG, checkExportNames, HANDLERS, isPageFile, METHODS } from '../paths.js';
3
4
  /** the exports of a page's route file that are server code: the browser gets the page (default) alone */
4
5
  const SERVER_EXPORTS = new Set([...HANDLERS, ...CONFIG, ...METHODS]);
5
6
  const nameOf = (n) => (n.name ?? n.value);
@@ -275,9 +276,26 @@ function importOf(code, node, kept) {
275
276
  ].filter(Boolean);
276
277
  return `import ${clauses.join(', ')} from ${source};`;
277
278
  }
279
+ /** the names a module exports, as its namespace lists them (sorted); `export *` is not followed */
280
+ function exportedNames(body) {
281
+ const names = new Set();
282
+ for (const node of body) {
283
+ if (node.type === 'ExportDefaultDeclaration')
284
+ names.add('default');
285
+ if (node.type !== 'ExportNamedDeclaration')
286
+ continue;
287
+ for (const name of bound(node.declaration))
288
+ names.add(name);
289
+ for (const s of node.specifiers)
290
+ names.add(nameOf(s.exported));
291
+ }
292
+ return [...names].sort();
293
+ }
278
294
  /** The browser's copy of every page's route file (`.tsx` in `app/routes/`): its server code removed */
279
295
  export function stripRoutes() {
280
296
  let root = process.cwd();
297
+ // the route files the strip changed (the build's): their source maps must not carry the original
298
+ const changed = new Set();
281
299
  return {
282
300
  name: 'fondu:strip-routes',
283
301
  enforce: 'post', // after the JSX is compiled: plain JavaScript to read
@@ -288,10 +306,48 @@ export function stripRoutes() {
288
306
  if (this.environment.config.consumer !== 'client')
289
307
  return;
290
308
  const file = relative(`${root}/app/routes`, id.split('?')[0]).split(sep).join('/');
291
- if (file.startsWith('..') || !isPageFile(file) || file.endsWith('.mdx'))
309
+ if (file.startsWith('..'))
310
+ return;
311
+ // a layout or the error page is not stripped: what the server refuses at startup fails the build
312
+ if (/(?:^|\/)_(?:layout|error)\.tsx$/.test(file)) {
313
+ const program = this.parse(code);
314
+ return void checkExportNames(file, exportedNames(program.body));
315
+ }
316
+ if (!isPageFile(file) || file.endsWith('.mdx'))
292
317
  return;
293
318
  const stripped = stripServerCode(code, this.parse(code), file);
294
- return stripped === code ? undefined : { code: stripped, map: null };
319
+ if (stripped === code)
320
+ return;
321
+ changed.add(id.split('?')[0]);
322
+ return { code: stripped, map: null };
323
+ },
324
+ // The maps' `sourcesContent` holds the file as it was read, the loaders in it. Stopgap: the entries of the files
325
+ // the strip changed are blanked (`null` keeps the indexes valid). The full fix: strip in `load`, so that the
326
+ // stripped text is the source (#241).
327
+ generateBundle(options, bundle) {
328
+ if (this.environment.config.consumer !== 'client' || !changed.size)
329
+ return;
330
+ const outDir = resolve(root, this.environment.config.build.outDir);
331
+ const blank = (map, from) => {
332
+ map.sources.forEach((source, i) => {
333
+ if (source && changed.has(normalizePath(resolve(outDir, dirname(from), source))))
334
+ map.sourcesContent[i] = null;
335
+ });
336
+ };
337
+ for (const [name, file] of Object.entries(bundle)) {
338
+ if (file.type === 'chunk' && file.map?.sourcesContent)
339
+ blank(file.map, name);
340
+ // a map written as a file of its own (`.map`): its text
341
+ else if (file.type === 'asset' &&
342
+ name.endsWith('.map') &&
343
+ typeof file.source === 'string') {
344
+ const map = JSON.parse(file.source);
345
+ if (!map.sourcesContent)
346
+ continue;
347
+ blank(map, name);
348
+ file.source = JSON.stringify(map);
349
+ }
350
+ }
295
351
  },
296
352
  };
297
353
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",