fondu 0.17.0 → 0.18.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.
@@ -21,6 +21,10 @@ type StandardResult = {
21
21
  * the pointer)
22
22
  * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
23
23
  * by the server's keys (`email`, `user.name`)
24
+ * - an async schema: the form is sent once the schema has said yes to the values it was asked about. A result that
25
+ * comes late is dropped, and sends nothing: after a newer submit, a visit to another page, or the form leaving the
26
+ * screen, and when the fields are no longer what was checked (changed while the schema was working). That form is
27
+ * not sent unchecked, nor checked again for the user: submit it again
24
28
  * - `submitting`: this form is being sent
25
29
  * - `failed`: this form could not be sent (offline…): it stays, to send again
26
30
  *
@@ -31,6 +31,15 @@ function check(schema, value) {
31
31
  const errors = (r) => (r.issues ? issueErrors(r.issues) : {});
32
32
  return result instanceof Promise ? result.then(errors) : errors(result);
33
33
  }
34
+ /** a form's fields as one string, files by what identifies them: two snapshots of a form are equal if this is */
35
+ function snapshot(form, submitter) {
36
+ try {
37
+ return JSON.stringify([...new FormData(form, submitter ?? undefined)].map(([k, v]) => typeof v === 'string' ? [k, v] : [k, v.name, v.size, v.lastModified, v.type]));
38
+ }
39
+ catch {
40
+ return undefined; // a submitter that is no longer in the form: not what was checked
41
+ }
42
+ }
34
43
  /** a field's errors: its own, and those inside it (`tags` has `tags.0`'s) */
35
44
  const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.startsWith(`${key}.`));
36
45
  /**
@@ -44,6 +53,10 @@ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.st
44
53
  * the pointer)
45
54
  * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
46
55
  * by the server's keys (`email`, `user.name`)
56
+ * - an async schema: the form is sent once the schema has said yes to the values it was asked about. A result that
57
+ * comes late is dropped, and sends nothing: after a newer submit, a visit to another page, or the form leaving the
58
+ * screen, and when the fields are no longer what was checked (changed while the schema was working). That form is
59
+ * not sent unchecked, nor checked again for the user: submit it again
47
60
  * - `submitting`: this form is being sent
48
61
  * - `failed`: this form could not be sent (offline…): it stays, to send again
49
62
  *
@@ -77,6 +90,11 @@ export function useForm(schema) {
77
90
  const dirty = useRef(new Set());
78
91
  const runs = useRef(new Map());
79
92
  const passed = useRef(false);
93
+ // which whole-form check may still send: each submit takes the next number, and so does what makes a pending one
94
+ // obsolete (a visit, the form leaving). The result of an older one is dropped
95
+ const generation = useRef(0);
96
+ // the checks of single fields that began before the whole form's result: that result is the newer word
97
+ const epoch = useRef(0);
80
98
  /** what a check found, for the fields it covers (`key`: one field and those inside it; else all) */
81
99
  const apply = (found, from, key) => {
82
100
  if (latest.current !== from)
@@ -130,14 +148,25 @@ export function useForm(schema) {
130
148
  if (element && Object.keys(server).length)
131
149
  focusFirst(element, server);
132
150
  }, [submitting, failed, server, element]);
