fondu 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 }) });
@@ -72,7 +77,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
72
77
  return;
73
78
  const answer = (async () => {
74
79
  try {
75
- const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
80
+ const response = await fetch(key, {
81
+ headers: { ...headers(), 'X-Fondu-Prefetch': 'true' },
82
+ // not in the way of the page's own requests
83
+ priority: 'low',
84
+ });
76
85
  if (response.status === 200 && response.headers.has('X-Fondu'))
77
86
  return { body: await response.text(), headers: response.headers };
78
87
  }
@@ -97,6 +106,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
97
106
  ask = async (names) => {
98
107
  const at = shows;
99
108
  const page = on;
109
+ const id = ++requests;
100
110
  const controller = new AbortController();
101
111
  asking.add(controller);
102
112
  // a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
@@ -115,7 +125,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
115
125
  });
116
126
  const answer = response.ok && response.headers.has('X-Fondu') ? (await response.json()) : null;
117
127
  if (answer?.component === page.component)
118
- got = Object.fromEntries(Object.entries(answer.props).filter(([key]) => names.includes(key)));
128
+ got = answer.props;
119
129
  }
120
130
  catch { } // offline, aborted
121
131
  asking.delete(controller);
@@ -124,9 +134,13 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
124
134
  // asked at the URL of a shallow entry, which the page has left since: not its answer
125
135
  if (page.url !== answered && page.url !== on.url)
126
136
  return;
137
+ // the props of this answer that no newer request has answered already
138
+ const take = names.filter((n) => got && Object.hasOwn(got, n) && id > (answers.get(n) ?? 0));
139
+ for (const n of take)
140
+ answers.set(n, id);
127
141
  const next = {
128
142
  ...on,
129
- props: { ...on.props, ...got },
143
+ props: { ...on.props, ...Object.fromEntries(take.map((n) => [n, got[n]])) },
130
144
  deferred: on.deferred?.filter((n) => !names.includes(n)),
131
145
  };
132
146
  on = next; // before the module is awaited: another answer merges into this one
@@ -136,8 +150,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
136
150
  group = new Set([scroll.key()]);
137
151
  answered = page.url;
138
152
  }
139
- await show(next, false, () => shows !== at);
140
- if (shows === at)
153
+ // not once another answer has merged into the page since: its own show() has these props too
154
+ const stale = () => shows !== at || on !== next;
155
+ await show(next, false, stale);
156
+ if (!stale())
141
157
  keep(next);
142
158
  };
143
159
  /** a document load: in place of this entry, or after it */
@@ -251,6 +267,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
251
267
  const page = (await response.json());
252
268
  if (signal.aborted)
253
269
  return;
270
+ // A prerendered page's file is made without a query. Its answer, not redirected, is for the URL asked: the
271
+ // visitor's query stays (as at a document load); a redirect, which the server made, is its target's
272
+ if (!response.redirected && page.url === url.pathname)
273
+ page.url += url.search;
254
274
  if (version && page.version && page.version !== version)
255
275
  return documentLoad(page.url, options.history !== 'push');
256
276
  version = page.version;
@@ -366,7 +386,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
366
386
  const link = target?.closest?.('a[href]');
367
387
  if (!(link instanceof HTMLAnchorElement))
368
388
  return;
369
- if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
389
+ // its own `target`, else the document's `<base target>`; SVG `<a>` and `<area>` are not matched: the browser's
390
+ const into = link.target || document.querySelector('base[target]')?.target;
391
+ if ((into && into !== '_self') || link.hasAttribute('download'))
370
392
  return;
371
393
  const url = new URL(link.href);
372
394
  if (url.origin !== location.origin || !isWebUrl(url.href))
@@ -443,6 +465,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
443
465
  const url = new URL(attr('action', 'formaction') || location.href, location.href);
444
466
  if (url.origin !== location.origin || !isWebUrl(url.href))
445
467
  return;
468
+ // a GET to a URL that is none of the app's pages (a `.ts` route): the browser's, as for a link; asking first would
469
+ // run its handler twice
470
+ if (method === 'get' && !isPage(url.pathname))
471
+ return;
446
472
  event.preventDefault();
