fondu 0.9.6 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -12
- package/dist/client/app.d.ts +40 -0
- package/dist/client/app.js +162 -0
- package/dist/client/navigation.d.ts +35 -0
- package/dist/client/navigation.js +210 -0
- package/dist/client/progress.d.ts +16 -0
- package/dist/client/progress.js +51 -0
- package/dist/client.d.ts +4 -15
- package/dist/client.js +3 -47
- package/dist/index.d.ts +3 -4
- package/dist/index.js +3 -4
- package/dist/paths.d.ts +10 -7
- package/dist/paths.js +15 -15
- package/dist/server/app.d.ts +4 -5
- package/dist/server/app.js +81 -16
- package/dist/server/document.d.ts +3 -3
- package/dist/server/document.js +7 -6
- package/dist/server/errors.d.ts +4 -2
- package/dist/server/errors.js +21 -10
- package/dist/server/flash.d.ts +4 -7
- package/dist/server/flash.js +9 -14
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +1 -1
- package/dist/server/http.d.ts +7 -5
- package/dist/server/http.js +15 -6
- package/dist/server/prerender.d.ts +1 -1
- package/dist/server/prerender.js +6 -6
- package/dist/server/protocol.d.ts +22 -35
- package/dist/server/protocol.js +65 -195
- package/dist/server/routes.d.ts +1 -1
- package/dist/server/validate.d.ts +7 -9
- package/dist/server/validate.js +8 -21
- package/dist/types.d.ts +10 -6
- package/dist/virtual.d.ts +3 -5
- package/dist/vite/hmr.d.ts +3 -3
- package/dist/vite/hmr.js +5 -5
- package/dist/vite/index.d.ts +9 -5
- package/dist/vite/index.js +158 -79
- package/dist/vite/prerender.d.ts +3 -3
- package/dist/vite/prerender.js +17 -12
- package/dist/vite/strip.d.ts +21 -0
- package/dist/vite/strip.js +301 -0
- package/dist/vite/typegen.d.ts +3 -2
- package/dist/vite/typegen.js +6 -10
- package/package.json +2 -9
- package/dist/server/props.d.ts +0 -85
- package/dist/server/props.js +0 -44
- package/dist/vite/layouts.d.ts +0 -10
- package/dist/vite/layouts.js +0 -110
- package/dist/vite/vitest-cache.d.ts +0 -19
- package/dist/vite/vitest-cache.js +0 -30
package/dist/index.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
export { defineHandler, defineMiddleware } from './server/handler.js';
|
|
2
|
-
export { render, share
|
|
3
|
-
export { back
|
|
4
|
-
export {
|
|
5
|
-
export { flash, clearHistory } from './server/flash.js';
|
|
2
|
+
export { render, share } from './server/protocol.js';
|
|
3
|
+
export { back } from './server/http.js';
|
|
4
|
+
export { flash } from './server/flash.js';
|
|
6
5
|
export { ValidationError } from './server/validate.js';
|
|
7
6
|
export { withoutSsr } from './server/document.js';
|
|
8
7
|
// last: createApp imports the app's routes, which import this module (the exports above are ready by then)
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `routes/` file → its URL patterns (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
|
|
3
3
|
*
|
|
4
|
-
* - `index.ts` is its directory: `routes/users/index.ts` → `/users`
|
|
4
|
+
* - `index.ts` (or `.tsx`, `.mdx`) is its directory: `routes/users/index.ts` → `/users`
|
|
5
5
|
* - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
|
|
6
6
|
* - `[[lang]]`, an optional segment: two patterns, without it and with it (`/about`, `/:lang/about`), as Hono takes
|
|
7
7
|
* an optional param only at the end of a path. One per route.
|
|
@@ -9,14 +9,17 @@
|
|
|
9
9
|
* - `_middleware.ts` applies to its directory
|
|
10
10
|
*/
|
|
11
11
|
export declare function routePatterns(file: string): string[];
|
|
12
|
-
/** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
|
|
13
|
-
export declare function isRouteFile(file: string): boolean;
|
|
14
12
|
/**
|
|
15
|
-
* a path inside `
|
|
16
|
-
* directory on its path starting with `_` (`
|
|
13
|
+
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.jsx`, `.mdx` (a page), but
|
|
14
|
+
* tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
|
|
15
|
+
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
17
16
|
*/
|
|
18
|
-
export declare function
|
|
19
|
-
/**
|
|
17
|
+
export declare function isRouteFile(file: string): boolean;
|
|
18
|
+
/** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
|
|
19
|
+
export declare const isPageFile: (file: string) => boolean;
|
|
20
|
+
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
21
|
+
export declare const pageId: (file: string) => string;
|
|
22
|
+
/** the directories of `routes/` whose `_layout.tsx` wraps a page, outermost first: `docs/intro.mdx` → `['', 'docs']` */
|
|
20
23
|
export declare function layoutsOf(file: string): string[];
|
|
21
24
|
/** the `_middleware.ts` files that apply to a route file, outermost first */
|
|
22
25
|
export declare function middlewareFor(file: string, middleware: readonly string[]): string[];
|
package/dist/paths.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `routes/` file → its URL patterns (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
|
|
3
3
|
*
|
|
4
|
-
* - `index.ts` is its directory: `routes/users/index.ts` → `/users`
|
|
4
|
+
* - `index.ts` (or `.tsx`, `.mdx`) is its directory: `routes/users/index.ts` → `/users`
|
|
5
5
|
* - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
|
|
6
6
|
* - `[[lang]]`, an optional segment: two patterns, without it and with it (`/about`, `/:lang/about`), as Hono takes
|
|
7
7
|
* an optional param only at the end of a path. One per route.
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export function routePatterns(file) {
|
|
12
12
|
const segments = file
|
|
13
|
-
.replace(
|
|
13
|
+
.replace(ROUTE_EXTENSION, '')
|
|
14
14
|
.split('/')
|
|
15
15
|
.filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s));
|
|
16
16
|
const optional = segments.filter((s) => /^\[\[(?:\.\.\.)?\w+\]\]$/.test(s));
|
|
@@ -28,23 +28,23 @@ export function routePatterns(file) {
|
|
|
28
28
|
.join('/');
|
|
29
29
|
return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
|
|
30
30
|
}
|
|
31
|
-
|
|
32
|
-
export function isRouteFile(file) {
|
|
33
|
-
return (file.endsWith('.ts') &&
|
|
34
|
-
!file.endsWith('.d.ts') &&
|
|
35
|
-
!/\.(test|spec)\.ts$/.test(file) &&
|
|
36
|
-
file.split('/').at(-1) !== '_middleware.ts');
|
|
37
|
-
}
|
|
31
|
+
const ROUTE_EXTENSION = /\.(?:ts|[jt]sx|mdx)$/;
|
|
38
32
|
/**
|
|
39
|
-
* a path inside `
|
|
40
|
-
* directory on its path starting with `_` (`
|
|
33
|
+
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.jsx`, `.mdx` (a page), but
|
|
34
|
+
* tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
|
|
35
|
+
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
41
36
|
*/
|
|
42
|
-
export function
|
|
43
|
-
return (
|
|
44
|
-
|
|
37
|
+
export function isRouteFile(file) {
|
|
38
|
+
return (ROUTE_EXTENSION.test(file) &&
|
|
39
|
+
!file.endsWith('.d.ts') &&
|
|
40
|
+
!/\.(?:test|spec)\.(?:ts|[jt]sx)$/.test(file) &&
|
|
45
41
|
!file.split('/').some((s) => s.startsWith('_')));
|
|
46
42
|
}
|
|
47
|
-
/**
|
|
43
|
+
/** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
|
|
44
|
+
export const isPageFile = (file) => isRouteFile(file) && !file.endsWith('.ts');
|
|
45
|
+
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
46
|
+
export const pageId = (file) => file.replace(ROUTE_EXTENSION, '');
|
|
47
|
+
/** the directories of `routes/` whose `_layout.tsx` wraps a page, outermost first: `docs/intro.mdx` → `['', 'docs']` */
|
|
48
48
|
export function layoutsOf(file) {
|
|
49
49
|
const dirs = file.split('/').slice(0, -1);
|
|
50
50
|
return ['', ...dirs.map((_, i) => dirs.slice(0, i + 1).join('/'))];
|
package/dist/server/app.d.ts
CHANGED
|
@@ -5,8 +5,6 @@ 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
|
-
/** the page for 404 / 500… (it gets `{ status }`), default `'error'` (`app/pages/error.tsx`); `false`: plain text */
|
|
9
|
-
errorPage?: string | false;
|
|
10
8
|
/** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): Hono's trailing-slash middleware */
|
|
11
9
|
trailingSlash?: 'trim' | 'append';
|
|
12
10
|
/** `hono/csrf`'s options; `false`: off */
|
|
@@ -21,9 +19,10 @@ export interface CreateAppOptions {
|
|
|
21
19
|
}
|
|
22
20
|
type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
|
|
23
21
|
/**
|
|
24
|
-
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL
|
|
25
|
-
* -
|
|
26
|
-
*
|
|
22
|
+
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
23
|
+
* - 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`
|
|
27
26
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
28
27
|
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
29
28
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
package/dist/server/app.js
CHANGED
|
@@ -5,17 +5,18 @@ import { HTTPException } from 'hono/http-exception';
|
|
|
5
5
|
import { NONCE, secureHeaders } from 'hono/secure-headers';
|
|
6
6
|
import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
|
|
7
7
|
import { prerender, version } from 'virtual:fondu/assets';
|
|
8
|
+
import { isPageFile, isRouteFile, pageId } from '../paths.js';
|
|
8
9
|
import { settings } from './document.js';
|
|
9
10
|
import { errorResponse } from './errors.js';
|
|
10
11
|
import { prerenderRoutes } from './prerender.js';
|
|
11
|
-
import { protocol } from './protocol.js';
|
|
12
|
+
import { protocol, registerPage, renderPage, routePage } from './protocol.js';
|
|
12
13
|
import { routeTable } from './routes.js';
|
|
13
14
|
import { ValidationError, validationErrorResponse } from './validate.js';
|
|
14
15
|
/** the default Content Security Policy: scripts of this site or with the request's nonce (the document's) */
|
|
15
16
|
const CSP = {
|
|
16
17
|
defaultSrc: ["'self'"],
|
|
17
18
|
scriptSrc: ["'self'", NONCE],
|
|
18
|
-
styleSrc: ["'self'", "'unsafe-inline'"], // style attributes (React, Base UI)
|
|
19
|
+
styleSrc: ["'self'", "'unsafe-inline'"], // style attributes (React, Base UI)
|
|
19
20
|
imgSrc: ["'self'", 'data:'],
|
|
20
21
|
fontSrc: ["'self'", 'data:'],
|
|
21
22
|
objectSrc: ["'none'"],
|
|
@@ -23,6 +24,42 @@ const CSP = {
|
|
|
23
24
|
};
|
|
24
25
|
const ROOT = '/app/routes/';
|
|
25
26
|
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
27
|
+
const HANDLERS = ['loader', 'action', 'actions'];
|
|
28
|
+
const CONFIG = ['prerender', 'params'];
|
|
29
|
+
/**
|
|
30
|
+
* What a file of `app/routes/` may export, and what to do with anything else: a page's route file is its page and
|
|
31
|
+
* the handlers of its URL; the rest of its code goes to modules of its own (the browser gets the page alone)
|
|
32
|
+
*/
|
|
33
|
+
function exportsOf(file) {
|
|
34
|
+
const name = file.split('/').at(-1);
|
|
35
|
+
if (name === '_middleware.ts')
|
|
36
|
+
return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
|
|
37
|
+
if (/^_(?:layout|error)\.[jt]sx$/.test(name))
|
|
38
|
+
return { allowed: ['default'], hint: 'its component only (default)' };
|
|
39
|
+
if (file.endsWith('.mdx'))
|
|
40
|
+
return {
|
|
41
|
+
allowed: [],
|
|
42
|
+
hint: "its content: an MDX page has no handlers (a _middleware.ts's prerender, params)",
|
|
43
|
+
};
|
|
44
|
+
if (file.endsWith('.ts'))
|
|
45
|
+
return {
|
|
46
|
+
allowed: [...HANDLERS, ...METHODS, ...CONFIG],
|
|
47
|
+
hint: 'loader, action or actions, GET, POST…, prerender, params',
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
allowed: ['default', ...HANDLERS, ...CONFIG],
|
|
51
|
+
hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function checkExports(file, mod) {
|
|
55
|
+
const { allowed, hint } = exportsOf(file);
|
|
56
|
+
const mdx = file.endsWith('.mdx');
|
|
57
|
+
const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
|
|
58
|
+
if (extra.length)
|
|
59
|
+
throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}`);
|
|
60
|
+
if (/\.(?:[jt]sx|mdx)$/.test(file) && typeof mod.default !== 'function')
|
|
61
|
+
throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
|
|
62
|
+
}
|
|
26
63
|
/** a thrown `ValidationError` becomes the page it came from with its errors (or 422 for an API client) */
|
|
27
64
|
const handle = (h) => async (c, next) => {
|
|
28
65
|
try {
|
|
@@ -41,16 +78,36 @@ function actionName(url) {
|
|
|
41
78
|
return first && first[1] === '' ? first[0] : null;
|
|
42
79
|
}
|
|
43
80
|
/**
|
|
44
|
-
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL
|
|
45
|
-
* -
|
|
46
|
-
*
|
|
81
|
+
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
82
|
+
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
83
|
+
* own), `action` (POST) or `actions` (POST `?name`)
|
|
84
|
+
* - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
|
|
47
85
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
48
86
|
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
49
87
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
50
88
|
*/
|
|
51
89
|
export function createApp(options = {}) {
|
|
52
90
|
const app = new Hono();
|
|
53
|
-
const
|
|
91
|
+
const modules = Object.fromEntries(Object.entries(
|
|
92
|
+
// without a type argument: Vitest's module cache leaves out a module with `import.meta.glob(` only
|
|
93
|
+
import.meta.glob([
|
|
94
|
+
'/app/routes/**/*.{ts,tsx,jsx,mdx}',
|
|
95
|
+
'!/app/routes/**/*.d.ts',
|
|
96
|
+
'!/app/routes/**/*.{test,spec}.{ts,tsx,jsx}', // test files aren't the app's
|
|
97
|
+
'!/app/routes/**/_*/**', // nor what a directory keeps beside its routes
|
|
98
|
+
], { eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
|
|
99
|
+
for (const [file, mod] of Object.entries(modules)) {
|
|
100
|
+
if (!isRouteFile(file) &&
|
|
101
|
+
!/(?:^|\/)_(?:middleware\.ts|layout\.[jt]sx|error\.[jt]sx)$/.test(file))
|
|
102
|
+
continue; // a file of a directory's own (`_badge.tsx`)
|
|
103
|
+
checkExports(file, mod);
|
|
104
|
+
if (isPageFile(file))
|
|
105
|
+
registerPage(mod.default, pageId(file));
|
|
106
|
+
}
|
|
107
|
+
const own = {
|
|
108
|
+
document: options.document,
|
|
109
|
+
errorPage: Boolean(modules['_error.tsx'] ?? modules['_error.jsx']),
|
|
110
|
+
};
|
|
54
111
|
const append = options.trailingSlash === 'append';
|
|
55
112
|
app.use(async (c, next) => {
|
|
56
113
|
settings.set(c, own);
|
|
@@ -76,20 +133,23 @@ export function createApp(options = {}) {
|
|
|
76
133
|
return error.getResponse();
|
|
77
134
|
return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
|
|
78
135
|
});
|
|
79
|
-
const modules = Object.fromEntries(Object.entries(import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts', '!/app/routes/**/*.{test,spec}.ts'], // test files aren't the app's
|
|
80
|
-
{ eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
|
|
81
136
|
// a _middleware.ts may only set what applies to its directory (`prerender`, `params`), without a default export
|
|
82
137
|
const rootMiddleware = modules['_middleware.ts']?.default;
|
|
83
138
|
if (rootMiddleware)
|
|
84
139
|
app.use(...chain(rootMiddleware));
|
|
85
140
|
for (const { file, pattern, path, middleware } of routeTable(modules, append)) {
|
|
86
141
|
const mod = modules[file];
|
|
87
|
-
const
|
|
142
|
+
const page = isPageFile(file) ? pageId(file) : undefined;
|
|
143
|
+
// a page's route: render() renders that page; with no loader, a GET renders it with no props of its own
|
|
144
|
+
const mws = [
|
|
145
|
+
...(page ? [routePage(page)] : []),
|
|
146
|
+
...middleware.flatMap((f) => chain(modules[f].default ?? [])),
|
|
147
|
+
];
|
|
88
148
|
prerendered.push({
|
|
89
149
|
file,
|
|
90
150
|
pattern: path,
|
|
91
151
|
settings: [file, ...[...middleware].reverse(), '_middleware.ts'].map((f) => modules[f]?.prerender),
|
|
92
|
-
get: Boolean(mod.loader ?? mod.GET),
|
|
152
|
+
get: Boolean(mod.loader ?? mod.GET ?? page),
|
|
93
153
|
others: [
|
|
94
154
|
...(mod.action || mod.actions || mod.POST ? ['POST'] : []),
|
|
95
155
|
...METHODS.filter((m) => m !== 'GET' && m !== 'POST' && mod[m]),
|
|
@@ -102,8 +162,12 @@ export function createApp(options = {}) {
|
|
|
102
162
|
conflict('loader', 'GET');
|
|
103
163
|
conflict('action', 'POST');
|
|
104
164
|
conflict('actions', 'POST');
|
|
165
|
+
if (mod.action && mod.actions)
|
|
166
|
+
throw new Error(`fondu: routes/${file} exports both \`action\` and \`actions\`: one form posts to \`action\`, several each to one of \`actions\` (?name)`);
|
|
105
167
|
const add = (method, handlers) => app.on(method, pattern, ...handlers);
|
|
106
|
-
const get = mod.loader ??
|
|
168
|
+
const get = mod.loader ??
|
|
169
|
+
mod.GET ??
|
|
170
|
+
(page === undefined ? undefined : (c) => renderPage(c, page, {}));
|
|
107
171
|
if (get)
|
|
108
172
|
add('GET', [...mws, ...chain(get)]);
|
|
109
173
|
if (mod.action || mod.actions || mod.POST) {
|
|
@@ -113,11 +177,12 @@ export function createApp(options = {}) {
|
|
|
113
177
|
...mws,
|
|
114
178
|
async (c, next) => {
|
|
115
179
|
const name = actionName(c.req.url);
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
?
|
|
120
|
-
: undefined
|
|
180
|
+
// actions: the one named (?name), else none; otherwise the one action
|
|
181
|
+
const picked = mod.actions
|
|
182
|
+
? name !== null && Object.hasOwn(actions, name)
|
|
183
|
+
? actions[name]
|
|
184
|
+
: undefined
|
|
185
|
+
: defaultPost;
|
|
121
186
|
if (!picked)
|
|
122
187
|
return c.notFound();
|
|
123
188
|
return every(...chain(picked))(c, next);
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type { Page } from '@inertiajs/core';
|
|
2
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
3
2
|
import type { ReactElement } from 'react';
|
|
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.
|
|
6
6
|
* An inline `<script>` of a JSX document gets the request's nonce, so the Content Security Policy runs it; a string's
|
|
7
7
|
* writes it: `<script nonce="${nonce}">`.
|
|
8
8
|
*/
|
|
9
9
|
export interface DocumentParts {
|
|
10
|
-
/** the page
|
|
10
|
+
/** the tags the page renders (`<title>`, `<meta>`: server render), then the client's styles and scripts */
|
|
11
11
|
head: string;
|
|
12
12
|
/** the page data (`<script data-page>`) and the rendered page (`<div id="app">`) */
|
|
13
13
|
body: string;
|
|
@@ -20,7 +20,7 @@ export type DocumentTemplate = (parts: DocumentParts) => ReactElement | string;
|
|
|
20
20
|
/** the options of the app (`createApp`) a request belongs to */
|
|
21
21
|
export declare const settings: WeakMap<Context<any, any, {}>, {
|
|
22
22
|
document?: DocumentTemplate;
|
|
23
|
-
errorPage:
|
|
23
|
+
errorPage: boolean;
|
|
24
24
|
}>;
|
|
25
25
|
/**
|
|
26
26
|
* Pages of these requests are rendered in the browser only (Laravel's `withoutSsr`): in `routes/admin/_middleware.ts`,
|
package/dist/server/document.js
CHANGED
|
@@ -13,7 +13,7 @@ export const withoutSsr = () => async (c, next) => {
|
|
|
13
13
|
browserOnly.add(c);
|
|
14
14
|
await next();
|
|
15
15
|
};
|
|
16
|
-
/**
|
|
16
|
+
/** the page data, `/` and `<` escaped (no `</script>` in it), no HTML entities */
|
|
17
17
|
const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
|
|
18
18
|
// where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
|
|
19
19
|
// never read as one
|
|
@@ -36,20 +36,21 @@ export async function renderDocument(c, page) {
|
|
|
36
36
|
const nonce = c.get('secureHeadersNonce');
|
|
37
37
|
let ssr = null;
|
|
38
38
|
try {
|
|
39
|
+
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
|
|
39
40
|
if (renderPage && !browserOnly.has(c))
|
|
40
|
-
ssr = await renderPage(page);
|
|
41
|
+
ssr = await renderPage(JSON.parse(JSON.stringify(page)));
|
|
41
42
|
}
|
|
42
43
|
catch (error) {
|
|
43
44
|
// like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
|
|
44
45
|
console.error(`[fondu] server render of "${page.component}" failed, sending it to render in the browser:`, error);
|
|
45
46
|
}
|
|
46
|
-
// the page data first
|
|
47
|
-
//
|
|
48
|
-
const body = ssr?.body ??
|
|
47
|
+
// the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
|
|
48
|
+
// content can come before it
|
|
49
|
+
const body = pageScript(page) + (ssr?.body ?? '<div id="app"></div>');
|
|
49
50
|
const template = settings.get(c)?.document ?? defaultTemplate;
|
|
50
51
|
const html = await shell(template, c, nonce);
|
|
51
52
|
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
52
53
|
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
53
54
|
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
54
|
-
return
|
|
55
|
+
return before + (ssr?.head ?? '') + assetTags(page.component, nonce) + between + body + after;
|
|
55
56
|
}
|
package/dist/server/errors.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
+
/** the error page's id: `app/routes/_error.tsx` */
|
|
3
|
+
export declare const ERROR_PAGE = "_error";
|
|
2
4
|
/**
|
|
3
5
|
* The answer to an unmatched URL or a thrown error (installed by `createApp`):
|
|
4
6
|
* - API clients: the `HTTPException`'s response, or plain text
|
|
5
|
-
* - pages, in development: a report of the error (
|
|
6
|
-
* - pages: the error page (`app/
|
|
7
|
+
* - pages, in development: a report of the error (a navigation loads it as a document)
|
|
8
|
+
* - pages: the error page (`app/routes/_error.tsx`, `{ status }`) with the shared props
|
|
7
9
|
*/
|
|
8
10
|
export declare function errorResponse(c: Context, status: number, error?: unknown): Promise<Response>;
|
package/dist/server/errors.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { HTTPException } from 'hono/http-exception';
|
|
2
2
|
import { settings } from './document.js';
|
|
3
3
|
import { wantsPage } from './http.js';
|
|
4
|
-
import {
|
|
4
|
+
import { renderPage } from './protocol.js';
|
|
5
|
+
/** the error page's id: `app/routes/_error.tsx` */
|
|
6
|
+
export const ERROR_PAGE = '_error';
|
|
5
7
|
const TEXT = {
|
|
6
8
|
401: 'Unauthorized',
|
|
7
9
|
403: 'Forbidden',
|
|
@@ -13,8 +15,8 @@ const TEXT = {
|
|
|
13
15
|
/**
|
|
14
16
|
* The answer to an unmatched URL or a thrown error (installed by `createApp`):
|
|
15
17
|
* - API clients: the `HTTPException`'s response, or plain text
|
|
16
|
-
* - pages, in development: a report of the error (
|
|
17
|
-
* - pages: the error page (`app/
|
|
18
|
+
* - pages, in development: a report of the error (a navigation loads it as a document)
|
|
19
|
+
* - pages: the error page (`app/routes/_error.tsx`, `{ status }`) with the shared props
|
|
18
20
|
*/
|
|
19
21
|
export async function errorResponse(c, status, error) {
|
|
20
22
|
if (status >= 500)
|
|
@@ -25,10 +27,9 @@ export async function errorResponse(c, status, error) {
|
|
|
25
27
|
return error instanceof HTTPException ? error.getResponse() : c.text(text, code);
|
|
26
28
|
if (import.meta.env.DEV && status >= 500)
|
|
27
29
|
return c.html(report(c, error), 500);
|
|
28
|
-
|
|
29
|
-
if (page && hasPage(page)) {
|
|
30
|
+
if (settings.get(c)?.errorPage) {
|
|
30
31
|
try {
|
|
31
|
-
return await
|
|
32
|
+
return await renderPage(c, ERROR_PAGE, { status }, { status });
|
|
32
33
|
}
|
|
33
34
|
catch (failure) {
|
|
34
35
|
console.error('[fondu] the error page failed to render:', failure);
|
|
@@ -37,7 +38,10 @@ export async function errorResponse(c, status, error) {
|
|
|
37
38
|
return c.text(text, code);
|
|
38
39
|
}
|
|
39
40
|
const escape = (s) => s.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
|
40
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
* the development error report: what failed, where (your files first), for which request; reloaded once an edit is
|
|
43
|
+
* saved (Vite's client, as the app's pages have it)
|
|
44
|
+
*/
|
|
41
45
|
function report(c, error) {
|
|
42
46
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
43
47
|
const frames = (err.stack ?? '')
|
|
@@ -51,7 +55,7 @@ function report(c, error) {
|
|
|
51
55
|
const own = /\/app\//.test(line) && !line.includes('node_modules');
|
|
52
56
|
return `<li class="${own ? 'own' : ''}">${escape(line.replace(/^at /, ''))}</li>`;
|
|
53
57
|
};
|
|
54
|
-
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title
|
|
58
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Something went wrong</title>
|
|
55
59
|
<style${nonce ? ` nonce="${nonce}"` : ''}>
|
|
56
60
|
*{box-sizing:border-box}body{margin:0;padding:clamp(16px,6vw,80px);font:14px/1.55 ui-sans-serif,system-ui,sans-serif;color:#1f2328;background:#f9f9f9;--x:clamp(16px,4vw,32px)}
|
|
57
61
|
article{background:#fff;border:1px solid #eaecef;border-radius:6px;overflow:hidden}
|
|
@@ -66,8 +70,15 @@ li{white-space:pre;padding:1px 8px;border-radius:4px}li.own{color:#1f2328;backgr
|
|
|
66
70
|
footer{padding:0 var(--x) 24px;color:#afb8c1;font-size:12px;font-weight:400}
|
|
67
71
|
</style></head><body><article>
|
|
68
72
|
<header><p class="kind">${escape(err.name)} · 500</p><h1>${escape(err.message)}</h1>
|
|
69
|
-
<p class="req"><b>${escape(c.req.method)}</b> ${escape(url.pathname + url.search)}${c.req.header('x-
|
|
73
|
+
<p class="req"><b>${escape(c.req.method)}</b> ${escape(url.pathname + url.search)}${c.req.header('x-fondu') ? ' · navigation' : ''}</p></header>
|
|
70
74
|
<main><h2>Stack — your files are highlighted</h2><ol>${frames.map(frame).join('')}</ol></main>
|
|
71
75
|
<footer>Shown in development only. In production this request gets your error page with status 500.</footer>
|
|
72
|
-
</article
|
|
76
|
+
</article>
|
|
77
|
+
<script type="module"${nonce ? ` nonce="${nonce}"` : ''}>
|
|
78
|
+
import { createHotContext } from '${import.meta.env.BASE_URL}@vite/client'
|
|
79
|
+
// fixed and saved: the page again (what the edit reached, a route or the browser's code)
|
|
80
|
+
const hot = createHotContext('/@fondu/error-report')
|
|
81
|
+
hot.on('fondu:props', () => location.reload())
|
|
82
|
+
hot.on('vite:afterUpdate', () => location.reload())
|
|
83
|
+
</script></body></html>`;
|
|
73
84
|
}
|
package/dist/server/flash.d.ts
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
import type { FlashData } from '@inertiajs/core';
|
|
2
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import type { Flash } from '../types.js';
|
|
3
3
|
/** https, directly or behind a proxy that says so */
|
|
4
4
|
export declare const isSecure: (c: Context) => boolean;
|
|
5
|
-
/** Flash data for the next page (`
|
|
6
|
-
export declare function flash(c: Context, data: Partial<
|
|
5
|
+
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
|
6
|
+
export declare function flash(c: Context, data: Partial<Flash>): void;
|
|
7
7
|
/** Validation errors for the next page (its `errors` prop). */
|
|
8
8
|
export declare function flashErrors(c: Context, errors: Record<string, unknown>): void;
|
|
9
|
-
/** The next page clears the browser history Inertia kept (and encrypted): after signing out, for example. */
|
|
10
|
-
export declare function clearHistory(c: Context): void;
|
|
11
9
|
/** What this page shows: carried over from the previous request (read once), plus what this request set. */
|
|
12
|
-
export declare function takeCarried(c: Context
|
|
10
|
+
export declare function takeCarried(c: Context): {
|
|
13
11
|
flash: Record<string, unknown>;
|
|
14
12
|
errors: Record<string, unknown>;
|
|
15
|
-
clearHistory: boolean;
|
|
16
13
|
};
|
|
17
14
|
/** Writes what is left for the next request; clears what was shown. Installed by `createApp()`. */
|
|
18
15
|
export declare const flashCookie: MiddlewareHandler;
|
package/dist/server/flash.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { generateCookie, getCookie } from 'hono/cookie';
|
|
2
|
+
import { appendHeader } from './http.js';
|
|
2
3
|
const states = new WeakMap();
|
|
3
4
|
const state = (c) => {
|
|
4
5
|
let s = states.get(c);
|
|
@@ -10,7 +11,7 @@ const state = (c) => {
|
|
|
10
11
|
export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
|
|
11
12
|
c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
12
13
|
const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
|
|
13
|
-
/** Flash data for the next page (`
|
|
14
|
+
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
|
14
15
|
export function flash(c, data) {
|
|
15
16
|
const out = state(c).outgoing;
|
|
16
17
|
out.flash = { ...out.flash, ...data };
|
|
@@ -19,14 +20,10 @@ export function flash(c, data) {
|
|
|
19
20
|
export function flashErrors(c, errors) {
|
|
20
21
|
state(c).outgoing.errors = errors;
|
|
21
22
|
}
|
|
22
|
-
/** The next page clears the browser history Inertia kept (and encrypted): after signing out, for example. */
|
|
23
|
-
export function clearHistory(c) {
|
|
24
|
-
state(c).outgoing.clearHistory = true;
|
|
25
|
-
}
|
|
26
23
|
/** What this page shows: carried over from the previous request (read once), plus what this request set. */
|
|
27
|
-
export function takeCarried(c
|
|
24
|
+
export function takeCarried(c) {
|
|
28
25
|
const s = state(c);
|
|
29
|
-
if (
|
|
26
|
+
if (!s.read) {
|
|
30
27
|
s.read = true;
|
|
31
28
|
try {
|
|
32
29
|
s.incoming = JSON.parse(getCookie(c, cookieName(c)) ?? 'null') ?? undefined;
|
|
@@ -38,10 +35,8 @@ export function takeCarried(c, consume) {
|
|
|
38
35
|
const carried = {
|
|
39
36
|
flash: { ...s.incoming?.flash, ...s.outgoing.flash },
|
|
40
37
|
errors: { ...s.incoming?.errors, ...s.outgoing.errors },
|
|
41
|
-
clearHistory: Boolean(s.incoming?.clearHistory || s.outgoing.clearHistory),
|
|
42
38
|
};
|
|
43
|
-
|
|
44
|
-
s.outgoing = {};
|
|
39
|
+
s.outgoing = {};
|
|
45
40
|
return carried;
|
|
46
41
|
}
|
|
47
42
|
/** Writes what is left for the next request; clears what was shown. Installed by `createApp()`. */
|
|
@@ -52,13 +47,13 @@ export const flashCookie = async (c, next) => {
|
|
|
52
47
|
return;
|
|
53
48
|
const name = cookieName(c);
|
|
54
49
|
const options = { path: '/', httpOnly: true, sameSite: 'Lax', secure: isSecure(c) };
|
|
55
|
-
if (s.outgoing.flash || s.outgoing.errors
|
|
50
|
+
if (s.outgoing.flash || s.outgoing.errors) {
|
|
56
51
|
const value = JSON.stringify(s.outgoing);
|
|
57
52
|
// browsers drop a cookie over ~4 KB without a word: the next page would show no errors, no flash
|
|
58
53
|
if (encodeURIComponent(value).length > 4000)
|
|
59
54
|
console.error(`[fondu] flash data and errors are too large for a cookie (${encodeURIComponent(value).length} bytes, about 4000 fit): the browser will drop them`);
|
|
60
|
-
|
|
55
|
+
appendHeader(c, 'Set-Cookie', generateCookie(name, value, { ...options, maxAge: 60 }));
|
|
61
56
|
}
|
|
62
57
|
else if (s.read && s.incoming)
|
|
63
|
-
|
|
58
|
+
appendHeader(c, 'Set-Cookie', generateCookie(name, '', { ...options, maxAge: 0 }));
|
|
64
59
|
};
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ interface WithInput<S extends Schemas> {
|
|
|
12
12
|
/**
|
|
13
13
|
* Validated input for the handler, after the middleware (a guard runs before the request body is read):
|
|
14
14
|
* `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
|
|
15
|
-
* Any Standard Schema. Invalid input: back to the page with the errors
|
|
15
|
+
* Any Standard Schema. Invalid input: back to the page with the errors, or 422 `{ errors }`.
|
|
16
16
|
* More than three middleware: combine them with `every()` from `hono/combine`.
|
|
17
17
|
*/
|
|
18
18
|
declare function withValidator<S extends Schemas>(schemas: S): WithInput<S>;
|
package/dist/server/handler.js
CHANGED
|
@@ -4,7 +4,7 @@ const factory = createFactory();
|
|
|
4
4
|
/**
|
|
5
5
|
* Validated input for the handler, after the middleware (a guard runs before the request body is read):
|
|
6
6
|
* `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
|
|
7
|
-
* Any Standard Schema. Invalid input: back to the page with the errors
|
|
7
|
+
* Any Standard Schema. Invalid input: back to the page with the errors, or 422 `{ errors }`.
|
|
8
8
|
* More than three middleware: combine them with `every()` from `hono/combine`.
|
|
9
9
|
*/
|
|
10
10
|
function withValidator(schemas) {
|
package/dist/server/http.d.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
/** a navigation of fondu/client: it wants the page as JSON */
|
|
3
|
+
export declare const isPageRequest: (c: Context) => boolean;
|
|
4
|
+
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
4
5
|
export declare const wantsPage: (c: Context) => boolean;
|
|
5
6
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
6
7
|
export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
|
|
7
8
|
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
8
9
|
export declare const back: (c: Context, fallback?: string) => Response & import("hono").TypedResponse<undefined, 303, "redirect">;
|
|
9
10
|
/**
|
|
10
|
-
* A
|
|
11
|
-
*
|
|
11
|
+
* A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
|
|
12
|
+
* the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
|
|
13
|
+
* unless they can't change (a `fetch()`'s): the copy.
|
|
12
14
|
*/
|
|
13
|
-
export declare
|
|
15
|
+
export declare function appendHeader(c: Context, name: string, value: string): void;
|
package/dist/server/http.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/** a navigation of fondu/client: it wants the page as JSON */
|
|
2
|
+
export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
|
|
3
|
+
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
4
|
+
export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
|
|
4
5
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
5
6
|
export function sameOrigin(c, url) {
|
|
6
7
|
if (!url)
|
|
@@ -19,7 +20,15 @@ export const back = (c, fallback = '/') => {
|
|
|
19
20
|
return c.redirect(from ? from.pathname.replace(/^\/+/, '/') + from.search : fallback, 303);
|
|
20
21
|
};
|
|
21
22
|
/**
|
|
22
|
-
* A
|
|
23
|
-
*
|
|
23
|
+
* A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
|
|
24
|
+
* the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
|
|
25
|
+
* unless they can't change (a `fetch()`'s): the copy.
|
|
24
26
|
*/
|
|
25
|
-
export
|
|
27
|
+
export function appendHeader(c, name, value) {
|
|
28
|
+
try {
|
|
29
|
+
c.res.headers.append(name, value);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
c.header(name, value, { append: true });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -18,6 +18,6 @@ export declare function prerenderPaths(routes: PrerenderRoute[]): Promise<{
|
|
|
18
18
|
}>;
|
|
19
19
|
/**
|
|
20
20
|
* `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
|
|
21
|
-
* a
|
|
21
|
+
* a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
|
|
22
22
|
*/
|
|
23
23
|
export declare function prerenderRoutes(app: Hono, routes: () => PrerenderRoute[], version: string | null): void;
|