151
+ // a visit to another page (a link, another form) or the form leaving the screen: a pending check can't send
152
+ const visiting = navigation.state === 'loading' || navigation.state === 'submitting';
153
+ useEffect(() => {
154
+ if (visiting)
155
+ generation.current++;
156
+ }, [visiting]);
157
+ useEffect(() => () => {
158
+ generation.current++;
159
+ }, []);
133
160
  const checkField = (form, key) => {
134
161
  if (!schema)
135
162
  return;
136
163
  const run = (runs.current.get(key) ?? 0) + 1;
137
164
  runs.current.set(key, run);
138
165
  const from = server;
166
+ const began = epoch.current;
139
167
  const done = (found) => {
140
- if (runs.current.get(key) === run)
168
+ // not after a newer check of the field, nor after the whole form's result (it began with these values or later)
169
+ if (runs.current.get(key) === run && epoch.current === began)
141
170
  apply(found, from, key);
142
171
  };
143
172
  const found = check(schema, () => fieldsOf(form));
@@ -159,6 +188,8 @@ export function useForm(schema) {
159
188
  const form = event.currentTarget;
160
189
  const submitter = event.nativeEvent.submitter;
161
190
  const from = server;
191
+ const mine = ++generation.current;
192
+ const before = snapshot(form, submitter);
162
193
  const found = check(schema, () => fieldsOf(form, submitter));
163
194
  const answer = (found) => {
164
195
  apply(found, from);
@@ -173,11 +204,21 @@ export function useForm(schema) {
173
204
  // an async schema: sent again once it says yes
174
205
  event.preventDefault();
175
206
  void found.then((found) => {
207
+ // obsolete (a newer submit, a visit, the form gone) or about other values than the form has now: it says
208
+ // nothing about what would be sent
209
+ if (generation.current !== mine || snapshot(form, submitter) !== before)
210
+ return;
211
+ epoch.current++;
176
212
  answer(found);
177
213
  if (Object.keys(found).length || latest.current !== from)
178
214
  return;
179
215
  passed.current = true;
180
- form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
216
+ try {
217
+ form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
218
+ }
219
+ finally {
220
+ passed.current = false; // a submit that was cancelled has not used it up
221
+ }
181
222
  });
182
223
  },
183
224
  },
@@ -40,6 +40,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
40
40
  // the URL the page's props are the loader's answer for: `on.url` changes with a shallow navigation, this does not
41
41
  let answered = initial.url;
42
42
  const asking = new Set();
43
+ // each prop's newest answer put in the page: the request it came from (their order). An older request answering
44
+ // after it is dropped for that prop, as an answer for a page no longer there is
45
+ let requests = 0;
46
+ let answers = new Map();
43
47
  const put = async (page, fresh, stale) => {
44
48
  await show(page, fresh, stale);
45
49
  if (stale())
@@ -51,6 +55,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
51
55
  // the page they were for is gone
52
56
  for (const quiet of asking)
53
57
  quiet.abort();
58
+ answers = new Map();
54
59
  };
55
60
  shownUrl = () => new URL(on.url, location.href);
56
61
  const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
@@ -97,6 +102,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
97
102
  ask = async (names) => {
98
103
  const at = shows;
99
104
  const page = on;
105
+ const id = ++requests;
100
106
  const controller = new AbortController();
101
107
  asking.add(controller);
102
108
  // a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
@@ -115,7 +121,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
115
121
  });
116
122
  const answer = response.ok && response.headers.has('X-Fondu') ? (await response.json()) : null;
117
123
  if (answer?.component === page.component)
118
- got = Object.fromEntries(Object.entries(answer.props).filter(([key]) => names.includes(key)));
124
+ got = answer.props;
119
125
  }
120
126
  catch { } // offline, aborted
121
127
  asking.delete(controller);
@@ -124,9 +130,13 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
124
130
  // asked at the URL of a shallow entry, which the page has left since: not its answer
125
131
  if (page.url !== answered && page.url !== on.url)
126
132
  return;
133
+ // the props of this answer that no newer request has answered already
134
+ const take = names.filter((n) => got && Object.hasOwn(got, n) && id > (answers.get(n) ?? 0));
135
+ for (const n of take)
136
+ answers.set(n, id);
127
137
  const next = {
128
138
  ...on,
129
- props: { ...on.props, ...got },
139
+ props: { ...on.props, ...Object.fromEntries(take.map((n) => [n, got[n]])) },
130
140
  deferred: on.deferred?.filter((n) => !names.includes(n)),
131
141
  };
132
142
  on = next; // before the module is awaited: another answer merges into this one
@@ -136,8 +146,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
136
146
  group = new Set([scroll.key()]);
137
147
  answered = page.url;
138
148
  }
139
- await show(next, false, () => shows !== at);
140
- if (shows === at)
149
+ // not once another answer has merged into the page since: its own show() has these props too
150
+ const stale = () => shows !== at || on !== next;
151
+ await show(next, false, stale);
152
+ if (!stale())
141
153
  keep(next);
142
154
  };
143
155
  /** a document load: in place of this entry, or after it */
@@ -251,6 +263,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
251
263
  const page = (await response.json());
252
264
  if (signal.aborted)
253
265
  return;
266
+ // A prerendered page's file is made without a query. Its answer, not redirected, is for the URL asked: the
267
+ // visitor's query stays (as at a document load); a redirect, which the server made, is its target's
268
+ if (!response.redirected && page.url === url.pathname)
269
+ page.url += url.search;
254
270
  if (version && page.version && page.version !== version)
255
271
  return documentLoad(page.url, options.history !== 'push');
256
272
  version = page.version;
