fondu 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { schemasOf } from './server/handler.js';
1
+ import type { TypedResponse } from 'hono';
2
+ import type { StatusCode } from 'hono/utils/http-status';
3
+ import type { answerOf, schemasOf } from './server/handler.js';
2
4
  import type { Routes } from './types.js';
3
5
  type Keys = keyof Routes & string;
4
6
  type Actions = {
@@ -22,9 +24,10 @@ type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extend
22
24
  } ? G : never : never;
23
25
  /** a query value: what its schema takes (`unknown`, as a coercing schema's input: any) */
24
26
  type QueryValue = string | number | boolean | null | undefined;
25
- type QueryOf<P extends string> = HandlersOf<P> extends {
27
+ /** the query a handler's schema takes (a `withValidator` handler; any query otherwise) */
28
+ type QueryOfHandler<H> = [H] extends [{
26
29
  readonly [schemasOf]?: infer S;
27
- } ? S extends {
30
+ }] ? S extends {
28
31
  query: {
29
32
  '~standard': {
30
33
  types?: infer T;
@@ -35,17 +38,22 @@ type QueryOf<P extends string> = HandlersOf<P> extends {
35
38
  } ? {
36
39
  [K in keyof I]: unknown extends I[K] ? QueryValue : I[K];
37
40
  } : Record<string, QueryValue> : Record<string, QueryValue> : Record<string, QueryValue>;
41
+ type QueryOf<P extends string> = QueryOfHandler<HandlersOf<P>>;
42
+ /** `query`, required when its schema requires a field */
43
+ type QueryArg<Q> = {} extends Q ? {
44
+ query?: Q;
45
+ } : {
46
+ query: Q;
47
+ };
38
48
  /** `query` is required when its schema requires a field */
39
49
  type Extra<P extends string> = {
40
50
  hash?: string;
41
- } & ({} extends QueryOf<P> ? {
42
- query?: QueryOf<P>;
43
- } : {
44
- query: QueryOf<P>;
45
- });
46
- type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
51
+ } & QueryArg<QueryOf<P>>;
52
+ /** the params of a URL pattern, as the options take them */
53
+ type ParamArgs<P extends string> = {
47
54
  [K in ParamNames<P>]: string | number;
48
- } & Extra<P>];
55
+ };
56
+ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: ParamArgs<P> & Extra<P>];
49
57
  /**
50
58
  * Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
51
59
  * one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
@@ -53,7 +61,85 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends Query
53
61
  * `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
54
62
  */
55
63
  export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
