fondu 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,16 @@
1
1
  # Fondu
2
2
 
3
- **Inertia v3 on Hono.** The browser runs `@inertiajs/react` as it is; the server is Hono with Fondu's Inertia v3
4
- protocol; `app/routes/` holds the server side (loader, action, actions), `app/pages/` the React pages. The same app
5
- runs on **Node, Bun and Cloudflare Workers**.
3
+ **Server routes. React pages. No API in between.**
6
4
 
7
- Fondu is glue, not a new framework: it joins Hono, Inertia and Vite, and writes as little of its own as it can.
5
+ Fondu is a small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare
6
+ Workers and Node.
7
+
8
+ Routes are Hono handlers in `app/routes/`; pages are React components in `app/pages/`. A route renders a page with its
9
+ props, and Inertia does the rest in the browser: visits without full reloads, forms with validation, deferred and
10
+ merged props, all without an API to write or a client-side router to keep in sync.
11
+
12
+ Fondu writes as little of its own as it can: the server side of Inertia's protocol, file routes, typed pages and
13
+ URLs, the document and error pages. Everything else is Hono's, Vite's and Inertia's.
8
14
 
9
15
  ## Quick start
10
16
 
@@ -14,177 +20,44 @@ cd my-app
14
20
  bun dev
15
21
  ```
16
22
 
17
- It asks where the app runs (Node, Bun or Cloudflare Workers; or `--target node|bun|cloudflare`) and writes a small
23
+ It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cloudflare|node`) and writes a small
18
24
  app: a route, its page, the error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents.
19
25
 