@@ -463,11 +479,13 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
463
479
  window.addEventListener('popstate', (event) => {
464
480
  closing = false;
465
481
  const popped = scroll.pop(event.state);
482
+ // a visit on its way is given up by any Back or Forward, the browser's own #fragment entries too: its answer
483
+ // would put a page on the screen over the entry the visitor is at
484
+ current?.abort();
485
+ pending(null);
466
486
  // an entry that shows the page on the screen, at a URL of its own: its URL, nothing asked for, the scroll where it
467
- // is. A visit on its way is given up, as any Back does
487
+ // is
468
488
  if (!popped.fragment && popped.key && group.has(popped.key)) {
469
- current?.abort();
470
- pending(null);
471
489
  scroll.commit();
472
490
  return settle(false);
473
491
  }
@@ -527,12 +545,28 @@ let closing = false;
527
545
  /**
528
546
  * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
529
547
  * of another site and back): the browser's restoration is off. Each belongs to the entry on the screen, even once
530
- * the browser has started a traversal away from it.
548
+ * the browser has started a traversal away from it. The last 50 are kept (the page cache's number), their keys in
549
+ * the order they were used in `STORAGE` itself; an entry replaced by another page forgets its own.
531
550
  */
532
551
  function scrollPositions() {
533
552
  const KEY = SCROLL_KEY;
534
553
  const STORAGE = SCROLL_STORAGE;
535
554
  const positions = new Map();
555
+ const forget = (key) => {
556
+ positions.delete(key);
557
+ try {
558
+ sessionStorage.removeItem(STORAGE + key);
559
+ }
560
+ catch { }
561
+ };
562
+ /** the most recently used last: the oldest beyond 50 are forgotten */
563
+ const remember = (key, position) => {
564
+ positions.delete(key);
565
+ positions.set(key, position);
566
+ for (const old of positions.keys())
567
+ if (positions.size > 50)
568
+ forget(old);
569
+ };
536
570
  const keyOf = (state) => state &&
537
571
  typeof state === 'object' &&
538
572
  typeof state[KEY] === 'string'
@@ -559,9 +593,10 @@ function scrollPositions() {
559
593
  if (!rendered)
560
594
  return;
561
595
  const position = { x: scrollX, y: scrollY };
562
- positions.set(rendered, position);
596
+ remember(rendered, position);
563
597
  try {
564
598
  sessionStorage.setItem(STORAGE + rendered, JSON.stringify(position));
599
+ sessionStorage.setItem(STORAGE, JSON.stringify([...positions.keys()]));
565
600
  }
566
601
  catch { }
567
602
  };
@@ -575,7 +610,7 @@ function scrollPositions() {
575
610
  frame = requestAnimationFrame(() => {
576
611
  frame = 0;
577
612
  if (rendered === key)
578
- positions.set(key, { x: scrollX, y: scrollY });
613
+ remember(key, { x: scrollX, y: scrollY });
579
614
  });
580
615
  }, { passive: true });
581
616
  /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to): true if so */
@@ -599,29 +634,43 @@ function scrollPositions() {
599
634
  */
600
635
  start() {
601
636
  history.scrollRestoration = 'manual';
637
+ // the positions saved before this document (the last 50, as left), in their order
638
+ try {
639
+ for (const key of JSON.parse(sessionStorage.getItem(STORAGE) ?? '[]')) {
640
+ const saved = read(key);
641
+ if (saved)
642
+ positions.set(key, saved);
643
+ }
644
+ }
645
+ catch { }
602
646
  commit();
603
647
  return read(rendered);
604
648
  },
605
649
  /**
606
650
  * The page on the screen, at `url`: a new entry or this one. `shallow`: by a shallow navigation, which marks a
607
651
  * new entry (SHALLOW); a replaced entry keeps its state, but another URL, by a navigation that is not
608
- * shallow, takes the mark away: `closeShallow()` there must not go Back off it.
652
+ * shallow, takes the mark away: `closeShallow()` there must not go Back off it. A replaced entry is the same
653
+ * entry (its key stays) for a shallow navigation and an answer at its URL; another page is a new one, and
654
+ * nothing can visit the entry it replaced.
609
655
  */
610
656
  write(url, replace, shallow = false) {
657
+ const to = new URL(url, location.href);
658
+ // the same URL (a form's answer, reload()): the same overlay
659
+ const same = to.pathname + to.search === location.pathname + location.search;
660
+ const old = keyOf(history.state);
661
+ const kept = replace && old && (shallow || same);
611
662
  const state = {
612
663
  ...(replace ? history.state : {}),
613
- [KEY]: newKey(),
664
+ [KEY]: kept ? old : newKey(),
614
665
  };
666
+ if (replace && old && !kept)
667
+ forget(old);
615
668
  if (shallow) {
616
669
  if (!replace)
617
670
  state[SHALLOW] = true;
618
671
  }
619
- else {
620
- // the same URL (a form's answer, reload()): the same overlay. Another page: not a shallow entry
621
- const to = new URL(url, location.href);
622
- if (to.pathname + to.search !== location.pathname + location.search)
623
- delete state[SHALLOW];
624
- }
672
+ else if (!same)
673
+ delete state[SHALLOW]; // another page: not a shallow entry
625
674
  if (replace)
626
675
  history.replaceState(state, '', url);
627
676
  else
package/dist/client.d.ts CHANGED
@@ -102,13 +102,13 @@ type BodyArg<M extends string, B> = M extends 'GET' ? {
102
102
  } : {
103
103
  body: B;
104
104
  };
105
- /** `method`: omitted is GET, so required when the route has no GET */
106
- type MethodArg<P extends string, M extends string> = 'GET' extends MethodsOf<P> ? {
105
+ /** `method`: omitted is GET, so it is left out only for a call that is GET: any other method, or a union, names it */
106
+ type MethodArg<M extends string> = [M] extends ['GET'] ? {
107
107
  method?: M;
108
108
  } : {
109
109
  method: M;
110
110
  };
111
- type FetchOptions<P extends string, M extends HttpMethod> = ParamArgs<P> & MethodArg<P, M> & QueryArg<QueryOfHandler<HandlerOf<P, M>>> & BodyArg<M, BodyOfHandler<HandlerOf<P, M>>> & {
111
+ type FetchOptions<P extends string, M extends HttpMethod> = ParamArgs<P> & MethodArg<M> & QueryArg<QueryOfHandler<HandlerOf<P, M>>> & BodyArg<M, BodyOfHandler<HandlerOf<P, M>>> & {
112
112
  headers?: HeadersInit;
113
113
  signal?: AbortSignal;
114
114
  };
package/dist/paths.js CHANGED
@@ -19,10 +19,13 @@ export function routePatterns(file) {
19
19
  throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
20
20
  if (optional.length > 1)
21
21
  throw new Error(`fondu: routes/${file} has ${optional.length} optional segments; one at most`);
22
- // href()'s options, next to the params
23
- const reserved = segments.find((s) => /^\[{1,2}(?:\.\.\.)?(?:query|hash)\]{1,2}$/.test(s));
24
- if (reserved)
25
- throw new Error(`fondu: routes/${file}: a param can't be named ${reserved.replace(/[[\].]/g, '')} (href()'s query and hash); rename it`);
22
+ // the options of href() and fetch(), next to the params
23
+ for (const segment of segments) {
24
+ const name = /^\[{1,2}(?:\.\.\.)?(\w+)\]{1,2}$/.exec(segment)?.[1];
25
+ const api = name && RESERVED[name];
26
+ if (api)
27
+ throw new Error(`fondu: routes/${file}: a param can't be named ${name} (${api}'s option); rename the file's [${name}]`);
28
+ }
26
29
  const pattern = (withOptional) => '/' +
27
30
  segments
28
31
  .filter((s) => withOptional || !optional.includes(s))
@@ -33,6 +36,15 @@ export function routePatterns(file) {
33
36
  .join('/');
34
37
  return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
35
38
  }
39
+ /** the names a param can't have, and the function whose option each is: `href()`'s and `fetch()`'s */
40
+ const RESERVED = Object.assign(Object.create(null), {
41
+ query: 'href()',
42
+ hash: 'href()',
43
+ method: 'fetch()',
44
+ body: 'fetch()',
45
+ headers: 'fetch()',
46
+ signal: 'fetch()',
47
+ });
36
48
  const ROUTE_EXTENSION = /\.(?:tsx?|mdx)$/;
37
49
  /**
38
50
  * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
@@ -1,5 +1,19 @@
1
1
  import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
2
2
  import { isPrerendering } from './http.js';
3
+ /**
4
+ * A param's value becomes a file name (`/items/:id` → `items/<id>.html`): not a path of its own. A `/` or a `\`
5
+ * in it (Windows' separator) would make a directory of it, or leave the build's directory (`../../x`); a catch-all
6
+ * is the path of its segments, each of which is a name. Throws, naming the value.
7
+ */
8
+ function fileNames(pattern, params) {
9
+ for (const [, name, catchAll] of pattern.matchAll(/:(\w+)(\{[^}]*\})?/g)) {
10
+ const value = String(params[name]);
11
+ for (const part of catchAll ? value.split('/') : [value])
12
+ if (part === '.' || part === '..' || part.includes('\\') || (!catchAll && part.includes('/')))
13
+ throw new Error(`param "${name}" is ${JSON.stringify(value)}: a prerendered URL is a file, and its names have no ` +
14
+ `separators (/ or \\) and are not . or ..`);
15
+ }
16
+ }
3
17
  /** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
4
18
  export async function prerenderPaths(routes) {
5
19
  const paths = new Set();
@@ -28,8 +42,11 @@ export async function prerenderPaths(routes) {
28
42
  continue;
29
43
  }
30
44
  try {
31
- for (const params of await setting())
32
- add(fillPattern(route.pattern, params));
45
+ for (const params of await setting()) {
46
+ const path = fillPattern(route.pattern, params);
47
+ fileNames(route.pattern, params);
48
+ add(path);
49
+ }
33
50
  }
34
51
  catch (error) {
35
52
  problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
@@ -135,10 +135,13 @@ function askedFor(c, id) {
135
135
  !isPageRequest(c) ||
136
136
  c.req.header('x-fondu-component') !== id)
137
137
  return;
138
- return only
139
- .split(',')
140
- .map((name) => name.trim())
141
- .filter(Boolean);
138
+ // each name once, in the order first given: a name asked twice does not run its loader twice
139
+ return [
140
+ ...new Set(only
141
+ .split(',')
142
+ .map((name) => name.trim())
143
+ .filter(Boolean)),
144
+ ];
142
145
  }
143
146
  /** an http(s) URL, as `to` resolves from the request's */
144
147
  function webUrl(c, to) {
@@ -150,17 +153,22 @@ function webUrl(c, to) {
150
153
  }
151
154
  }
152
155
  // ---- the protocol middleware (installed by createApp)
156
+ /**
157
+ * Every header that selects what a navigation answers: the page object (`X-Fondu`), the 409 of an old build
158
+ * (`X-Fondu-Version`), a partial answer (`X-Fondu-Only`, for `X-Fondu-Component`'s page)
159
+ */
160
+ const NAVIGATION_VARY = 'X-Fondu, X-Fondu-Version, X-Fondu-Only, X-Fondu-Component';
153
161
  const versionCheck = async (c, next) => {
154
162
  // a navigation of a client built from other assets: the page loads as a document
155
163
  if (version &&
156
164
  c.req.method === 'GET' &&
157
165
  isPageRequest(c) &&
158
166
  c.req.header('x-fondu-version') !== version) {
159
- return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: 'X-Fondu' });
167
+ return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: NAVIGATION_VARY });
160
168
  }
161
169
  await next();
162
170
  // a URL answers a navigation and a document differently: caches keep them apart
163
- appendHeader(c, 'Vary', isPageRequest(c) ? 'X-Fondu, X-Fondu-Only' : 'X-Fondu');
171
+ appendHeader(c, 'Vary', isPageRequest(c) ? NAVIGATION_VARY : 'X-Fondu');
164
172
  // an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
165
173
  // isn't read to tell (a stream's would be, to its end)
166
174
  if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
@@ -65,7 +65,7 @@ export function routeTable(modules, append) {
65
65
  : 'Move one, or list the values of a param: `export const params = { name: [...] }`'));
66
66
  byKey.set(key, route);
67
67
  }