56
- export { usePage, useNavigation, reload, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
64
+ export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
57
65
  export { useForm } from './client/form.js';
58
66
  export { loadDocument, navigate, type Page } from './client/navigation.js';
59
67
  export type { ProgressOptions } from './client/progress.js';
68
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
69
+ /** no generated types (or none of routes): everything is loose, as `Href` is */
70
+ type Loose = string extends Keys ? true : [Keys] extends [never] ? true : false;
71
+ /** the HTTP methods a route file exports (a page has none) */
72
+ type MethodsOf<P extends string> = Loose extends true ? HttpMethod : P extends Keys ? keyof Routes[P] & HttpMethod : never;
73
+ /**
74
+ * The URL patterns of route files that export an HTTP method (`.ts` files). A page's pattern is not one: a page's
75
+ * data is its props (its loader, `defer()`), and `fetch()` is for effects and events.
76
+ */
77
+ export type ApiPath = Loose extends true ? string : {
78
+ [P in Keys]: [MethodsOf<P>] extends [never] ? never : P;
79
+ }[Keys];
80
+ /** the handler of the route's method */
81
+ type HandlerOf<P extends string, M extends string> = Loose extends true ? unknown : P extends Keys ? Routes[P] extends {
82
+ [K in M]: infer H;
83
+ } ? H : never : never;
84
+ /** what the handler's `withValidator` body schema takes (any JSON when it has none) */
85
+ type BodyOfHandler<H> = [H] extends [{
86
+ readonly [schemasOf]?: infer S;
87
+ }] ? S extends {
88
+ body: {
89
+ '~standard': {
90
+ types?: infer T;
91
+ };
92
+ };
93
+ } ? NonNullable<T> extends {
94
+ input: infer I;
95
+ } ? I : unknown : unknown : unknown;
96
+ type BodyArg<M extends string, B> = M extends 'GET' ? {
97
+ body?: never;
98
+ } : {} extends B ? {
99
+ body?: B;
100
+ } : undefined extends B ? {
101
+ body?: B;
102
+ } : {
103
+ body: B;
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> ? {
107
+ method?: M;
108
+ } : {
109
+ method: M;
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>>> & {
112
+ headers?: HeadersInit;
113
+ signal?: AbortSignal;
114
+ };
115
+ /** the options are optional when nothing is required: no params, no `body`, `query` or `method` to give */
116
+ export type FetchArgs<P extends string, M extends HttpMethod> = {} extends FetchOptions<P, M> ? [options?: FetchOptions<P, M>] : [options: FetchOptions<P, M>];
117
+ /** what a handler returns, in the type: a `defineHandler(...)` tuple, a `withValidator` handler, a function */
118
+ type ReturnedBy<H> = typeof answerOf extends keyof H ? NonNullable<H[typeof answerOf & keyof H]> : H extends readonly [...unknown[], infer Last] ? Returned<Last> : Returned<H>;
119
+ type Returned<F> = F extends (...args: never[]) => infer R ? Exclude<Awaited<R>, void> : unknown;
120
+ /**
121
+ * The answer as JSON delivers it: Hono's `c.json(data)` is a `TypedResponse` whose data is already what JSON makes of
122
+ * it (a `Date` is a string, `undefined` fields are dropped). Any other answer (text, a redirect, a body, or a
123
+ * branch that is not `c.json`) is `unknown`.
124
+ */
125
+ type AnswerOfResponse<R> = [R] extends [never] ? unknown : [R] extends [TypedResponse<unknown, StatusCode, 'json'>] ? R extends TypedResponse<infer T, StatusCode, 'json'> ? T : never : unknown;
126
+ export type AnswerOf<P extends string, M extends string> = Loose extends true ? unknown : AnswerOfResponse<ReturnedBy<HandlerOf<P, M>>>;
127
+ /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
128
+ export declare class FetchError extends Error {
129
+ readonly status: number;
130
+ readonly data: unknown;
131
+ readonly response: Response;
132
+ constructor(method: string, url: string, response: Response, data: unknown);
133
+ }
134
+ /**
135
+ * Calls a `.ts` route of the app from the browser (an effect, an event), typed by the route file: the params as
136
+ * `href()` takes them, `query` and `body` by the handler's `withValidator` schemas, `method` one the file exports
137
+ * (GET when left out), the answer by what the handler returns with `c.json()`, as JSON delivers it.
138
+ *
139
+ * const usage = await fetch('/api/usage')
140
+ * await fetch('/api/settings', { method: 'POST', body: { emails: false } })
141
+ *
142
+ * A non-2xx answer throws a `FetchError`. No retry, no cache. A page's data comes from its loader or `defer()`:
143
+ * called during the server render, it throws. (Follows Void's typed fetch.)
144
+ */
145
+ export declare function fetch<P extends ApiPath, M extends MethodsOf<P> & HttpMethod = Extract<MethodsOf<P>, 'GET'>>(path: P, ...[options]: FetchArgs<P, M>): Promise<AnswerOf<P, M>>;
package/dist/client.js CHANGED
@@ -7,6 +7,9 @@ import { fillPattern } from './paths.js';
7
7
  */
8
8
  export function href(path, ...[options]) {
9
9
  const { query, hash, ...params } = (options ?? {});
10
+ return buildUrl(path, params, query, hash);
11
+ }
12
+ function buildUrl(path, params, query, hash) {
10
13
  let url = fillPattern(path, params);
11
14
  const search = new URLSearchParams();
12
15
  for (const [name, value] of Object.entries(query ?? {}))
@@ -20,6 +23,68 @@ export function href(path, ...[options]) {
20
23
  url += `#${encodeURI(hash)}`;
21
24
  return url;
22
25
  }
23
- export { usePage, useNavigation, reload, __entry, renderPage, } from './client/app.js';
26
+ export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
24
27
  export { useForm } from './client/form.js';
25
28
  export { loadDocument, navigate } from './client/navigation.js';
29
+ /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
30
+ export class FetchError extends Error {
31
+ status;
32
+ data;
33
+ response;
34
+ constructor(method, url, response, data) {
35
+ super(`${method} ${url}: ${response.status}`);
36
+ this.name = 'FetchError';
37
+ this.status = response.status;
38
+ this.data = data;
39
+ this.response = response;
40
+ }
41
+ }
42
+ /**
43
+ * Calls a `.ts` route of the app from the browser (an effect, an event), typed by the route file: the params as
44
+ * `href()` takes them, `query` and `body` by the handler's `withValidator` schemas, `method` one the file exports
45
+ * (GET when left out), the answer by what the handler returns with `c.json()`, as JSON delivers it.
46
+ *
47
+ * const usage = await fetch('/api/usage')
48
+ * await fetch('/api/settings', { method: 'POST', body: { emails: false } })
49
+ *
50
+ * A non-2xx answer throws a `FetchError`. No retry, no cache. A page's data comes from its loader or `defer()`:
51
+ * called during the server render, it throws. (Follows Void's typed fetch.)
52
+ */
53
+ export async function fetch(path, ...[options]) {
54
+ if (typeof document === 'undefined')
55
+ throw new Error("fondu: fetch() from fondu/client is for the browser (effects, events); a page's data comes from its loader or defer()");
56
+ const { method = 'GET', query, body, headers, signal, ...params } = (options ?? {});
57
+ const url = buildUrl(path, params, query, undefined);
58
+ // a Headers object: the call's headers replace ours whatever their case
59
+ const all = new Headers({ Accept: 'application/json' });
60
+ if (body !== undefined)
61
+ all.set('Content-Type', 'application/json');
62
+ new Headers(headers).forEach((value, name) => all.set(name, value));
63
+ const response = await globalThis.fetch(url, {
64
+ method,
65
+ headers: all,
66
+ body: JSON.stringify(body),
67
+ signal,
68
+ });
69
+ const data = await readAnswer(response);
70
+ if (!response.ok)
71
+ throw new FetchError(method, url, response, data);
72
+ return data;
73
+ }
74
+ /** the answer's body: JSON when its content type says so, else text; none for 204 or an empty body */
75
+ async function readAnswer(response) {
76
+ const text = await response.text();
77
+ if (!text)
78
+ return undefined;
79
+ if (!/[/+]json\b/i.test(response.headers.get('content-type') ?? ''))
80
+ return text;
81
+ try {
82
+ return JSON.parse(text);
83
+ }
84
+ catch (error) {
85
+ // an error page that says it is JSON and isn't: its text is the data
86
+ if (!response.ok)
87
+ return text;
88
+ throw error;
89
+ }
90
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share, type RenderOptions } from './server/protocol.js';
2
+ export { defer, render, share, type RenderOptions } from './server/protocol.js';
3
3
  export { back } from './server/http.js';
4
4
  export { flash } from './server/flash.js';
5
5
  export { ValidationError, type StandardSchemaV1 } from './server/validate.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share } from './server/protocol.js';
2
+ export { defer, render, share } from './server/protocol.js';
3
3
  export { back } from './server/http.js';
4
4
  export { flash } from './server/flash.js';
5
5
  export { ValidationError } from './server/validate.js';
package/dist/paths.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  export declare function routePatterns(file: string): string[];
12
12
  /**
13
- * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.jsx`, `.mdx` (a page), but
13
+ * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
14
14
  * tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
15
15
  * `_layout.tsx`, `_parts/badge.tsx`)
16
16
  */
@@ -19,7 +19,7 @@ export declare function isRouteFile(file: string): boolean;
19
19
  export declare const METHODS: readonly ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
20
20
  export declare const HANDLERS: readonly ['loader', 'action', 'actions'];
21
21
  export declare const CONFIG: readonly ['prerender', 'params'];
22
- /** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
22
+ /** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
23
23
  export declare const isPageFile: (file: string) => boolean;
24
24
  /** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
25
25
  export declare const pageId: (file: string) => string;
@@ -49,6 +49,11 @@ export declare function decoded(segment: string): string;
49
49
  export declare const endsInIndex: (path: string) => boolean;
50
50
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
51
51
  export declare function pathOfPageData(pathname: string): string | null;
52
+ /**
53
+ * a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
54
+ * `/docs/` → `docs/index.html`
55
+ */
56
+ export declare const htmlFile: (decodedPath: string) => string;
52
57
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
53
58
  export declare function staticFiles(path: string): {
54
59
  html: string;
package/dist/paths.js CHANGED
@@ -33,23 +33,23 @@ export function routePatterns(file) {
33
33
  .join('/');
34
34
  return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
35
35
  }
36
- const ROUTE_EXTENSION = /\.(?:ts|[jt]sx|mdx)$/;
36
+ const ROUTE_EXTENSION = /\.(?:tsx?|mdx)$/;
37
37
  /**
38
- * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.jsx`, `.mdx` (a page), but
38
+ * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
39
39
  * tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
40
40
  * `_layout.tsx`, `_parts/badge.tsx`)
41
41
  */
42
42
  export function isRouteFile(file) {
43
43
  return (ROUTE_EXTENSION.test(file) &&
44
44
  !file.endsWith('.d.ts') &&
45
- !/\.(?:test|spec)\.(?:ts|[jt]sx)$/.test(file) &&
45
+ !/\.(?:test|spec)\.tsx?$/.test(file) &&
46
46
  !file.split('/').some((s) => s.startsWith('_')));
47
47
  }
48
48
  /** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
49
49
  export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
50
50
  export const HANDLERS = ['loader', 'action', 'actions'];
51
51
  export const CONFIG = ['prerender', 'params'];
52
- /** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
52
+ /** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
53
53
  export const isPageFile = (file) => isRouteFile(file) && !file.endsWith('.ts');
54
54
  /** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
55
55
  export const pageId = (file) => file.replace(ROUTE_EXTENSION, '');
@@ -122,8 +122,15 @@ export function pathOfPageData(pathname) {
122
122
  return null;
123
123
  return m[1].replace(/(?<=\/)index$/, '').replace(/(?<=\/)~(~*index)$/, '$1');
124
124
  }
125
+ /**
126
+ * a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
127
+ * `/docs/` → `docs/index.html`
128
+ */
129
+ export const htmlFile = (decodedPath) => (decodedPath.endsWith('/') ? `${decodedPath}index.html` : `${decodedPath}.html`).slice(1);
125
130
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
126
131
  export function staticFiles(path) {
127
- const html = decodeURIComponent(path.endsWith('/') ? path + 'index.html' : path + '.html').slice(1);
128
- return { html, json: decodeURIComponent(pageDataPath(path)).slice(1) };
132
+ return {
133
+ html: htmlFile(decodeURIComponent(path)),
134
+ json: decodeURIComponent(pageDataPath(path)).slice(1),
135
+ };
129
136
  }
@@ -9,6 +9,8 @@ export interface CreateAppOptions {
9
9
  trailingSlash?: 'trim' | 'append';
10
10
  /** `hono/csrf`'s options; `false`: off */
11
11
  csrf?: Parameters<typeof csrf>[0] | false;
12
+ /** the largest request body, in bytes (default: 10 MB), then 413: `hono/body-limit`; `false`: no limit */
13
+ bodyLimit?: number | false;
12
14
  /**
13
15
  * `hono/secure-headers`' options; `false`: off. Defaults: `referrerPolicy: 'same-origin'` (which `back()` needs) and
14
16
  * a Content Security Policy whose directives yours replace one by one; `contentSecurityPolicy: false`: none
@@ -18,14 +20,16 @@ export interface CreateAppOptions {
18
20
  }) | false;
19
21
  }
20
22
  type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
23
+ export declare function checkExports(file: string, mod: Record<string, unknown>): void;
21
24
  /**
22
25
  * The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
23
26
  * - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
24
- * own), `action` (POST) or `actions` (POST `?name`)
25
- * - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`
27
+ * own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
28
+ * - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
29
+ * `action`, `actions`: those are a page's)
26
30
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
27
- * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
28
- * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
31
+ * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error
32
+ * page. Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
29
33
  */
30
34
  export declare function createApp(options?: CreateAppOptions): Hono;
31
35
  export {};
@@ -1,4 +1,5 @@
1
1
  import { Hono } from 'hono';
2
+ import { bodyLimit } from 'hono/body-limit';
2
3
  import { every } from 'hono/combine';
3
4
  import { csrf } from 'hono/csrf';
4
5
  import { HTTPException } from 'hono/http-exception';
@@ -24,14 +25,15 @@ const CSP = {
24
25
  };
25
26
  const ROOT = '/app/routes/';
26
27
  /**
27
- * What a file of `app/routes/` may export, and what to do with anything else: a page's route file is its page and
28
- * the handlers of its URL; the rest of its code goes to modules of its own (the browser gets the page alone)
28
+ * What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
29
+ * page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
30
+ * HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
29
31
  */
30
32
  function exportsOf(file) {
31
33
  const name = file.split('/').at(-1);
32
34
  if (name === '_middleware.ts')
33
35
  return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
34
- if (/^_(?:layout|error)\.[jt]sx$/.test(name))
36
+ if (/^_(?:layout|error)\.tsx$/.test(name))
35
37
  return { allowed: ['default'], hint: 'its component only (default)' };
36
38
  if (file.endsWith('.mdx'))
37
39
  return {
@@ -40,21 +42,32 @@ function exportsOf(file) {
40
42
  };
41
43
  if (file.endsWith('.ts'))
42
44
  return {
43
- allowed: [...HANDLERS, ...METHODS, ...CONFIG],
44
- hint: 'loader, action or actions, GET, POST…, prerender, params',
45
+ allowed: [...METHODS, ...CONFIG],
46
+ hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
45
47
  };
46
48
  return {
47
49
  allowed: ['default', ...HANDLERS, ...CONFIG],
48
50
  hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
49
51
  };
50
52
  }
51
- function checkExports(file, mod) {
53
+ /** what a page's handler is called in a `.ts` file */
54
+ const INSTEAD = {
55
+ loader: 'in a .ts file it is `GET`',
56
+ action: 'in a .ts file it is `POST`',
57
+ actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
58
+ };
59
+ export function checkExports(file, mod) {
52
60
  const { allowed, hint } = exportsOf(file);
53
61
  const mdx = file.endsWith('.mdx');
54
62
  const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
55
- if (extra.length)
56
- throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}`);
57
- if (/\.(?:[jt]sx|mdx)$/.test(file) && typeof mod.default !== 'function')
63
+ if (extra.length) {
64
+ const renamed = file.endsWith('.ts')
65
+ ? extra.filter((k) => k in INSTEAD)
66
+ : [];
67
+ throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
68
+ (renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
69
+ }
70
+ if (/\.(?:tsx|mdx)$/.test(file) && typeof mod.default !== 'function')
58
71
  throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
59
72
  }
60
73
  /** a thrown `ValidationError` becomes the page it came from with its errors (or 422 for an API client) */
@@ -77,25 +90,25 @@ function actionName(url) {
77
90
  /**
78
91
  * The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
79
92
  * - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
80
- * own), `action` (POST) or `actions` (POST `?name`)
81
- * - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`
93
+ * own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
94
+ * - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
95
+ * `action`, `actions`: those are a page's)
82
96
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
83
- * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
84
- * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
97
+ * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error
98
+ * page. Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
85
99
  */
86
100
  export function createApp(options = {}) {
87
101
  const app = new Hono();
88
102
  const modules = Object.fromEntries(Object.entries(
89
103
  // without a type argument: Vitest's module cache leaves out a module with `import.meta.glob(` only
90
104
  import.meta.glob([
91
- '/app/routes/**/*.{ts,tsx,jsx,mdx}',
105
+ '/app/routes/**/*.{ts,tsx,jsx,mdx}', // a .jsx file is found to be refused (routeTable)
92
106
  '!/app/routes/**/*.d.ts',
93
107
  '!/app/routes/**/*.{test,spec}.{ts,tsx,jsx}', // test files aren't the app's
94
108
  '!/app/routes/**/_*/**', // nor what a directory keeps beside its routes
95
109
  ], { eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
96
110
  for (const [file, mod] of Object.entries(modules)) {
97
- if (!isRouteFile(file) &&
98
- !/(?:^|\/)_(?:middleware\.ts|layout\.[jt]sx|error\.[jt]sx)$/.test(file))
111
+ if (!isRouteFile(file) && !/(?:^|\/)_(?:middleware\.ts|layout\.tsx|error\.tsx)$/.test(file))
99
112
  continue; // a file of a directory's own (`_badge.tsx`)
100
113
  checkExports(file, mod);
101
114
  if (isPageFile(file))
@@ -103,7 +116,7 @@ export function createApp(options = {}) {
103
116
  }
104
117
  const own = {
105
118
  document: options.document,
106
- errorPage: Boolean(modules['_error.tsx'] ?? modules['_error.jsx']),
119
+ errorPage: Boolean(modules['_error.tsx']),
107
120
  };
108
121
  const append = options.trailingSlash === 'append';
109
122
  app.use(async (c, next) => {
@@ -120,6 +133,14 @@ export function createApp(options = {}) {
120
133
  }
121
134
  if (options.csrf !== false)
122
135
  app.use(csrf(options.csrf));
136
+ if (options.bodyLimit !== false)
137
+ app.use(bodyLimit({
138
+ maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
139
+ // Fondu's own answer: the error page for a visitor, the status alone for an API client
140
+ onError: () => {
141
+ throw new HTTPException(413);
142
+ },
143
+ }));
123
144
  const prerendered = [];
124
145
  if (prerender)
125
146
  prerenderRoutes(app, () => prerendered, version);
@@ -152,13 +173,6 @@ export function createApp(options = {}) {
152
173
  ...METHODS.filter((m) => m !== 'GET' && m !== 'POST' && mod[m]),
153
174
  ],
154
175
  });
155
- const conflict = (a, b) => {
156
- if (mod[a] && mod[b])
157
- throw new Error(`fondu: routes/${file} exports both \`${a}\` and \`${b}\`, which handle the same requests`);
158
- };
159
- conflict('loader', 'GET');
160
- conflict('action', 'POST');
161
- conflict('actions', 'POST');
162
176
  if (mod.action && mod.actions)
163
177
  throw new Error(`fondu: routes/${file} exports both \`action\` and \`actions\`: one form posts to \`action\`, several each to one of \`actions\` (?name)`);
164
178
  const add = (method, handlers) => app.on(method, pattern, ...handlers);
@@ -1,5 +1,5 @@
1
1
  import type { Context, MiddlewareHandler } from 'hono';
2
- import type { ReactElement } from 'react';
2
+ import { type ReactElement } from 'react';
3
3
  import type { Page } from '../client/navigation.js';
4
4
  /**
5
5
  * The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
@@ -28,4 +28,12 @@ export declare const settings: WeakMap<Context<any, any, {}>, {
28
28
  * `fondu({ ssr: false })`.
29
29
  */
30
30
  export declare const withoutSsr: () => MiddlewareHandler;
31
- export declare function renderDocument(c: Context, page: Page): Promise<string>;
31
+ /**
32
+ * The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
33
+ * (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
34
+ * boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
35
+ * first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
36
+ * `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
37
+ * `renderToString` gave).
38
+ */
39
+ export declare function renderDocument(c: Context, page: Page, whole?: boolean): Promise<string | ReadableStream<Uint8Array>>;
@@ -1,3 +1,4 @@
1
+ import { createElement } from 'react';
1
2
  import { assetTags } from 'virtual:fondu/assets';
2
3
  import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
3
4
  import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
@@ -23,7 +24,7 @@ const pageScript = (page) => `<script data-page="app" type="application/json">${
23
24
  * their own until then (to the #fragment, WebKit and Firefox), fondu/client keeping their restoration off. Not once
24
25
  * the visitor has scrolled, typed or clicked: their own scrolling wins.
25
26
  */
26
- 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));if(p){var go=function(){scrollTo(+p.x||0,+p.y||0)},off=function(){go=0};go();["wheel","touchstart","keydown","mousedown"].forEach(function(t){addEventListener(t,off,{once:!0,passive:!0})});addEventListener("load",function(){setTimeout(function(){go&&go()})})}}catch(e){}</script>`;
27
+ const restoreScroll = `try{var k=history.state&&history.state[${JSON.stringify(SCROLL_KEY)}],p=k&&JSON.parse(sessionStorage.getItem(${JSON.stringify(SCROLL_STORAGE)}+k));if(p){var go=function(){scrollTo(+p.x||0,+p.y||0)},off=function(){go=0};go();["wheel","touchstart","keydown","mousedown"].forEach(function(t){addEventListener(t,off,{once:!0,passive:!0})});addEventListener("load",function(){setTimeout(function(){go&&go()})})}}catch(e){}`;
27
28
  // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
28
29
  // never read as one
29
30
  const HEAD = 'fondu:document-head';
@@ -41,13 +42,43 @@ async function shell(template, c, nonce) {
41
42
  return html;
42
43
  return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
43
44
  }
44
- export async function renderDocument(c, page) {
45
+ /**
46
+ * The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
47
+ * (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
48
+ * boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
49
+ * first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
50
+ * `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
51
+ * `renderToString` gave).
52
+ */
53
+ export async function renderDocument(c, page, whole = false) {
45
54
  const nonce = nonceOf(c);
55
+ // the template first: one that is wrong fails before anything renders (no stream left running)
56
+ const template = settings.get(c)?.document ?? defaultTemplate;
57
+ const html = await shell(template, c, nonce);
58
+ const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
59
+ if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
60
+ throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
46
61
  let ssr = null;
62
+ // what fails in a boundary is for the browser to render, and is logged. The shell's failure is logged below, once:
63
+ // React reports it to `onError` too, so what it reports is held until the shell is known to be there
64
+ const pending = [];
65
+ let live = false;
66
+ const late = (error) => console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
47
67
  try {
48
- // the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
49
- if (renderPage && !browserOnly.has(c))
50
- ssr = await renderPage(JSON.parse(JSON.stringify(page)));
68
+ // a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
69
+ if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
70
+ // the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
71
+ const stream = await renderPage(JSON.parse(JSON.stringify(page)), { nonce, onError: (error) => (live ? late(error) : void pending.push(error)) },
72
+ // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
73
+ // shell, right after the page, before what the boundaries add
74
+ createElement('script', { nonce, dangerouslySetInnerHTML: { __html: restoreScroll } }));
75
+ if (whole)
76
+ await stream.allReady;
77
+ ssr = stream.pipeThrough(new TextDecoderStream());
78
+ for (const error of pending)
79
+ late(error);
80
+ live = true;
81
+ }
51
82
  }
52
83
  catch (error) {
53
84
  // like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
@@ -55,13 +86,7 @@ export async function renderDocument(c, page) {
55
86
  }
56
87
  // the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
57
88
  // content can come before it
58
- // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet)
59
- const body = pageScript(page) + (ssr ? ssr.body + restoreScroll(nonce) : '<div id="app"></div>');
60
- const template = settings.get(c)?.document ?? defaultTemplate;
61
- const html = await shell(template, c, nonce);
62
- const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
63
- if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
64
- throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
89
+ const data = pageScript(page);
65
90
  // the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
66
91
  // document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
67
92
  // the page out early (Firefox's, with its tools open) has them sooner
@@ -69,10 +94,36 @@ export async function renderDocument(c, page) {
69
94
  const css = tags.match(/<link rel="stylesheet"[^>]*>/g)?.join('') ?? '';
70
95
  const charset = /<meta charset=[^>]*>/i;
71
96
  const top = css && charset.test(before) ? before.replace(charset, (meta) => meta + css) : before + css;
72
- return (top +
73
- tags.replace(/<link rel="stylesheet"[^>]*>/g, '') +
74
- (ssr?.head ?? '') +
75
- between +
76
- body +
77
- after);
97
+ const start = top + tags.replace(/<link rel="stylesheet"[^>]*>/g, '');
98
+ if (!ssr)
99
+ return start + between + data + '<div id="app"></div>' + after;
100
+ // React's own: the tags the page hoists, then the page (`<div id="app"`), found across chunks
101
+ const reader = ssr.getReader();
102
+ let text = '';
103
+ let at = -1;
104
+ while (at < 0) {
105
+ const { done, value } = await reader.read();
106
+ if (done)
107
+ break;
108
+ text += value;
109
+ at = text.indexOf('<div id="app"');
110
+ }
111
+ const out = new TextEncoder();
112
+ return new ReadableStream({
113
+ start(controller) {
114
+ controller.enqueue(out.encode(start + text.slice(0, at) + between + data + text.slice(at)));
115
+ },
116
+ async pull(controller) {
117
+ const { done, value } = await reader.read();
118
+ if (!done)
119
+ return controller.enqueue(out.encode(value));
120
+ controller.enqueue(out.encode(after));
121
+ controller.close();
122
+ },
123
+ // the visitor left: React stops (its abort reaches `onError`: not an error of the page)
124
+ cancel(reason) {
125
+ live = false;
126
+ return reader.cancel(reason);
127
+ },
128
+ });
78
129
  }
@@ -8,6 +8,7 @@ const TEXT = {
8
8
  401: 'Unauthorized',
9
9
  403: 'Forbidden',
10
10
  404: 'Not Found',
11
+ 413: 'Content Too Large',
11
12
  419: 'Page Expired',
12
13
  429: 'Too Many Requests',
13
14
  503: 'Service Unavailable',