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.
Files changed (51) hide show
  1. package/README.md +11 -15
  2. package/dist/client/app.d.ts +40 -0
  3. package/dist/client/app.js +185 -0
  4. package/dist/client/navigation.d.ts +36 -0
  5. package/dist/client/navigation.js +432 -0
  6. package/dist/client/progress.d.ts +16 -0
  7. package/dist/client/progress.js +64 -0
  8. package/dist/client.d.ts +4 -15
  9. package/dist/client.js +3 -47
  10. package/dist/index.d.ts +3 -4
  11. package/dist/index.js +3 -4
  12. package/dist/paths.d.ts +23 -8
  13. package/dist/paths.js +52 -21
  14. package/dist/server/app.d.ts +4 -5
  15. package/dist/server/app.js +81 -16
  16. package/dist/server/document.d.ts +3 -3
  17. package/dist/server/document.js +27 -6
  18. package/dist/server/errors.d.ts +4 -2
  19. package/dist/server/errors.js +23 -10
  20. package/dist/server/flash.d.ts +4 -7
  21. package/dist/server/flash.js +9 -14
  22. package/dist/server/handler.d.ts +1 -1
  23. package/dist/server/handler.js +1 -1
  24. package/dist/server/http.d.ts +7 -5
  25. package/dist/server/http.js +15 -6
  26. package/dist/server/prerender.d.ts +1 -1
  27. package/dist/server/prerender.js +18 -10
  28. package/dist/server/protocol.d.ts +22 -35
  29. package/dist/server/protocol.js +67 -195
  30. package/dist/server/routes.d.ts +1 -1
  31. package/dist/server/validate.d.ts +8 -9
  32. package/dist/server/validate.js +23 -37
  33. package/dist/types.d.ts +10 -6
  34. package/dist/virtual.d.ts +3 -5
  35. package/dist/vite/hmr.d.ts +3 -3
  36. package/dist/vite/hmr.js +5 -5
  37. package/dist/vite/index.d.ts +9 -5
  38. package/dist/vite/index.js +174 -80
  39. package/dist/vite/prerender.d.ts +3 -3
  40. package/dist/vite/prerender.js +17 -12
  41. package/dist/vite/strip.d.ts +21 -0
  42. package/dist/vite/strip.js +306 -0
  43. package/dist/vite/typegen.d.ts +3 -2
  44. package/dist/vite/typegen.js +6 -10
  45. package/package.json +2 -9
  46. package/dist/server/props.d.ts +0 -85
  47. package/dist/server/props.js +0 -44
  48. package/dist/vite/layouts.d.ts +0 -10
  49. package/dist/vite/layouts.js +0 -110
  50. package/dist/vite/vitest-cache.d.ts +0 -19
  51. package/dist/vite/vitest-cache.js +0 -30
@@ -2,8 +2,8 @@ import { HTTPException } from 'hono/http-exception';
2
2
  import { flashErrors } from './flash.js';
3
3
  import { back, wantsPage } from './http.js';
4
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
5
+ * Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: navigations
6
+ * and forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
7
7
  * requests (an API client) get 422 `{ errors }`.
8
8
  */
