fondu 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +168 -2
- package/dist/client.d.ts +19 -0
- package/dist/client.js +4 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/paths.d.ts +15 -0
- package/dist/paths.js +46 -0
- package/dist/server/app.d.ts +32 -0
- package/dist/server/app.js +130 -0
- package/dist/server/document.d.ts +23 -0
- package/dist/server/document.js +34 -0
- package/dist/server/errors.d.ts +8 -0
- package/dist/server/errors.js +73 -0
- package/dist/server/flash.d.ts +18 -0
- package/dist/server/flash.js +63 -0
- package/dist/server/handler.d.ts +25 -0
- package/dist/server/handler.js +20 -0
- package/dist/server/http.d.ts +13 -0
- package/dist/server/http.js +25 -0
- package/dist/server/props.d.ts +81 -0
- package/dist/server/props.js +28 -0
- package/dist/server/protocol.d.ts +50 -0
- package/dist/server/protocol.js +174 -0
- package/dist/server/validate.d.ts +58 -0
- package/dist/server/validate.js +110 -0
- package/dist/types.d.ts +15 -0
- package/dist/types.js +1 -0
- package/dist/virtual.d.ts +13 -0
- package/dist/vite/index.d.ts +19 -0
- package/dist/vite/index.js +271 -0
- package/dist/vite/typegen.d.ts +5 -0
- package/dist/vite/typegen.js +64 -0
- package/package.json +63 -4
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
|
2
|
+
const states = new WeakMap();
|
|
3
|
+
const state = (c) => {
|
|
4
|
+
let s = states.get(c);
|
|
5
|
+
if (!s)
|
|
6
|
+
states.set(c, (s = { outgoing: {}, incoming: undefined, read: false }));
|
|
7
|
+
return s;
|
|
8
|
+
};
|
|
9
|
+
/** https, directly or behind a proxy that says so */
|
|
10
|
+
export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' || c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
11
|
+
const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
|
|
12
|
+
/** Flash data for the next page (`page.flash` / `usePage().flash`, Inertia's `flash` event). */
|
|
13
|
+
export function flash(c, data) {
|
|
14
|
+
const out = state(c).outgoing;
|
|
15
|
+
out.flash = { ...out.flash, ...data };
|
|
16
|
+
}
|
|
17
|
+
/** Validation errors for the next page (its `errors` prop). */
|
|
18
|
+
export function flashErrors(c, errors) {
|
|
19
|
+
state(c).outgoing.errors = errors;
|
|
20
|
+
}
|
|
21
|
+
/** The next page clears the browser history Inertia kept (and encrypted): after signing out, for example. */
|
|
22
|
+
export function clearHistory(c) {
|
|
23
|
+
state(c).outgoing.clearHistory = true;
|
|
24
|
+
}
|
|
25
|
+
/** What this page shows: carried over from the previous request (read once), plus what this request set. */
|
|
26
|
+
export function takeCarried(c, consume) {
|
|
27
|
+
const s = state(c);
|
|
28
|
+
if (consume && !s.read) {
|
|
29
|
+
s.read = true;
|
|
30
|
+
try {
|
|
31
|
+
s.incoming = JSON.parse(getCookie(c, cookieName(c)) ?? 'null') ?? undefined;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
s.incoming = undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const carried = {
|
|
38
|
+
flash: { ...s.incoming?.flash, ...s.outgoing.flash },
|
|
39
|
+
errors: { ...s.incoming?.errors, ...s.outgoing.errors },
|
|
40
|
+
clearHistory: Boolean(s.incoming?.clearHistory || s.outgoing.clearHistory),
|
|
41
|
+
};
|
|
42
|
+
if (consume)
|
|
43
|
+
s.outgoing = {};
|
|
44
|
+
return carried;
|
|
45
|
+
}
|
|
46
|
+
/** Writes what is left for the next request; clears what was shown. Installed by `createApp()`. */
|
|
47
|
+
export const flashCookie = async (c, next) => {
|
|
48
|
+
await next();
|
|
49
|
+
const s = states.get(c);
|
|
50
|
+
if (!s)
|
|
51
|
+
return;
|
|
52
|
+
const name = cookieName(c);
|
|
53
|
+
const options = { path: '/', httpOnly: true, sameSite: 'Lax', secure: isSecure(c) };
|
|
54
|
+
if (s.outgoing.flash || s.outgoing.errors || s.outgoing.clearHistory) {
|
|
55
|
+
const value = JSON.stringify(s.outgoing);
|
|
56
|
+
// browsers drop a cookie over ~4 KB without a word: the next page would show no errors, no flash
|
|
57
|
+
if (encodeURIComponent(value).length > 4000)
|
|
58
|
+
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`);
|
|
59
|
+
setCookie(c, name, value, { ...options, maxAge: 60 });
|
|
60
|
+
}
|
|
61
|
+
else if (s.read && s.incoming)
|
|
62
|
+
deleteCookie(c, name, options);
|
|
63
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Context, Handler, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { type Input, type Schemas } from './validate.js';
|
|
3
|
+
type Final<S extends Schemas> = (c: Context, input: Input<S>) => Response | Promise<Response>;
|
|
4
|
+
type Handlers = Array<Handler | MiddlewareHandler>;
|
|
5
|
+
/** overloads, as Hono's `createHandlers` has them: the last handler's parameters are typed reliably */
|
|
6
|
+
interface WithInput<S extends Schemas> {
|
|
7
|
+
(handler: Final<S>): Handlers;
|
|
8
|
+
(m1: MiddlewareHandler, handler: Final<S>): Handlers;
|
|
9
|
+
(m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S>): Handlers;
|
|
10
|
+
(m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S>): Handlers;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Validated input for the handler, after the middleware (a guard runs before the request body is read):
|
|
14
|
+
* `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
|
|
15
|
+
* Any Standard Schema. Invalid input: back to the page with the errors (Inertia), or 422 `{ errors }`.
|
|
16
|
+
* More than three middleware: combine them with `every()` from `hono/combine`.
|
|
17
|
+
*/
|
|
18
|
+
declare function withValidator<S extends Schemas>(schemas: S): WithInput<S>;
|
|
19
|
+
/** Route handlers: `defineHandler(...middleware, handler)` (Hono's `createHandlers`), and `.withValidator()`. */
|
|
20
|
+
export declare const defineHandler: import("hono/factory").CreateHandlersInterface<import("hono").Env, string> & {
|
|
21
|
+
withValidator: typeof withValidator;
|
|
22
|
+
};
|
|
23
|
+
/** A middleware, for `_middleware.ts` files and your own guards (Hono's `createMiddleware`). */
|
|
24
|
+
export declare const defineMiddleware: <I extends import("hono").Input = {}, R extends import("hono/types").HandlerResponse<any> | void = void>(middleware: MiddlewareHandler<import("hono").Env, string, I, R extends void ? Response : R>) => MiddlewareHandler<import("hono").Env, string, I, R extends void ? Response : R>;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createFactory } from 'hono/factory';
|
|
2
|
+
import { validator } from './validate.js';
|
|
3
|
+
const factory = createFactory();
|
|
4
|
+
/**
|
|
5
|
+
* Validated input for the handler, after the middleware (a guard runs before the request body is read):
|
|
6
|
+
* `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
|
|
7
|
+
* Any Standard Schema. Invalid input: back to the page with the errors (Inertia), or 422 `{ errors }`.
|
|
8
|
+
* More than three middleware: combine them with `every()` from `hono/combine`.
|
|
9
|
+
*/
|
|
10
|
+
function withValidator(schemas) {
|
|
11
|
+
return (...handlers) => {
|
|
12
|
+
const handler = handlers.pop();
|
|
13
|
+
const [validate, input] = validator(schemas);
|
|
14
|
+
return [...handlers, validate, (c) => handler(c, input(c))];
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Route handlers: `defineHandler(...middleware, handler)` (Hono's `createHandlers`), and `.withValidator()`. */
|
|
18
|
+
export const defineHandler = Object.assign(factory.createHandlers, { withValidator });
|
|
19
|
+
/** A middleware, for `_middleware.ts` files and your own guards (Hono's `createMiddleware`). */
|
|
20
|
+
export const defineMiddleware = factory.createMiddleware;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
export declare const isInertia: (c: Context) => boolean;
|
|
3
|
+
/** a visit or a document load (gets a page), not an API client (gets data) */
|
|
4
|
+
export declare const wantsPage: (c: Context) => boolean;
|
|
5
|
+
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
6
|
+
export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
|
|
7
|
+
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
8
|
+
export declare const back: (c: Context, fallback?: string) => Response & import("hono").TypedResponse<undefined, 303, "redirect">;
|
|
9
|
+
/**
|
|
10
|
+
* A full page load of `url` (another site, a non-Inertia page): Inertia's requests get 409 + `X-Inertia-Location`
|
|
11
|
+
* (the client then sets `window.location`), others a plain redirect.
|
|
12
|
+
*/
|
|
13
|
+
export declare const location: (c: Context, url: string) => (Response & import("hono").TypedResponse<undefined, 302, "redirect">) | (Response & import("hono").TypedResponse<null, 409, "body">);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const isInertia = (c) => c.req.header('x-inertia') === 'true';
|
|
2
|
+
/** a visit or a document load (gets a page), not an API client (gets data) */
|
|
3
|
+
export const wantsPage = (c) => isInertia(c) || (c.req.header('accept') ?? '').includes('text/html');
|
|
4
|
+
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
5
|
+
export function sameOrigin(c, url) {
|
|
6
|
+
if (!url)
|
|
7
|
+
return null;
|
|
8
|
+
try {
|
|
9
|
+
const parsed = new URL(url, c.req.url);
|
|
10
|
+
return parsed.origin === new URL(c.req.url).origin ? parsed : null;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
17
|
+
export const back = (c, fallback = '/') => {
|
|
18
|
+
const from = sameOrigin(c, c.req.header('referer'));
|
|
19
|
+
return c.redirect(from ? from.pathname.replace(/^\/+/, '/') + from.search : fallback, 303);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* A full page load of `url` (another site, a non-Inertia page): Inertia's requests get 409 + `X-Inertia-Location`
|
|
23
|
+
* (the client then sets `window.location`), others a plain redirect.
|
|
24
|
+
*/
|
|
25
|
+
export const location = (c, url) => isInertia(c) ? c.body(null, 409, { 'X-Inertia-Location': url }) : c.redirect(url, 302);
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
|
|
3
|
+
* a function is called only when its prop is sent.
|
|
4
|
+
*
|
|
5
|
+
* - `optional(fn)`: never on a full visit, only when a partial reload asks for it
|
|
6
|
+
* - `always(value)`: sent on partial reloads too, even when not asked for
|
|
7
|
+
* - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
|
|
8
|
+
* request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
|
|
9
|
+
* - `merge(value)` / `prepend(value)` / `deepMerge(value)`: partial reloads merge into what the client holds
|
|
10
|
+
* - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
|
|
11
|
+
* (`fresh`: send it anyway)
|
|
12
|
+
* - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
|
|
13
|
+
* previousPage, nextPage }` for the page in the query (`?page=`)
|
|
14
|
+
*/
|
|
15
|
+
declare const PROP: unique symbol;
|
|
16
|
+
type Resolver<T> = () => T | Promise<T>;
|
|
17
|
+
export type Lazy<T> = T | Resolver<T>;
|
|
18
|
+
export interface Paginated<T> {
|
|
19
|
+
data: T[];
|
|
20
|
+
currentPage: number | string;
|
|
21
|
+
previousPage: number | string | null;
|
|
22
|
+
nextPage: number | string | null;
|
|
23
|
+
}
|
|
24
|
+
export type PropSpec = {
|
|
25
|
+
[PROP]: 'optional';
|
|
26
|
+
value: Lazy<unknown>;
|
|
27
|
+
} | {
|
|
28
|
+
[PROP]: 'always';
|
|
29
|
+
value: Lazy<unknown>;
|
|
30
|
+
} | {
|
|
31
|
+
[PROP]: 'defer';
|
|
32
|
+
value: Lazy<unknown>;
|
|
33
|
+
group: string;
|
|
34
|
+
rescue: boolean;
|
|
35
|
+
} | {
|
|
36
|
+
[PROP]: 'merge';
|
|
37
|
+
value: Lazy<unknown>;
|
|
38
|
+
strategy: 'append' | 'prepend' | 'deep';
|
|
39
|
+
matchOn: string[];
|
|
40
|
+
} | {
|
|
41
|
+
[PROP]: 'once';
|
|
42
|
+
value: Lazy<unknown>;
|
|
43
|
+
key?: string;
|
|
44
|
+
ttl?: number;
|
|
45
|
+
fresh?: boolean;
|
|
46
|
+
} | {
|
|
47
|
+
[PROP]: 'scroll';
|
|
48
|
+
value: Lazy<unknown>;
|
|
49
|
+
pageName: string;
|
|
50
|
+
};
|
|
51
|
+
/** A prop with an Inertia behaviour; at the type level it stands for the value it resolves to. */
|
|
52
|
+
export type Prop<T> = T & {
|
|
53
|
+
readonly [PROP]?: never;
|
|
54
|
+
};
|
|
55
|
+
export declare const optional: <T>(value: Resolver<T>) => Prop<T>;
|
|
56
|
+
export declare const always: <T>(value: Lazy<T>) => Prop<T>;
|
|
57
|
+
export declare const defer: <T>(value: Resolver<T>, { group, rescue }?: {
|
|
58
|
+
group?: string;
|
|
59
|
+
rescue?: boolean;
|
|
60
|
+
}) => Prop<T>;
|
|
61
|
+
export declare const once: <T>(value: Resolver<T>, options?: {
|
|
62
|
+
key?: string;
|
|
63
|
+
ttl?: number;
|
|
64
|
+
fresh?: boolean;
|
|
65
|
+
}) => Prop<T>;
|
|
66
|
+
export declare const scroll: <T>(value: Resolver<Paginated<T>>, { pageName }?: {
|
|
67
|
+
pageName?: string;
|
|
68
|
+
}) => Prop<Paginated<T>>;
|
|
69
|
+
export declare const merge: <T>(value: Lazy<T>, options?: {
|
|
70
|
+
matchOn?: string | string[];
|
|
71
|
+
}) => Prop<T>;
|
|
72
|
+
export declare const prepend: <T>(value: Lazy<T>, options?: {
|
|
73
|
+
matchOn?: string | string[];
|
|
74
|
+
}) => Prop<T>;
|
|
75
|
+
export declare const deepMerge: <T>(value: Lazy<T>, options?: {
|
|
76
|
+
matchOn?: string | string[];
|
|
77
|
+
}) => Prop<T>;
|
|
78
|
+
export declare const propSpec: (value: unknown) => PropSpec | null;
|
|
79
|
+
export declare const kindOf: (spec: PropSpec) => "always" | "defer" | "merge" | "once" | "optional" | "scroll";
|
|
80
|
+
export declare const resolve: (value: Lazy<unknown>) => Promise<unknown>;
|
|
81
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
|
|
3
|
+
* a function is called only when its prop is sent.
|
|
4
|
+
*
|
|
5
|
+
* - `optional(fn)`: never on a full visit, only when a partial reload asks for it
|
|
6
|
+
* - `always(value)`: sent on partial reloads too, even when not asked for
|
|
7
|
+
* - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
|
|
8
|
+
* request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
|
|
9
|
+
* - `merge(value)` / `prepend(value)` / `deepMerge(value)`: partial reloads merge into what the client holds
|
|
10
|
+
* - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
|
|
11
|
+
* (`fresh`: send it anyway)
|
|
12
|
+
* - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
|
|
13
|
+
* previousPage, nextPage }` for the page in the query (`?page=`)
|
|
14
|
+
*/
|
|
15
|
+
const PROP = Symbol.for('fondu.prop');
|
|
16
|
+
const make = (spec) => spec;
|
|
17
|
+
export const optional = (value) => make({ [PROP]: 'optional', value });
|
|
18
|
+
export const always = (value) => make({ [PROP]: 'always', value });
|
|
19
|
+
export const defer = (value, { group = 'default', rescue = false } = {}) => make({ [PROP]: 'defer', value, group, rescue });
|
|
20
|
+
export const once = (value, options = {}) => make({ [PROP]: 'once', value, ...options });
|
|
21
|
+
export const scroll = (value, { pageName = 'page' } = {}) => make({ [PROP]: 'scroll', value, pageName });
|
|
22
|
+
const merger = (strategy) => (value, options = {}) => make({ [PROP]: 'merge', value, strategy, matchOn: [options.matchOn ?? []].flat() });
|
|
23
|
+
export const merge = merger('append');
|
|
24
|
+
export const prepend = merger('prepend');
|
|
25
|
+
export const deepMerge = merger('deep');
|
|
26
|
+
export const propSpec = (value) => typeof value === 'object' && value !== null && PROP in value ? value : null;
|
|
27
|
+
export const kindOf = (spec) => spec[PROP];
|
|
28
|
+
export const resolve = async (value) => typeof value === 'function' ? value() : value;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { SharedPageProps } from '@inertiajs/core';
|
|
2
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
3
|
+
import type { Pages } from '../types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The server side of the Inertia v3 protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
|
|
6
|
+
* The client is `@inertiajs/react`, unchanged.
|
|
7
|
+
*/
|
|
8
|
+
type Shareable<T> = {
|
|
9
|
+
[K in keyof T]?: T[K] | (() => T[K] | Promise<T[K]>);
|
|
10
|
+
};
|
|
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<SharedPageProps> & Record<string, unknown>): void;
|
|
13
|
+
type PageName = [keyof Pages] extends [never] ? string : Extract<keyof Pages, string>;
|
|
14
|
+
type ComponentProps<N> = N extends keyof Pages ? Pages[N] extends {
|
|
15
|
+
default: (...args: infer A) => unknown;
|
|
16
|
+
} ? A extends [infer P, ...unknown[]] ? P : Record<string, never> : Record<string, unknown> : Record<string, unknown>;
|
|
17
|
+
/** shared props the page takes with the same type: `render` may leave them out (every page gets them) */
|
|
18
|
+
type FromShared<P> = {
|
|
19
|
+
[K in keyof P & keyof SharedPageProps]: SharedPageProps[K] extends P[K] ? K : never;
|
|
20
|
+
}[keyof P & keyof SharedPageProps];
|
|
21
|
+
/** a page prop named like a shared prop, of another type: it would hide the shared one from the layout */
|
|
22
|
+
type Clashing<P> = string extends keyof SharedPageProps ? never : Exclude<keyof P & keyof SharedPageProps, FromShared<P>>;
|
|
23
|
+
type ClashError = 'fondu: this page prop has the name of a shared prop (share()); rename it';
|
|
24
|
+
/** what `render` takes: the component's props, less `errors` and the shared props it gets anyway (may still be given) */
|
|
25
|
+
type OwnProps<N> = Omit<ComponentProps<N>, FromShared<ComponentProps<N>> | Clashing<ComponentProps<N>> | 'errors'> & Partial<Pick<ComponentProps<N>, FromShared<ComponentProps<N>>>> & {
|
|
26
|
+
[K in Clashing<ComponentProps<N>>]: ClashError;
|
|
27
|
+
};
|
|
28
|
+
type PropsInput<P> = {
|
|
29
|
+
[K in keyof P]: P[K] | (() => P[K] | Promise<P[K]>);
|
|
30
|
+
};
|
|
31
|
+
type RequiredKeys<T> = {
|
|
32
|
+
[K in keyof T]-?: object extends Pick<T, K> ? never : K;
|
|
33
|
+
}[keyof T];
|
|
34
|
+
export interface RenderOptions {
|
|
35
|
+
status?: number;
|
|
36
|
+
encryptHistory?: boolean;
|
|
37
|
+
clearHistory?: boolean;
|
|
38
|
+
preserveFragment?: boolean;
|
|
39
|
+
}
|
|
40
|
+
type RenderArgs<N> = [RequiredKeys<OwnProps<N>>] extends [never] ? OptionalArgs<N> : string extends keyof OwnProps<N> ? OptionalArgs<N> : RequiredArgs<N>;
|
|
41
|
+
type OptionalArgs<N> = [props?: PropsInput<OwnProps<N>>, options?: RenderOptions];
|
|
42
|
+
type RequiredArgs<N> = [props: PropsInput<OwnProps<N>>, options?: RenderOptions];
|
|
43
|
+
export declare const hasPage: (name: string) => boolean;
|
|
44
|
+
/**
|
|
45
|
+
* The page `component` (a file in `pages/`, without extension) with these props: JSON for Inertia's requests,
|
|
46
|
+
* the HTML document (server-rendered) otherwise. Props are checked against the component's own props.
|
|
47
|
+
*/
|
|
48
|
+
export declare function render<N extends PageName>(c: Context, component: N, ...[props, options]: RenderArgs<N>): Promise<Response>;
|
|
49
|
+
export declare const protocol: MiddlewareHandler[];
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { pages, version } from 'virtual:fondu/assets';
|
|
2
|
+
import { renderDocument } from './document.js';
|
|
3
|
+
import { flashCookie, takeCarried } from './flash.js';
|
|
4
|
+
import { isInertia, sameOrigin } from './http.js';
|
|
5
|
+
import { kindOf, propSpec, resolve } from './props.js';
|
|
6
|
+
const shared = new WeakMap();
|
|
7
|
+
/** Props every page of this request gets (a middleware calls it: the signed-in user…). */
|
|
8
|
+
export function share(c, props) {
|
|
9
|
+
shared.set(c, { ...shared.get(c), ...props });
|
|
10
|
+
}
|
|
11
|
+
// development: the files in app/pages/ (Vite keeps the list current); a build: the pages in the client manifest
|
|
12
|
+
const devPages = import.meta.env.DEV ? import.meta.glob(['/app/pages/**/*.tsx', '/app/pages/**/*.jsx']) : {};
|
|
13
|
+
export const hasPage = (name) => pages ? pages.includes(name) : `/app/pages/${name}.tsx` in devPages || `/app/pages/${name}.jsx` in devPages;
|
|
14
|
+
const headerSet = (c, name) => {
|
|
15
|
+
const value = c.req.header(name);
|
|
16
|
+
return value === undefined
|
|
17
|
+
? null
|
|
18
|
+
: new Set(value
|
|
19
|
+
.split(',')
|
|
20
|
+
.map((s) => s.trim())
|
|
21
|
+
.filter(Boolean));
|
|
22
|
+
};
|
|
23
|
+
const isPrefetch = (c) => c.req.header('purpose') === 'prefetch' || c.req.header('sec-purpose')?.includes('prefetch') === true;
|
|
24
|
+
/** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
|
|
25
|
+
function pageUrl(c) {
|
|
26
|
+
const here = new URL(c.req.url);
|
|
27
|
+
const from = c.req.method === 'GET' ? here : (sameOrigin(c, c.req.header('referer')) ?? here);
|
|
28
|
+
return from.pathname.replace(/^\/+/, '/') + from.search;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The page `component` (a file in `pages/`, without extension) with these props: JSON for Inertia's requests,
|
|
32
|
+
* the HTML document (server-rendered) otherwise. Props are checked against the component's own props.
|
|
33
|
+
*/
|
|
34
|
+
export async function render(c, component, ...[props = {}, options = {}]) {
|
|
35
|
+
if (!hasPage(component))
|
|
36
|
+
throw new Error(`fondu: there is no page "${component}": create app/pages/${component}.tsx`);
|
|
37
|
+
const partial = c.req.header('x-inertia-partial-component') === component;
|
|
38
|
+
const only = partial ? headerSet(c, 'x-inertia-partial-data') : null;
|
|
39
|
+
const except = partial ? headerSet(c, 'x-inertia-partial-except') : null;
|
|
40
|
+
const reset = headerSet(c, 'x-inertia-reset') ?? new Set();
|
|
41
|
+
const heldOnce = headerSet(c, 'x-inertia-except-once-props') ?? new Set();
|
|
42
|
+
const carried = takeCarried(c, !partial && !isPrefetch(c));
|
|
43
|
+
const sharedProps = shared.get(c) ?? {};
|
|
44
|
+
const all = { ...sharedProps, ...props };
|
|
45
|
+
const page = {
|
|
46
|
+
component,
|
|
47
|
+
props: { errors: {} },
|
|
48
|
+
url: pageUrl(c),
|
|
49
|
+
version: version ?? null,
|
|
50
|
+
flash: carried.flash,
|
|
51
|
+
};
|
|
52
|
+
const lists = {
|
|
53
|
+
mergeProps: [],
|
|
54
|
+
prependProps: [],
|
|
55
|
+
deepMergeProps: [],
|
|
56
|
+
matchPropsOn: [],
|
|
57
|
+
};
|
|
58
|
+
const deferred = {};
|
|
59
|
+
const onceProps = {};
|
|
60
|
+
const pending = [];
|
|
61
|
+
for (const [key, value] of Object.entries(all)) {
|
|
62
|
+
const spec = propSpec(value);
|
|
63
|
+
const kind = spec && kindOf(spec);
|
|
64
|
+
const asked = only ? only.has(key) : true;
|
|
65
|
+
const sent = kind === 'always' || (asked && !except?.has(key));
|
|
66
|
+
if (kind === 'defer' && !partial) {
|
|
67
|
+
;
|
|
68
|
+
(deferred[spec.group] ??= []).push(key);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (kind === 'optional' && !only?.has(key))
|
|
72
|
+
continue;
|
|
73
|
+
if (kind === 'once') {
|
|
74
|
+
const once = spec;
|
|
75
|
+
const name = once.key ?? key;
|
|
76
|
+
onceProps[name] = { prop: key, expiresAt: once.ttl ? Date.now() + once.ttl * 1000 : null };
|
|
77
|
+
if (heldOnce.has(name) && !only?.has(key) && !once.fresh)
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (!sent)
|
|
81
|
+
continue;
|
|
82
|
+
if (kind === 'merge' && !reset.has(key)) {
|
|
83
|
+
const m = spec;
|
|
84
|
+
lists[m.strategy === 'append' ? 'mergeProps' : m.strategy === 'prepend' ? 'prependProps' : 'deepMergeProps'].push(key);
|
|
85
|
+
lists.matchPropsOn.push(...m.matchOn.map((field) => `${key}.${field}`));
|
|
86
|
+
}
|
|
87
|
+
if (kind === 'scroll' && !reset.has(key)) {
|
|
88
|
+
// <InfiniteScroll> says which side it loads: the previous page goes before what the client holds
|
|
89
|
+
lists[c.req.header('x-inertia-infinite-scroll-merge-intent') === 'prepend' ? 'prependProps' : 'mergeProps'].push(`${key}.data`);
|
|
90
|
+
}
|
|
91
|
+
pending.push([key, value]);
|
|
92
|
+
}
|
|
93
|
+
const rescued = [];
|
|
94
|
+
const resolved = await Promise.all(pending.map(async ([key, value]) => {
|
|
95
|
+
const spec = propSpec(value);
|
|
96
|
+
try {
|
|
97
|
+
return [[key, await resolve(spec ? spec.value : value)]];
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (!(spec && kindOf(spec) === 'defer' && spec.rescue))
|
|
101
|
+
throw error;
|
|
102
|
+
console.error(`[fondu] deferred prop "${key}" failed (rescued):`, error);
|
|
103
|
+
rescued.push(key);
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
}));
|
|
107
|
+
page.props = { ...Object.fromEntries(resolved.flat()), errors: carried.errors };
|
|
108
|
+
if (rescued.length)
|
|
109
|
+
page.rescuedProps = rescued;
|
|
110
|
+
const scrollProps = {};
|
|
111
|
+
for (const [key, value] of pending) {
|
|
112
|
+
const spec = propSpec(value);
|
|
113
|
+
if (spec && kindOf(spec) === 'scroll' && key in page.props) {
|
|
114
|
+
const { currentPage, previousPage, nextPage } = page.props[key];
|
|
115
|
+
scrollProps[key] = {
|
|
116
|
+
pageName: spec.pageName,
|
|
117
|
+
currentPage,
|
|
118
|
+
previousPage,
|
|
119
|
+
nextPage,
|
|
120
|
+
reset: reset.has(key),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (Object.keys(scrollProps).length)
|
|
125
|
+
page.scrollProps = scrollProps;
|
|
126
|
+
for (const [name, list] of Object.entries(lists))
|
|
127
|
+
if (list.length)
|
|
128
|
+
page[name] = list;
|
|
129
|
+
if (Object.keys(deferred).length)
|
|
130
|
+
page.deferredProps = deferred;
|
|
131
|
+
if (Object.keys(onceProps).length)
|
|
132
|
+
page.onceProps = onceProps;
|
|
133
|
+
const sharedKeys = Object.keys(sharedProps);
|
|
134
|
+
if (sharedKeys.length)
|
|
135
|
+
page.sharedProps = sharedKeys;
|
|
136
|
+
if (options.encryptHistory)
|
|
137
|
+
page.encryptHistory = true;
|
|
138
|
+
if (options.clearHistory || carried.clearHistory)
|
|
139
|
+
page.clearHistory = true;
|
|
140
|
+
if (options.preserveFragment)
|
|
141
|
+
page.preserveFragment = true;
|
|
142
|
+
c.header('Vary', 'X-Inertia', { append: true });
|
|
143
|
+
// a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
|
|
144
|
+
if (!c.res.headers.has('Cache-Control'))
|
|
145
|
+
c.header('Cache-Control', 'private, no-cache');
|
|
146
|
+
if (isInertia(c)) {
|
|
147
|
+
c.header('X-Inertia', 'true');
|
|
148
|
+
return c.json(page, (options.status ?? 200));
|
|
149
|
+
}
|
|
150
|
+
return c.html(await renderDocument(c, page), (options.status ?? 200));
|
|
151
|
+
}
|
|
152
|
+
// ---- the protocol middleware (installed by createApp)
|
|
153
|
+
const versionCheck = async (c, next) => {
|
|
154
|
+
// an Inertia visit made by a client built from other assets: reload the page as a document
|
|
155
|
+
if (version && c.req.method === 'GET' && isInertia(c) && c.req.header('x-inertia-version') !== version) {
|
|
156
|
+
return c.body(null, 409, { 'X-Inertia-Location': c.req.url, 'X-Inertia-Version': version });
|
|
157
|
+
}
|
|
158
|
+
await next();
|
|
159
|
+
if (!isInertia(c) || c.res.status < 300 || c.res.status > 399)
|
|
160
|
+
return;
|
|
161
|
+
const to = c.res.headers.get('location') ?? '';
|
|
162
|
+
if (to.includes('#')) {
|
|
163
|
+
// the browser's fetch would follow the redirect and drop the #fragment: the client visits it itself
|
|
164
|
+
const headers = new Headers(c.res.headers);
|
|
165
|
+
headers.delete('location');
|
|
166
|
+
headers.set('X-Inertia-Redirect', to);
|
|
167
|
+
c.res = new Response(null, { status: 409, headers });
|
|
168
|
+
}
|
|
169
|
+
else if (c.res.status === 302 && ['PUT', 'PATCH', 'DELETE'].includes(c.req.method)) {
|
|
170
|
+
// a 302 after PUT / PATCH / DELETE would be followed with the same method: make it 303 (Inertia's rule)
|
|
171
|
+
c.res = new Response(c.res.body, { status: 303, headers: c.res.headers });
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
export const protocol = [flashCookie, versionCheck];
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
/** The Standard Schema interface (zod, valibot, arktype…), the part used here. */
|
|
3
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
4
|
+
readonly '~standard': {
|
|
5
|
+
readonly version: 1;
|
|
6
|
+
readonly vendor: string;
|
|
7
|
+
readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
|
|
8
|
+
readonly types?: {
|
|
9
|
+
readonly input: Input;
|
|
10
|
+
readonly output: Output;
|
|
11
|
+
} | undefined;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
type StandardResult<Output> = {
|
|
15
|
+
readonly value: Output;
|
|
16
|
+
readonly issues?: undefined;
|
|
17
|
+
} | {
|
|
18
|
+
readonly issues: ReadonlyArray<{
|
|
19
|
+
readonly message: string;
|
|
20
|
+
readonly path?: ReadonlyArray<PropertyKey | {
|
|
21
|
+
readonly key: PropertyKey;
|
|
22
|
+
}>;
|
|
23
|
+
}>;
|
|
24
|
+
};
|
|
25
|
+
type InferOutput<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
|
|
26
|
+
/**
|
|
27
|
+
* Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: Inertia's requests
|
|
28
|
+
* and plain forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
|
|
29
|
+
* requests (an API client) get 422 `{ errors }`.
|
|
30
|
+
*/
|
|
31
|
+
export declare class ValidationError extends Error {
|
|
32
|
+
readonly errors: Record<string, string>;
|
|
33
|
+
constructor(errors: Record<string, string>);
|
|
34
|
+
}
|
|
35
|
+
export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
|
|
36
|
+
/**
|
|
37
|
+
* A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
|
|
38
|
+
* (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
|
|
39
|
+
* are left out. Names that would change the object itself (`__proto__`…) are ignored.
|
|
40
|
+
*/
|
|
41
|
+
export declare function readBody(c: Context): Promise<unknown>;
|
|
42
|
+
/** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
|
|
43
|
+
export interface Schemas {
|
|
44
|
+
body?: StandardSchemaV1;
|
|
45
|
+
query?: StandardSchemaV1;
|
|
46
|
+
params?: StandardSchemaV1;
|
|
47
|
+
}
|
|
48
|
+
export type Input<S extends Schemas> = {
|
|
49
|
+
[K in keyof S]: S[K] extends StandardSchemaV1 ? InferOutput<S[K]> : never;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
|
|
53
|
+
* fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`. A Precognition
|
|
54
|
+
* request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
|
|
55
|
+
* valid, 422 `{ errors }` otherwise, the handler never runs.
|
|
56
|
+
*/
|
|
57
|
+
export declare function validator<S extends Schemas>(schemas: S): [MiddlewareHandler, (c: Context) => Input<S>];
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { HTTPException } from 'hono/http-exception';
|
|
2
|
+
import { flashErrors } from './flash.js';
|
|
3
|
+
import { back, wantsPage } from './http.js';
|
|
4
|
+
/**
|
|
5
|
+
* Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: Inertia's requests
|
|
6
|
+
* and plain forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
|
|
7
|
+
* requests (an API client) get 422 `{ errors }`.
|
|
8
|
+
*/
|
|
9
|
+
export class ValidationError extends Error {
|
|
10
|
+
errors;
|
|
11
|
+
constructor(errors) {
|
|
12
|
+
super('Validation failed');
|
|
13
|
+
this.errors = errors;
|
|
14
|
+
this.name = 'ValidationError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function validationErrorResponse(c, error) {
|
|
18
|
+
if (!wantsPage(c))
|
|
19
|
+
return c.json({ errors: error.errors }, 422);
|
|
20
|
+
const bag = c.req.header('x-inertia-error-bag');
|
|
21
|
+
flashErrors(c, bag ? { [bag]: error.errors } : error.errors);
|
|
22
|
+
return back(c);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
|
|
26
|
+
* (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
|
|
27
|
+
* are left out. Names that would change the object itself (`__proto__`…) are ignored.
|
|
28
|
+
*/
|
|
29
|
+
export async function readBody(c) {
|
|
30
|
+
const type = c.req.header('content-type') ?? '';
|
|
31
|
+
if (type.includes('application/json'))
|
|
32
|
+
return c.req.json();
|
|
33
|
+
if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
|
|
34
|
+
return {};
|
|
35
|
+
const form = await c.req.formData();
|
|
36
|
+
const body = {};
|
|
37
|
+
for (const [key, value] of form.entries()) {
|
|
38
|
+
if (typeof value !== 'string' && value.size === 0 && value.name === '')
|
|
39
|
+
continue;
|
|
40
|
+
const path = key.replace(/\]/g, '').split('[');
|
|
41
|
+
if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
|
|
42
|
+
continue;
|
|
43
|
+
let target = body;
|
|
44
|
+
path.forEach((segment, i) => {
|
|
45
|
+
const last = i === path.length - 1;
|
|
46
|
+
const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
|
|
47
|
+
if (last) {
|
|
48
|
+
if (name in target && path.length === 1)
|
|
49
|
+
target[name] = [target[name], value].flat(); // `a=1&a=2`
|
|
50
|
+
else
|
|
51
|
+
target[name] = value;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
target = (target[name] ??= {});
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return arrays(body);
|
|
59
|
+
}
|
|
60
|
+
/** objects whose keys are 0..n-1 become arrays */
|
|
61
|
+
const arrays = (value) => {
|
|
62
|
+
if (typeof value !== 'object' || value === null || value instanceof File || Array.isArray(value))
|
|
63
|
+
return value;
|
|
64
|
+
const entries = Object.entries(value).map(([k, v]) => [k, arrays(v)]);
|
|
65
|
+
const isList = entries.length > 0 && entries.every(([k], i) => k === String(i));
|
|
66
|
+
return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
|
|
67
|
+
};
|
|
68
|
+
const pathOf = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
69
|
+
/**
|
|
70
|
+
* The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
|
|
71
|
+
* fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`. A Precognition
|
|
72
|
+
* request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
|
|
73
|
+
* valid, 422 `{ errors }` otherwise, the handler never runs.
|
|
74
|
+
*/
|
|
75
|
+
export function validator(schemas) {
|
|
76
|
+
const inputs = new WeakMap();
|
|
77
|
+
const middleware = async (c, next) => {
|
|
78
|
+
const values = {
|
|
79
|
+
body: () => readBody(c),
|
|
80
|
+
query: () => c.req.query(),
|
|
81
|
+
params: () => c.req.param(),
|
|
82
|
+
};
|
|
83
|
+
const input = {};
|
|
84
|
+
const errors = {};
|
|
85
|
+
for (const key of Object.keys(schemas)) {
|
|
86
|
+
const result = await schemas[key]['~standard'].validate(await values[key]());
|
|
87
|
+
// route params that don't fit: the URL names nothing here
|
|
88
|
+
if (result.issues && key === 'params')
|
|
89
|
+
throw new HTTPException(404);
|
|
90
|
+
if (result.issues)
|
|
91
|
+
for (const issue of result.issues)
|
|
92
|
+
errors[pathOf(issue.path)] ??= issue.message;
|
|
93
|
+
else
|
|
94
|
+
input[key] = result.value;
|
|
95
|
+
}
|
|
96
|
+
if (c.req.header('precognition') === 'true') {
|
|
97
|
+
const only = c.req.header('precognition-validate-only')?.split(',').filter(Boolean);
|
|
98
|
+
const shown = only ? Object.fromEntries(Object.entries(errors).filter(([field]) => only.includes(field))) : errors;
|
|
99
|
+
const headers = { Precognition: 'true', Vary: 'Precognition' };
|
|
100
|
+
return Object.keys(shown).length
|
|
101
|
+
? c.json({ errors: shown }, 422, headers)
|
|
102
|
+
: c.body(null, 204, { ...headers, 'Precognition-Success': 'true' });
|
|
103
|
+
}
|
|
104
|
+
if (Object.keys(errors).length)
|
|
105
|
+
throw new ValidationError(errors);
|
|
106
|
+
inputs.set(c, input);
|
|
107
|
+
await next();
|
|
108
|
+
};
|
|
109
|
+
return [middleware, (c) => inputs.get(c)];
|
|
110
|
+
}
|