68
- return routes.sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
68
+ return routes.sort((a, b) => compare(a.pattern, b.pattern));
69
69
  }
70
70
  function paramsOf(file, mod) {
71
71
  const params = mod?.params;
@@ -81,8 +81,23 @@ function paramsOf(file, mod) {
81
81
  }
82
82
  // a catch-all takes the rest of the path: never a trailing slash
83
83
  const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('{.+}') ? pattern + '/' : pattern;
84
- /** sort key: static segments, then params with listed values, then params, then catch-alls */
85
- const rank = (pattern) => pattern
86
- .split('/')
87
- .map((s) => (s.endsWith('{.+}') ? '3' : s.includes('{') ? '1' : s.startsWith(':') ? '2' : '0') + s)
88
- .join('/');
84
+ /** a segment's specificity: static, then a param with listed values, then a param, then a catch-all */
85
+ const priority = (s) => s.endsWith('{.+}') ? 3 : s.includes('{') ? 1 : s.startsWith(':') ? 2 : 0;
86
+ /**
87
+ * Hono's order: the specificity of each segment, from the first (static segments of another spelling are other
88
+ * URLs: alphabetical); a param's name decides only between patterns equally specific at every segment, so
89
+ * renaming a param never changes which route answers
90
+ */
91
+ function compare(a, b) {
92
+ const x = a.split('/');
93
+ const y = b.split('/');
94
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
95
+ const d = priority(x[i]) - priority(y[i]);
96
+ if (d)
97
+ return d;
98
+ // two static segments that differ: the routes are apart, any order is right (the alphabetical one is steady)
99
+ if (priority(x[i]) === 0 && x[i] !== y[i])
100
+ return x[i] < y[i] ? -1 : 1;
101
+ }
102
+ return x.length - y.length || (a < b ? -1 : a > b ? 1 : 0);
103
+ }
@@ -32,3 +32,5 @@ 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;
@@ -131,7 +131,8 @@ function dependencies(root = '') {
131
131
  * Node / Bun: the server build's entry, dist/server/index.js. The client build's files first (found next to the
132
132
  * server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
133
133
  * on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
134
- * serves the default export itself and reads `PORT` (with the app's `websocket`, if it has one).
134
+ * serves the default export itself, on `PORT` (else the option; Bun's own default without one), with the app's
135
+ * `websocket`, if it has one.
135
136
  * With `prerender`, the pages the build wrote are served from their files first, with the headers it decided
136
137
  * (`prerender.json`, next to this entry).
137
138
  */
@@ -154,44 +155,51 @@ function serverEntry(options) {
154
155
  .filter((e) => e.name !== '.vite')
155
156
  .map((e) => (e.isDirectory() ? `/${e.name}/*` : `/${e.name}`))
156
157
  : [];
157
- const bun = options.target === 'bun';
158
- return [
159
- `import { Hono } from 'hono'`,
160
- `import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
161
- `import { fileURLToPath } from 'node:url'`,
162
- `import app from '${SERVER.slice(1)}'`,
163
- `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
164
- `const main = new Hono()`,
165
- `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
166
- // prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
167
- // this server was built: not there while the build prerenders, so the app renders them then)
168
- ...(options.prerender
169
- ? [
170
- `import { existsSync, readFileSync } from 'node:fs'`,
171
- `import { staticPages } from ${JSON.stringify(staticModule)}`,
172
- `const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
173
- `if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
174
- ]
175
- : []),
176
- ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
177
- `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
178
- ...(bun
179
- ? [
180
- `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`,
181
- ]
182
- : [
183
- `import { serve } from '@hono/node-server'`,
184
- `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
185
- `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
186
- `process.on('SIGINT', shutdown)`,
187
- `process.on('SIGTERM', shutdown)`,
188
- `export default main`,
189
- ]),
190
- ].join('\n');
158
+ return entryCode(options, paths);
191
159
  },
192
160
  },
193
161
  };
194
162
  }
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) {
165
+ const bun = options.target === 'bun';
166
+ 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)}'`,
171
+ `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
172
+ `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
+ // prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
175
+ // this server was built: not there while the build prerenders, so the app renders them then)
176
+ ...(options.prerender
177
+ ? [
178
+ `import { existsSync, readFileSync } from 'node:fs'`,
179
+ `import { staticPages } from ${JSON.stringify(staticModule)}`,
180
+ `const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
181
+ `if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
182
+ ]
183
+ : []),
184
+ ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
185
+ `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
186
+ ...(bun
187
+ ? [
188
+ // Bun serves the default export: its `port` (`PORT` first, as on Node), else Bun's own default (PORT, 3000)
189
+ options.port === undefined
190
+ ? `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`
191
+ : `export default { fetch: main.fetch, port: Number(process.env.PORT) || ${Number(options.port)}, ...(app.websocket && { websocket: app.websocket }) }`,
192
+ ]
193
+ : [
194
+ `import { serve } from '@hono/node-server'`,
195
+ `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
196
+ `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
197
+ `process.on('SIGINT', shutdown)`,
198
+ `process.on('SIGTERM', shutdown)`,
199
+ `export default main`,
200
+ ]),
201
+ ].join('\n');
202
+ }
195
203
  function runtimePlugins(options) {
196
204
  return [
197
205
  {
@@ -38,6 +38,17 @@ export declare function prerender(start: () => Promise<Server>, clientDir: strin
38
38
  }): Promise<undefined>;
39
39
  /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
40
40
  export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
41
- /** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
42
- export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;
41
+ /** how long the built server may take to answer, in ms: to start (a wall-clock deadline), and each request, its body read included */
42
+ export interface Deadlines {
43
+ startup: number;
44
+ request: number;
45
+ }
46
+ /**
47
+ * Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
48
+ * until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
49
+ * child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
50
+ */
51
+ export declare const nodeServer: (root: string, runtime: string, { startup, request }?: Deadlines) => () => Promise<Server>;
52
+ /** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
53
+ export declare function outputProblems(paths: string[], dir: string): string[];
43
54
  export {};
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { createServer } from 'node:net';
6
- import { dirname, join, resolve } from 'node:path';
6
+ import { dirname, join, resolve, sep } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { PAGE_DATA, staticFiles } from '../paths.js';
9
9
  /** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
@@ -101,6 +101,10 @@ export async function prerender(start, clientDir, logger, where) {
101
101
  logger.warn('fondu: prerender is on, and no route has `export const prerender`');
102
102
  return;
103
103
  }
104
+ // every file to write, known before the first: all inside the client directory, none two pages' (or a directory)
105
+ const unsafe = outputProblems(paths, clientDir);
106
+ if (unsafe.length)
107
+ return fail(unsafe);
104
108
  let security;
105
109
  const errors = [];
106
110
  for (const path of paths) {
@@ -145,6 +149,12 @@ export async function prerender(start, clientDir, logger, where) {
145
149
  writeFileSync(file, withHeaderRules(own, security ?? {}));
146
150
  }
147
151
  }
152
+ catch (error) {
153
+ // a request, or the read of its body, that did not finish: the deadline of the server's fetch
154
+ if (timedOut(error))
155
+ fail([`the server did not finish an answer in time (${error.message})`]);
156
+ throw error;
157
+ }
148
158
  finally {
149
159
  await server.dispose();
150
160
  }
@@ -167,35 +177,56 @@ export const worker = (root, workerConfig) => async () => {
167
177
  await started.ready;
168
178
  return {
169
179
  // a Worker that throws as it starts: wrangler logs it, then its requests never answer
180
+ // the signal covers the body's read too, as the Node / Bun server's does (the timer below, its headers only)
170
181
  fetch: (path, headers = {}) => {
171
182
  let timer;
172
183
  const late = new Promise((_, reject) => {
173
184
  timer = setTimeout(() => reject(new Error(`the Worker did not answer ${path} (an error above?)`)), 60_000);
174
185
  });
175
186
  return Promise.race([
176
- started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
187
+ started.fetch(new URL(path, 'http://localhost').href, {
188
+ headers,
189
+ redirect: 'manual',
190
+ signal: AbortSignal.timeout(60_000),
191
+ }),
177
192
  late,
178
193
  ]).finally(() => clearTimeout(timer));
179
194
  },
180
195
  dispose: () => started.dispose(),
181
196
  };
182
197
  };
183
- /** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
184
- export const nodeServer = (root, runtime) => async () => {
198
+ /** a failed request: the server did not answer in time (the timeout and the abort of a signal are DOMExceptions) */
199
+ const timedOut = (error) => error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError');
200
+ /**
201
+ * Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
202
+ * until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
203
+ * child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
204
+ */
205
+ export const nodeServer = (root, runtime, { startup, request } = { startup: 30_000, request: 60_000 }) => async () => {
185
206
  const port = await freePort();
186
207
  const child = spawn(runtime, ['dist/server/index.js'], {
187
208
  cwd: root,
188
209
  env: { ...process.env, PORT: String(port), FONDU_PRERENDER: '1', NODE_ENV: 'production' },
189
210
  stdio: ['ignore', 'pipe', 'pipe'],
190
211
  });
212
+ // the last of what it wrote: the reason it gives for failing to start, not all of what a long build writes
191
213
  let output = '';
192
- child.stdout.on('data', (d) => (output += d));
193
- child.stderr.on('data', (d) => (output += d));
214
+ const keep = (d) => (output = (output + d).slice(-16_384));
215
+ child.stdout.on('data', keep);
216
+ child.stderr.on('data', keep);
217
+ // a child that cannot be spawned (no such executable) emits `error`, and, unhandled, that ends the build's process
218
+ let spawnError;
219
+ child.on('error', (error) => (spawnError = error));
194
220
  const base = `http://127.0.0.1:${port}`;