9
9
  export class ValidationError extends Error {
@@ -17,27 +17,30 @@ export class ValidationError extends Error {
17
17
  export function validationErrorResponse(c, error) {
18
18
  if (!wantsPage(c))
19
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);
20
+ flashErrors(c, error.errors);
22
21
  return back(c);
23
22
  }
24
23
  /** how deep form field names nest (`a[b][c]`: 3) */
25
24
  const DEPTH = 32;
26
25
  /**
27
- * A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
28
- * (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
29
- * are left out. Names that would change the object itself (`__proto__`…) are ignored. A body that can't be one
30
- * object (JSON that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a 400.
26
+ * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
27
+ * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
28
+ * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
29
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
30
+ * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
31
31
  */
32
32
  export async function readBody(c) {
33
33
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
34
- const type = c.req.header('content-type') ?? '';
34
+ const type = (c.req.header('content-type') ?? '').toLowerCase();
35
35
  if (type.includes('application/json'))
36
36
  return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
37
37
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
38
38
  return {};
39
- const form = await c.req.formData();
39
+ const form = await c.req.formData().catch(() => Promise.reject(malformed('invalid form data')));
40
40
  const body = Object.create(null);
41
+ // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
42
+ const next = new WeakMap();
43
+ const isObject = (v) => typeof v === 'object' && !(v instanceof File) && !Array.isArray(v);
41
44
  for (const [key, value] of form.entries()) {
42
45
  if (typeof value !== 'string' && value.size === 0 && value.name === '')
43
46
  continue;
@@ -48,25 +51,19 @@ export async function readBody(c) {
48
51
  continue;
49
52
  let target = body;
50
53
  path.forEach((segment, i) => {
51
- const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
54
+ const name = segment === '' ? String(next.get(target) ?? 0) : segment;
55
+ if (/^\d+$/.test(name))
56
+ next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
52
57
  const has = Object.hasOwn(target, name);
53
58
  if (i === path.length - 1) {
54
- if (has &&
55
- typeof target[name] === 'object' &&
56
- !(target[name] instanceof File) &&
57
- !Array.isArray(target[name]))
59
+ if (has && isObject(target[name]))
58
60
  throw malformed(`\`${key}\` is both a value and an object`);
59
- if (has && path.length === 1)
60
- target[name] = [target[name], value].flat(); // `a=1&a=2`
61
- else
62
- target[name] = value;
61
+ target[name] = has ? [target[name], value].flat() : value; // given again: a list
63
62
  }
64
63
  else {
65
64
  if (!has)
66
65
  target[name] = Object.create(null);
67
- else if (typeof target[name] !== 'object' ||
68
- target[name] instanceof File ||
69
- Array.isArray(target[name]))
66
+ else if (!isObject(target[name]))
70
67
  throw malformed(`\`${key}\` is both a value and an object`);
71
68
  target = target[name];
72
69
  }
@@ -85,9 +82,7 @@ const arrays = (value) => {
85
82
  const pathOf = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
86
83
  /**
87
84
  * The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
88
- * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`. A Precognition
89
- * request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
90
- * valid, 422 `{ errors }` otherwise, the handler never runs.
85
+ * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
91
86
  */
92
87
  export function validator(schemas) {
93
88
  const inputs = new WeakMap();
@@ -97,8 +92,9 @@ export function validator(schemas) {
97
92
  query: () => c.req.query(),
98
93
  params: () => c.req.param(),
99
94
  };
100
- const input = {};
101
- const errors = {};
95
+ // no prototype: a field named `toString` or `constructor` is a field like any other
96
+ const input = Object.create(null);
97
+ const errors = Object.create(null);
102
98
  for (const key of Object.keys(schemas)) {
103
99
  const result = await schemas[key]['~standard'].validate(await values[key]());
104
100
  // route params that don't fit: the URL names nothing here
@@ -110,16 +106,6 @@ export function validator(schemas) {
110
106
  else
111
107
  input[key] = result.value;
112
108
  }
113
- if (c.req.header('precognition') === 'true') {
114
- const only = c.req.header('precognition-validate-only')?.split(',').filter(Boolean);
115
- const shown = only
116
- ? Object.fromEntries(Object.entries(errors).filter(([field]) => only.includes(field)))
117
- : errors;
118
- const headers = { Precognition: 'true', Vary: 'Precognition' };
119
- return Object.keys(shown).length
120
- ? c.json({ errors: shown }, 422, headers)
121
- : c.body(null, 204, { ...headers, 'Precognition-Success': 'true' });
122
- }
123
109
  if (Object.keys(errors).length)
124
110
  throw new ValidationError(errors);
125
111
  inputs.set(c, input);
package/dist/types.d.ts CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * Filled in by the generated `app/fondu.gen.d.ts` (written by the Vite plugin, committed with the app):
3
- * `pages`: page name → its module, `routes`: URL pattern → its route module.
3
+ * `routes`: URL pattern → its route module.
4
4
  *
5
- * `c.get()` / `c.set()` are typed by Hono's own `ContextVariableMap`; shared props and flash by Inertia's
6
- * `InertiaConfig`.
5
+ * And by the app, where it likes (`declare module 'fondu' { interface Register { … } }`): `shared`, the props
6
+ * `share()` gives every page; `flash`, what `flash()` takes. `c.get()` / `c.set()` are typed by Hono's own
7
+ * `ContextVariableMap`.
7
8
  */
8
9
  export interface Register {
9
10
  }
10
- export type Pages = Register extends {
11
- pages: infer P;
12
- } ? P : Record<string, unknown>;
13
11
  export type Routes = Register extends {
14
12
  routes: infer R;
15
13
  } ? R : Record<string, unknown>;
14
+ export type Shared = Register extends {
15
+ shared: infer S;
16
+ } ? S : Record<string, unknown>;
17
+ export type Flash = Register extends {
18
+ flash: infer F;
19
+ } ? F : Record<string, unknown>;
package/dist/virtual.d.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  // Modules generated by the fondu Vite plugin.
2
2
  declare module 'virtual:fondu/assets' {
3
- /** client asset version (production builds); a page visit from other assets is reloaded as a document */
3
+ /** client asset version (production builds); a navigation from other assets loads as a document */
4
4
  export const version: string | null
5
- /** the page names of a build (from the client manifest); null in development */
6
- export const pages: string[] | null
7
5
  /** `fondu({ prerender: true })`: page objects of pages without a static file are answered (`/_fondu/pages/…`) */
8
6
  export const prerender: boolean
9
7
  /** the `<head>` tags a page needs: the client entry and its styles, the page component's chunk */
10
8
  export function assetTags(component: string, nonce?: string): string
11
9
  }
12
10
  declare module 'virtual:fondu/ssr' {
13
- /** the app's `createInertiaApp(...)` rendering a page on the server (null: `fondu({ ssr: false })`) */
11
+ /** the server render of a page (null: `fondu({ ssr: false })`) */
14
12
  export const renderPage:
15
- | ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>)
13
+ | ((page: import('./client/navigation.js').Page) => Promise<{ head: string; body: string }>)
16
14
  | null
17
15
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
18
16
  export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
@@ -1,5 +1,5 @@
1
1
  import type { Plugin } from 'vite';
2
- /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
2
+ /** the browser's event for "the current page's props may have changed" (the client entry: `reload()`) */
3
3
  export declare const PROPS_EVENT = "fondu:props";
4
4
  /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
5
5
  export declare const PAGE_EXPORTS = "__fondu_pageExports";
@@ -10,7 +10,7 @@ type Node = {
10
10
  /**
11
11
  * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
12
12
  * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
13
- * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
13
+ * other than through a route).
14
14
  */
15
15
  export declare function reach(start: Iterable<Node>, root: string): {
16
16
  routes: boolean;
@@ -20,7 +20,7 @@ export declare function reach(start: Iterable<Node>, root: string): {
20
20
  * Dev: a change updates what it changes, without reloading the page where it can.
21
21
  * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
22
22
  * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
23
- * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
23
+ * - What a route depends on: the browser asks for the page's props again (fondu/client's `reload()`), its state
24
24
  * and scroll kept, as React Router's "Hot Data Revalidation".
25
25
  * - The document (`server.ts` and what only it imports): the page reloads.
26
26
  */
package/dist/vite/hmr.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { relative, sep } from 'node:path';
2
2
  import { isPageFile } from '../paths.js';
3
- /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
3
+ /** the browser's event for "the current page's props may have changed" (the client entry: `reload()`) */
4
4
  export const PROPS_EVENT = 'fondu:props';
5
5
  /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
6
6
  export const PAGE_EXPORTS = '__fondu_pageExports';
7
7
  /**
8
8
  * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
9
9
  * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
10
- * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
10
+ * other than through a route).
11
11
  */
12
12
  export function reach(start, root) {
13
13
  const found = { routes: false, document: false };
@@ -25,7 +25,7 @@ export function reach(start, root) {
25
25
  found.routes = true;
26
26
  else if (rel === 'app/server.ts')
27
27
  found.document = true;
28
- else if (rel !== 'app/app.tsx')
28
+ else
29
29
  queue.push(...mod.importers);
30
30
  }
31
31
  return found;
@@ -34,7 +34,7 @@ export function reach(start, root) {
34
34
  * Dev: a change updates what it changes, without reloading the page where it can.
35
35
  * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
36
36
  * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
37
- * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
37
+ * - What a route depends on: the browser asks for the page's props again (fondu/client's `reload()`), its state
38
38
  * and scroll kept, as React Router's "Hot Data Revalidation".
39
39
  * - The document (`server.ts` and what only it imports): the page reloads.
40
40
  */
@@ -53,7 +53,7 @@ export function hmr() {
53
53
  if (this.environment.config.consumer !== 'client')
54
54
  return;
55
55
  const file = id.split('?')[0];
56
- const rel = relative(`${root}/app/pages`, file).split(sep).join('/');
56
+ const rel = relative(`${root}/app/routes`, file).split(sep).join('/');
57
57
  if (rel.startsWith('..') || !isPageFile(rel))
58
58
  return;
59
59
  const names = namedExports(this.parse(code));
@@ -1,13 +1,15 @@
1
1
  import { type Options as ReactOptions } from '@vitejs/plugin-react';
2
- import type { PluginOption } from 'vite';
2
+ import { type PluginOption } from 'vite';
3
+ import type { ProgressOptions } from '../client/progress.js';
3
4
  /**
4
5
  * `vite.config.ts`: `plugins: [fondu({ target: 'node' })]` (or `'bun'`; for Cloudflare: `cloudflare()` and
5
6
  * `fondu({ target: 'cloudflare' })`). Composes the packages that do the work:
6
- * - `@vitejs/plugin-react`, and `@inertiajs/vite` (pages from `app/pages/`, the server render of `app/app.tsx`)
7
+ * - `@vitejs/plugin-react`
7
8
  * - Node / Bun: `@hono/vite-dev-server` (dev); the build is Vite's own, of two environments (`serverEntry()`)
8
9
  * - Cloudflare: `@cloudflare/vite-plugin` (yours: dev in workerd, the Worker's build)
9
- * and adds what none of them does: the document's asset tags, the generated types, the server-only guard. One
10
- * `vite build` builds the client, then the server, then the pages to prerender.
10
+ * and adds what none of them does: the app's entry (its pages and layouts, from `app/routes/`), the browser's copy of
11
+ * a page's route file (its server code removed), the document's asset tags, the generated types, the server-only
12
+ * guard. One `vite build` builds the client, then the server, then the pages to prerender.
11
13
  */
12
14
  export interface FonduOptions {
13
15
  target: 'node' | 'bun' | 'cloudflare';
@@ -18,9 +20,11 @@ export interface FonduOptions {
18
20
  react?: ReactOptions;
19
21
  /**
20
22
  * Routes with `export const prerender` (or under a `_middleware.ts` with it) are written as static files at build
21
- * time, and visits read them; the server (the Worker) answers the other pages
23
+ * time, and navigations read them; the server (the Worker) answers the other pages
22
24
  */
23
25
  prerender?: boolean;
26
+ /** the bar at the top of the page while a navigation is on its way: its `delay` (ms) and `color`; `false`: none */
27
+ progress?: ProgressOptions | false;
24
28
  }
25
29
  /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
26
30
  export declare const HONO: string[];