447
473
  const data = new FormData(form, submitter);
448
474
  // as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
@@ -463,11 +489,13 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
463
489
  window.addEventListener('popstate', (event) => {
464
490
  closing = false;
465
491
  const popped = scroll.pop(event.state);
492
+ // a visit on its way is given up by any Back or Forward, the browser's own #fragment entries too: its answer
493
+ // would put a page on the screen over the entry the visitor is at
494
+ current?.abort();
495
+ pending(null);
466
496
  // 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
497
+ // is
468
498
  if (!popped.fragment && popped.key && group.has(popped.key)) {
469
- current?.abort();
470
- pending(null);
471
499
  scroll.commit();
472
500
  return settle(false);
473
501
  }
@@ -527,12 +555,28 @@ let closing = false;
527
555
  /**
528
556
  * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
529
557
  * 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.
558
+ * the browser has started a traversal away from it. The last 50 are kept (the page cache's number), their keys in
559
+ * the order they were used in `STORAGE` itself; an entry replaced by another page forgets its own.
531
560
  */
532
561
  function scrollPositions() {
533
562
  const KEY = SCROLL_KEY;
534
563
  const STORAGE = SCROLL_STORAGE;
535
564
  const positions = new Map();
565
+ const forget = (key) => {
566
+ positions.delete(key);
567
+ try {
568
+ sessionStorage.removeItem(STORAGE + key);
569
+ }
570
+ catch { }
571
+ };
572
+ /** the most recently used last: the oldest beyond 50 are forgotten */
573
+ const remember = (key, position) => {
574
+ positions.delete(key);
575
+ positions.set(key, position);
576
+ for (const old of positions.keys())
577
+ if (positions.size > 50)
578
+ forget(old);
579
+ };
536
580
  const keyOf = (state) => state &&
537
581
  typeof state === 'object' &&
538
582
  typeof state[KEY] === 'string'
@@ -559,9 +603,10 @@ function scrollPositions() {
559
603
  if (!rendered)
560
604
  return;
561
605
  const position = { x: scrollX, y: scrollY };
562
- positions.set(rendered, position);
606
+ remember(rendered, position);
563
607
  try {
564
608
  sessionStorage.setItem(STORAGE + rendered, JSON.stringify(position));
609
+ sessionStorage.setItem(STORAGE, JSON.stringify([...positions.keys()]));
565
610
  }
566
611
  catch { }
567
612
  };
@@ -575,7 +620,7 @@ function scrollPositions() {
575
620
  frame = requestAnimationFrame(() => {
576
621
  frame = 0;
577
622
  if (rendered === key)
578
- positions.set(key, { x: scrollX, y: scrollY });
623
+ remember(key, { x: scrollX, y: scrollY });
579
624
  });
580
625
  }, { passive: true });
581
626
  /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to): true if so */
@@ -599,29 +644,43 @@ function scrollPositions() {
599
644
  */
600
645
  start() {
601
646
  history.scrollRestoration = 'manual';
647
+ // the positions saved before this document (the last 50, as left), in their order
648
+ try {
649
+ for (const key of JSON.parse(sessionStorage.getItem(STORAGE) ?? '[]')) {
650
+ const saved = read(key);
651
+ if (saved)
652
+ positions.set(key, saved);
653
+ }
654
+ }
655
+ catch { }
602
656
  commit();
603
657
  return read(rendered);
604
658
  },
605
659
  /**
606
660
  * The page on the screen, at `url`: a new entry or this one. `shallow`: by a shallow navigation, which marks a
607
661
  * 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.
662
+ * shallow, takes the mark away: `closeShallow()` there must not go Back off it. A replaced entry is the same
663
+ * entry (its key stays) for a shallow navigation and an answer at its URL; another page is a new one, and
664
+ * nothing can visit the entry it replaced.
609
665
  */
610
666
  write(url, replace, shallow = false) {
667
+ const to = new URL(url, location.href);
668
+ // the same URL (a form's answer, reload()): the same overlay
669
+ const same = to.pathname + to.search === location.pathname + location.search;
670
+ const old = keyOf(history.state);
671
+ const kept = replace && old && (shallow || same);
611
672
  const state = {
612
673
  ...(replace ? history.state : {}),
613
- [KEY]: newKey(),
674
+ [KEY]: kept ? old : newKey(),
614
675
  };
676
+ if (replace && old && !kept)
677
+ forget(old);
615
678
  if (shallow) {
616
679
  if (!replace)
617
680
  state[SHALLOW] = true;
618
681
  }
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
- }
682
+ else if (!same)
683
+ delete state[SHALLOW]; // another page: not a shallow entry
625
684
  if (replace)
626
685
  history.replaceState(state, '', url);
627
686
  else
@@ -700,6 +759,11 @@ const isWebUrl = (url) => {
700
759
  return false;
701
760
  }
702
761
  };
762
+ /** `javascript:` is never handed to `location`: the page's CSP would be all that stops it (the URL parser drops leading space, lowers the scheme) */
763
+ function refuseScript(url) {
764
+ if (url.protocol === 'javascript:')
765
+ throw new Error('fondu: refusing to load a javascript: URL');
766
+ }
703
767
  /** a Content-Disposition's file name: `filename*=UTF-8''…` (RFC 6266), else `filename="…"`; '' for none */
704
768
  function fileName(disposition) {
705
769
  const encoded = /filename\*\s*=\s*UTF-8''([^;\s]+)/i.exec(disposition)?.[1];
@@ -716,6 +780,7 @@ function fileName(disposition) {
716
780
  * can't change in place (`<html lang>`: another language).
717
781
  */
718
782
  export function loadDocument(href) {
783
+ refuseScript(new URL(href, location.href));
719
784
  location.assign(href);
720
785
  }
721
786
  /**
@@ -737,6 +802,7 @@ export function navigate(href, options = {}) {
737
802
  const shown = shownUrl?.();
738
803
  // a shallow navigation is relative to the page on the screen, whose URL `location` may have left
739
804
  const url = new URL(href, shallow ? (shown ?? location.href) : location.href);
805
+ refuseScript(url);
740
806
  if (shallow) {
741
807
  if (url.origin !== location.origin || url.pathname !== (shown ?? location).pathname)
742
808
  throw new Error(`fondu: a shallow navigation stays on this page (its query, its #fragment); ${url.origin === location.origin ? url.pathname : url.href} is another page: leave out \`shallow\``);
package/dist/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/form.d.ts CHANGED
@@ -12,7 +12,8 @@ export declare const crlf: (text: string) => string;
12
12
  * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
13
13
  * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
14
14
  * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
15
- * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
15
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32) and for more than 10,000 entries
16
+ * (files and empty file inputs count).
16
17
  */
17
18
  export declare function formObject(entries: Iterable<Entry>): Record<string, unknown>;
18
19
  /** A Standard Schema's issue, the part used here */
package/dist/form.js CHANGED
@@ -4,6 +4,8 @@
4
4
  */
5
5
  /** how deep form field names nest (`a[b][c]`: 3) */
6
6
  const DEPTH = 32;
7
+ /** how many entries (fields, files, empty file inputs too) a form may have */
8
+ const ENTRIES = 10_000;
7
9
  /** a body that can't be one object: a 400 on the server */
8
10
  export class MalformedForm extends Error {
9
11
  }
@@ -13,17 +15,22 @@ export const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
13
15
  * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
14
16
  * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
15
17
  * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
16
- * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
18
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32) and for more than 10,000 entries
19
+ * (files and empty file inputs count).
17
20
  */
18
21
  export function formObject(entries) {
19
22
  const body = Object.create(null);
20
23
  // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
21
24
  const next = new WeakMap();
22
25
  const isObject = (v) => typeof v === 'object' && !isFile(v) && !Array.isArray(v);
26
+ let count = 0;
23
27
  for (const [key, value] of entries) {
28
+ if (++count > ENTRIES)
29
+ throw new MalformedForm(`more than ${ENTRIES} fields`);
24
30
  if (typeof value !== 'string' && value.size === 0 && value.name === '')
25
31
  continue;
26
- const path = key.replace(/\]/g, '').split('[');
32
+ // a limit: a name that is too deep is known from its first parts, the rest is not split
33
+ const path = key.replace(/\]/g, '').split('[', DEPTH + 1);
27
34
  if (path.length > DEPTH)
28
35
  throw new MalformedForm(`a field name nests deeper than ${DEPTH}`);
29
36
  if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
package/dist/paths.d.ts CHANGED
@@ -59,3 +59,8 @@ export declare function staticFiles(path: string): {
59
59
  html: string;
60
60
  json: string;
61
61
  };
62
+ /**
63
+ * Throws if a route file (`file`, relative to `routes/`) exports a name it may not. The server checks it at startup
64
+ * (the exports of the loaded module), the build too (the names in the source): one message.
65
+ */
66
+ export declare function checkExportNames(file: string, names: readonly string[]): void;
package/dist/paths.js CHANGED
@@ -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
@@ -134,3 +146,51 @@ export function staticFiles(path) {
134
146
  json: decodeURIComponent(pageDataPath(path)).slice(1),
135
147
  };
136
148
  }
149
+ /**
150
+ * What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
151
+ * page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
152
+ * HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
153
+ */
154
+ function exportsOf(file) {
155
+ const name = file.split('/').at(-1);
156
+ if (name === '_middleware.ts')
157
+ return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
158
+ if (/^_(?:layout|error)\.tsx$/.test(name))
159
+ return { allowed: ['default'], hint: 'its component only (default)' };
160
+ if (file.endsWith('.mdx'))
161
+ return {
162
+ allowed: [],
163
+ hint: "its content: an MDX page has no handlers (a _middleware.ts's prerender, params)",
164
+ };
165
+ if (file.endsWith('.ts'))
166
+ return {
167
+ allowed: [...METHODS, ...CONFIG],
168
+ hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
169
+ };
170
+ return {
171
+ allowed: ['default', ...HANDLERS, ...CONFIG],
172
+ hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
173
+ };
174
+ }
175
+ /** what a page's handler is called in a `.ts` file */
176
+ const INSTEAD = {
177
+ loader: 'in a .ts file it is `GET`',
178
+ action: 'in a .ts file it is `POST`',
179
+ actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
180
+ };
181
+ /**
182
+ * Throws if a route file (`file`, relative to `routes/`) exports a name it may not. The server checks it at startup
183
+ * (the exports of the loaded module), the build too (the names in the source): one message.
184
+ */
185
+ export function checkExportNames(file, names) {
186
+ const { allowed, hint } = exportsOf(file);
187
+ const mdx = file.endsWith('.mdx');
188
+ const extra = names.filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
189
+ if (!extra.length)
190
+ return;
191
+ const renamed = file.endsWith('.ts')
192
+ ? extra.filter((k) => k in INSTEAD)
193
+ : [];
194
+ throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
195
+ (renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
196
+ }
@@ -5,7 +5,7 @@ import { type DocumentTemplate } from './document.js';
5
5
  export interface CreateAppOptions {
6
6
  /** the HTML document around pages (default: a minimal one) */
7
7
  document?: DocumentTemplate;
8
- /** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): Hono's trailing-slash middleware */
8
+ /** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): a 301 to a relative URL */
9
9
  trailingSlash?: 'trim' | 'append';
10
10
  /** `hono/csrf`'s options; `false`: off */
11
11
  csrf?: Parameters<typeof csrf>[0] | false;
@@ -33,7 +33,8 @@ export declare function checkExports(file: string, mod: Record<string, unknown>)
33
33
  * `action`, `actions`: those are a page's)
34
34
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
35
35
  * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page, and a request body
36
- * limit (413, after the root `_middleware.ts`, so its error page has the shared props; CSRF's 403 is plain text).
36
+ * limit (413, in each route that takes a body, after its directories' `_middleware.ts`, so its error page has the
37
+ * shared props; CSRF's 403 is plain text).
37
38
  * Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
38
39
  */
39
40
  export declare function createApp(options?: CreateAppOptions): Hono;