fondu 0.9.6 → 0.11.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 +11 -15
- package/dist/client/app.d.ts +40 -0
- package/dist/client/app.js +185 -0
- package/dist/client/navigation.d.ts +36 -0
- package/dist/client/navigation.js +432 -0
- package/dist/client/progress.d.ts +16 -0
- package/dist/client/progress.js +64 -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 +23 -8
- package/dist/paths.js +52 -21
- 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 +27 -6
- package/dist/server/errors.d.ts +4 -2
- package/dist/server/errors.js +23 -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 +18 -10
- package/dist/server/protocol.d.ts +22 -35
- package/dist/server/protocol.js +67 -195
- package/dist/server/routes.d.ts +1 -1
- package/dist/server/validate.d.ts +8 -9
- package/dist/server/validate.js +23 -37
- 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 +174 -80
- 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 +306 -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/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;
|
package/dist/server/prerender.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
|
|
2
|
-
import {
|
|
1
|
+
import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
|
|
2
|
+
import { isPageRequest } 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
5
|
/** a page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment */
|
|
@@ -19,16 +19,21 @@ export async function prerenderPaths(routes) {
|
|
|
19
19
|
continue;
|
|
20
20
|
}
|
|
21
21
|
const dynamic = route.pattern.includes(':');
|
|
22
|
+
// a page whose URL ends in index: its file would be its directory's page's (index.html), another page
|
|
23
|
+
const add = (path) => endsInIndex(path)
|
|
24
|
+
? problems.push(`${where}: ${path} ends in index, so its static file would be the page of its directory: ` +
|
|
25
|
+
`leave it out of \`prerender\``)
|
|
26
|
+
: paths.add(path);
|
|
22
27
|
if (setting === true) {
|
|
23
28
|
if (dynamic)
|
|
24
29
|
problems.push(`${where} is dynamic: \`export const prerender = () => [{ …params }]\` lists its pages, or \`= false\``);
|
|
25
30
|
else
|
|
26
|
-
|
|
31
|
+
add(route.pattern);
|
|
27
32
|
continue;
|
|
28
33
|
}
|
|
29
34
|
try {
|
|
30
35
|
for (const params of await setting())
|
|
31
|
-
|
|
36
|
+
add(fillPattern(route.pattern, params));
|
|
32
37
|
}
|
|
33
38
|
catch (error) {
|
|
34
39
|
problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -38,7 +43,7 @@ export async function prerenderPaths(routes) {
|
|
|
38
43
|
}
|
|
39
44
|
/**
|
|
40
45
|
* `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
|
|
41
|
-
* a
|
|
46
|
+
* a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
|
|
42
47
|
*/
|
|
43
48
|
export function prerenderRoutes(app, routes, version) {
|
|
44
49
|
// Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
|
|
@@ -47,8 +52,11 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
47
52
|
const read = globalThis[STATIC_FILES];
|
|
48
53
|
if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
|
|
49
54
|
return next();
|
|
50
|
-
const data = pathOfPageData(c.req.path) !== null; // a
|
|
51
|
-
if (!data && (
|
|
55
|
+
const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
|
|
56
|
+
if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
|
|
57
|
+
return next();
|
|
58
|
+
// a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
|
|
59
|
+
if (!data && endsInIndex(c.req.path))
|
|
52
60
|
return next();
|
|
53
61
|
let file;
|
|
54
62
|
try {
|
|
@@ -64,7 +72,7 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
64
72
|
return next();
|
|
65
73
|
c.header('Cache-Control', 'private, no-cache');
|
|
66
74
|
if (data)
|
|
67
|
-
c.header('X-
|
|
75
|
+
c.header('X-Fondu', 'true');
|
|
68
76
|
// the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
|
|
69
77
|
// security headers give it a new one
|
|
70
78
|
const nonce = c.get('secureHeadersNonce');
|
|
@@ -81,12 +89,12 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
81
89
|
app.get(`${PAGE_DATA}/*`, (c) => {
|
|
82
90
|
const path = pathOfPageData(c.req.path);
|
|
83
91
|
// a page object's own URL is not a page: no page object of a page object (and so on)
|
|
84
|
-
if (!path || path.startsWith(
|
|
92
|
+
if (!path || path.startsWith('/_fondu/'))
|
|
85
93
|
return c.notFound();
|
|
86
94
|
const url = new URL(c.req.url);
|
|
87
95
|
url.pathname = path;
|
|
88
96
|
const headers = new Headers(c.req.raw.headers);
|
|
89
|
-
headers.set('X-
|
|
97
|
+
headers.set('X-Fondu', 'true');
|
|
90
98
|
let ctx;
|
|
91
99
|
try {
|
|
92
100
|
ctx = c.executionCtx;
|
|
@@ -1,36 +1,30 @@
|
|
|
1
|
-
import type { SharedPageProps } from '@inertiajs/core';
|
|
2
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
3
|
-
import type {
|
|
2
|
+
import type { Component, ReactNode } from 'react';
|
|
3
|
+
import type { Shared } from '../types.js';
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
* The client is `@inertiajs/react`, unchanged.
|
|
5
|
+
* Fondu's protocol: a document gets the HTML page, a navigation of fondu/client (`X-Fondu`) the page as JSON.
|
|
7
6
|
*/
|
|
8
7
|
type Shareable<T> = {
|
|
9
8
|
[K in keyof T]?: T[K] | (() => T[K] | Promise<T[K]>);
|
|
10
9
|
};
|
|
11
|
-
/** Props every page of this request gets (a middleware calls it: the signed-in user…)
|
|
12
|
-
export declare function share(c: Context, props: Shareable<
|
|
13
|
-
|
|
14
|
-
type
|
|
15
|
-
default: (...args: infer A) => unknown;
|
|
16
|
-
} ? A extends [infer P, ...unknown[]] ? P : Record<string, never> : Record<string, unknown> : Record<string, unknown>;
|
|
10
|
+
/** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
|
|
11
|
+
export declare function share(c: Context, props: Shareable<Shared>): void;
|
|
12
|
+
/** a page: a component, its props what it receives (a function component, or a class one) */
|
|
13
|
+
type PageComponent<P> = ((props: P) => ReactNode | Promise<ReactNode>) | (new (props: P) => Component<P>);
|
|
17
14
|
/** the props a page names: not an index signature (a page without props takes `Record<string, never>`) */
|
|
18
15
|
type Named<P> = keyof {
|
|
19
16
|
[K in keyof P as string extends K ? never : number extends K ? never : K]: 0;
|
|
20
17
|
};
|
|
21
18
|
/** shared props the page takes with the same type: `render` may leave them out (every page gets them) */
|
|
22
19
|
type FromShared<P> = {
|
|
23
|
-
[K in Named<P> & keyof
|
|
24
|
-
}[Named<P> & keyof
|
|
20
|
+
[K in Named<P> & keyof Shared]: Shared[K] extends P[K] ? K : never;
|
|
21
|
+
}[Named<P> & keyof Shared];
|
|
25
22
|
/** a page prop named like a shared prop, of another type: it would hide the shared one from the layout */
|
|
26
|
-
type Clashing<P> = string extends keyof
|
|
23
|
+
type Clashing<P> = string extends keyof Shared ? never : Exclude<Named<P> & keyof Shared, FromShared<P>>;
|
|
27
24
|
type ClashError = 'fondu: this page prop has the name of a shared prop (share()); rename it';
|
|
28
25
|
/** what `render` takes: the component's props, less `errors` and the shared props it gets anyway (may still be given) */
|
|
29
|
-
type OwnProps<
|
|
30
|
-
[K in Clashing<
|
|
31
|
-
};
|
|
32
|
-
type PropsInput<P> = {
|
|
33
|
-
[K in keyof P]: P[K] | (() => P[K] | Promise<P[K]>);
|
|
26
|
+
type OwnProps<P> = Omit<P, FromShared<P> | Clashing<P> | 'errors'> & Partial<Pick<P, FromShared<P>>> & {
|
|
27
|
+
[K in Clashing<P>]: ClashError;
|
|
34
28
|
};
|
|
35
29
|
type Json = string | number | boolean | null;
|
|
36
30
|
/** types JSON doesn't deliver as they are: a Date arrives as a string, a Map or a Set as {}, a function not at all */
|
|
@@ -57,27 +51,20 @@ export type Delivered<P> = {
|
|
|
57
51
|
type RequiredKeys<T> = {
|
|
58
52
|
[K in keyof T]-?: object extends Pick<T, K> ? never : K;
|
|
59
53
|
}[keyof T];
|
|
60
|
-
/**
|
|
61
|
-
* The pages of these requests are encrypted in the browser's history (Laravel's `EncryptHistory` middleware), so Back
|
|
62
|
-
* after signing out can't show them: in `routes/account/_middleware.ts`, `export default encryptHistory()`. A route
|
|
63
|
-
* can still opt out: `render(c, page, props, { encryptHistory: false })`.
|
|
64
|
-
*/
|
|
65
|
-
export declare const encryptHistory: () => MiddlewareHandler;
|
|
66
54
|
export interface RenderOptions {
|
|
67
55
|
status?: number;
|
|
68
|
-
/** the page's state is encrypted in the browser's history; default: `encryptHistory()` above the route, or not */
|
|
69
|
-
encryptHistory?: boolean;
|
|
70
|
-
clearHistory?: boolean;
|
|
71
|
-
preserveFragment?: boolean;
|
|
72
56
|
}
|
|
73
|
-
type RenderArgs<
|
|
74
|
-
type OptionalArgs<
|
|
75
|
-
type RequiredArgs<
|
|
76
|
-
export declare const
|
|
57
|
+
type RenderArgs<P> = [keyof OwnProps<P>] extends [never] ? [props?: Record<string, never>, options?: RenderOptions] : [RequiredKeys<OwnProps<P>>] extends [never] ? OptionalArgs<P> : string extends keyof OwnProps<P> ? OptionalArgs<P> : RequiredArgs<P>;
|
|
58
|
+
type OptionalArgs<P> = [props?: Delivered<OwnProps<P>>, options?: RenderOptions];
|
|
59
|
+
type RequiredArgs<P> = [props: Delivered<OwnProps<P>>, options?: RenderOptions];
|
|
60
|
+
export declare const registerPage: (component: object, id: string) => void;
|
|
61
|
+
export declare const routePage: (id: string) => MiddlewareHandler;
|
|
77
62
|
/**
|
|
78
|
-
* The
|
|
79
|
-
*
|
|
63
|
+
* The route file's page (its default export) with these props: JSON for a navigation, the HTML document
|
|
64
|
+
* (server-rendered) otherwise. Props are checked against the component's own, as JSON delivers them.
|
|
80
65
|
*/
|
|
81
|
-
export declare function render<
|
|
66
|
+
export declare function render<P extends object>(c: Context, page: PageComponent<P>, ...[props, options]: RenderArgs<P>): Promise<Response>;
|
|
67
|
+
/** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
|
|
68
|
+
export declare function renderPage(c: Context, id: string, props: Record<string, unknown>, options?: RenderOptions): Promise<Response>;
|
|
82
69
|
export declare const protocol: MiddlewareHandler[];
|
|
83
70
|
export {};
|
package/dist/server/protocol.js
CHANGED
|
@@ -1,41 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { isPageFile } from '../paths.js';
|
|
1
|
+
import { version } from 'virtual:fondu/assets';
|
|
3
2
|
import { renderDocument } from './document.js';
|
|
4
3
|
import { flashCookie, takeCarried } from './flash.js';
|
|
5
|
-
import { back,
|
|
6
|
-
import { propSpec, resolve } from './props.js';
|
|
4
|
+
import { appendHeader, back, isPageRequest, sameOrigin } from './http.js';
|
|
7
5
|
const shared = new WeakMap();
|
|
8
|
-
/** Props every page of this request gets (a middleware calls it: the signed-in user…)
|
|
6
|
+
/** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
|
|
9
7
|
export function share(c, props) {
|
|
10
8
|
shared.set(c, { ...shared.get(c), ...props });
|
|
11
9
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
encrypted.add(c);
|
|
20
|
-
await next();
|
|
10
|
+
// the pages of app/routes/ (createApp): a component → its ids; and, per request, the page of the route answering it
|
|
11
|
+
// (the ids: a page may be the default export of several, `export { default } from './index.tsx'`)
|
|
12
|
+
const pageIds = new WeakMap();
|
|
13
|
+
const ownPages = new WeakMap();
|
|
14
|
+
export const registerPage = (component, id) => {
|
|
15
|
+
const ids = pageIds.get(component) ?? new Set();
|
|
16
|
+
pageIds.set(component, ids.add(id));
|
|
21
17
|
};
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
? pages.includes(name)
|
|
26
|
-
: isPageFile(`${name}.tsx`) &&
|
|
27
|
-
['tsx', 'jsx', 'mdx'].some((ext) => `/app/pages/${name}.${ext}` in devPages);
|
|
28
|
-
const headerSet = (c, name) => {
|
|
29
|
-
const value = c.req.header(name);
|
|
30
|
-
return value === undefined
|
|
31
|
-
? null
|
|
32
|
-
: new Set(value
|
|
33
|
-
.split(',')
|
|
34
|
-
.map((s) => s.trim())
|
|
35
|
-
.filter(Boolean));
|
|
18
|
+
export const routePage = (id) => async (c, next) => {
|
|
19
|
+
ownPages.set(c, id);
|
|
20
|
+
await next();
|
|
36
21
|
};
|
|
37
|
-
const isPrefetch = (c) => c.req.header('purpose') === 'prefetch' ||
|
|
38
|
-
c.req.header('sec-purpose')?.includes('prefetch') === true;
|
|
39
22
|
/** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
|
|
40
23
|
function pageUrl(c) {
|
|
41
24
|
const here = new URL(c.req.url);
|
|
@@ -43,191 +26,80 @@ function pageUrl(c) {
|
|
|
43
26
|
return from.pathname.replace(/^\/+/, '/') + from.search;
|
|
44
27
|
}
|
|
45
28
|
/**
|
|
46
|
-
* The
|
|
47
|
-
*
|
|
29
|
+
* The route file's page (its default export) with these props: JSON for a navigation, the HTML document
|
|
30
|
+
* (server-rendered) otherwise. Props are checked against the component's own, as JSON delivers them.
|
|
48
31
|
*/
|
|
49
|
-
export
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
const
|
|
32
|
+
export function render(c, page, ...[props = {}, options = {}]) {
|
|
33
|
+
const own = ownPages.get(c);
|
|
34
|
+
if (!own || !pageIds.get(page)?.has(own))
|
|
35
|
+
throw new Error(own
|
|
36
|
+
? `fondu: render() renders the page of its own route file, routes/${own}: its default export`
|
|
37
|
+
: 'fondu: render() renders the page of its route file (a .tsx or .mdx file, its default export); this route has none');
|
|
38
|
+
return renderPage(c, own, props, options);
|
|
39
|
+
}
|
|
40
|
+
/** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
|
|
41
|
+
export async function renderPage(c, id, props, options = {}) {
|
|
42
|
+
const carried = takeCarried(c);
|
|
43
|
+
const fromShared = await Promise.all(Object.entries(shared.get(c) ?? {}).map(async ([key, value]) => [
|
|
44
|
+
key,
|
|
45
|
+
typeof value === 'function' ? await value() : value,
|
|
46
|
+
]));
|
|
61
47
|
const page = {
|
|
62
|
-
component,
|
|
63
|
-
props: { errors:
|
|
48
|
+
component: id,
|
|
49
|
+
props: { ...Object.fromEntries(fromShared), ...props, errors: carried.errors },
|
|
64
50
|
url: pageUrl(c),
|
|
65
51
|
version: version ?? null,
|
|
66
52
|
flash: carried.flash,
|
|
67
53
|
};
|
|
68
|
-
const lists = {
|
|
69
|
-
mergeProps: [],
|
|
70
|
-
prependProps: [],
|
|
71
|
-
deepMergeProps: [],
|
|
72
|
-
matchPropsOn: [],
|
|
73
|
-
};
|
|
74
|
-
const deferred = {};
|
|
75
|
-
const onceProps = {};
|
|
76
|
-
const pending = [];
|
|
77
|
-
const listOnce = (key, once) => {
|
|
78
|
-
onceProps[once.key ?? key] = {
|
|
79
|
-
prop: key,
|
|
80
|
-
expiresAt: once.ttl ? Date.now() + once.ttl * 1000 : null,
|
|
81
|
-
};
|
|
82
|
-
};
|
|
83
|
-
const listMerge = (key, spec) => {
|
|
84
|
-
if (reset.has(key))
|
|
85
|
-
return;
|
|
86
|
-
if (spec.scroll) {
|
|
87
|
-
// <InfiniteScroll> says which side it loads: the previous page goes before what the client holds
|
|
88
|
-
const intent = c.req.header('x-inertia-infinite-scroll-merge-intent') === 'prepend'
|
|
89
|
-
? 'prependProps'
|
|
90
|
-
: 'mergeProps';
|
|
91
|
-
lists[intent].push(`${key}.data`);
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
const { strategy, paths, matchOn } = spec.merge;
|
|
95
|
-
const into = strategy === 'append'
|
|
96
|
-
? 'mergeProps'
|
|
97
|
-
: strategy === 'prepend'
|
|
98
|
-
? 'prependProps'
|
|
99
|
-
: 'deepMergeProps';
|
|
100
|
-
lists[into].push(...(paths.length ? paths.map((path) => `${key}.${path}`) : [key]));
|
|
101
|
-
lists.matchPropsOn.push(...matchOn.map((field) => `${key}.${field}`));
|
|
102
|
-
};
|
|
103
|
-
for (const [key, value] of Object.entries(all)) {
|
|
104
|
-
const spec = propSpec(value);
|
|
105
|
-
// a partial reload: the props it names (`only`) or keeps (`except`), and the `always` ones
|
|
106
|
-
if (!spec?.always && ((only && !only.has(key)) || except?.has(key)))
|
|
107
|
-
continue;
|
|
108
|
-
// only when named (Inertia's docs: `only`), not with `except`, though inertia-laravel's code sends it then
|
|
109
|
-
if (spec?.optional && !only?.has(key)) {
|
|
110
|
-
if (!partial && spec.once)
|
|
111
|
-
listOnce(key, spec.once);
|
|
112
|
-
continue;
|
|
113
|
-
}
|
|
114
|
-
// held by the client: not sent again on a visit (a partial reload sends what it asks for), still listed
|
|
115
|
-
const held = !partial && spec?.once && heldOnce.has(spec.once.key ?? key) && !spec.once.fresh;
|
|
116
|
-
if (spec?.defer && !partial) {
|
|
117
|
-
if (!held)
|
|
118
|
-
(deferred[spec.defer.group] ??= []).push(key);
|
|
119
|
-
if (spec.once)
|
|
120
|
-
listOnce(key, spec.once);
|
|
121
|
-
if (spec.merge || spec.scroll)
|
|
122
|
-
listMerge(key, spec);
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
if (held) {
|
|
126
|
-
listOnce(key, spec.once);
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
if (spec?.once)
|
|
130
|
-
listOnce(key, spec.once);
|
|
131
|
-
if (spec?.merge || spec?.scroll)
|
|
132
|
-
listMerge(key, spec);
|
|
133
|
-
pending.push([key, value]);
|
|
134
|
-
}
|
|
135
|
-
const rescued = [];
|
|
136
|
-
const resolved = await Promise.all(pending.map(async ([key, value]) => {
|
|
137
|
-
const spec = propSpec(value);
|
|
138
|
-
try {
|
|
139
|
-
return [[key, await resolve(spec ? spec.value : value)]];
|
|
140
|
-
}
|
|
141
|
-
catch (error) {
|
|
142
|
-
if (!spec?.defer?.rescue)
|
|
143
|
-
throw error;
|
|
144
|
-
console.error(`[fondu] deferred prop "${key}" failed (rescued):`, error);
|
|
145
|
-
rescued.push(key);
|
|
146
|
-
return [];
|
|
147
|
-
}
|
|
148
|
-
}));
|
|
149
|
-
page.props = { ...Object.fromEntries(resolved.flat()), errors: carried.errors };
|
|
150
|
-
if (rescued.length)
|
|
151
|
-
page.rescuedProps = rescued;
|
|
152
|
-
const scrollProps = {};
|
|
153
|
-
for (const [key, value] of pending) {
|
|
154
|
-
const spec = propSpec(value);
|
|
155
|
-
if (spec?.scroll && key in page.props) {
|
|
156
|
-
const { currentPage, previousPage, nextPage } = page.props[key];
|
|
157
|
-
scrollProps[key] = {
|
|
158
|
-
pageName: spec.scroll.pageName,
|
|
159
|
-
currentPage,
|
|
160
|
-
previousPage,
|
|
161
|
-
nextPage,
|
|
162
|
-
reset: reset.has(key),
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
if (Object.keys(scrollProps).length)
|
|
167
|
-
page.scrollProps = scrollProps;
|
|
168
|
-
for (const [name, list] of Object.entries(lists))
|
|
169
|
-
if (list.length)
|
|
170
|
-
page[name] = list;
|
|
171
|
-
if (Object.keys(deferred).length)
|
|
172
|
-
page.deferredProps = deferred;
|
|
173
|
-
if (Object.keys(onceProps).length)
|
|
174
|
-
page.onceProps = onceProps;
|
|
175
|
-
const sharedKeys = Object.keys(sharedProps);
|
|
176
|
-
if (sharedKeys.length)
|
|
177
|
-
page.sharedProps = sharedKeys;
|
|
178
|
-
if (options.encryptHistory ?? encrypted.has(c))
|
|
179
|
-
page.encryptHistory = true;
|
|
180
|
-
if (options.clearHistory || carried.clearHistory)
|
|
181
|
-
page.clearHistory = true;
|
|
182
|
-
if (options.preserveFragment)
|
|
183
|
-
page.preserveFragment = true;
|
|
184
54
|
// a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
|
|
185
55
|
if (!c.res.headers.has('Cache-Control'))
|
|
186
56
|
c.header('Cache-Control', 'private, no-cache');
|
|
187
|
-
if (
|
|
188
|
-
c.header('X-
|
|
57
|
+
if (isPageRequest(c)) {
|
|
58
|
+
c.header('X-Fondu', 'true');
|
|
189
59
|
return c.json(page, (options.status ?? 200));
|
|
190
60
|
}
|
|
191
61
|
return c.html(await renderDocument(c, page), (options.status ?? 200));
|
|
192
62
|
}
|
|
63
|
+
/** an http(s) URL, as `to` resolves from the request's */
|
|
64
|
+
function webUrl(c, to) {
|
|
65
|
+
try {
|
|
66
|
+
return /^https?:$/.test(new URL(to, c.req.url).protocol);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
193
72
|
// ---- the protocol middleware (installed by createApp)
|
|
194
73
|
const versionCheck = async (c, next) => {
|
|
195
|
-
//
|
|
74
|
+
// a navigation of a client built from other assets: the page loads as a document
|
|
196
75
|
if (version &&
|
|
197
76
|
c.req.method === 'GET' &&
|
|
198
|
-
|
|
199
|
-
c.req.header('x-
|
|
200
|
-
return c.body(null, 409, {
|
|
201
|
-
'X-Inertia-Location': c.req.url,
|
|
202
|
-
'X-Inertia-Version': version,
|
|
203
|
-
Vary: 'X-Inertia',
|
|
204
|
-
});
|
|
77
|
+
isPageRequest(c) &&
|
|
78
|
+
c.req.header('x-fondu-version') !== version) {
|
|
79
|
+
return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: 'X-Fondu' });
|
|
205
80
|
}
|
|
206
81
|
await next();
|
|
207
|
-
// a URL answers a
|
|
208
|
-
c
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
if (c.res.status === 200 &&
|
|
213
|
-
!c.res.headers.has('x-inertia') &&
|
|
214
|
-
(await c.res.clone().text()) === '') {
|
|
82
|
+
// a URL answers a navigation and a document differently: caches keep them apart
|
|
83
|
+
appendHeader(c, 'Vary', 'X-Fondu');
|
|
84
|
+
// an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
|
|
85
|
+
// isn't read to tell (a stream's would be, to its end)
|
|
86
|
+
if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
|
|
215
87
|
c.res = back(c);
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
88
|
+
const to = c.res.headers.get('location');
|
|
89
|
+
if (isPageRequest(c) && c.res.status >= 300 && c.res.status < 400 && to) {
|
|
90
|
+
// to another site: fetch() can't follow it (CORS), the client loads it as a document; http(s) only (a browser
|
|
91
|
+
// follows no redirect to `javascript:`, and neither does the client)
|
|
92
|
+
const here = sameOrigin(c, to);
|
|
93
|
+
if (!here) {
|
|
94
|
+
if (webUrl(c, to))
|
|
95
|
+
c.res = c.body(null, 409, { 'X-Fondu-Location': to });
|
|
96
|
+
}
|
|
97
|
+
// to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows, from
|
|
98
|
+
// this site's root (a relative Location is the request's, not the page's on the screen)
|
|
99
|
+
else if (to.includes('#'))
|
|
100
|
+
c.res = c.body(null, 200, {
|
|
101
|
+
'X-Fondu-Redirect': here.pathname.replace(/^\/+/, '/') + here.search + here.hash,
|
|
102
|
+
});
|
|
231
103
|
}
|
|
232
104
|
};
|
|
233
105
|
export const protocol = [flashCookie, versionCheck];
|
package/dist/server/routes.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export interface RouteModule {
|
|
|
8
8
|
prerender?: Prerender;
|
|
9
9
|
/** the values its params take, `{ lang: ['de', 'fr'] }`, any other not its URL (also in a `_middleware.ts`) */
|
|
10
10
|
params?: Params;
|
|
11
|
-
/** a `_middleware.ts`: the middleware */
|
|
11
|
+
/** a `_middleware.ts`: the middleware; a page: its component */
|
|
12
12
|
default?: Handlers;
|
|
13
13
|
loader?: Handlers;
|
|
14
14
|
action?: Handlers;
|
|
@@ -24,8 +24,8 @@ type StandardResult<Output> = {
|
|
|
24
24
|
};
|
|
25
25
|
type InferOutput<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
|
|
26
26
|
/**
|
|
27
|
-
* Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`:
|
|
28
|
-
* and
|
|
27
|
+
* Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: navigations
|
|
28
|
+
* and forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
|
|
29
29
|
* requests (an API client) get 422 `{ errors }`.
|
|
30
30
|
*/
|
|
31
31
|
export declare class ValidationError extends Error {
|
|
@@ -34,10 +34,11 @@ export declare class ValidationError extends Error {
|
|
|
34
34
|
}
|
|
35
35
|
export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
|
|
36
36
|
/**
|
|
37
|
-
* A request body as one object: JSON, or form fields with PHP-style names, as
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
37
|
+
* A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
|
|
38
|
+
* `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
|
|
39
|
+
* `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
|
|
40
|
+
* (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
|
|
41
|
+
* `a=1&a[b]=2`, names nested deeper than 32) is a 400.
|
|
41
42
|
*/
|
|
42
43
|
export declare function readBody(c: Context): Promise<unknown>;
|
|
43
44
|
/** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
|
|
@@ -51,9 +52,7 @@ export type Input<S extends Schemas> = {
|
|
|
51
52
|
};
|
|
52
53
|
/**
|
|
53
54
|
* The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
|
|
54
|
-
* fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
|
|
55
|
-
* request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
|
|
56
|
-
* valid, 422 `{ errors }` otherwise, the handler never runs.
|
|
55
|
+
* fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
|
|
57
56
|
*/
|
|
58
57
|
export declare function validator<S extends Schemas>(schemas: S): [MiddlewareHandler, (c: Context) => Input<S>];
|
|
59
58
|
export {};
|