fondu 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,9 +5,10 @@
5
5
  Fondu is a small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers
6
6
  and Node.
7
7
 
8
- The files in `app/routes/` are the URLs: Hono handlers that run on the server, and for a page, the React component its
9
- loader renders with props, in the same file (the browser gets the component alone). In the browser, links and forms are plain `<a>` and `<form>`: Fondu's small client, on the Navigation API, swaps
10
- the pages in place, without an API to write or a client-side router to keep in sync.
8
+ The files in `app/routes/` are the URLs. A page's file holds its Hono handlers, which run on the server, and its React
9
+ component, which the loader renders with props; the browser gets the component alone. Links and forms are plain `<a>`
10
+ and `<form>`: Fondu's small client swaps the pages in place, with no API to write and no client-side router to keep in
11
+ sync.
11
12
 
12
13
  ## Quick start
13
14
 
@@ -27,8 +28,8 @@ on Cloudflare Workers with D1 and Better Auth.
27
28
  ## Docs
28
29
 
29
30
  **[fondu.dev](https://fondu.dev/docs)**: routes, pages and props, layouts, forms and validation, errors, type safety,
30
- server-side rendering, static pages, MDX pages, internationalization, deploying, and the API. Every page is also Markdown for coding agents
31
- ([llms.txt](https://fondu.dev/llms.txt)).
31
+ server and client code, server-side rendering, static pages, MDX pages, internationalization, deploying, and the API.
32
+ Every page is also Markdown for coding agents ([llms.txt](https://fondu.dev/llms.txt)).
32
33
 
33
34
  ## Contributing
34
35
 
@@ -41,7 +42,7 @@ apps/site fondu.dev: the docs, MDX and static pages on Workers
41
42
 
42
43
  ```bash
43
44
  bun install # also builds packages/fondu (the examples use the built package, like a real app)
44
- bun run test # the protocol, on a small app with app.request()
45
+ bun run test # the package: a small app with app.request(), the routes, the client
45
46
  bun run typecheck # the package, the demo (with apps/demo/e2e/types.ts) and the site
46
47
  bun run check # format (oxfmt), lint (oxlint), typecheck
47
48
  bun run dev # rebuild packages/fondu on change
@@ -1,10 +1,11 @@
1
- import { createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
1
+ import { Component, createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
2
2
  import { flushSync } from 'react-dom';
3
3
  import { createRoot, hydrateRoot } from 'react-dom/client';
4
4
  import { layoutsOf, pageId, routePatterns } from '../paths.js';
5
5
  import { again, startNavigation } from './navigation.js';
6
6
  import { progressBar } from './progress.js';
7
7
  const ROUTES = '/app/routes/';
8
+ const ERROR = '_error';
8
9
  // set by the app's entry (the Vite plugin's): the pages and layouts of app/routes/, and the build's settings
9
10
  let pages = new Map();
10
11
  let layoutModules = {};
@@ -45,8 +46,27 @@ function App({ initial }) {
45
46
  useLayoutEffect(() => mounted?.(set), [set]);
46
47
  const { Component, layouts } = view;
47
48
  // the page mounted anew by each navigation, its layouts kept (the same components: React keeps them)
48
- const content = layouts.reduceRight((children, L) => createElement(L, null, children), createElement(Component, { key: mounts, ...page.props }));
49
- return createElement(PageContext.Provider, { value: page }, content);
49
+ // a page that throws in the browser: the error page in its place, in its layouts; a layout that throws: the error
50
+ // page alone. Until the next page
51
+ const content = layouts.reduceRight((children, L) => createElement(L, null, children), createElement(Failed, { key: mounts, page }, createElement(Component, { ...page.props })));
52
+ return createElement(PageContext.Provider, { value: page }, createElement(Failed, { page }, content));
53
+ }
54
+ /** the app's error page (routes/_error.tsx), loaded once the app starts: a failed render can't wait for it */
55
+ let ErrorPage;
56
+ /** what failed to render, until another page (the layouts it is around are kept: no key) */
57
+ class Failed extends Component {
58
+ state = { failed: false, page: this.props.page };
59
+ static getDerivedStateFromError() {
60
+ return { failed: true };
61
+ }
62
+ static getDerivedStateFromProps(props, state) {
63
+ return props.page === state.page ? null : { failed: false, page: props.page };
64
+ }
65
+ render() {
66
+ if (!this.state.failed)
67
+ return this.props.children;
68
+ return ErrorPage ? createElement(ErrorPage, { status: 500 }) : 'Something went wrong';
69
+ }
50
70
  }
51
71
  /**
52
72
  * @internal The page a URL most likely is, by its route file's patterns (static segments first): its modules load with its
@@ -107,6 +127,9 @@ function start(settings) {
107
127
  if (!data || !root)
108
128
  throw new Error('fondu: the document has no page (script[data-page="app"], #app)');
109
129
  const initial = JSON.parse(data);
130
+ void pages
131
+ .get(ERROR)?.()
132
+ .then((m) => (ErrorPage = m.default));
110
133
  void load(initial.component).then((view) => {
111
134
  // dev: the stylesheet the server gave the page until its layouts brought their CSS (they have now)
112
135
  document.querySelector('[data-fondu-dev-css]')?.remove();
@@ -21,13 +21,14 @@ interface Options {
21
21
  preload: (pathname: string) => void;
22
22
  }
23
23
  /**
24
- * Same-origin links, GET and POST forms, Back and Forward, through the Navigation API: the page fetched as JSON and
25
- * shown in place. Without the Navigation API, links and forms load documents.
24
+ * Same-origin links and forms, Back and Forward, through the History API (as Void's client, MIT): the page fetched
25
+ * as JSON, its URL in the history, the page shown in place, then the scroll position (Fondu's own, per history entry:
26
+ * the browsers' differ). What isn't for it (another site, a new tab, a download, a modified click) is the browser's.
26
27
  */
27
28
  export declare function startNavigation({ initial, show, prerender, pending, preload }: Options): void;
28
29
  /**
29
- * `href` loaded as a document. Every other navigation is the client's, `location.assign()` and `location.href = …`
30
- * too: this is for what a page can't change in place (`<html lang>`: another language).
30
+ * `href` loaded as a document. Every other navigation is the client's, links and forms: this is for what a page
31
+ * can't change in place (`<html lang>`: another language).
31
32
  */
32
33
  export declare function loadDocument(href: string): void;
33
34
  /** the page asked for again, its state and the scroll position kept */
@@ -1,169 +1,401 @@
1
- import { pageDataPath } from '../paths.js';
2
- const noop = () => { };
3
- const navigation = () => globalThis.navigation;
1
+ import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
2
+ let visit;
4
3
  /**
5
- * Same-origin links, GET and POST forms, Back and Forward, through the Navigation API: the page fetched as JSON and
6
- * shown in place. Without the Navigation API, links and forms load documents.
4
+ * Same-origin links and forms, Back and Forward, through the History API (as Void's client, MIT): the page fetched
5
+ * as JSON, its URL in the history, the page shown in place, then the scroll position (Fondu's own, per history entry:
6
+ * the browsers' differ). What isn't for it (another site, a new tab, a download, a modified click) is the browser's.
7
7
  */
8
8
  export function startNavigation({ initial, show, prerender, pending, preload }) {
9
- const nav = navigation();
10
- if (!nav)
11
- return;
9
+ const scroll = scrollPositions();
12
10
  let version = initial.version;
13
- let submitting;
14
- let current = 0;
15
- // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigating()), and for
16
- // assistive technology
17
- const begin = (form = null) => {
18
- const id = ++current;
19
- form?.setAttribute('aria-busy', 'true');
20
- pending(true, form !== null);
21
- return () => {
22
- form?.removeAttribute('aria-busy');
23
- if (id === current)
24
- pending(false, false);
25
- };
11
+ let current;
12
+ // the page each entry showed, for Back and Forward: in memory only (gone on reload), the last 50; all of them
13
+ // forgotten once a form is sent (what it changed, a signed-out user's pages), its flash data not shown again
14
+ const kept = new Map();
15
+ const keep = (page) => {
16
+ const key = scroll.key();
17
+ if (!key)
18
+ return;
19
+ kept.delete(key);
20
+ kept.set(key, { ...page, flash: {} });
21
+ if (kept.size > 50)
22
+ kept.delete(kept.keys().next().value);
26
23
  };
27
- const here = () => location.pathname + location.search;
28
- const display = (page, scroll, fresh, history) => nav.navigate(page.url, { history, info: { fondu: { page, scroll, fresh } } });
29
- /**
30
- * A document load: a POST's after the page it was sent from (`push`); a GET's in place of the entry it committed:
31
- * `instead` when that entry was pushed. A document replacing it would take the entries before it, of this
32
- * document, for its own (Chromium): Back would change the URL only. So back to the entry it was pushed from, then
33
- * the document pushed from there.
34
- */
35
- const documentLoad = async (url, history) => {
24
+ const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
25
+ /** a document load: in place of this entry, or after it */
26
+ const documentLoad = (url, replace) => {
36
27
  // http(s) only: a header's URL never runs as `javascript:` (an app's redirect to a URL it was given)
37
28
  if (!isWebUrl(url))
38
29
  return console.error(`fondu: not loading ${url}: not an http(s) URL`);
39
- const info = { fondu: 'document' };
40
- if (history === 'instead')
41
- await nav.back({ info }).committed?.catch(noop);
42
- nav.navigate(url, { history: history === 'replace' ? 'replace' : 'push', info });
30
+ if (replace)
31
+ location.replace(url);
32
+ else
33
+ location.assign(url);
43
34
  };
44
- /** the page a response is, or undefined when it's handled here (a new build, not a page) */
45
- const read = async (response, url, history) => {
46
- const post = history === 'push';
47
- const to = response.headers.get('X-Fondu-Location');
48
- if (response.status === 409 && to)
49
- return void documentLoad(to, history);
50
- // a redirect to a #fragment, followed here: fetch() would lose it
51
- const redirect = response.headers.get('X-Fondu-Redirect');
52
- if (redirect && isWebUrl(redirect))
53
- return void nav.navigate(redirect, { history: post ? 'push' : 'replace' });
54
- if (!response.headers.has('X-Fondu')) {
55
- // a proxy's error page, a file: the URL as a document (a POST's redirect: its target); the answer to a POST
56
- // itself can't be asked for again
57
- if (!post || response.redirected)
58
- return void documentLoad(url, history);
59
- const html = await response.text();
60
- document.open();
61
- document.write(html);
62
- document.close();
63
- return;
64
- }
65
- const page = (await response.json());
66
- if (version && page.version && page.version !== version)
67
- return void documentLoad(page.url, history);
68
- version = page.version;
69
- return page;
70
- };
71
- const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
72
- const failed = (url, history) => (error) => {
73
- if (error.name !== 'AbortError')
74
- void documentLoad(url, history); // offline: the browser says so
35
+ visit = (href, options) => {
36
+ current?.abort();
37
+ const controller = (current = new AbortController());
38
+ const { signal } = controller;
39
+ const url = new URL(href, location.href);
40
+ if (url.origin !== location.origin)
41
+ return documentLoad(url.href, options.history !== 'push');
42
+ const post = options.body !== undefined;
43
+ if (options.history !== 'none')
44
+ scroll.save();
45
+ const form = options.form ?? null;
46
+ // a kept page is on the screen at once: the server's comes quietly, no pending state (the navigation it
47
+ // interrupted, aborted, ends here)
48
+ const shown = options.kept;
49
+ // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigating()), and for
50
+ // assistive technology
51
+ form?.setAttribute('aria-busy', 'true');
52
+ pending(!shown, form !== null);
53
+ const done = () => {
54
+ form?.removeAttribute('aria-busy');
55
+ if (!shown && current === controller)
56
+ pending(false, false);
57
+ };
58
+ if (!post)
59
+ preload(url.pathname);
60
+ const from = !post && prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
61
+ void (async () => {
62
+ try {
63
+ if (shown) {
64
+ scroll.commit();
65
+ await show(shown, true, () => signal.aborted);
66
+ if (signal.aborted)
67
+ return;
68
+ announce();
69
+ restore(options.scroll, url.hash);
70
+ }
71
+ const response = await fetch(from, {
72
+ method: post ? 'POST' : 'GET',
73
+ body: options.body,
74
+ headers: headers(),
75
+ signal,
76
+ });
77
+ if (signal.aborted)
78
+ return;
79
+ if (post)
80
+ kept.clear();
81
+ // a new build, another site: the document
82
+ const to = response.headers.get('X-Fondu-Location');
83
+ if (response.status === 409 && to)
84
+ return documentLoad(to, options.history !== 'push');
85
+ // a redirect to a #fragment, followed here: fetch() would lose it
86
+ const redirect = response.headers.get('X-Fondu-Redirect');
87
+ if (redirect) {
88
+ if (isWebUrl(redirect))
89
+ visit(redirect, { history: options.history === 'push' ? 'push' : 'replace' });
90
+ return;
91
+ }
92
+ if (!response.headers.has('X-Fondu')) {
93
+ // a proxy's error page, a file: the URL as a document (a POST's redirect: its target), this answer unread
94
+ if (!post || response.redirected) {
95
+ void response.body?.cancel();
96
+ return documentLoad(post ? response.url : url.href, options.history !== 'push');
97
+ }
98
+ // the answer to a POST itself, which can't be asked for again: as the browser would show it
99
+ const disposition = response.headers.get('Content-Disposition') ?? '';
100
+ if (/^\s*attachment/i.test(disposition)) {
101
+ // a file: downloaded, the page stays
102
+ const link = document.createElement('a'); // with `download`: let through by the click listener
103
+ link.href = URL.createObjectURL(await response.blob());
104
+ link.download = fileName(disposition);
105
+ link.click();
106
+ setTimeout(() => URL.revokeObjectURL(link.href), 60_000); // once the download has it
107
+ return;
108
+ }
109
+ const html = /^\s*text\/html\b/i.test(response.headers.get('Content-Type') ?? '');
110
+ const text = await response.text();
111
+ document.open(); // the page's listeners gone with it, popstate's too
112
+ // anything else as text, never as HTML (an action's `c.text()` with what a user typed)
113
+ document.write(html ? text : '<!doctype html><meta charset="utf-8"><pre></pre>');
114
+ document.close();
115
+ if (!html)
116
+ document.querySelector('pre').textContent = text;
117
+ // Back and Forward stay in this document (the entries before it are its own): their URL as a document
118
+ addEventListener('popstate', () => location.reload());
119
+ return;
120
+ }
121
+ const page = (await response.json());
122
+ if (signal.aborted)
123
+ return;
124
+ if (version && page.version && page.version !== version)
125
+ return documentLoad(page.url, options.history !== 'push');
126
+ version = page.version;
127
+ // the answer to a form at the URL it was sent from: in place, its scroll position kept; back with errors,
128
+ // the form and what was typed stay too
129
+ const here = location.pathname + location.search;
130
+ const same = post && page.url === here;
131
+ const errors = Object.keys(page.props.errors ?? {}).length > 0;
132
+ const asked = url.pathname + url.search;
133
+ // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
134
+ const fresh = shown ? asked !== page.url : !options.keep && !(same && errors);
135
+ // its URL first, as the browser's own navigations: a page's render reads it (`location`, a URL's language);
136
+ // a redirect's, the fragment asked for if it is still this page's
137
+ const target = page.url + (asked === page.url ? url.hash : '');
138
+ // a form's answer at its URL replaces the entry; Back's or reload()'s page redirected elsewhere too
139
+ const history = options.history === 'push' && same
140
+ ? 'replace'
141
+ : options.history === 'none' && asked !== page.url
142
+ ? 'replace'
143
+ : options.history;
144
+ if (history !== 'none')
145
+ scroll.write(target, history === 'replace');
146
+ scroll.commit();
147
+ await show(page, fresh, () => signal.aborted);
148
+ if (signal.aborted)
149
+ return;
150
+ keep(page);
151
+ if (shown && !fresh)
152
+ return;
153
+ if (!options.keep)
154
+ announce();
155
+ // a page asked for again stays where it is: reload(), a form's answer at its URL
156
+ if (options.keep || same)
157
+ return;
158
+ // at once, the page in the DOM (show() renders it synchronously): no frame drawn where it doesn't belong
159
+ restore(options.history === 'none' ? options.scroll : null, url.hash);
160
+ }
161
+ catch (error) {
162
+ if (error.name === 'AbortError' || shown)
163
+ return; // offline, Back: the kept page stays
164
+ if (post)
165
+ throw error; // the form stays, to send again
166
+ documentLoad(url.href, options.history !== 'push'); // offline: the browser says so
167
+ }
168
+ finally {
169
+ done();
170
+ }
171
+ })();
75
172
  };
76
- nav.addEventListener('navigate', (event) => {
77
- const info = event.info;
78
- const url = new URL(event.destination.url);
79
- if (info?.fondu === 'document' || !event.canIntercept || event.hashChange)
173
+ // links: a plain click on a same-origin <a href>, which the page let through
174
+ document.addEventListener('click', (event) => {
175
+ if (event.defaultPrevented || event.button !== 0)
176
+ return;
177
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
80
178
  return;
81
- // `location.reload()` (Vite's full reload, an app's own): the document, as asked; `reload()` is fondu/client's
82
- if (event.navigationType === 'reload' && info?.fondu !== 'reload')
179
+ const link = event.target?.closest?.('a[href]');
180
+ if (!(link instanceof HTMLAnchorElement))
83
181
  return;
84
- if (event.downloadRequest !== null || url.origin !== location.origin)
182
+ if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
85
183
  return;
86
- submitting?.abort();
87
- // a page already fetched (a form's answer, a redirect's target): shown by this navigation
88
- if (typeof info?.fondu === 'object') {
89
- const { page, scroll, fresh } = info.fondu;
90
- event.intercept({
91
- scroll: 'manual',
92
- // the same page (a form back with its errors): the focus stays where it was, as the scroll position does
93
- focusReset: fresh ? 'after-transition' : 'manual',
94
- async handler() {
95
- await show(page, fresh, () => event.signal.aborted);
96
- if (scroll && !event.signal.aborted)
97
- scrollAfter(event);
98
- },
99
- });
184
+ const url = new URL(link.href);
185
+ if (url.origin !== location.origin || !isWebUrl(url.href))
186
+ return;
187
+ // a #fragment of this page: the browser scrolls to it (the position left saved for Back)
188
+ if (url.pathname + url.search === location.pathname + location.search && url.hash) {
189
+ scroll.save();
100
190
  return;
101
191
  }
102
- // a POST form: sent outside the navigation (no history entry for the POST), its answer shown by one
103
- if (event.formData) {
104
- event.preventDefault();
105
- const done = begin(formOf(event));
106
- const controller = (submitting = new AbortController());
107
- fetch(url, {
108
- method: 'POST',
109
- body: event.formData,
110
- headers: headers(),
111
- signal: controller.signal,
112
- })
113
- .then(async (response) => {
114
- const page = await read(response, response.url, 'push');
115
- if (!page || controller.signal.aborted)
116
- return;
117
- // the same URL: in place, at the same scroll position; back with errors, the form and its values stay too
118
- const same = page.url === here();
119
- const errors = Object.keys(page.props.errors ?? {}).length > 0;
120
- // pending until the page is on the screen
121
- const shown = display(page, !same, !(same && errors), same ? 'replace' : 'push');
122
- await shown.finished?.catch(noop);
123
- })
124
- .catch((error) => {
125
- if (error.name !== 'AbortError')
126
- throw error; // the form stays, to send again
127
- })
128
- .finally(done);
192
+ event.preventDefault();
193
+ visit(url.href, { history: url.href === location.href ? 'replace' : 'push' });
194
+ });
195
+ // forms: GET and POST to this origin, in this window, which the page let through
196
+ document.addEventListener('submit', (event) => {
197
+ if (event.defaultPrevented)
129
198
  return;
199
+ const form = event.target;
200
+ if (!(form instanceof HTMLFormElement))
201
+ return;
202
+ const submitter = event.submitter;
203
+ const attr = (name, own) => submitter?.getAttribute(own) ?? form.getAttribute(name) ?? '';
204
+ const method = attr('method', 'formmethod').toLowerCase() || 'get';
205
+ const target = attr('target', 'formtarget');
206
+ if ((method !== 'get' && method !== 'post') || (target && target !== '_self'))
207
+ return;
208
+ const url = new URL(attr('action', 'formaction') || location.href, location.href);
209
+ if (url.origin !== location.origin || !isWebUrl(url.href))
210
+ return;
211
+ event.preventDefault();
212
+ const data = new FormData(form, submitter);
213
+ // as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF (a <textarea>'s)
214
+ const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
215
+ const fields = [...data].map(([k, v]) => [crlf(k), crlf(typeof v === 'string' ? v : v.name)]);
216
+ if (method === 'post') {
217
+ const enctype = attr('enctype', 'formenctype').toLowerCase();
218
+ const body = enctype === 'multipart/form-data'
219
+ ? data
220
+ : enctype === 'text/plain'
221
+ ? fields.map(([k, v]) => `${k}=${v}\r\n`).join('')
222
+ : new URLSearchParams(fields);
223
+ return visit(url.href, { history: 'push', body, form });
130
224
  }
131
- event.intercept({
132
- scroll: 'manual',
133
- focusReset: event.navigationType === 'reload' ? 'manual' : 'after-transition',
134
- async handler() {
135
- const done = begin(formOf(event));
136
- const pushed = event.navigationType === 'push' ? 'instead' : 'replace';
137
- try {
138
- // Back and Forward too: the server's page, as for a link (nothing kept in memory to go stale, as a
139
- // private page after signing out); the scroll position is the browser's
140
- const path = url.pathname + url.search;
141
- preload(url.pathname);
142
- const from = prerender ? pageDataPath(url.pathname) + url.search : url;
143
- const response = await fetch(from, { headers: headers(), signal: event.signal });
144
- const page = await read(response, url.href, pushed);
145
- if (!page || event.signal.aborted)
146
- return;
147
- // redirected: the page at its own URL, in place of this entry
148
- if (page.url !== path)
149
- return void (await display(page, true, true, 'replace').finished?.catch(noop));
150
- const reload = event.navigationType === 'reload';
151
- // Back and Forward commit after the navigate event: scrolled before, the page would show at the top first
152
- await nav.transition?.committed;
153
- // superseded meanwhile (Back pressed before it was on the screen): neither shown nor scrolled
154
- await show(page, !reload, () => event.signal.aborted);
155
- if (!reload && !event.signal.aborted)
156
- scrollAfter(event);
157
- }
158
- catch (error) {
159
- failed(url.href, pushed)(error);
160
- }
161
- finally {
162
- done();
163
- }
164
- },
225
+ url.search = new URLSearchParams(fields).toString();
226
+ visit(url.href, { history: 'push', form });
227
+ });
228
+ // Back and Forward: the entry's page, where it was scrolled
229
+ window.addEventListener('popstate', (event) => {
230
+ const popped = scroll.pop(event.state);
231
+ if (popped.fragment)
232
+ return restore(popped.position, location.hash);
233
+ visit(location.href, {
234
+ history: 'none',
235
+ scroll: popped.position,
236
+ kept: kept.get(popped.key ?? ''),
165
237
  });
166
238
  });
239
+ // leaving the document (a reload, another site): its position, and the browser's restoration back on for this
240
+ // entry, so a reload or Back to it is scrolled at first paint, as any document
241
+ window.addEventListener('pagehide', () => {
242
+ scroll.save();
243
+ history.scrollRestoration = 'auto';
244
+ });
245
+ window.addEventListener('pageshow', (event) => {
246
+ if (event.persisted)
247
+ history.scrollRestoration = 'manual'; // back from the back/forward cache
248
+ });
249
+ // the browser's own #fragment navigations: the entry gets its key
250
+ window.addEventListener('hashchange', scroll.commit);
251
+ // an entry with a position (a reload, Back from another site): that position, the #fragment's target or not, as
252
+ // the browser restores it; otherwise, a first visit, the #fragment's target (rendered by now)
253
+ const { position, restored } = scroll.start();
254
+ if (position) {
255
+ if (!restored)
256
+ window.scrollTo(position.x, position.y);
257
+ }
258
+ else
259
+ restore(null, location.hash, true);
260
+ keep(initial);
261
+ }
262
+ /**
263
+ * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
264
+ * of another site and back): the browser's restoration is off. Each belongs to the entry on the screen, even once
265
+ * the browser has started a traversal away from it.
266
+ */
267
+ function scrollPositions() {
268
+ const KEY = SCROLL_KEY;
269
+ const STORAGE = SCROLL_STORAGE;
270
+ const positions = new Map();
271
+ const keyOf = (state) => state &&
272
+ typeof state === 'object' &&
273
+ typeof state[KEY] === 'string'
274
+ ? state[KEY]
275
+ : null;
276
+ const newKey = () => Math.random().toString(36).slice(2, 10);
277
+ let rendered = keyOf(history.state);
278
+ let renderedUrl = location.pathname + location.search;
279
+ const read = (key) => {
280
+ if (!key)
281
+ return null;
282
+ const kept = positions.get(key);
283
+ if (kept)
284
+ return kept;
285
+ try {
286
+ const saved = JSON.parse(sessionStorage.getItem(STORAGE + key) ?? 'null');
287
+ return typeof saved?.x === 'number' && typeof saved.y === 'number' ? saved : null;
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ };
293
+ const save = () => {
294
+ if (!rendered)
295
+ return;
296
+ const position = { x: scrollX, y: scrollY };
297
+ positions.set(rendered, position);
298
+ try {
299
+ sessionStorage.setItem(STORAGE + rendered, JSON.stringify(position));
300
+ }
301
+ catch { }
302
+ };
303
+ // the entry on the screen follows its scrolling (once a frame, in memory): its position is the one it was left at,
304
+ // whenever the browser starts a traversal away from it
305
+ let frame = 0;
306
+ addEventListener('scroll', () => {
307
+ const key = rendered; // the entry scrolled, before a popstate makes another one rendered
308
+ if (frame || !key)
309
+ return;
310
+ frame = requestAnimationFrame(() => {
311
+ frame = 0;
312
+ if (rendered === key)
313
+ positions.set(key, { x: scrollX, y: scrollY });
314
+ });
315
+ }, { passive: true });
316
+ /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to) */
317
+ const commit = () => {
318
+ let key = keyOf(history.state);
319
+ if (!key)
320
+ history.replaceState({ ...history.state, [KEY]: (key = newKey()) }, '');
321
+ rendered = key;
322
+ renderedUrl = location.pathname + location.search;
323
+ };
324
+ return {
325
+ save,
326
+ commit,
327
+ /** the key of the entry on the screen */
328
+ key: () => rendered,
329
+ /**
330
+ * The document's entry: its key; where it was scrolled, if it was (an entry this client pushed, loaded again: a
331
+ * reload, Back from another site past it), and whether the browser or the document's script put it back already
332
+ */
333
+ start() {
334
+ // restored already, by the browser or the document's own script: the page is scrolled (one rendered in the
335
+ // browser was empty for them, it has its content only now)
336
+ const restored = scrollX !== 0 || scrollY !== 0;
337
+ history.scrollRestoration = 'manual';
338
+ commit();
339
+ return { position: read(rendered), restored };
340
+ },
341
+ /** the page on the screen, at `url`: a new entry or this one */
342
+ write(url, replace) {
343
+ const state = { ...(replace ? history.state : {}), [KEY]: newKey() };
344
+ if (replace)
345
+ history.replaceState(state, '', url);
346
+ else
347
+ history.pushState(state, '', url);
348
+ },
349
+ /** Back or Forward to `state`'s entry: where it was; `fragment`: the same page, another #fragment */
350
+ pop(state) {
351
+ // nothing saved here: the browser may have scrolled already (Firefox and Safari to a #fragment, before its
352
+ // popstate); the entry left has its position from its scroll events
353
+ const key = keyOf(state);
354
+ const fragment = location.pathname + location.search === renderedUrl;
355
+ const position = read(key);
356
+ if (fragment)
357
+ commit();
358
+ return { fragment, position, key };
359
+ },
360
+ };
361
+ }
362
+ /** an entry's position, or its #fragment, or the top */
363
+ function restore(position, hash, first = false) {
364
+ if (position)
365
+ return window.scrollTo(position.x, position.y);
366
+ const target = hash && fragmentTarget(hash.slice(1));
367
+ if (target)
368
+ return target.scrollIntoView();
369
+ if (!first)
370
+ window.scrollTo(0, 0);
371
+ }
372
+ /** the element a #fragment names: decoded, or as it is (`#100%` doesn't decode); null for none */
373
+ function fragmentTarget(fragment) {
374
+ try {
375
+ return (document.getElementById(decodeURIComponent(fragment)) ?? document.getElementById(fragment));
376
+ }
377
+ catch {
378
+ return document.getElementById(fragment);
379
+ }
380
+ }
381
+ /** the new page's title, for screen readers: a navigation in place is otherwise silent */
382
+ let announcer;
383
+ function announce() {
384
+ if (!announcer) {
385
+ announcer = document.createElement('div');
386
+ announcer.setAttribute('aria-live', 'assertive');
387
+ announcer.setAttribute('aria-atomic', 'true');
388
+ Object.assign(announcer.style, {
389
+ position: 'absolute',
390
+ width: '1px',
391
+ height: '1px',
392
+ overflow: 'hidden',
393
+ clip: 'rect(0 0 0 0)',
394
+ whiteSpace: 'nowrap',
395
+ });
396
+ document.body.append(announcer);
397
+ }
398
+ announcer.textContent = document.title;
167
399
  }
168
400
  const isWebUrl = (url) => {
169
401
  try {
@@ -173,38 +405,28 @@ const isWebUrl = (url) => {
173
405
  return false;
174
406
  }
175
407
  };
176
- /** the form a navigation sends (a POST's, a GET form's): the element it started from, a form or its submitter */
177
- function formOf(event) {
178
- const from = event.sourceElement;
179
- if (from instanceof HTMLFormElement)
180
- return from;
181
- return from?.form ?? null;
408
+ /** a Content-Disposition's file name: `filename*=UTF-8''…` (RFC 6266), else `filename="…"`; '' for none */
409
+ function fileName(disposition) {
410
+ const encoded = /filename\*\s*=\s*UTF-8''([^;\s]+)/i.exec(disposition)?.[1];
411
+ if (encoded)
412
+ try {
413
+ return decodeURIComponent(encoded);
414
+ }
415
+ catch { }
416
+ const m = /filename\s*=\s*(?:"([^"]*)"|([^;\s]+))/i.exec(disposition);
417
+ return m?.[1] ?? m?.[2] ?? '';
182
418
  }
183
419
  /**
184
- * `href` loaded as a document. Every other navigation is the client's, `location.assign()` and `location.href = …`
185
- * too: this is for what a page can't change in place (`<html lang>`: another language).
420
+ * `href` loaded as a document. Every other navigation is the client's, links and forms: this is for what a page
421
+ * can't change in place (`<html lang>`: another language).
186
422
  */
187
423
  export function loadDocument(href) {
188
- const nav = navigation();
189
- if (nav)
190
- nav.navigate(href, { info: { fondu: 'document' } });
191
- else
192
- location.assign(href);
424
+ location.assign(href);
193
425
  }
194
426
  /** the page asked for again, its state and the scroll position kept */
195
427
  export function again() {
196
- const nav = navigation();
197
- if (nav)
198
- nav.reload({ info: { fondu: 'reload' } });
428
+ if (visit)
429
+ visit(location.href, { history: 'none', keep: true });
199
430
  else
200
431
  location.reload();
201
432
  }
202
- /**
203
- * Where a navigation leaves the page: Back and Forward where it was, a #fragment at its target, else the top (which
204
- * `event.scroll()` does too since whatwg/html#11987; Chromium 141 doesn't yet).
205
- */
206
- function scrollAfter(event) {
207
- event.scroll();
208
- if (event.navigationType !== 'traverse' && !new URL(event.destination.url).hash)
209
- window.scrollTo(0, 0);
210
- }
@@ -9,8 +9,8 @@ export interface ProgressOptions {
9
9
  }
10
10
  /**
11
11
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
12
- * transition, slower as it gets there), filled and faded out when it is done. Drawn with CSSOM styles (no stylesheet,
13
- * nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree: `useNavigating()`
14
- * is the app's way to say it in its own words. With reduced motion, a still bar.
12
+ * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
13
+ * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
14
+ * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
15
15
  */
16
16
  export declare function progressBar({ delay, color }: ProgressOptions, pending: () => boolean): () => void;
@@ -1,16 +1,26 @@
1
1
  /**
2
2
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
3
- * transition, slower as it gets there), filled and faded out when it is done. Drawn with CSSOM styles (no stylesheet,
4
- * nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree: `useNavigating()`
5
- * is the app's way to say it in its own words. With reduced motion, a still bar.
3
+ * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
4
+ * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
5
+ * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
6
6
  */
7
7
  export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
8
8
  const still = matchMedia('(prefers-reduced-motion: reduce)');
9
9
  let bar;
10
10
  let wait;
11
+ const bars = new Set(); // on the screen, the one fading out included
12
+ // leaving the document: no bar kept in the back/forward cache, to be seen again on Back
13
+ addEventListener('pagehide', () => {
14
+ clearTimeout(wait);
15
+ wait = bar = undefined;
16
+ for (const el of bars)
17
+ el.remove();
18
+ bars.clear();
19
+ });
11
20
  const show = () => {
12
21
  wait = undefined;
13
22
  const el = (bar = document.createElement('div')); // a new one: the last may still be fading out
23
+ bars.add(el);
14
24
  Object.assign(el.style, {
15
25
  position: 'fixed',
16
26
  inset: '0 0 auto',
@@ -36,11 +46,14 @@ export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
36
46
  bar = undefined;
37
47
  if (!el)
38
48
  return;
39
- // from where it is: a transition starts from the value on the screen
40
- el.style.transition = 'transform 200ms ease-out, opacity 200ms 100ms';
49
+ // filled from where it is (a transition starts from the value on the screen), then faded out
50
+ el.style.transition = 'transform 200ms ease-out, opacity 200ms 200ms';
41
51
  el.style.transform = 'scaleX(1)';
42
52
  el.style.opacity = '0';
43
- setTimeout(() => el.remove(), 400);
53
+ setTimeout(() => {
54
+ el.remove();
55
+ bars.delete(el);
56
+ }, 450);
44
57
  };
45
58
  return () => {
46
59
  if (!pending())
package/dist/paths.d.ts CHANGED
@@ -25,10 +25,22 @@ export declare function layoutsOf(file: string): string[];
25
25
  export declare function middlewareFor(file: string, middleware: readonly string[]): string[];
26
26
  /** `/users/:id` + `{ id: 7 }` → `/users/7`; catch-alls keep their slashes */
27
27
  export declare function fillPattern(pattern: string, params?: Record<string, string | number>): string;
28
+ /** fondu/client's scroll positions: each history entry's key in `history.state`, its position in sessionStorage */
29
+ export declare const SCROLL_KEY = "__fondu";
30
+ export declare const SCROLL_STORAGE = "fondu-scroll:";
28
31
  /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
29
32
  export declare const PAGE_DATA = "/_fondu/pages";
30
- /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
33
+ /**
34
+ * a page's URL path → the URL of its page object, one for one whatever the app's trailing slashes: `/docs/intro` →
35
+ * `/_fondu/pages/docs/intro.json`; a trailing slash is `index` (`/docs/` → `…/docs/index.json`, `/` →
36
+ * `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
37
+ */
31
38
  export declare function pageDataPath(path: string): string;
39
+ /**
40
+ * a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
41
+ * (`index.html`, `docs/index.html`), which is another page
42
+ */
43
+ export declare const endsInIndex: (path: string) => boolean;
32
44
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
33
45
  export declare function pathOfPageData(pathname: string): string | null;
34
46
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
package/dist/paths.js CHANGED
@@ -9,10 +9,11 @@
9
9
  * - `_middleware.ts` applies to its directory
10
10
  */
11
11
  export function routePatterns(file) {
12
- const segments = file
13
- .replace(ROUTE_EXTENSION, '')
14
- .split('/')
15
- .filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s));
12
+ const parts = file.replace(ROUTE_EXTENSION, '').split('/');
13
+ // the file named index is its directory; a directory named index is a segment like any other
14
+ if (parts.at(-1) === 'index')
15
+ parts.pop();
16
+ const segments = parts.filter((s) => s !== '' && !/^\(.+\)$/.test(s));
16
17
  const optional = segments.filter((s) => /^\[\[(?:\.\.\.)?\w+\]\]$/.test(s));
17
18
  if (optional.some((s) => s.startsWith('[[...')))
18
19
  throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
@@ -72,16 +73,46 @@ export function fillPattern(pattern, params = {}) {
72
73
  return parts.map(encodeURIComponent).join('/');
73
74
  });
74
75
  }
76
+ /** fondu/client's scroll positions: each history entry's key in `history.state`, its position in sessionStorage */
77
+ export const SCROLL_KEY = '__fondu';
78
+ export const SCROLL_STORAGE = 'fondu-scroll:';
75
79
  /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
76
80
  export const PAGE_DATA = '/_fondu/pages';
77
- /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
81
+ /**
82
+ * a page's URL path → the URL of its page object, one for one whatever the app's trailing slashes: `/docs/intro` →
83
+ * `/_fondu/pages/docs/intro.json`; a trailing slash is `index` (`/docs/` → `…/docs/index.json`, `/` →
84
+ * `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
85
+ */
78
86
  export function pageDataPath(path) {
79
- return `${PAGE_DATA}${path.endsWith('/') ? path + 'index' : path}.json`;
87
+ const last = path.slice(path.lastIndexOf('/') + 1);
88
+ // as the server reads it, decoded: `%69ndex` is index too (written as it, of unreserved characters)
89
+ const named = path.endsWith('/')
90
+ ? `${path}index`
91
+ : /^~*index$/.test(decoded(last))
92
+ ? `${path.slice(0, -last.length)}~${decoded(last)}`
93
+ : path;
94
+ return `${PAGE_DATA}${named}.json`;
80
95
  }
96
+ /** a URL segment decoded, or as it is if it doesn't decode */
97
+ function decoded(segment) {
98
+ try {
99
+ return decodeURIComponent(segment);
100
+ }
101
+ catch {
102
+ return segment;
103
+ }
104
+ }
105
+ /**
106
+ * a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
107
+ * (`index.html`, `docs/index.html`), which is another page
108
+ */
109
+ export const endsInIndex = (path) => decoded(path.slice(path.lastIndexOf('/') + 1)) === 'index';
81
110
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
82
111
  export function pathOfPageData(pathname) {
83
112
  const m = pathname.match(/^\/_fondu\/pages(\/.+)\.json$/);
84
- return m ? m[1].replace(/\/index$/, '/') : null;
113
+ if (!m)
114
+ return null;
115
+ return m[1].replace(/(?<=\/)index$/, '').replace(/(?<=\/)~(~*index)$/, '$1');
85
116
  }
86
117
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
87
118
  export function staticFiles(path) {
@@ -1,5 +1,6 @@
1
1
  import { assetTags } from 'virtual:fondu/assets';
2
2
  import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
3
+ import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
3
4
  const defaultTemplate = ({ head, body }) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}</head><body>${body}</body></html>`;
4
5
  /** the options of the app (`createApp`) a request belongs to */
5
6
  export const settings = new WeakMap();
@@ -15,6 +16,12 @@ export const withoutSsr = () => async (c, next) => {
15
16
  };
16
17
  /** the page data, `/` and `<` escaped (no `</script>` in it), no HTML entities */
17
18
  const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
19
+ /**
20
+ * A reload, Back to a page of another site: this entry's position, where fondu/client left it, before the first
21
+ * paint (the stylesheets are in: the page is laid out). The browser may not restore it itself (Safari: the client's
22
+ * own restoration, off until the page is left, is still off for it), and the client would only once it runs.
23
+ */
24
+ const restoreScroll = (nonce) => `<script${nonce ? ` nonce="${nonce}"` : ''}>try{var k=history.state&&history.state[${JSON.stringify(SCROLL_KEY)}],p=k&&JSON.parse(sessionStorage.getItem(${JSON.stringify(SCROLL_STORAGE)}+k));p&&!scrollY&&scrollTo(+p.x||0,+p.y||0)}catch(e){}</script>`;
18
25
  // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
19
26
  // never read as one
20
27
  const HEAD = 'fondu:document-head';
@@ -46,11 +53,24 @@ export async function renderDocument(c, page) {
46
53
  }
47
54
  // the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
48
55
  // content can come before it
49
- const body = pageScript(page) + (ssr?.body ?? '<div id="app"></div>');
56
+ // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet)
57
+ const body = pageScript(page) + (ssr ? ssr.body + restoreScroll(nonce) : '<div id="app"></div>');
50
58
  const template = settings.get(c)?.document ?? defaultTemplate;
51
59
  const html = await shell(template, c, nonce);
52
60
  const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
53
61
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
54
62
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
55
- return before + (ssr?.head ?? '') + assetTags(page.component, nonce) + between + body + after;
63
+ // the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
64
+ // document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
65
+ // the page out early (Firefox's, with its tools open) has them sooner
66
+ const tags = assetTags(page.component, nonce);
67
+ const css = tags.match(/<link rel="stylesheet"[^>]*>/g)?.join('') ?? '';
68
+ const charset = /<meta charset=[^>]*>/i;
69
+ const top = css && charset.test(before) ? before.replace(charset, (meta) => meta + css) : before + css;
70
+ return (top +
71
+ tags.replace(/<link rel="stylesheet"[^>]*>/g, '') +
72
+ (ssr?.head ?? '') +
73
+ between +
74
+ body +
75
+ after);
56
76
  }
@@ -80,5 +80,7 @@ import { createHotContext } from '${import.meta.env.BASE_URL}@vite/client'
80
80
  const hot = createHotContext('/@fondu/error-report')
81
81
  hot.on('fondu:props', () => location.reload())
82
82
  hot.on('vite:afterUpdate', () => location.reload())
83
+ // Back and Forward to the app's entries before it (this document may be given them): their URL as a document
84
+ addEventListener('popstate', () => location.reload())
83
85
  </script></body></html>`;
84
86
  }
@@ -1,4 +1,4 @@
1
- import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
1
+ import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
2
  import { isPageRequest } from './http.js';
3
3
  /** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
4
4
  const STATIC_FILES = Symbol.for('fondu.staticFiles');
@@ -19,16 +19,21 @@ export async function prerenderPaths(routes) {
19
19
  continue;
20
20
  }
21
21
  const dynamic = route.pattern.includes(':');
22
+ // a page whose URL ends in index: its file would be its directory's page's (index.html), another page
23
+ const add = (path) => endsInIndex(path)
24
+ ? problems.push(`${where}: ${path} ends in index, so its static file would be the page of its directory: ` +
25
+ `leave it out of \`prerender\``)
26
+ : paths.add(path);
22
27
  if (setting === true) {
23
28
  if (dynamic)
24
29
  problems.push(`${where} is dynamic: \`export const prerender = () => [{ …params }]\` lists its pages, or \`= false\``);
25
30
  else
26
- paths.add(route.pattern);
31
+ add(route.pattern);
27
32
  continue;
28
33
  }
29
34
  try {
30
35
  for (const params of await setting())
31
- paths.add(fillPattern(route.pattern, params));
36
+ add(fillPattern(route.pattern, params));
32
37
  }
33
38
  catch (error) {
34
39
  problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
@@ -50,6 +55,9 @@ export function prerenderRoutes(app, routes, version) {
50
55
  const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
51
56
  if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
52
57
  return next();
58
+ // a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
59
+ if (!data && endsInIndex(c.req.path))
60
+ return next();
53
61
  let file;
54
62
  try {
55
63
  file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
@@ -81,7 +89,7 @@ export function prerenderRoutes(app, routes, version) {
81
89
  app.get(`${PAGE_DATA}/*`, (c) => {
82
90
  const path = pathOfPageData(c.req.path);
83
91
  // a page object's own URL is not a page: no page object of a page object (and so on)
84
- if (!path || path.startsWith(`${PAGE_DATA}/`))
92
+ if (!path || path.startsWith('/_fondu/'))
85
93
  return c.notFound();
86
94
  const url = new URL(c.req.url);
87
95
  url.pathname = path;
@@ -81,23 +81,25 @@ const versionCheck = async (c, next) => {
81
81
  await next();
82
82
  // a URL answers a navigation and a document differently: caches keep them apart
83
83
  appendHeader(c, 'Vary', 'X-Fondu');
84
- // an empty answer to a form (an action that returns nothing to show): back to the page
85
- if (isPageRequest(c) &&
86
- c.res.status === 200 &&
87
- !c.res.headers.has('x-fondu') &&
88
- (await c.res.clone().text()) === '')
84
+ // an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
85
+ // isn't read to tell (a stream's would be, to its end)
86
+ if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
89
87
  c.res = back(c);
90
88
  const to = c.res.headers.get('location');
91
89
  if (isPageRequest(c) && c.res.status >= 300 && c.res.status < 400 && to) {
92
90
  // to another site: fetch() can't follow it (CORS), the client loads it as a document; http(s) only (a browser
93
91
  // follows no redirect to `javascript:`, and neither does the client)
94
- if (!sameOrigin(c, to)) {
92
+ const here = sameOrigin(c, to);
93
+ if (!here) {
95
94
  if (webUrl(c, to))
96
95
  c.res = c.body(null, 409, { 'X-Fondu-Location': to });
97
96
  }
98
- // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows
97
+ // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows, from
98
+ // this site's root (a relative Location is the request's, not the page's on the screen)
99
99
  else if (to.includes('#'))
100
- c.res = c.body(null, 200, { 'X-Fondu-Redirect': to });
100
+ c.res = c.body(null, 200, {
101
+ 'X-Fondu-Redirect': here.pathname.replace(/^\/+/, '/') + here.search + here.hash,
102
+ });
101
103
  }
102
104
  };
103
105
  export const protocol = [flashCookie, versionCheck];
@@ -35,9 +35,10 @@ export declare class ValidationError extends Error {
35
35
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
36
36
  /**
37
37
  * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
38
- * `user[name]`); files are `File`s, empty file inputs are left out. Names that would change the object itself
39
- * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
40
- * deeper than 32) is a 400.
38
+ * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
39
+ * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
40
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
41
+ * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
41
42
  */
42
43
  export declare function readBody(c: Context): Promise<unknown>;
43
44
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -24,19 +24,23 @@ export function validationErrorResponse(c, error) {
24
24
  const DEPTH = 32;
25
25
  /**
26
26
  * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
27
- * `user[name]`); files are `File`s, empty file inputs are left out. Names that would change the object itself
28
- * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
29
- * deeper than 32) is a 400.
27
+ * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
28
+ * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
29
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
30
+ * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
30
31
  */
31
32
  export async function readBody(c) {
32
33
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
33
- const type = c.req.header('content-type') ?? '';
34
+ const type = (c.req.header('content-type') ?? '').toLowerCase();
34
35
  if (type.includes('application/json'))
35
36
  return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
36
37
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
37
38
  return {};
38
- const form = await c.req.formData();
39
+ const form = await c.req.formData().catch(() => Promise.reject(malformed('invalid form data')));
39
40
  const body = Object.create(null);
41
+ // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
42
+ const next = new WeakMap();
43
+ const isObject = (v) => typeof v === 'object' && !(v instanceof File) && !Array.isArray(v);
40
44
  for (const [key, value] of form.entries()) {
41
45
  if (typeof value !== 'string' && value.size === 0 && value.name === '')
42
46
  continue;
@@ -47,25 +51,19 @@ export async function readBody(c) {
47
51
  continue;
48
52
  let target = body;
49
53
  path.forEach((segment, i) => {
50
- const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
54
+ const name = segment === '' ? String(next.get(target) ?? 0) : segment;
55
+ if (/^\d+$/.test(name))
56
+ next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
51
57
  const has = Object.hasOwn(target, name);
52
58
  if (i === path.length - 1) {
53
- if (has &&
54
- typeof target[name] === 'object' &&
55
- !(target[name] instanceof File) &&
56
- !Array.isArray(target[name]))
59
+ if (has && isObject(target[name]))
57
60
  throw malformed(`\`${key}\` is both a value and an object`);
58
- if (has && path.length === 1)
59
- target[name] = [target[name], value].flat(); // `a=1&a=2`
60
- else
61
- target[name] = value;
61
+ target[name] = has ? [target[name], value].flat() : value; // given again: a list
62
62
  }
63
63
  else {
64
64
  if (!has)
65
65
  target[name] = Object.create(null);
66
- else if (typeof target[name] !== 'object' ||
67
- target[name] instanceof File ||
68
- Array.isArray(target[name]))
66
+ else if (!isObject(target[name]))
69
67
  throw malformed(`\`${key}\` is both a value and an object`);
70
68
  target = target[name];
71
69
  }
@@ -94,8 +92,9 @@ export function validator(schemas) {
94
92
  query: () => c.req.query(),
95
93
  params: () => c.req.param(),
96
94
  };
97
- const input = {};
98
- const errors = {};
95
+ // no prototype: a field named `toString` or `constructor` is a field like any other
96
+ const input = Object.create(null);
97
+ const errors = Object.create(null);
99
98
  for (const key of Object.keys(schemas)) {
100
99
  const result = await schemas[key]['~standard'].validate(await values[key]());
101
100
  // route params that don't fit: the URL names nothing here
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { builtinModules, createRequire } from 'node:module';
4
4
  import { dirname, join, relative, resolve, sep } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
@@ -294,6 +294,7 @@ function core(options) {
294
294
  if (options.prerender && existsSync(wrangler)) {
295
295
  const clientDir = resolve(config.root, client.config.build.outDir);
296
296
  await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
297
+ workerFirstForIndex(wrangler);
297
298
  }
298
299
  }
299
300
  },
@@ -495,6 +496,20 @@ const isServerOnly = (id, root) => {
495
496
  (file.startsWith(`${root}/app/routes/`) && file.endsWith('.ts')) ||
496
497
  file === `${root}/app/server.ts`);
497
498
  };
499
+ /**
500
+ * The built Worker's config: URLs ending in index go to the Worker first. Static assets would answer them with the
501
+ * page of their directory (`/docs/index` → `docs/index.html`, redirected to `/docs/`), while a route (a param's value)
502
+ * may be theirs. Added to the app's own `run_worker_first`, unless it is `true` (every request first) already.
503
+ */
504
+ function workerFirstForIndex(file) {
505
+ const config = JSON.parse(readFileSync(file, 'utf8'));
506
+ const assets = (config.assets ??= {});
507
+ if (assets.run_worker_first === true)
508
+ return;
509
+ const own = Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
510
+ assets.run_worker_first = [...new Set([...own, '/index', '/*/index'])];
511
+ writeFileSync(file, JSON.stringify(config));
512
+ }
498
513
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
499
514
  function devAssets(base) {
500
515
  const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true;window.__getReactRefreshIgnoredExports=({id})=>window.${PAGE_EXPORTS}?.[id]??[]`;
@@ -9,7 +9,7 @@ type Node = {
9
9
  };
10
10
  /**
11
11
  * The browser's copy of a page's route file: its server exports removed (`loader`, `action`, `actions`…), then
12
- * what only they used: imports and top-level declarations no other code names, until none is left. Conservative: a
12
+ * what only they used: the imports and top-level declarations the code kept doesn't reach. Conservative: a
13
13
  * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
14
14
  * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
15
15
  */
@@ -171,7 +171,7 @@ function lexical(statements, scope = new Set()) {
171
171
  }
172
172
  /**
173
173
  * The browser's copy of a page's route file: its server exports removed (`loader`, `action`, `actions`…), then
174
- * what only they used: imports and top-level declarations no other code names, until none is left. Conservative: a
174
+ * what only they used: the imports and top-level declarations the code kept doesn't reach. Conservative: a
175
175
  * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
176
176
  * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
177
177
  */
@@ -223,28 +223,33 @@ export function stripServerCode(code, program, file) {
223
223
  else if (['VariableDeclaration', 'FunctionDeclaration', 'ClassDeclaration'].includes(node.type))
224
224
  part.declares = bound(node);
225
225
  }
226
- // what nobody names goes, until nothing more does
227
- for (let changed = true; changed;) {
228
- changed = false;
229
- const live = (part) => part.text !== '';
230
- for (const part of parts) {
231
- if (!live(part) || !part.declares.length)
226
+ // what the code kept reaches stays, the rest goes: declarations that only name each other (a loader's helpers
227
+ // calling one another) go together
228
+ const kept = (part) => part.text !== '';
229
+ const live = new Set(parts.filter((part) => kept(part) && !part.declares.length));
230
+ const reached = new Set();
231
+ for (const queue = [...live]; queue.length;)
232
+ for (const name of queue.pop().uses) {
233
+ if (reached.has(name))
232
234
  continue;
233
- const used = (name) => parts.some((other) => other !== part && live(other) && other.uses.has(name));
234
- if (part.node.type === 'ImportDeclaration') {
235
- const specifiers = part.node.specifiers;
236
- const kept = specifiers.filter((s) => used(nameOf(s.local)));
237
- if (kept.length === part.declares.length)
238
- continue;
239
- changed = true;
240
- part.declares = kept.map((s) => nameOf(s.local));
241
- part.text = kept.length ? importOf(code, part.node, kept) : '';
242
- }
243
- else if (!part.declares.some(used)) {
244
- changed = true;
245
- part.text = '';
246
- }
235
+ reached.add(name);
236
+ for (const part of parts)
237
+ if (kept(part) && !live.has(part) && part.declares.includes(name)) {
238
+ live.add(part);
239
+ queue.push(part);
240
+ }
241
+ }
242
+ for (const part of parts) {
243
+ if (!kept(part) || !part.declares.length)
244
+ continue;
245
+ if (part.node.type === 'ImportDeclaration') {
246
+ const specifiers = part.node.specifiers;
247
+ const used = specifiers.filter((s) => reached.has(nameOf(s.local)));
248
+ if (used.length < specifiers.length)
249
+ part.text = used.length ? importOf(code, part.node, used) : '';
247
250
  }
251
+ else if (!live.has(part))
252
+ part.text = '';
248
253
  }
249
254
  for (const part of parts)
250
255
  if (part.text !== '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
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",