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