221
+ const gone = () => child.exitCode !== null || child.signalCode !== null || spawnError;
195
222
  const server = {
196
- fetch: (path, headers = {}) => fetch(base + path, { headers, redirect: 'manual' }),
223
+ fetch: (path, headers = {}) => fetch(base + path, {
224
+ headers,
225
+ redirect: 'manual',
226
+ signal: AbortSignal.timeout(request),
227
+ }),
197
228
  dispose: async () => {
198
- if (child.exitCode !== null)
229
+ if (gone())
199
230
  return;
200
231
  const exited = new Promise((r) => child.once('exit', r));
201
232
  child.kill();
@@ -204,17 +235,32 @@ export const nodeServer = (root, runtime) => async () => {
204
235
  clearTimeout(force);
205
236
  },
206
237
  };
207
- for (let tries = 0;; tries++) {
208
- if (child.exitCode !== null || tries === 200)
209
- throw new Error(`the server (${runtime} dist/server/index.js) did not start:\n${output.trim()}`);
210
- try {
211
- await fetch(base + '/__fondu/prerender');
212
- return server;
213
- }
214
- catch {
215
- await new Promise((r) => setTimeout(r, 50));
238
+ try {
239
+ const deadline = Date.now() + startup;
240
+ for (;;) {
241
+ if (spawnError)
242
+ throw new Error(`the server (${runtime} dist/server/index.js) did not start: ${spawnError.message}`);
243
+ if (child.exitCode !== null || child.signalCode !== null || Date.now() >= deadline)
244
+ throw new Error(`the server (${runtime} dist/server/index.js) did not start${gone() ? '' : `: no answer within ${startup / 1000} s`}:\n${output.trim()}`);
245
+ try {
246
+ // an answer, any, or the next try: a server that takes the connection and sends nothing is one try
247
+ const left = Math.max(1, deadline - Date.now());
248
+ const res = await fetch(base + '/__fondu/prerender', {
249
+ redirect: 'manual',
250
+ signal: AbortSignal.timeout(Math.min(2000, left)),
251
+ });
252
+ await res.body?.cancel();
253
+ return server;
254
+ }
255
+ catch {
256
+ await new Promise((r) => setTimeout(r, 50));
257
+ }
216
258
  }
217
259
  }
260
+ catch (error) {
261
+ await server.dispose();
262
+ throw error;
263
+ }
218
264
  };
219
265
  const freePort = () => new Promise((resolve, reject) => {
220
266
  const s = createServer();
@@ -224,7 +270,47 @@ const freePort = () => new Promise((resolve, reject) => {
224
270
  s.close(() => resolve(port));
225
271
  });
226
272
  });
273
+ /** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
274
+ export function outputProblems(paths, dir) {
275
+ const problems = [];
276
+ const owner = new Map();
277
+ for (const path of paths) {
278
+ let files;
279
+ try {
280
+ files = Object.values(staticFiles(path));
281
+ }
282
+ catch {
283
+ problems.push(`${path}: not a valid URL path (it does not decode)`);
284
+ continue;
285
+ }
286
+ for (const file of files) {
287
+ if (file.includes('\\') || !inside(dir, file)) {
288
+ problems.push(`${path}: its file (${JSON.stringify(file)}) is not inside the build's directory`);
289
+ continue;
290
+ }
291
+ const other = owner.get(file);
292
+ if (other !== undefined)
293
+ problems.push(`${path} and ${other} are the same file (${file})`);
294
+ else
295
+ owner.set(file, path);
296
+ }
297
+ }
298
+ // a page's file that is another's directory (`/a.html` is `a.html.html`, but `/a` is `a.html`: `/a.html/b` its child)
299
+ for (const [file, path] of owner)
300
+ for (let at = file.indexOf('/'); at !== -1; at = file.indexOf('/', at + 1)) {
301
+ const other = owner.get(file.slice(0, at));
302
+ if (other !== undefined)
303
+ problems.push(`${path} needs ${file.slice(0, at)} to be a directory, the file of ${other}`);
304
+ }
305
+ return problems;
306
+ }
307
+ const inside = (dir, file) => {
308
+ const to = resolve(dir, file);
309
+ return to.startsWith(resolve(dir) + sep);
310
+ };
227
311
  function write(dir, file, content) {
312
+ if (!inside(dir, file))
313
+ throw new Error(`fondu: ${JSON.stringify(file)} is not inside ${dir}`);
228
314
  const to = join(dir, file);
229
315
  mkdirSync(dirname(to), { recursive: true });
230
316
  writeFileSync(to, content);
@@ -79,16 +79,19 @@ function references(node, out = new Set(), scopes = []) {
79
79
  case 'FunctionDeclaration':
80
80
  case 'FunctionExpression':
81
81
  case 'ArrowFunctionExpression': {
82
- const scope = new Set();
82
+ // the parameters' scope (a function expression's own name, the parameters): what their default expressions
83
+ // see. The body's own declarations are another scope, inside it: a default never reaches them
84
+ const params = new Set();
83
85
  if (n.type === 'FunctionExpression')
84
- bound(n.id, []).forEach((x) => scope.add(x));
86
+ bound(n.id, []).forEach((x) => params.add(x));
85
87
  for (const p of n.params)
86
- bound(p).forEach((x) => scope.add(x));
87
- vars(n.body, scope);
88
+ bound(p).forEach((x) => params.add(x));
89
+ const body = new Set();
90
+ vars(n.body, body);
88
91
  if (n.body.type === 'BlockStatement')
89
- lexical(n.body.body, scope);
90
- visit(n.params, [...scopes, scope]);
91
- visit(n.body, [...scopes, scope]);
92
+ lexical(n.body.body, body);
93
+ visit(n.params, [...scopes, params]);
94
+ visit(n.body, [...scopes, params, body]);
92
95
  return out;
93
96
  }
94
97
  case 'ClassDeclaration':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.17.0",
3
+ "version": "0.18.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",