20
- Two examples in this repository show more: [apps/node](apps/node) (Node and Bun) and [apps/cloudflare](apps/cloudflare)
21
- (every Inertia v3 feature, one page each, with D1 and Better Auth).
22
-
23
- ## Who does what
24
-
25
- | Part | Done by |
26
- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
27
- | Browser: visits, history, prefetch, forms, progress, `<Head>`, deferred, merging, infinite scroll, optimistic updates, Precognition | `@inertiajs/react` |
28
- | HTTP, middleware, CSRF, security headers, trailing slashes | Hono and its middleware |
29
- | Dev server, production build | Node / Bun: `@hono/vite-dev-server`, `@hono/vite-build`; Cloudflare: `@cloudflare/vite-plugin` |
30
- | Page resolution, the server render's entry | `@inertiajs/vite` (rendered in the same process) |
31
- | The Inertia v3 server protocol, `routes/`, generated types, the document, error pages, server-only guard | Fondu |
32
-
33
- ## An app
34
-
35
- ```
36
- package.json fondu hono @inertiajs/react react react-dom (Node: also @hono/node-server)
37
- "imports": { "#/*": "./app/*" }: import '#/lib/db.server.ts' from anywhere in app/
38
- vite.config.ts plugins: [fondu({ target: 'node' })] 'bun'; Cloudflare: [cloudflare(), fondu({ target: 'cloudflare' })]
39
- app/
40
- server.ts export default createApp()
41
- app.tsx createInertiaApp({ pages: './pages', … }): browser and server render
42
- routes/ server code only; the file path is the URL
43
- _middleware.ts for its directory and below (routes/_middleware.ts: every request, 404s too)
44
- index.ts /
45
- users/[id].ts /users/:id
46
- api/health.ts /api/health
47
- pages/ React pages, rendered by name: 'users/show' is pages/users/show.tsx
48
- error.tsx the error page (404, 403, 500…)
49
- fondu.gen.d.ts generated types (commit it)
50
- ```
51
-
52
- `createApp()` comes with CSRF protection, security headers (`Referrer-Policy: same-origin`, which `back()` needs), a
53
- Content Security Policy, one URL per page (`/users/` → `/users`) and error handling. Options: `document` (the HTML
54
- around pages: `<html>` attributes, the viewport, fonts…), `errorPage`, `trailingSlash: 'append'`, `csrf` and
55
- `secureHeaders` (Hono's options, or `false`).
56
-
57
- The policy: `default-src 'self'`, scripts of this site or with the request's nonce (the document's scripts have it),
58
- inline styles (style attributes), `data:` images and fonts, no plugins (`object-src 'none'`), `base-uri 'self'`. A
59
- directive of yours replaces that one: `secureHeaders: { contentSecurityPolicy: { fontSrc: ["'self'",
60
- 'https://fonts.gstatic.com'] } }` (apps/node does so for Google Fonts); `contentSecurityPolicy: false`: none.
61
-
62
- ### routes/: loader, action, actions
63
-
64
- ```ts
65
- // app/routes/users/[id].ts
66
- import { back, defineHandler, flash, render } from 'fondu'
67
- import * as z from 'zod/mini'
68
-
69
- const params = z.object({ id: z.coerce.number() })
70
-
71
- export const loader = defineHandler.withValidator({ params })(async (c, { params }) =>
72
- // GET /users/7
73
- render(c, 'users/show', { user: await getUser(params.id) }),
74
- )
75
-
76
- export const actions = {
77
- rename: defineHandler.withValidator({ params, body: renameSchema })(requireUser, async (c, { params, body }) => {
78
- await renameUser(params.id, body.name) // POST /users/7?rename
79
- return back(c)
80
- }),
81
- }
82
- ```
83
-
84
- - `loader` is GET, `action` POST, `actions.x` `POST ?x` (a plain form can pick one). HTTP routes export `GET` / `POST` / `PUT` / `PATCH` / `DELETE`.
85
- - `defineHandler(...middleware, handler)` is Hono's `createHandlers`. `.withValidator({ body, query, params })(...middleware, (c, input) => …)`: the middleware first (up to three; more: `every()` from `hono/combine`), then the schemas (any Standard Schema).
86
- - Every `.ts` file in `routes/` is a route, except `_middleware.ts` and tests. `(group)` directories take no URL segment.
87
-
88
- ### Validation (Inertia's way)
89
-
90
- Invalid `body` or `query`: Inertia visits and plain forms get a 303 back with the errors in the next page's `errors`
91
- prop (in the `X-Inertia-Error-Bag` bag when there is one); API clients get 422 `{ errors }`. Params that don't fit are
92
- a 404. A Precognition request (`<Form>`'s `validate()`, `useForm().withPrecognition()`) is only validated: 204 or 422.
93
- The same schema can be imported by the page to check before sending.
94
-
95
- ### Pages and props
96
-
97
- ```tsx
98
- // app/pages/users/show.tsx — the component's parameter is the page's props
99
- export default function Show({ user }: { user: User }) { … }
100
- ```
101
-
102
- `render(c, 'users/show', props, options?)` takes only pages that exist, with the component's props; a page prop named
103
- like a shared prop is a type error. A function prop is called only when it is sent.
104
-
105
- | prop | |
106
- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
107
- | `optional(fn)` | only when a partial reload names it |
108
- | `always(v)` | partial reloads too |
109
- | `defer(fn, { group?, rescue? })` | after the page renders, one request per group; `rescue`: a failure is listed in `rescuedProps` |
110
- | `merge` / `prepend` / `deepMerge(v, { matchOn? })` | merged with what the client holds |
111
- | `once(fn, { key?, ttl?, fresh? })` | skipped when the client holds it |
112
- | `scroll(fn, { pageName? })` | a page of a list for `<InfiniteScroll>`: `{ data, currentPage, previousPage, nextPage }` |
113
-
114
- Options: `status`, `encryptHistory`, `clearHistory`, `preserveFragment`. Also `flash(c, data)`, `clearHistory(c)`,
115
- `back(c)`, `location(c, url)` (409 + `X-Inertia-Location`); a redirect with a `#fragment` becomes a 409
116
- `X-Inertia-Redirect` by itself.
117
-
118
- ### Types
119
-
120
- ```ts
121
- // where the values are set (e.g. routes/_middleware.ts)
122
- declare module 'hono' {
123
- interface ContextVariableMap {
124
- user: User | null
125
- } // c.get('user')
126
- }
127
- declare module '@inertiajs/core' {
128
- interface InertiaConfig {
129
- sharedPageProps: { auth: { user: { name: string } | null } } // share(), usePage().props
130
- flashDataType: { message?: string } // flash(), usePage().flash
131
- }
132
- }
133
- ```
134
-
135
- `href(path, params?)` from `fondu/client`: a URL of `routes/` (or one of a file's actions: `'/users/:id?rename'`),
136
- params required, a typo is a type error. The method is Inertia's: `<Link href={href('/logout')} method="post" as="button">`.
137
-
138
- ### Server-side rendering
139
-
140
- Document loads are rendered on the server in the same process, then hydrated. Off for the whole app:
141
- `fondu({ ssr: false })`. Off for some routes: `withoutSsr()` (in a `_middleware.ts` for a directory, or in one
142
- handler). A browser-only part of a page: Inertia's `<WhenMounted>`.
143
-
144
- ### Errors
145
-
146
- Unknown URLs and thrown errors: API clients get plain text; pages get `pages/error.tsx` with `{ status }`, inside the
147
- layout with the shared props. In development a 500 is a report of the error instead (Inertia shows it in its dialog
148
- during a visit). `render()` of a page that doesn't exist says which file to create. Your own handling: Hono's
149
- `app.notFound()` / `app.onError()` on the app `createApp()` returns.
150
-
151
- ### Editor snippets
152
-
153
- `.vscode/fondu.code-snippets`: `/route`, `/api`, `/loader`, `/action`, `/actions`, `/validated`, `/get` … `/delete`,
154
- `/middleware` in routes; `/page`, `/layout`, `/form` in pages. A new app has it; edit it freely.
26
+ [demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo)) shows every Inertia feature, one page each, on
27
+ Cloudflare Workers with D1 and Better Auth.
155
28
 
156
- ## Deploying
29
+ ## Docs
157
30
 
158
- - **Node**: `vite build --mode client && vite build`, then `NODE_ENV=production node dist/index.js` (dependencies stay in `node_modules`; `NODE_ENV` makes React use its production build). `PORT` sets the port (default 3000); SIGTERM / SIGINT wait for running requests (10 s).
159
- - **Bun**: `fondu({ target: 'bun' })`, `NODE_ENV=production bun dist/index.js`.
160
- - **Cloudflare Workers**: `wrangler.jsonc` `main` is `./app/server.ts`; one `vite build` (the Worker minified: it starts faster; `build.minify: false` in its Vite environment keeps it readable); `wrangler deploy`. `/assets/*` get long-lived caching from a generated `_headers` (unless `public/_headers` exists).
31
+ **[fondu.dev](https://fondu.dev/docs)**: routes, pages and props, layouts, forms and validation, type safety,
32
+ server-side rendering, static pages, MDX pages, deploying, and the API. Every page is also Markdown for coding agents
33
+ ([llms.txt](https://fondu.dev/llms.txt)).
161
34
 
162
35
  ## Contributing
163
36
 
164
37
  ```
165
- packages/fondu the package (≈1,100 lines)
38
+ packages/fondu the package
166
39
  packages/create-fondu `bun create fondu`
167
- apps/node a small example: Link, loader, action, HTTP routes — Node and Bun
168
- apps/cloudflare every Inertia v3 feature, one page each — Workers, D1, Better Auth, Base UI
40
+ apps/demo every Inertia feature, one page each — Workers, D1, Better Auth, coss ui
41
+ apps/site fondu.dev: the docs, MDX and static pages on Workers
169
42
  ```
170
43
 
171
44
  ```bash
172
45
  bun install # also builds packages/fondu (the examples use the built package, like a real app)
173
46
  bun run test # the protocol, on a small app with app.request()
174
- bun run typecheck # the package and both examples (with apps/cloudflare/e2e/types.ts)
47
+ bun run typecheck # the package, the demo (with apps/demo/e2e/types.ts) and the site
175
48
  bun run check # format (oxfmt), lint (oxlint), typecheck
176
49
  bun run dev # rebuild packages/fondu on change
177
50
  ```
178
51
 
179
52
  Commits follow [Conventional Commits](https://www.conventionalcommits.org) (lefthook runs commitlint, and formats and
180
- lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI publishes the tag to npm
181
- (trusted publishing, with provenance) and writes the GitHub Release from the commits.
53
+ lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI stages it on npm (trusted
54
+ publishing, with provenance), a maintainer approves it, and CI writes the GitHub Release from the commits.
182
55
 
183
- `apps/node`: `bun run dev`; `bun run build && bun run start` (Node); `bun run build:bun && bun run start:bun` (Bun).
184
- `apps/cloudflare`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
56
+ `apps/demo`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
185
57
 
186
- See [CONTRIBUTING.md](CONTRIBUTING.md) for the details, and [SECURITY.md](SECURITY.md) to report a vulnerability.
58
+ See [CONTRIBUTING.md](https://github.com/fondujs/fondu/blob/main/CONTRIBUTING.md) for the details, and [SECURITY.md](https://github.com/fondujs/fondu/blob/main/SECURITY.md) to report a
59
+ vulnerability.
187
60
 
188
61
  ## License
189
62
 
190
- Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
63
+ Distributed under the MIT License. See [LICENSE](https://github.com/fondujs/fondu/blob/main/LICENSE) for more information.
package/dist/client.d.ts CHANGED
@@ -16,4 +16,10 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? [] : [params: {
16
16
  [K in ParamNames<P>]: string | number;
17
17
  }];
18
18
  export declare function href<P extends Href>(path: P, ...[params]: Args<P>): string;
19
+ /**
20
+ * `fondu({ prerender: true })` adds this to the client entry: visits ask for the page object at
21
+ * `/_fondu/pages/<path>.json`, a static file for a prerendered page, the server's answer for any other. A page
22
+ * object of another build reloads the page as a document, as the server's 409 would.
23
+ */
24
+ export declare function prerendered(): void;
19
25
  export {};
package/dist/client.js CHANGED
@@ -1,4 +1,28 @@
1
- import { fillPattern } from './paths.js';
1
+ import { http } from '@inertiajs/react';
2
+ import { fillPattern, pageDataPath } from './paths.js';
2
3
  export function href(path, ...[params]) {
3
4
  return fillPattern(path, params);
4
5
  }
6
+ /**
7
+ * `fondu({ prerender: true })` adds this to the client entry: visits ask for the page object at
8
+ * `/_fondu/pages/<path>.json`, a static file for a prerendered page, the server's answer for any other. A page
9
+ * object of another build reloads the page as a document, as the server's 409 would.
10
+ */
11
+ export function prerendered() {
12
+ const loaded = document.querySelector('script[data-page]')?.textContent;
13
+ const version = loaded ? JSON.parse(loaded).version : null;
14
+ http.onRequest((config) => {
15
+ const url = new URL(config.url, location.href);
16
+ if (config.method !== 'get' || !config.headers?.['X-Inertia'] || url.origin !== location.origin)
17
+ return config;
18
+ return { ...config, url: pageDataPath(url.pathname) + url.search };
19
+ });
20
+ http.onResponse((response) => {
21
+ if (!version || response.status !== 200 || !response.headers['x-inertia'])
22
+ return response;
23
+ const page = JSON.parse(response.data);
24
+ if (!page.version || page.version === version)
25
+ return response;
26
+ return { status: 409, data: '', headers: { 'x-inertia-location': page.url, 'x-inertia-version': page.version } };
27
+ });
28
+ }
package/dist/paths.d.ts CHANGED
@@ -9,7 +9,22 @@
9
9
  export declare function routePattern(file: string): string;
10
10
  /** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
11
11
  export declare function isRouteFile(file: string): boolean;
12
+ /** a path inside `pages/` that is a page: a .tsx, .jsx or .mdx file whose name doesn't start with `_` (`_layout.tsx`) */
13
+ export declare function isPageFile(file: string): boolean;
14
+ /** the directories of `pages/` whose `_layout.tsx` wraps a page, outermost first: `docs/intro.mdx` → `['', 'docs']` */
15
+ export declare function layoutsOf(file: string): string[];
12
16
  /** the `_middleware.ts` files that apply to a route file, outermost first */
13
17
  export declare function middlewareFor(file: string, middleware: readonly string[]): string[];
14
18
  /** `/users/:id` + `{ id: 7 }` → `/users/7`; catch-alls keep their slashes */
15
19
  export declare function fillPattern(pattern: string, params?: Record<string, string | number>): string;
20
+ /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
21
+ export declare const PAGE_DATA = "/_fondu/pages";
22
+ /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
23
+ export declare function pageDataPath(path: string): string;
24
+ /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
25
+ export declare function pathOfPageData(pathname: string): string | null;
26
+ /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
27
+ export declare function staticFiles(path: string): {
28
+ html: string;
29
+ json: string;
30
+ };
package/dist/paths.js CHANGED
@@ -21,6 +21,15 @@ export function isRouteFile(file) {
21
21
  !/\.(test|spec)\.ts$/.test(file) &&
22
22
  file.split('/').at(-1) !== '_middleware.ts');
23
23
  }
24
+ /** a path inside `pages/` that is a page: a .tsx, .jsx or .mdx file whose name doesn't start with `_` (`_layout.tsx`) */
25
+ export function isPageFile(file) {
26
+ return /\.(?:[jt]sx|mdx)$/.test(file) && !file.split('/').at(-1).startsWith('_');
27
+ }
28
+ /** the directories of `pages/` whose `_layout.tsx` wraps a page, outermost first: `docs/intro.mdx` → `['', 'docs']` */
29
+ export function layoutsOf(file) {
30
+ const dirs = file.split('/').slice(0, -1);
31
+ return ['', ...dirs.map((_, i) => dirs.slice(0, i + 1).join('/'))];
32
+ }
24
33
  /** the `_middleware.ts` files that apply to a route file, outermost first */
25
34
  export function middlewareFor(file, middleware) {
26
35
  const dirs = file.split('/').slice(0, -1);
@@ -44,3 +53,19 @@ export function fillPattern(pattern, params = {}) {
44
53
  return parts.map(encodeURIComponent).join('/');
45
54
  });
46
55
  }
56
+ /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
57
+ export const PAGE_DATA = '/_fondu/pages';
58
+ /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
59
+ export function pageDataPath(path) {
60
+ return `${PAGE_DATA}${path.endsWith('/') ? path + 'index' : path}.json`;
61
+ }
62
+ /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
63
+ export function pathOfPageData(pathname) {
64
+ const m = pathname.match(/^\/_fondu\/pages(\/.+)\.json$/);
65
+ return m ? m[1].replace(/\/index$/, '/') : null;
66
+ }
67
+ /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
68
+ export function staticFiles(path) {
69
+ const html = decodeURIComponent(path.endsWith('/') ? path + 'index.html' : path + '.html').slice(1);
70
+ return { html, json: decodeURIComponent(pageDataPath(path)).slice(1) };
71
+ }
@@ -4,9 +4,11 @@ import { csrf } from 'hono/csrf';
4
4
  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
+ import { prerender, version } from 'virtual:fondu/assets';
7
8
  import { isRouteFile, middlewareFor, routePattern } from '../paths.js';
8
9
  import { settings } from './document.js';
9
10
  import { errorResponse } from './errors.js';
11
+ import { prerenderRoutes } from './prerender.js';
10
12
  import { protocol } from './protocol.js';
11
13
  import { ValidationError, validationErrorResponse } from './validate.js';
12
14
  /** the default Content Security Policy: scripts of this site or with the request's nonce (the document's) */
@@ -64,6 +66,9 @@ export function createApp(options = {}) {
64
66
  }
65
67
  if (options.csrf !== false)
66
68
  app.use(csrf(options.csrf));
69
+ const prerendered = [];
70
+ if (prerender)
71
+ prerenderRoutes(app, () => prerendered, version);
67
72
  app.use(append ? appendTrailingSlash() : trimTrailingSlash(), ...protocol);
68
73
  app.notFound((c) => errorResponse(c, 404));
69
74
  app.onError((error, c) => {
@@ -73,8 +78,10 @@ export function createApp(options = {}) {
73
78
  });
74
79
  const modules = import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts'], { eager: true });
75
80
  const files = Object.keys(modules).map((k) => k.slice(ROOT.length));
76
- if (modules[ROOT + '_middleware.ts'])
77
- app.use(...chain(modules[ROOT + '_middleware.ts'].default ?? []));
81
+ // a _middleware.ts may only set what applies to its directory (`prerender`), without a default export
82
+ const rootMiddleware = modules[ROOT + '_middleware.ts']?.default;
83
+ if (rootMiddleware)
84
+ app.use(...chain(rootMiddleware));
78
85
  const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
79
86
  const routes = files
80
87
  .filter(isRouteFile)
@@ -83,6 +90,16 @@ export function createApp(options = {}) {
83
90
  .sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
84
91
  for (const { file, pattern, mod } of routes) {
85
92
  const mws = middlewareFor(file, middlewareFiles).flatMap((f) => chain(modules[ROOT + f].default ?? []));
93
+ prerendered.push({
94
+ file,
95
+ pattern,
96
+ settings: [file, ...middlewareFor(file, [...middlewareFiles, '_middleware.ts']).reverse()].map((f) => modules[ROOT + f]?.prerender),
97
+ get: Boolean(mod.loader ?? mod.GET),
98
+ others: [
99
+ ...(mod.action || mod.actions || mod.POST ? ['POST'] : []),
100
+ ...METHODS.filter((m) => m !== 'GET' && m !== 'POST' && mod[m]),
101
+ ],
102
+ });
86
103
  const conflict = (a, b) => {
87
104
  if (mod[a] && mod[b])
88
105
  throw new Error(`fondu: routes/${file} exports both \`${a}\` and \`${b}\`, which handle the same requests`);
@@ -1,6 +1,10 @@
1
1
  import type { Page } from '@inertiajs/core';
2
2
  import type { Context, MiddlewareHandler } from 'hono';
3
- /** The HTML document around a page. */
3
+ import type { ReactElement } from 'react';
4
+ /**
5
+ * The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
6
+ * An inline `<script>` of the document gets the request's nonce, so the Content Security Policy runs it.
7
+ */
4
8
  export interface DocumentParts {
5
9
  /** the page's `<Head>` tags (server render), then the client's styles and scripts */
6
10
  head: string;
@@ -8,7 +12,8 @@ export interface DocumentParts {
8
12
  body: string;
9
13
  c: Context;
10
14
  }
11
- export type DocumentTemplate = (parts: DocumentParts) => string;
15
+ /** the document as JSX (`<html>…</html>`), or as an HTML string */
16
+ export type DocumentTemplate = (parts: DocumentParts) => ReactElement | string;
12
17
  /** the options of the app (`createApp`) a request belongs to */
13
18
  export declare const settings: WeakMap<Context<any, any, {}>, {
14
19
  document?: DocumentTemplate;
@@ -1,5 +1,5 @@
1
1
  import { assetTags } from 'virtual:fondu/assets';
2
- import { renderPage } from 'virtual:fondu/ssr';
2
+ import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
3
3
  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
4
  /** the options of the app (`createApp`) a request belongs to */
5
5
  export const settings = new WeakMap();
@@ -15,6 +15,20 @@ export const withoutSsr = () => async (c, next) => {
15
15
  };
16
16
  /** Inertia's own encoding of the page data (`buildSSRBody`): `/` and `<` escaped, no HTML entities. */
17
17
  const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
18
+ // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
19
+ // never read as one
20
+ const HEAD = 'fondu:document-head';
21
+ const BODY = 'fondu:document-body';
22
+ /** the document's own markup: JSX rendered (no whitespace between tags), its inline scripts given the nonce */
23
+ async function shell(template, c, nonce) {
24
+ const out = template({ head: HEAD, body: BODY, c });
25
+ let html = out;
26
+ if (typeof out !== 'string')
27
+ html = `<!doctype html>${await renderMarkup(out)}`;
28
+ if (!nonce)
29
+ return html;
30
+ return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
31
+ }
18
32
  export async function renderDocument(c, page) {
19
33
  const nonce = c.get('secureHeadersNonce');
20
34
  let ssr = null;
@@ -30,5 +44,9 @@ export async function renderDocument(c, page) {
30
44
  // nothing in the page's content can come before it
31
45
  const body = ssr?.body ?? `${pageScript(page)}<div id="app"></div>`;
32
46
  const template = settings.get(c)?.document ?? defaultTemplate;
33
- return template({ head: (ssr?.head.join('') ?? '') + assetTags(page.component, nonce), body, c });
47
+ const html = await shell(template, c, nonce);
48
+ const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
49
+ if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
50
+ throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
51
+ return before + (ssr?.head.join('') ?? '') + assetTags(page.component, nonce) + between + body + after;
34
52
  }
@@ -0,0 +1,23 @@
1
+ import type { Hono } from 'hono';
2
+ /** `export const prerender` of a route or a `_middleware.ts`: the params of a dynamic route's pages, or on / off */
3
+ export type Prerender = boolean | (() => Array<Record<string, string | number>> | Promise<Array<Record<string, string | number>>>);
4
+ export interface PrerenderRoute {
5
+ file: string;
6
+ pattern: string;
7
+ /** the route's own setting, then its directories' (`_middleware.ts`), nearest first */
8
+ settings: Array<Prerender | undefined>;
9
+ /** it answers GET (`loader` / `GET`) */
10
+ get: boolean;
11
+ /** the other methods it answers: a static file would answer them 405 */
12
+ others: string[];
13
+ }
14
+ /** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
15
+ export declare function prerenderPaths(routes: PrerenderRoute[]): Promise<{
16
+ paths: string[];
17
+ problems: string[];
18
+ }>;
19
+ /**
20
+ * `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
21
+ * a visit), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
22
+ */
23
+ export declare function prerenderRoutes(app: Hono, routes: () => PrerenderRoute[], version: string | null): void;
@@ -0,0 +1,96 @@
1
+ import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
+ import { isInertia } from './http.js';
3
+ /** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
4
+ const STATIC_FILES = Symbol.for('fondu.staticFiles');
5
+ /** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
6
+ export async function prerenderPaths(routes) {
7
+ const paths = new Set();
8
+ const problems = [];
9
+ for (const route of routes) {
10
+ const setting = route.settings.find((s) => s !== undefined) ?? false;
11
+ if (setting === false || !route.get)
12
+ continue;
13
+ const where = `routes/${route.file}`;
14
+ if (route.others.length) {
15
+ problems.push(`${where} takes ${route.others.join(', ')}: a prerendered URL is a static file, which answers them 405. ` +
16
+ `Post to another route, or \`export const prerender = false\``);
17
+ continue;
18
+ }
19
+ const dynamic = route.pattern.includes(':');
20
+ if (setting === true) {
21
+ if (dynamic)
22
+ problems.push(`${where} is dynamic: \`export const prerender = () => [{ …params }]\` lists its pages, or \`= false\``);
23
+ else
24
+ paths.add(route.pattern);
25
+ continue;
26
+ }
27
+ try {
28
+ for (const params of await setting())
29
+ paths.add(fillPattern(route.pattern, params));
30
+ }
31
+ catch (error) {
32
+ problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ }
35
+ return { paths: [...paths].sort(), problems };
36
+ }
37
+ /**
38
+ * `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
39
+ * a visit), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
40
+ */
41
+ export function prerenderRoutes(app, routes, version) {
42
+ // Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
43
+ // Cloudflare, Workers Static Assets serve the files before the Worker runs). The built server says how to read them.
44
+ app.use(async (c, next) => {
45
+ const read = globalThis[STATIC_FILES];
46
+ if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
47
+ return next();
48
+ const data = pathOfPageData(c.req.path) !== null; // a visit, rewritten to the page object by fondu/client
49
+ if (!data && (isInertia(c) || !(c.req.header('accept') ?? '').includes('text/html')))
50
+ return next();
51
+ let file;
52
+ try {
53
+ file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
54
+ }
55
+ catch {
56
+ return next(); // not a path a file could have
57
+ }
58
+ const body = await read(file);
59
+ if (!body)
60
+ return next();
61
+ c.header('Cache-Control', 'private, no-cache');
62
+ if (data)
63
+ c.header('X-Inertia', 'true');
64
+ // the document's scripts had the build's nonce: this response's, as the security headers give it a new one
65
+ const nonce = c.get('secureHeadersNonce');
66
+ if (!data && nonce) {
67
+ const html = new TextDecoder().decode(body).replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
68
+ return c.html(html, 200);
69
+ }
70
+ return c.body(body, 200, {
71
+ 'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
72
+ });
73
+ });
74
+ app.get(`${PAGE_DATA}/*`, (c) => {
75
+ const path = pathOfPageData(c.req.path);
76
+ if (!path)
77
+ return c.notFound();
78
+ const url = new URL(c.req.url);
79
+ url.pathname = path;
80
+ const headers = new Headers(c.req.raw.headers);
81
+ headers.set('X-Inertia', 'true');
82
+ let ctx;
83
+ try {
84
+ ctx = c.executionCtx;
85
+ }
86
+ catch { } // none outside a Worker
87
+ return app.fetch(new Request(url, { headers }), c.env, ctx);
88
+ });
89
+ app.get('/__fondu/prerender', async (c) => {
90
+ // set for the build only: a Worker binding, or the environment of `node` / `bun dist/index.js`
91
+ const env = c.env?.FONDU_PRERENDER ?? globalThis.process?.env?.FONDU_PRERENDER;
92
+ if (!env)
93
+ return c.notFound();
94
+ return c.json({ version, ...(await prerenderPaths(routes())) });
95
+ });
96
+ }
@@ -2,7 +2,7 @@ import type { SharedPageProps } from '@inertiajs/core';
2
2
  import type { Context, MiddlewareHandler } from 'hono';
3
3
  import type { Pages } from '../types.js';
4
4
  /**
5
- * The server side of the Inertia v3 protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
5
+ * The server side of Inertia's protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
6
6
  * The client is `@inertiajs/react`, unchanged.
7
7
  */
8
8
  type Shareable<T> = {
@@ -1,4 +1,5 @@
1
1
  import { pages, version } from 'virtual:fondu/assets';
2
+ import { isPageFile } from '../paths.js';
2
3
  import { renderDocument } from './document.js';
3
4
  import { flashCookie, takeCarried } from './flash.js';
4
5
  import { isInertia, sameOrigin } from './http.js';
@@ -9,8 +10,10 @@ export function share(c, props) {
9
10
  shared.set(c, { ...shared.get(c), ...props });
10
11
  }
11
12
  // 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;
13
+ const devPages = import.meta.env.DEV ? import.meta.glob('/app/pages/**/*.{tsx,jsx,mdx}') : {};
14
+ export const hasPage = (name) => pages
15
+ ? pages.includes(name)
16
+ : isPageFile(`${name}.tsx`) && ['tsx', 'jsx', 'mdx'].some((ext) => `/app/pages/${name}.${ext}` in devPages);
14
17
  const headerSet = (c, name) => {
15
18
  const value = c.req.header(name);
16
19
  return value === undefined
@@ -33,7 +36,7 @@ function pageUrl(c) {
33
36
  */
34
37
  export async function render(c, component, ...[props = {}, options = {}]) {
35
38
  if (!hasPage(component))
36
- throw new Error(`fondu: there is no page "${component}": create app/pages/${component}.tsx`);
39
+ throw new Error(`fondu: there is no page "${component}": create app/pages/${component}.tsx (or .mdx)`);
37
40
  const partial = c.req.header('x-inertia-partial-component') === component;
38
41
  const only = partial ? headerSet(c, 'x-inertia-partial-data') : null;
39
42
  const except = partial ? headerSet(c, 'x-inertia-partial-except') : null;
package/dist/virtual.d.ts CHANGED
@@ -4,10 +4,14 @@ declare module 'virtual:fondu/assets' {
4
4
  export const version: string | null
5
5
  /** the page names of a build (from the client manifest); null in development */
6
6
  export const pages: string[] | null
7
+ /** `fondu({ prerender: true })`: page objects of pages without a static file are answered (`/_fondu/pages/…`) */
8
+ export const prerender: boolean
7
9
  /** the `<head>` tags a page needs: the client entry and its styles, the page component's chunk */
8
10
  export function assetTags(component: string, nonce?: string): string
9
11
  }
10
12
  declare module 'virtual:fondu/ssr' {
11
13
  /** the app's `createInertiaApp(...)` rendering a page on the server (null: `fondu({ ssr: false })`) */
12
14
  export const renderPage: ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>) | null
15
+ /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
16
+ export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
13
17
  }