fondu 0.12.0 → 0.13.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/app.js +26 -25
- package/dist/client/form.js +1 -3
- package/dist/client/navigation.js +2 -2
- package/dist/client.d.ts +11 -7
- package/dist/client.js +6 -0
- package/dist/form.d.ts +2 -2
- package/dist/form.js +9 -2
- package/dist/paths.d.ts +6 -0
- package/dist/paths.js +5 -1
- package/dist/server/app.d.ts +1 -1
- package/dist/server/app.js +2 -5
- package/dist/server/document.js +2 -1
- package/dist/server/errors.d.ts +0 -2
- package/dist/server/errors.js +3 -3
- package/dist/server/flash.d.ts +0 -2
- package/dist/server/flash.js +1 -1
- package/dist/server/http.d.ts +2 -0
- package/dist/server/http.js +2 -0
- package/dist/server/prerender.js +8 -5
- package/dist/server/protocol.js +1 -1
- package/dist/server/routes.d.ts +2 -1
- package/dist/server/routes.js +5 -1
- package/dist/server/validate.d.ts +2 -6
- package/dist/vite/index.d.ts +4 -1
- package/dist/vite/index.js +3 -4
- package/dist/vite/prerender.d.ts +1 -2
- package/dist/vite/prerender.js +4 -3
- package/dist/vite/strip.d.ts +0 -2
- package/dist/vite/strip.js +2 -14
- package/dist/vite/typegen.d.ts +0 -6
- package/dist/vite/typegen.js +2 -2
- package/package.json +1 -1
package/dist/client/app.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Component, createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
|
|
2
2
|
import { flushSync } from 'react-dom';
|
|
3
3
|
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
4
|
-
import { layoutsOf, pageId, routePatterns } from '../paths.js';
|
|
4
|
+
import { decoded, layoutsOf, pageId, routePatterns } from '../paths.js';
|
|
5
5
|
import { again, startNavigation } from './navigation.js';
|
|
6
6
|
import { progressBar } from './progress.js';
|
|
7
7
|
const ROUTES = '/app/routes/';
|
|
@@ -9,6 +9,8 @@ const ERROR = '_error';
|
|
|
9
9
|
// set by the app's entry (the Vite plugin's): the pages and layouts of app/routes/, and the build's settings
|
|
10
10
|
let pages = new Map();
|
|
11
11
|
let layoutModules = {};
|
|
12
|
+
/** each page's URL patterns, segment by segment: for `pageAt` */
|
|
13
|
+
let patterns = [];
|
|
12
14
|
/**
|
|
13
15
|
* @internal the app's entry (the Vite plugin writes it), in the browser and for the server render: `import.meta.glob`
|
|
14
16
|
* of the pages and layouts of `app/routes/`, and `fondu({ prerender, progress })`. In the browser it starts the app:
|
|
@@ -17,6 +19,9 @@ let layoutModules = {};
|
|
|
17
19
|
export function __entry(pageModules, layouts, settings) {
|
|
18
20
|
pages = new Map(Object.entries(pageModules).map(([key, loader]) => [pageId(key.slice(ROUTES.length)), loader]));
|
|
19
21
|
layoutModules = layouts;
|
|
22
|
+
patterns = [...pages.keys()]
|
|
23
|
+
.filter((id) => !id.split('/').some((s) => s.startsWith('_'))) // the error page is no URL
|
|
24
|
+
.flatMap((id) => routePatterns(id).map((p) => ({ id, segments: p.split('/').filter(Boolean) })));
|
|
20
25
|
if (typeof document !== 'undefined')
|
|
21
26
|
start(settings);
|
|
22
27
|
}
|
|
@@ -74,32 +79,28 @@ class Failed extends Component {
|
|
|
74
79
|
* listed values are the server's), so the page shown is the one the server says.
|
|
75
80
|
*/
|
|
76
81
|
export function pageAt(pathname) {
|
|
77
|
-
|
|
82
|
+
// decoded, as the server matches them (`/caf%C3%A9` is `café.tsx`)
|
|
83
|
+
const parts = pathname.split('/').filter(Boolean).map(decoded);
|
|
78
84
|
let best;
|
|
79
|
-
for (const id of
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
for (const
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
score += s === part ? 3 : -Infinity;
|
|
96
|
-
i = s.endsWith('{.+}') ? parts.length : i + 1;
|
|
97
|
-
if (score < 0)
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
if (score >= 0 && i === parts.length && (!best || score > best.score))
|
|
101
|
-
best = { id, score };
|
|
85
|
+
for (const { id, segments } of patterns) {
|
|
86
|
+
let score = 0;
|
|
87
|
+
let i = 0;
|
|
88
|
+
for (const s of segments) {
|
|
89
|
+
const part = parts[i];
|
|
90
|
+
if (part === undefined)
|
|
91
|
+
score = -1;
|
|
92
|
+
else if (s.endsWith('{.+}'))
|
|
93
|
+
score += 1; // a catch-all: the rest
|
|
94
|
+
else if (s.startsWith(':'))
|
|
95
|
+
score += 2;
|
|
96
|
+
else
|
|
97
|
+
score += s === part ? 3 : -Infinity;
|
|
98
|
+
i = s.endsWith('{.+}') ? parts.length : i + 1;
|
|
99
|
+
if (score < 0)
|
|
100
|
+
break;
|
|
102
101
|
}
|
|
102
|
+
if (score >= 0 && i === parts.length && (!best || score > best.score))
|
|
103
|
+
best = { id, score };
|
|
103
104
|
}
|
|
104
105
|
return best?.id;
|
|
105
106
|
}
|
package/dist/client/form.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react';
|
|
2
|
-
import { fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
|
|
2
|
+
import { crlf, fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
|
|
3
3
|
import { useNavigation, usePage } from './app.js';
|
|
4
4
|
/** a form's fields as the server reads them: its body for a POST (`withValidator({ body })`), its query for a GET */
|
|
5
5
|
function fieldsOf(form, submitter) {
|
|
6
6
|
const data = new FormData(form, submitter ?? undefined);
|
|
7
|
-
// as the browser sends them: line breaks as CRLF (a <textarea>'s)
|
|
8
|
-
const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
9
7
|
const entries = [...data].map(([k, v]) => [crlf(k), typeof v === 'string' ? crlf(v) : v]);
|
|
10
8
|
const method = (submitter?.getAttribute('formmethod') ??
|
|
11
9
|
form.getAttribute('method') ??
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { crlf } from '../form.js';
|
|
1
2
|
import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
|
|
2
3
|
let visit;
|
|
3
4
|
/** a URL path is one of the app's pages (the client's, once it has started) */
|
|
@@ -216,8 +217,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
216
217
|
return;
|
|
217
218
|
event.preventDefault();
|
|
218
219
|
const data = new FormData(form, submitter);
|
|
219
|
-
// as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
|
|
220
|
-
const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
220
|
+
// as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
|
|
221
221
|
const fields = [...data].map(([k, v]) => [crlf(k), crlf(typeof v === 'string' ? v : v.name)]);
|
|
222
222
|
if (method === 'post') {
|
|
223
223
|
const enctype = attr('enctype', 'formenctype').toLowerCase();
|
package/dist/client.d.ts
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
import type { schemasOf } from './server/handler.js';
|
|
2
2
|
import type { Routes } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
5
|
-
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
6
|
-
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
7
|
-
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
8
|
-
*/
|
|
9
3
|
type Keys = keyof Routes & string;
|
|
10
4
|
type Actions = {
|
|
11
5
|
[P in Keys]: Routes[P] extends {
|
|
@@ -13,7 +7,11 @@ type Actions = {
|
|
|
13
7
|
} ? `${P}?${keyof A & string}` : never;
|
|
14
8
|
}[Keys];
|
|
15
9
|
export type Href = [Keys] extends [never] ? string : Keys | Actions;
|
|
16
|
-
|
|
10
|
+
/** the params of a URL pattern, without its action (`?name`): `/users/:id/files/:path{.+}` → id, path */
|
|
11
|
+
type ParamNames<P extends string> = P extends `${infer Path}?${string}` ? PathParams<Path> : PathParams<P>;
|
|
12
|
+
type PathParams<P extends string> = P extends `${string}:${infer Rest}` ? Rest extends `${infer Segment}/${infer More}` ? ParamName<Segment> | PathParams<More> : ParamName<Rest> : never;
|
|
13
|
+
/** a param's name, without its pattern (a catch-all's `{.+}`) */
|
|
14
|
+
type ParamName<S extends string> = S extends `${infer Name}{${string}` ? Name : S;
|
|
17
15
|
/** the handlers answering a GET of the URL (its page's `loader`, a `.ts` file's `GET`), or the action's */
|
|
18
16
|
type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extends Keys ? Routes[K] extends {
|
|
19
17
|
actions: infer As;
|
|
@@ -48,6 +46,12 @@ type Extra<P extends string> = {
|
|
|
48
46
|
type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
|
|
49
47
|
[K in ParamNames<P>]: string | number;
|
|
50
48
|
} & Extra<P>];
|
|
49
|
+
/**
|
|
50
|
+
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
51
|
+
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
52
|
+
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
53
|
+
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
54
|
+
*/
|
|
51
55
|
export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
|
|
52
56
|
export { usePage, useNavigation, reload, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
|
|
53
57
|
export { useForm } from './client/form.js';
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { fillPattern } from './paths.js';
|
|
2
|
+
/**
|
|
3
|
+
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
4
|
+
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
5
|
+
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
6
|
+
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
7
|
+
*/
|
|
2
8
|
export function href(path, ...[options]) {
|
|
3
9
|
const { query, hash, ...params } = (options ?? {});
|
|
4
10
|
let url = fillPattern(path, params);
|
package/dist/form.d.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
export declare class MalformedForm extends Error {
|
|
7
7
|
}
|
|
8
8
|
type Entry = [string, FormDataEntryValue];
|
|
9
|
+
/** a field's text as the browser sends it: line breaks as CRLF (a <textarea>'s) */
|
|
10
|
+
export declare const crlf: (text: string) => string;
|
|
9
11
|
/**
|
|
10
12
|
* Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
|
|
11
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
|
|
@@ -20,8 +22,6 @@ export interface Issue {
|
|
|
20
22
|
readonly key: PropertyKey;
|
|
21
23
|
}> | undefined;
|
|
22
24
|
}
|
|
23
|
-
/** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
|
|
24
|
-
export declare const issueKey: (path: Issue['path']) => string;
|
|
25
25
|
/** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
|
|
26
26
|
export declare const fieldKey: (name: string) => string;
|
|
27
27
|
/** each field's first message (no prototype: a field named `toString` is a field like any other) */
|
package/dist/form.js
CHANGED
|
@@ -7,6 +7,8 @@ const DEPTH = 32;
|
|
|
7
7
|
/** a body that can't be one object: a 400 on the server */
|
|
8
8
|
export class MalformedForm extends Error {
|
|
9
9
|
}
|
|
10
|
+
/** a field's text as the browser sends it: line breaks as CRLF (a <textarea>'s) */
|
|
11
|
+
export const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
10
12
|
/**
|
|
11
13
|
* Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
|
|
12
14
|
* 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
|
|
@@ -35,7 +37,12 @@ export function formObject(entries) {
|
|
|
35
37
|
if (i === path.length - 1) {
|
|
36
38
|
if (has && isObject(target[name]))
|
|
37
39
|
throw new MalformedForm(`\`${key}\` is both a value and an object`);
|
|
38
|
-
|
|
40
|
+
// given again: a list, added to in place (a copy for each value is quadratic: a small body, much work)
|
|
41
|
+
const previous = target[name];
|
|
42
|
+
if (Array.isArray(previous))
|
|
43
|
+
previous.push(value);
|
|
44
|
+
else
|
|
45
|
+
target[name] = has ? [previous, value] : value;
|
|
39
46
|
}
|
|
40
47
|
else {
|
|
41
48
|
if (!has)
|
|
@@ -58,7 +65,7 @@ const arrays = (value) => {
|
|
|
58
65
|
return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
|
|
59
66
|
};
|
|
60
67
|
/** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
|
|
61
|
-
|
|
68
|
+
const issueKey = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
62
69
|
/** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
|
|
63
70
|
export const fieldKey = (name) => name.replace(/\]/g, '').split('[').filter(Boolean).join('.');
|
|
64
71
|
/** each field's first message (no prototype: a field named `toString` is a field like any other) */
|
package/dist/paths.d.ts
CHANGED
|
@@ -15,6 +15,10 @@ export declare function routePatterns(file: string): string[];
|
|
|
15
15
|
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
16
16
|
*/
|
|
17
17
|
export declare function isRouteFile(file: string): boolean;
|
|
18
|
+
/** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
|
|
19
|
+
export declare const METHODS: readonly ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
20
|
+
export declare const HANDLERS: readonly ['loader', 'action', 'actions'];
|
|
21
|
+
export declare const CONFIG: readonly ['prerender', 'params'];
|
|
18
22
|
/** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
|
|
19
23
|
export declare const isPageFile: (file: string) => boolean;
|
|
20
24
|
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
@@ -36,6 +40,8 @@ export declare const PAGE_DATA = "/_fondu/pages";
|
|
|
36
40
|
* `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
|
|
37
41
|
*/
|
|
38
42
|
export declare function pageDataPath(path: string): string;
|
|
43
|
+
/** a URL segment decoded, or as it is if it doesn't decode */
|
|
44
|
+
export declare function decoded(segment: string): string;
|
|
39
45
|
/**
|
|
40
46
|
* a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
|
|
41
47
|
* (`index.html`, `docs/index.html`), which is another page
|
package/dist/paths.js
CHANGED
|
@@ -45,6 +45,10 @@ export function isRouteFile(file) {
|
|
|
45
45
|
!/\.(?:test|spec)\.(?:ts|[jt]sx)$/.test(file) &&
|
|
46
46
|
!file.split('/').some((s) => s.startsWith('_')));
|
|
47
47
|
}
|
|
48
|
+
/** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
|
|
49
|
+
export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
50
|
+
export const HANDLERS = ['loader', 'action', 'actions'];
|
|
51
|
+
export const CONFIG = ['prerender', 'params'];
|
|
48
52
|
/** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
|
|
49
53
|
export const isPageFile = (file) => isRouteFile(file) && !file.endsWith('.ts');
|
|
50
54
|
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
@@ -98,7 +102,7 @@ export function pageDataPath(path) {
|
|
|
98
102
|
return `${PAGE_DATA}${named}.json`;
|
|
99
103
|
}
|
|
100
104
|
/** a URL segment decoded, or as it is if it doesn't decode */
|
|
101
|
-
function decoded(segment) {
|
|
105
|
+
export function decoded(segment) {
|
|
102
106
|
try {
|
|
103
107
|
return decodeURIComponent(segment);
|
|
104
108
|
}
|
package/dist/server/app.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
|
|
|
22
22
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
23
23
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
24
24
|
* own), `action` (POST) or `actions` (POST `?name`)
|
|
25
|
-
* - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
|
|
25
|
+
* - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`
|
|
26
26
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
27
27
|
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
28
28
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
package/dist/server/app.js
CHANGED
|
@@ -5,7 +5,7 @@ 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
|
+
import { CONFIG, HANDLERS, isPageFile, isRouteFile, METHODS, pageId } from '../paths.js';
|
|
9
9
|
import { settings } from './document.js';
|
|
10
10
|
import { errorResponse } from './errors.js';
|
|
11
11
|
import { prerenderRoutes } from './prerender.js';
|
|
@@ -23,9 +23,6 @@ const CSP = {
|
|
|
23
23
|
baseUri: ["'self'"],
|
|
24
24
|
};
|
|
25
25
|
const ROOT = '/app/routes/';
|
|
26
|
-
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
27
|
-
const HANDLERS = ['loader', 'action', 'actions'];
|
|
28
|
-
const CONFIG = ['prerender', 'params'];
|
|
29
26
|
/**
|
|
30
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
|
|
31
28
|
* the handlers of its URL; the rest of its code goes to modules of its own (the browser gets the page alone)
|
|
@@ -81,7 +78,7 @@ function actionName(url) {
|
|
|
81
78
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
82
79
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
83
80
|
* own), `action` (POST) or `actions` (POST `?name`)
|
|
84
|
-
* - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
|
|
81
|
+
* - server code, `.ts`: the same handlers, or plain HTTP ones: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`
|
|
85
82
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
86
83
|
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
87
84
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
package/dist/server/document.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { assetTags } from 'virtual:fondu/assets';
|
|
2
2
|
import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
|
|
3
3
|
import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
|
|
4
|
+
import { nonceOf } from './http.js';
|
|
4
5
|
const defaultTemplate = ({ head, body }) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}</head><body>${body}</body></html>`;
|
|
5
6
|
/** the options of the app (`createApp`) a request belongs to */
|
|
6
7
|
export const settings = new WeakMap();
|
|
@@ -41,7 +42,7 @@ async function shell(template, c, nonce) {
|
|
|
41
42
|
return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
|
|
42
43
|
}
|
|
43
44
|
export async function renderDocument(c, page) {
|
|
44
|
-
const nonce = c
|
|
45
|
+
const nonce = nonceOf(c);
|
|
45
46
|
let ssr = null;
|
|
46
47
|
try {
|
|
47
48
|
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
|
package/dist/server/errors.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
-
/** the error page's id: `app/routes/_error.tsx` */
|
|
3
|
-
export declare const ERROR_PAGE = "_error";
|
|
4
2
|
/**
|
|
5
3
|
* The answer to an unmatched URL or a thrown error (installed by `createApp`):
|
|
6
4
|
* - API clients: the `HTTPException`'s response, or plain text
|
package/dist/server/errors.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { HTTPException } from 'hono/http-exception';
|
|
2
2
|
import { settings } from './document.js';
|
|
3
|
-
import { wantsPage } from './http.js';
|
|
3
|
+
import { nonceOf, wantsPage } from './http.js';
|
|
4
4
|
import { renderPage } from './protocol.js';
|
|
5
5
|
/** the error page's id: `app/routes/_error.tsx` */
|
|
6
|
-
|
|
6
|
+
const ERROR_PAGE = '_error';
|
|
7
7
|
const TEXT = {
|
|
8
8
|
401: 'Unauthorized',
|
|
9
9
|
403: 'Forbidden',
|
|
@@ -49,7 +49,7 @@ function report(c, error) {
|
|
|
49
49
|
.slice(1)
|
|
50
50
|
.map((line) => line.trim())
|
|
51
51
|
.filter(Boolean);
|
|
52
|
-
const nonce = c
|
|
52
|
+
const nonce = nonceOf(c);
|
|
53
53
|
const url = new URL(c.req.url);
|
|
54
54
|
const frame = (line) => {
|
|
55
55
|
const own = /\/app\//.test(line) && !line.includes('node_modules');
|
package/dist/server/flash.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
2
|
import type { Flash } from '../types.js';
|
|
3
|
-
/** https, directly or behind a proxy that says so */
|
|
4
|
-
export declare const isSecure: (c: Context) => boolean;
|
|
5
3
|
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
|
6
4
|
export declare function flash(c: Context, data: Partial<Flash>): void;
|
|
7
5
|
/** Validation errors for the next page (its `errors` prop). */
|
package/dist/server/flash.js
CHANGED
|
@@ -8,7 +8,7 @@ const state = (c) => {
|
|
|
8
8
|
return s;
|
|
9
9
|
};
|
|
10
10
|
/** https, directly or behind a proxy that says so */
|
|
11
|
-
|
|
11
|
+
const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
|
|
12
12
|
c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
13
13
|
const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
|
|
14
14
|
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
package/dist/server/http.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { Context } from 'hono';
|
|
|
3
3
|
export declare const isPageRequest: (c: Context) => boolean;
|
|
4
4
|
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
5
5
|
export declare const wantsPage: (c: Context) => boolean;
|
|
6
|
+
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
7
|
+
export declare const nonceOf: (c: Context) => string | undefined;
|
|
6
8
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
7
9
|
export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
|
|
8
10
|
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
package/dist/server/http.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
|
|
3
3
|
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
4
4
|
export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
|
|
5
|
+
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
6
|
+
export const nonceOf = (c) => c.get('secureHeadersNonce');
|
|
5
7
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
6
8
|
export function sameOrigin(c, url) {
|
|
7
9
|
if (!url)
|
package/dist/server/prerender.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
|
|
2
|
-
import { isPageRequest } from './http.js';
|
|
2
|
+
import { isPageRequest, nonceOf } from './http.js';
|
|
3
3
|
/** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
|
|
4
4
|
const STATIC_FILES = Symbol.for('fondu.staticFiles');
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* a prerendered page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment; `\\`
|
|
7
|
+
* separates segments too (Windows)
|
|
8
|
+
*/
|
|
9
|
+
const isStaticFile = (file) => file.split(/[\\/]/).every((s) => s !== '' && !s.startsWith('.'));
|
|
7
10
|
/** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
|
|
8
11
|
export async function prerenderPaths(routes) {
|
|
9
12
|
const paths = new Set();
|
|
@@ -65,7 +68,7 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
65
68
|
catch {
|
|
66
69
|
return next(); // not a path a file could have
|
|
67
70
|
}
|
|
68
|
-
if (!
|
|
71
|
+
if (!isStaticFile(file))
|
|
69
72
|
return next();
|
|
70
73
|
const body = await read(file);
|
|
71
74
|
if (!body)
|
|
@@ -75,7 +78,7 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
75
78
|
c.header('X-Fondu', 'true');
|
|
76
79
|
// the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
|
|
77
80
|
// security headers give it a new one
|
|
78
|
-
const nonce = c
|
|
81
|
+
const nonce = nonceOf(c);
|
|
79
82
|
if (!data && nonce) {
|
|
80
83
|
const html = new TextDecoder()
|
|
81
84
|
.decode(body)
|
package/dist/server/protocol.js
CHANGED
|
@@ -48,7 +48,7 @@ export async function renderPage(c, id, props, options = {}) {
|
|
|
48
48
|
component: id,
|
|
49
49
|
props: { ...Object.fromEntries(fromShared), ...props, errors: carried.errors },
|
|
50
50
|
url: pageUrl(c),
|
|
51
|
-
version
|
|
51
|
+
version,
|
|
52
52
|
flash: carried.flash,
|
|
53
53
|
};
|
|
54
54
|
// a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
|
package/dist/server/routes.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export interface Route {
|
|
|
33
33
|
* The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
|
|
34
34
|
* by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
|
|
35
35
|
* on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
|
|
36
|
-
* other's middleware), `params` that no route takes or that aren't single segments
|
|
36
|
+
* other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
|
|
37
|
+
* app's.
|
|
37
38
|
*/
|
|
38
39
|
export declare function routeTable(modules: Record<string, RouteModule>, append: boolean): Route[];
|
package/dist/server/routes.js
CHANGED
|
@@ -5,10 +5,14 @@ const SEGMENT = /^[\w.~-]+$/;
|
|
|
5
5
|
* The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
|
|
6
6
|
* by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
|
|
7
7
|
* on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
|
|
8
|
-
* other's middleware), `params` that no route takes or that aren't single segments
|
|
8
|
+
* other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
|
|
9
|
+
* app's.
|
|
9
10
|
*/
|
|
10
11
|
export function routeTable(modules, append) {
|
|
11
12
|
const files = Object.keys(modules);
|
|
13
|
+
const nested = files.find((f) => /\/_error\.[jt]sx$/.test(f));
|
|
14
|
+
if (nested)
|
|
15
|
+
throw new Error(`fondu: routes/${nested} is never shown: the error page is routes/_error.tsx, one for the app`);
|
|
12
16
|
const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
|
|
13
17
|
const used = new Set(); // `${file}:${name}`: a `params` entry that applies to a route
|
|
14
18
|
const routes = [];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { type Issue } from '../form.js';
|
|
2
3
|
/** The Standard Schema interface (zod, valibot, arktype…), the part used here. */
|
|
3
4
|
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
4
5
|
readonly '~standard': {
|
|
@@ -15,12 +16,7 @@ type StandardResult<Output> = {
|
|
|
15
16
|
readonly value: Output;
|
|
16
17
|
readonly issues?: undefined;
|
|
17
18
|
} | {
|
|
18
|
-
readonly issues: ReadonlyArray<
|
|
19
|
-
readonly message: string;
|
|
20
|
-
readonly path?: ReadonlyArray<PropertyKey | {
|
|
21
|
-
readonly key: PropertyKey;
|
|
22
|
-
}>;
|
|
23
|
-
}>;
|
|
19
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
24
20
|
};
|
|
25
21
|
type InferOutput<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
|
|
26
22
|
/**
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -23,7 +23,10 @@ export interface FonduOptions {
|
|
|
23
23
|
* time, and navigations read them; the server (the Worker) answers the other pages
|
|
24
24
|
*/
|
|
25
25
|
prerender?: boolean;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* the bar at the top of the page while a navigation is on its way: its `delay` (ms), its `color`, and whether forms'
|
|
28
|
+
* submissions show it (`forms`); `false`: none
|
|
29
|
+
*/
|
|
27
30
|
progress?: ProgressOptions | false;
|
|
28
31
|
}
|
|
29
32
|
/** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
|
package/dist/vite/index.js
CHANGED
|
@@ -10,8 +10,7 @@ import { isPageFile, layoutsOf, pageId } from '../paths.js';
|
|
|
10
10
|
import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
|
|
11
11
|
import { nodeServer, prerender, worker } from './prerender.js';
|
|
12
12
|
import { stripRoutes, stripServerCode } from './strip.js';
|
|
13
|
-
import { typegen } from './typegen.js';
|
|
14
|
-
import { walk as walkFiles } from './typegen.js';
|
|
13
|
+
import { typegen, walk as walkFiles } from './typegen.js';
|
|
15
14
|
/** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
|
|
16
15
|
export const HONO = [
|
|
17
16
|
'hono',
|
|
@@ -256,7 +255,7 @@ function core(options) {
|
|
|
256
255
|
isBuild = env.command === 'build';
|
|
257
256
|
const client = {
|
|
258
257
|
manifest: true,
|
|
259
|
-
|
|
258
|
+
rolldownOptions: {
|
|
260
259
|
input: V.entry,
|
|
261
260
|
// a page's or a layout's chunk named after its route file: (site)/users/[id].tsx is site-users-id
|
|
262
261
|
output: {
|
|
@@ -316,7 +315,7 @@ function core(options) {
|
|
|
316
315
|
emptyOutDir: true,
|
|
317
316
|
copyPublicDir: false,
|
|
318
317
|
minify: true,
|
|
319
|
-
|
|
318
|
+
rolldownOptions: {
|
|
320
319
|
input: V.serverEntry,
|
|
321
320
|
external: [
|
|
322
321
|
...builtinModules,
|
package/dist/vite/prerender.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { Logger } from 'vite';
|
|
2
|
-
import { staticFiles } from '../paths.js';
|
|
3
|
-
export { staticFiles };
|
|
4
2
|
/**
|
|
5
3
|
* A static document's own tags: those with the build's nonce (its Content Security Policy's). The nonce of a static
|
|
6
4
|
* document is replaced (Cloudflare: its inline scripts by their hashes; Node / Bun: by each response's nonce), which
|
|
@@ -38,3 +36,4 @@ export declare function prerender(start: () => Promise<Server>, clientDir: strin
|
|
|
38
36
|
export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
|
|
39
37
|
/** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
|
|
40
38
|
export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;
|
|
39
|
+
export {};
|
package/dist/vite/prerender.js
CHANGED
|
@@ -6,7 +6,6 @@ import { createServer } from 'node:net';
|
|
|
6
6
|
import { dirname, join, resolve } from 'node:path';
|
|
7
7
|
import { pathToFileURL } from 'node:url';
|
|
8
8
|
import { PAGE_DATA, staticFiles } from '../paths.js';
|
|
9
|
-
export { staticFiles };
|
|
10
9
|
/** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
|
|
11
10
|
const SECURITY_HEADERS = /^(content-security-policy(-report-only)?|strict-transport-security|referrer-policy|permissions-policy|x-content-type-options|x-frame-options|x-xss-protection|x-dns-prefetch-control|x-download-options|x-permitted-cross-domain-policies|origin-agent-cluster|cross-origin-(opener|embedder|resource)-policy)$/i;
|
|
12
11
|
/**
|
|
@@ -111,8 +110,10 @@ export async function prerender(start, clientDir, logger, headersFile) {
|
|
|
111
110
|
...(version && { 'X-Fondu-Version': version }),
|
|
112
111
|
});
|
|
113
112
|
if (doc.status !== 200 || visit.status !== 200) {
|
|
114
|
-
|
|
115
|
-
|
|
113
|
+
// the request that failed: the document's, else the navigation's
|
|
114
|
+
const [failed, as] = doc.status !== 200 ? [doc, 'a document'] : [visit, 'a navigation'];
|
|
115
|
+
const to = failed.headers.get('location');
|
|
116
|
+
errors.push(`${path}: ${failed.status}${to ? ` → ${to}` : ''} as ${as} (a prerendered page must answer 200 to anyone)`);
|
|
116
117
|
continue;
|
|
117
118
|
}
|
|
118
119
|
const page = (await visit.json());
|
package/dist/vite/strip.d.ts
CHANGED
package/dist/vite/strip.js
CHANGED
|
@@ -1,19 +1,7 @@
|
|
|
1
1
|
import { relative, sep } from 'node:path';
|
|
2
|
-
import { isPageFile } from '../paths.js';
|
|
2
|
+
import { CONFIG, HANDLERS, isPageFile, METHODS } from '../paths.js';
|
|
3
3
|
/** the exports of a page's route file that are server code: the browser gets the page (default) alone */
|
|
4
|
-
|
|
5
|
-
'loader',
|
|
6
|
-
'action',
|
|
7
|
-
'actions',
|
|
8
|
-
'prerender',
|
|
9
|
-
'params',
|
|
10
|
-
'GET',
|
|
11
|
-
'POST',
|
|
12
|
-
'PUT',
|
|
13
|
-
'PATCH',
|
|
14
|
-
'DELETE',
|
|
15
|
-
'OPTIONS',
|
|
16
|
-
]);
|
|
4
|
+
const SERVER_EXPORTS = new Set([...HANDLERS, ...CONFIG, ...METHODS]);
|
|
17
5
|
const nameOf = (n) => (n.name ?? n.value);
|
|
18
6
|
/** the names a declaration binds: `const { a, b: [c] } = …` → a, c */
|
|
19
7
|
function bound(node, out = []) {
|
package/dist/vite/typegen.d.ts
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
1
|
import type { Plugin } from 'vite';
|
|
2
2
|
export declare function walk(dir: string, out?: string[], base?: string): string[];
|
|
3
|
-
/**
|
|
4
|
-
* The registry the types are read from: URL pattern → route module (`href()`). Only `typeof import`s; an MDX page's
|
|
5
|
-
* keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
|
|
6
|
-
*/
|
|
7
|
-
export declare function generateTypes(root: string): string;
|
|
8
|
-
export declare function writeTypes(root: string): void;
|
|
9
3
|
export declare function typegen(): Plugin;
|
package/dist/vite/typegen.js
CHANGED
|
@@ -18,7 +18,7 @@ export function walk(dir, out = [], base = dir) {
|
|
|
18
18
|
* The registry the types are read from: URL pattern → route module (`href()`). Only `typeof import`s; an MDX page's
|
|
19
19
|
* keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
|
|
20
20
|
*/
|
|
21
|
-
|
|
21
|
+
function generateTypes(root) {
|
|
22
22
|
const routes = walk(join(root, 'app/routes')).filter(isRouteFile).sort();
|
|
23
23
|
const line = (key, path) => ` ${JSON.stringify(key)}: typeof import(${JSON.stringify(path)})`;
|
|
24
24
|
return `// Generated by fondu (vite dev / vite build). Commit it; do not edit.
|
|
@@ -41,7 +41,7 @@ function patternsOf(file) {
|
|
|
41
41
|
return [];
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
|
|
44
|
+
function writeTypes(root) {
|
|
45
45
|
const file = join(root, OUT);
|
|
46
46
|
const content = generateTypes(root);
|
|
47
47
|
if (!existsSync(file) || readFileSync(file, 'utf8') !== content)
|