fondu 0.1.2 → 0.2.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,174 +1,61 @@
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
+ **A small meta-framework for full-stack React apps.** It stands on the shoulders of giants: built on Hono, Vite and
4
+ Inertia.
6
5
 
7
- Fondu is glue, not a new framework: it joins Hono, Inertia and Vite, and writes as little of its own as it can.
6
+ Routes are Hono handlers in `app/routes/`; pages are React components in `app/pages/`. A route renders a page with its
7
+ props, and Inertia does the rest in the browser: visits without full reloads, forms with validation, deferred and
8
+ merged props, all without an API to write or a client-side router to keep in sync. The same app runs on **Node, Bun and
9
+ Cloudflare Workers**.
8
10
 
9
- ```
10
- packages/fondu the package (≈1,100 lines)
11
- packages/create-fondu `bun create fondu`: a new app for Node, Bun or Cloudflare
12
- apps/node a small example: Link, loader, action, HTTP routes — Node and Bun
13
- apps/cloudflare every Inertia v3 feature, one page each — Workers, D1, Better Auth
14
- ```
15
-
16
- ## Who does what
11
+ Fondu writes as little of its own as it can: the server side of Inertia's protocol, file routes, typed pages and
12
+ URLs, the document and error pages. Everything else is Hono's, Vite's and Inertia's.
17
13
 
18
- | Part | Done by |
19
- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
20
- | Browser: visits, history, prefetch, forms, progress, `<Head>`, deferred, merging, infinite scroll, optimistic updates, Precognition | `@inertiajs/react` |
21
- | HTTP, middleware, CSRF, security headers, trailing slashes | Hono and its middleware |
22
- | Dev server, production build | Node / Bun: `@hono/vite-dev-server`, `@hono/vite-build`; Cloudflare: `@cloudflare/vite-plugin` |
23
- | Page resolution, the server render's entry | `@inertiajs/vite` (rendered in the same process) |
24
- | The Inertia v3 server protocol, `routes/`, generated types, the document, error pages, server-only guard | Fondu |
25
-
26
- ## This repository
14
+ ## Quick start
27
15
 
28
16
  ```bash
29
- bun install # also builds packages/fondu (the examples use the built package, like a real app)
30
- bun run test # the protocol, on a small app with app.request()
31
- bun run typecheck # the package and both examples (with apps/cloudflare/e2e/types.ts)
32
- bun run check # format (oxfmt), lint (oxlint), typecheck
33
- bun run dev # rebuild packages/fondu on change
34
- ```
35
-
36
- Commits follow [Conventional Commits](https://www.conventionalcommits.org) (lefthook runs commitlint, and formats and
37
- lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI publishes the tag to npm
38
- (trusted publishing, with provenance) and writes the GitHub Release from the commits.
39
-
40
- `apps/node`: `bun run dev`; `bun run build && bun run start` (Node); `bun run build:bun && bun run start:bun` (Bun).
41
- `apps/cloudflare`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
42
-
43
- ## An app
44
-
45
- ```bash
46
- bun create fondu my-app # or: npm create fondu@latest my-app — asks for the target, then installs
47
- ```
48
-
17
+ bun create fondu my-app # or: npm create fondu@latest my-app · pnpm create fondu my-app
18
+ cd my-app
19
+ bun dev
49
20
  ```
50
- package.json fondu hono @inertiajs/react react react-dom (Node: also @hono/node-server)
51
- "imports": { "#/*": "./app/*" }: import '#/lib/db.server.ts' from anywhere in app/
52
- vite.config.ts plugins: [fondu({ target: 'node' })] 'bun'; Cloudflare: [cloudflare(), fondu({ target: 'cloudflare' })]
53
- app/
54
- server.ts export default createApp()
55
- app.tsx createInertiaApp({ pages: './pages', … }): browser and server render
56
- routes/ server code only; the file path is the URL
57
- _middleware.ts for its directory and below (routes/_middleware.ts: every request, 404s too)
58
- index.ts /
59
- users/[id].ts /users/:id
60
- api/health.ts /api/health
61
- pages/ React pages, rendered by name: 'users/show' is pages/users/show.tsx
62
- error.tsx the error page (404, 403, 500…)
63
- fondu.gen.d.ts generated types (commit it)
64
- ```
65
-
66
- `createApp()` comes with CSRF protection, security headers (`Referrer-Policy: same-origin`, which `back()` needs), a
67
- Content Security Policy, one URL per page (`/users/` → `/users`) and error handling. Options: `document` (the HTML
68
- around pages: `<html>` attributes, the viewport, fonts…), `errorPage`, `trailingSlash: 'append'`, `csrf` and
69
- `secureHeaders` (Hono's options, or `false`).
70
21
 
71
- The policy: `default-src 'self'`, scripts of this site or with the request's nonce (the document's scripts have it),
72
- inline styles (style attributes), `data:` images and fonts, no plugins (`object-src 'none'`), `base-uri 'self'`. A
73
- directive of yours replaces that one: `secureHeaders: { contentSecurityPolicy: { fontSrc: ["'self'",
74
- 'https://fonts.gstatic.com'] } }` (apps/node does so for Google Fonts); `contentSecurityPolicy: false`: none.
22
+ It asks where the app runs (Node, Bun or Cloudflare Workers; or `--target node|bun|cloudflare`) and writes a small
23
+ app: a route, its page, the error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents.
75
24
 
76
- ### routes/: loader, action, actions
25
+ [demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](apps/demo)) shows every Inertia feature, one page each, on
26
+ Cloudflare Workers with D1 and Better Auth.
77
27
 
78
- ```ts
79
- // app/routes/users/[id].ts
80
- import { back, defineHandler, flash, render } from 'fondu'
81
- import * as z from 'zod/mini'
28
+ ## Docs
82
29
 
83
- const params = z.object({ id: z.coerce.number() })
30
+ **[fondu.dev](https://fondu.dev/docs)**: routes, pages and props, forms and validation, type safety, server-side
31
+ rendering, static pages, MDX pages, deploying, and the API. Every page is also Markdown for coding agents
32
+ ([llms.txt](https://fondu.dev/llms.txt)).
84
33
 
85
- export const loader = defineHandler.withValidator({ params })(async (c, { params }) =>
86
- // GET /users/7
87
- render(c, 'users/show', { user: await getUser(params.id) }),
88
- )
34
+ ## Contributing
89
35
 
90
- export const actions = {
91
- rename: defineHandler.withValidator({ params, body: renameSchema })(requireUser, async (c, { params, body }) => {
92
- await renameUser(params.id, body.name) // POST /users/7?rename
93
- return back(c)
94
- }),
95
- }
96
36
  ```
97
-
98
- - `loader` is GET, `action` POST, `actions.x` `POST ?x` (a plain form can pick one). HTTP routes export `GET` / `POST` / `PUT` / `PATCH` / `DELETE`.
99
- - `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).
100
- - Every `.ts` file in `routes/` is a route, except `_middleware.ts` and tests. `(group)` directories take no URL segment.
101
-
102
- ### Validation (Inertia's way)
103
-
104
- Invalid `body` or `query`: Inertia visits and plain forms get a 303 back with the errors in the next page's `errors`
105
- prop (in the `X-Inertia-Error-Bag` bag when there is one); API clients get 422 `{ errors }`. Params that don't fit are
106
- a 404. A Precognition request (`<Form>`'s `validate()`, `useForm().withPrecognition()`) is only validated: 204 or 422.
107
- The same schema can be imported by the page to check before sending.
108
-
109
- ### Pages and props
110
-
111
- ```tsx
112
- // app/pages/users/show.tsx — the component's parameter is the page's props
113
- export default function Show({ user }: { user: User }) { … }
37
+ packages/fondu the package (≈1,100 lines)
38
+ packages/create-fondu `bun create fondu`
39
+ apps/demo every Inertia feature, one page each — Workers, D1, Better Auth, coss ui
40
+ apps/site fondu.dev: the docs, MDX and static pages on Workers
114
41
  ```
115
42
 
116
- `render(c, 'users/show', props, options?)` takes only pages that exist, with the component's props; a page prop named
117
- like a shared prop is a type error. A function prop is called only when it is sent.
118
-
119
- | prop | |
120
- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
121
- | `optional(fn)` | only when a partial reload names it |
122
- | `always(v)` | partial reloads too |
123
- | `defer(fn, { group?, rescue? })` | after the page renders, one request per group; `rescue`: a failure is listed in `rescuedProps` |
124
- | `merge` / `prepend` / `deepMerge(v, { matchOn? })` | merged with what the client holds |
125
- | `once(fn, { key?, ttl?, fresh? })` | skipped when the client holds it |
126
- | `scroll(fn, { pageName? })` | a page of a list for `<InfiniteScroll>`: `{ data, currentPage, previousPage, nextPage }` |
127
-
128
- Options: `status`, `encryptHistory`, `clearHistory`, `preserveFragment`. Also `flash(c, data)`, `clearHistory(c)`,
129
- `back(c)`, `location(c, url)` (409 + `X-Inertia-Location`); a redirect with a `#fragment` becomes a 409
130
- `X-Inertia-Redirect` by itself.
131
-
132
- ### Types
133
-
134
- ```ts
135
- // where the values are set (e.g. routes/_middleware.ts)
136
- declare module 'hono' {
137
- interface ContextVariableMap {
138
- user: User | null
139
- } // c.get('user')
140
- }
141
- declare module '@inertiajs/core' {
142
- interface InertiaConfig {
143
- sharedPageProps: { auth: { user: { name: string } | null } } // share(), usePage().props
144
- flashDataType: { message?: string } // flash(), usePage().flash
145
- }
146
- }
43
+ ```bash
44
+ bun install # also builds packages/fondu (the examples use the built package, like a real app)
45
+ bun run test # the protocol, on a small app with app.request()
46
+ bun run typecheck # the package, the demo (with apps/demo/e2e/types.ts) and the site
47
+ bun run check # format (oxfmt), lint (oxlint), typecheck
48
+ bun run dev # rebuild packages/fondu on change
147
49
  ```
148
50
 
149
- `href(path, params?)` from `fondu/client`: a URL of `routes/` (or one of a file's actions: `'/users/:id?rename'`),
150
- params required, a typo is a type error. The method is Inertia's: `<Link href={href('/logout')} method="post" as="button">`.
151
-
152
- ### Server-side rendering
153
-
154
- Document loads are rendered on the server in the same process, then hydrated. Off for the whole app:
155
- `fondu({ ssr: false })`. Off for some routes: `withoutSsr()` (in a `_middleware.ts` for a directory, or in one
156
- handler). A browser-only part of a page: Inertia's `<WhenMounted>`.
157
-
158
- ### Errors
159
-
160
- Unknown URLs and thrown errors: API clients get plain text; pages get `pages/error.tsx` with `{ status }`, inside the
161
- layout with the shared props. In development a 500 is a report of the error instead (Inertia shows it in its dialog
162
- during a visit). `render()` of a page that doesn't exist says which file to create. Your own handling: Hono's
163
- `app.notFound()` / `app.onError()` on the app `createApp()` returns.
51
+ Commits follow [Conventional Commits](https://www.conventionalcommits.org) (lefthook runs commitlint, and formats and
52
+ lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI publishes the tag to npm
53
+ (trusted publishing, with provenance) and writes the GitHub Release from the commits.
164
54
 
165
- ### Editor snippets
55
+ `apps/demo`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
166
56
 
167
- `.vscode/fondu.code-snippets`: `/route`, `/api`, `/loader`, `/action`, `/actions`, `/validated`, `/get` … `/delete`,
168
- `/middleware` in routes; `/page`, `/layout`, `/form` in pages. Copy it into your app's `.vscode/` and edit it freely.
57
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the details, and [SECURITY.md](SECURITY.md) to report a vulnerability.
169
58
 
170
- ## Deploying
59
+ ## License
171
60
 
172
- - **Node**: `vite build --mode client && vite build`, then `node dist/index.js` (dependencies stay in `node_modules`). `PORT` sets the port; SIGTERM / SIGINT wait for running requests (10 s).
173
- - **Bun**: `fondu({ target: 'bun' })`, `bun dist/index.js`.
174
- - **Cloudflare Workers**: `wrangler.jsonc` `main` is `./app/server.ts`; one `vite build`; `wrangler deploy`. `/assets/*` get long-lived caching from a generated `_headers` (unless `public/_headers` exists).
61
+ Distributed under the MIT License. See [LICENSE](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`);
@@ -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,90 @@
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
+ return c.body(body, 200, {
65
+ 'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
66
+ });
67
+ });
68
+ app.get(`${PAGE_DATA}/*`, (c) => {
69
+ const path = pathOfPageData(c.req.path);
70
+ if (!path)
71
+ return c.notFound();
72
+ const url = new URL(c.req.url);
73
+ url.pathname = path;
74
+ const headers = new Headers(c.req.raw.headers);
75
+ headers.set('X-Inertia', 'true');
76
+ let ctx;
77
+ try {
78
+ ctx = c.executionCtx;
79
+ }
80
+ catch { } // none outside a Worker
81
+ return app.fetch(new Request(url, { headers }), c.env, ctx);
82
+ });
83
+ app.get('/__fondu/prerender', async (c) => {
84
+ // set for the build only: a Worker binding, or the environment of `node` / `bun dist/index.js`
85
+ const env = c.env?.FONDU_PRERENDER ?? globalThis.process?.env?.FONDU_PRERENDER;
86
+ if (!env)
87
+ return c.notFound();
88
+ return c.json({ version, ...(await prerenderPaths(routes())) });
89
+ });
90
+ }
@@ -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,6 +4,8 @@ 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
  }
@@ -15,5 +15,12 @@ export interface FonduOptions {
15
15
  /** `false`: pages render in the browser only, no server render is built (an admin app). Per route: `withoutSsr()` */
16
16
  ssr?: boolean;
17
17
  react?: ReactOptions;
18
+ /**
19
+ * Routes with `export const prerender` (or under a `_middleware.ts` with it) are written as static files at build
20
+ * time, and visits read them; the server (the Worker) answers the other pages
21
+ */
22
+ prerender?: boolean;
18
23
  }
24
+ /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
25
+ export declare const HONO: string[];
19
26
  export default function fondu(options: FonduOptions): PluginOption[];
@@ -1,13 +1,27 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
7
7
  import inertia from '@inertiajs/vite';
8
8
  import react, {} from '@vitejs/plugin-react';
9
+ import { isPageFile } from '../paths.js';
10
+ import { layouts } from './layouts.js';
11
+ import { nodeServer, prerender, worker } from './prerender.js';
9
12
  import { typegen } from './typegen.js';
10
13
  const ENTRY = 'app/app.tsx';
14
+ /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
15
+ export const HONO = [
16
+ 'hono',
17
+ 'hono/combine',
18
+ 'hono/cookie',
19
+ 'hono/csrf',
20
+ 'hono/factory',
21
+ 'hono/http-exception',
22
+ 'hono/secure-headers',
23
+ 'hono/trailing-slash',
24
+ ];
11
25
  const SERVER = './app/server.ts';
12
26
  const DEV_CSS = '/@fondu/dev.css';
13
27
  const V = { assets: 'virtual:fondu/assets', ssr: 'virtual:fondu/ssr' };
@@ -18,7 +32,7 @@ const resolved = (id) => '\0' + id;
18
32
  */
19
33
  const inertiaInProcess = {
20
34
  package: '@inertiajs/react',
21
- extensions: ['.tsx', '.jsx'],
35
+ extensions: ['.tsx', '.jsx', '.mdx'],
22
36
  extractDefault: true,
23
37
  ssr: (configureCall) => `
24
38
  import { renderToString } from 'react-dom/server'
@@ -29,6 +43,21 @@ export default async function renderPage(page) {
29
43
  }
30
44
  `,
31
45
  };
46
+ /** For the dependency scan: an MDX page as the JavaScript @mdx-js/rollup makes of it (nothing without it) */
47
+ function scanMdx(config) {
48
+ return {
49
+ name: 'fondu:scan-mdx',
50
+ load: {
51
+ filter: { id: /\.mdx$/ },
52
+ async handler(id) {
53
+ const hook = config().plugins.find((p) => p.name === '@mdx-js/rollup')?.transform;
54
+ const transform = typeof hook === 'function' ? hook : hook?.handler;
55
+ const out = await transform?.call(this, readFileSync(id, 'utf8'), id);
56
+ return { code: typeof out === 'string' ? out : String(out?.code ?? ''), moduleType: 'js' };
57
+ },
58
+ },
59
+ };
60
+ }
32
61
  export default function fondu(options) {
33
62
  const node = options.target !== 'cloudflare';
34
63
  return [
@@ -36,6 +65,7 @@ export default function fondu(options) {
36
65
  // `ssr: {}`: the server transform without an entry, so without @inertiajs/vite's dev SSR endpoint (Laravel's model)
37
66
  inertia({ ssr: options.ssr === false ? false : {}, frameworks: inertiaInProcess }),
38
67
  core(options),
68
+ layouts(),
39
69
  typegen(),
40
70
  ...(node ? runtimePlugins(options) : []),
41
71
  ];
@@ -49,11 +79,18 @@ async function buildPlugin(options) {
49
79
  entry: SERVER,
50
80
  external,
51
81
  outputDir: './dist',
52
- // Node: graceful shutdown on SIGTERM / SIGINT; the port is read when the server starts (`PORT`, else the
53
- // option): the adapter writes the value into the entry as code. Bun reads `PORT` itself.
82
+ // Node: @hono/node-server's serve() on `PORT` (else the option), saying where it listens, with a graceful
83
+ // shutdown on SIGTERM / SIGINT (10 s). Bun serves the default export itself and reads `PORT`.
54
84
  ...(options.target === 'node' && {
55
- shutdownTimeoutMs: 10_000,
56
- port: { toString: () => `(Number(process.env.PORT) || ${options.port ?? 3000})` },
85
+ entryContentAfterHooks: [
86
+ (app) => [
87
+ `import { serve } from '@hono/node-server'`,
88
+ `const server = serve({ fetch: ${app}.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
89
+ `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
90
+ `process.on('SIGINT', shutdown)`,
91
+ `process.on('SIGTERM', shutdown)`,
92
+ ].join('\n'),
93
+ ],
57
94
  }),
58
95
  // the client build's files (dist/client), found next to the server bundle wherever it runs from; hashed files
59
96
  // never change
@@ -71,6 +108,14 @@ async function buildPlugin(options) {
71
108
  `const clientRoot = fileURLToPath(new URL('./client', import.meta.url))`,
72
109
  `${app}.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
73
110
  ...paths.map((p) => `${app}.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
111
+ // prerender: how the app reads the prerendered pages (fondu's server/prerender.ts), in the client build
112
+ ...(options.prerender
113
+ ? [
114
+ `import { readFile } from 'node:fs/promises'`,
115
+ `import { join as joinPath, sep } from 'node:path'`,
116
+ `globalThis[Symbol.for('fondu.staticFiles')] = (file) => { const to = joinPath(clientRoot, file); return to.startsWith(clientRoot + sep) ? readFile(to).catch(() => null) : Promise.resolve(null) }`,
117
+ ]
118
+ : []),
74
119
  ].join('\n');
75
120
  },
76
121
  ],
@@ -107,11 +152,13 @@ function runtimePlugins(options) {
107
152
  function core(options) {
108
153
  let config;
109
154
  let isBuild = false;
155
+ let serverBuild = false; // Node / Bun: `vite build`, after `vite build --mode client`
110
156
  return {
111
157
  name: 'fondu',
112
158
  enforce: 'pre',
113
159
  config(_user, env) {
114
160
  isBuild = env.command === 'build';
161
+ serverBuild = isBuild && options.target !== 'cloudflare' && env.mode !== 'client';
115
162
  const client = { manifest: true, rollupOptions: { input: ENTRY } };
116
163
  if (options.target === 'cloudflare') {
117
164
  return {
@@ -119,10 +166,22 @@ function core(options) {
119
166
  // the worker reads the client manifest: client first
120
167
  builder: {
121
168
  async buildApp(builder) {
122
- await builder.build(builder.environments.client);
123
- for (const env of Object.values(builder.environments))
124
- if (env.name !== 'client')
125
- await builder.build(env);
169
+ const client = builder.environments.client;
170
+ await builder.build(client);
171
+ // the client manifest is for the build (asset tags, the version): not a static asset to deploy
172
+ const ignore = resolve(config.root, client.config.build.outDir, '.assetsignore');
173
+ if (existsSync(ignore))
174
+ appendFileSync(ignore, '.vite\n');
175
+ for (const env of Object.values(builder.environments)) {
176
+ if (env.name === 'client')
177
+ continue;
178
+ await builder.build(env);
179
+ const wrangler = resolve(config.root, env.config.build.outDir, 'wrangler.json');
180
+ if (options.prerender && existsSync(wrangler)) {
181
+ const clientDir = resolve(config.root, client.config.build.outDir);
182
+ await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
183
+ }
184
+ }
126
185
  },
127
186
  },
128
187
  ssr: { noExternal: ['fondu'] },
@@ -136,9 +195,41 @@ function core(options) {
136
195
  build: { copyPublicDir: false, rollupOptions: { output: { chunkFileNames: 'server/[name]-[hash].js' } } },
137
196
  };
138
197
  },
198
+ // dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
199
+ // so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
200
+ // for it by the app's @mdx-js/rollup
201
+ configEnvironment(name, env) {
202
+ const pages = ['app/pages/**/*.{tsx,jsx,mdx}'];
203
+ const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
204
+ if (name === 'client')
205
+ return { optimizeDeps: { entries: [ENTRY, ...pages], ...mdx } };
206
+ if (options.target !== 'cloudflare')
207
+ return;
208
+ // the Worker: fondu is not pre-bundled (its routes import it back: a bundle would hand them a half-loaded
209
+ // module), so the scan does not see what it imports (HONO); nor react-dom/server, imported by @inertiajs/vite's
210
+ // generated render. Found late, they would restart the Worker in the middle of requests.
211
+ // The build is minified, as Workers start faster with less code to parse
212
+ return {
213
+ optimizeDeps: {
214
+ exclude: ['fondu'],
215
+ include: [...HONO, ...(options.ssr === false ? [] : ['react-dom/server'])],
216
+ entries: [SERVER.slice(2), 'app/routes/**/*.ts', ENTRY, ...pages],
217
+ ...mdx,
218
+ },
219
+ ...(env.build?.minify === undefined && { build: { minify: true } }),
220
+ };
221
+ },
139
222
  configResolved(c) {
140
223
  config = c;
141
224
  },
225
+ // Node / Bun: the server built, its pages to prerender written next to the client build's files
226
+ async closeBundle() {
227
+ if (!options.prerender || !serverBuild || options.target === 'cloudflare')
228
+ return;
229
+ serverBuild = false; // once
230
+ const clientDir = resolve(config.root, 'dist/client');
231
+ await prerender(nodeServer(config.root, options.target), clientDir, config.logger, false);
232
+ },
142
233
  // dev: server code changed (a module of the server only: routes/, *.server.ts…): reload the page; a page component:
143
234
  // React Fast Refresh (the client's HMR)
144
235
  handleHotUpdate({ server, file }) {
@@ -197,13 +288,20 @@ function core(options) {
197
288
  if (id === V.assets || id === V.ssr)
198
289
  return resolved(id);
199
290
  },
291
+ // prerender: the client entry reads page objects from the prerendered files (fondu/client's `prerendered`)
292
+ transform(code, id) {
293
+ if (!options.prerender || this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
294
+ return;
295
+ return { code: `import { prerendered } from 'fondu/client';prerendered();${code}`, map: null };
296
+ },
200
297
  load(id) {
201
298
  if (id === resolved(V.ssr))
202
299
  return options.ssr === false
203
300
  ? 'export const renderPage = null'
204
301
  : `export { default as renderPage } from '/${ENTRY}'`;
205
302
  if (id === resolved(V.assets))
206
- return isBuild ? productionAssets(config, options) : devAssets(config.base);
303
+ return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
304
+ `\nexport const prerender = ${Boolean(options.prerender)}`);
207
305
  // the server-only guard: browser code must never import server code
208
306
  if (this.environment.config.consumer === 'client' && isServerOnly(id)) {
209
307
  this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/, server.ts, *.server.ts) and cannot be imported by browser code`);
@@ -250,8 +348,8 @@ function productionAssets(config, options) {
250
348
  const entry = tags(ENTRY);
251
349
  const pages = {};
252
350
  for (const key of Object.keys(manifest)) {
253
- const m = key.match(/^app\/pages\/(.+)\.[jt]sx$/);
254
- if (m)
351
+ const m = key.match(/^app\/pages\/(.+)\.(?:[jt]sx|mdx)$/);
352
+ if (m && isPageFile(key))
255
353
  pages[m[1]] = tags(key);
256
354
  }
257
355
  const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
@@ -0,0 +1,8 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
4
+ * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
5
+ * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
6
+ * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
7
+ */
8
+ export declare function layouts(): Plugin;
@@ -0,0 +1,77 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { isPageFile, layoutsOf } from '../paths.js';
4
+ const LAYOUT_EXTENSIONS = ['.tsx', '.jsx'];
5
+ /**
6
+ * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
7
+ * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
8
+ * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
9
+ * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
10
+ */
11
+ export function layouts() {
12
+ let root = process.cwd();
13
+ const pagesDir = () => join(root, 'app/pages');
14
+ // the `_layout.tsx` of a directory of app/pages/ ('' is the root), if there is one
15
+ const layoutFile = (dir) => LAYOUT_EXTENSIONS.map((ext) => join(pagesDir(), dir, `_layout${ext}`)).find((f) => existsSync(f));
16
+ return {
17
+ name: 'fondu:layouts',
18
+ enforce: 'post', // after the JSX and MDX are compiled: plain JavaScript to read
19
+ configResolved(c) {
20
+ root = c.root;
21
+ },
22
+ transform(code, id) {
23
+ const file = id.split('?')[0];
24
+ const rel = relative(pagesDir(), file).split(sep).join('/');
25
+ if (rel.startsWith('..') || !isPageFile(rel))
26
+ return;
27
+ const chain = layoutsOf(rel)
28
+ .map(layoutFile)
29
+ .filter((f) => f !== undefined);
30
+ if (!chain.length)
31
+ return;
32
+ const found = defaultExport(this.parse(code), code);
33
+ if (!found)
34
+ return;
35
+ // added at the end (imports are hoisted) and within a line: the lines stay where they were (`map: null`)
36
+ const imports = chain.map((f, i) => `import __fondu_layout_${i} from ${JSON.stringify(f)};`).join('\n');
37
+ const set = `${found.name}.layout ??= [${chain.map((_, i) => `__fondu_layout_${i}`).join(', ')}];`;
38
+ return { code: `${found.code}\n${imports}\n${set}\n`, map: null };
39
+ },
40
+ // dev: a `_layout.tsx` added or removed changes the chains of the pages below it: every module transformed anew
41
+ configureServer(server) {
42
+ const changed = (file) => {
43
+ const rel = relative(pagesDir(), file).split(sep).join('/');
44
+ if (rel.startsWith('..') || !/(^|\/)_layout\.[jt]sx$/.test(rel))
45
+ return;
46
+ for (const env of Object.values(server.environments))
47
+ env.moduleGraph.invalidateAll();
48
+ server.hot.send({ type: 'full-reload' });
49
+ };
50
+ server.watcher.on('add', changed);
51
+ server.watcher.on('unlink', changed);
52
+ },
53
+ };
54
+ }
55
+ /**
56
+ * The name of the module's default export, to set `layout` on: a named function or class as it is; an anonymous one,
57
+ * or an expression, given a name first (`const __fondu_page = …`, exported at the end)
58
+ */
59
+ function defaultExport(program, code) {
60
+ for (const node of program.body) {
61
+ if (node.type === 'ExportNamedDeclaration' && !node.source) {
62
+ const specifiers = node.specifiers;
63
+ const specifier = specifiers.find((sp) => sp.exported.name === 'default');
64
+ if (specifier)
65
+ return { name: specifier.local.name, code };
66
+ }
67
+ if (node.type !== 'ExportDefaultDeclaration')
68
+ continue;
69
+ const declaration = node.declaration;
70
+ if (declaration.id)
71
+ return { name: declaration.id.name, code };
72
+ return {
73
+ name: '__fondu_page',
74
+ code: `${code.slice(0, node.start)}const __fondu_page = ${code.slice(declaration.start)}\nexport default __fondu_page;`,
75
+ };
76
+ }
77
+ }
@@ -0,0 +1,23 @@
1
+ import type { Logger } from 'vite';
2
+ import { staticFiles } from '../paths.js';
3
+ export { staticFiles };
4
+ /** a Content Security Policy for a static document: no nonce (one for every visitor is none), `'self'` scripts */
5
+ export declare function staticPolicy(policy: string): string;
6
+ /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
7
+ export declare function headerRules(headers: Record<string, string>): string;
8
+ /** the built server, running for the prerender: fetch a path of it, stop it */
9
+ interface Server {
10
+ fetch(path: string, headers?: Record<string, string>): Promise<Response>;
11
+ dispose(): Promise<void>;
12
+ }
13
+ /**
14
+ * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/index.js`), started with
15
+ * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
16
+ * a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
17
+ * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
18
+ */
19
+ export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, headersFile: boolean): Promise<undefined>;
20
+ /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
21
+ export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
22
+ /** Node / Bun: `node dist/index.js` (or `bun`), on a free port, until it answers */
23
+ export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;
@@ -0,0 +1,164 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { createServer } from 'node:net';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { PAGE_DATA, staticFiles } from '../paths.js';
8
+ export { staticFiles };
9
+ /** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
10
+ const SECURITY_HEADERS = /^(content-security-policy(-report-only)?|strict-transport-security|referrer-policy|permissions-policy|x-content-type-options|x-frame-options|x-xss-protection|x-dns-prefetch-control|x-download-options|x-permitted-cross-domain-policies|origin-agent-cluster|cross-origin-(opener|embedder|resource)-policy)$/i;
11
+ /** a Content Security Policy for a static document: no nonce (one for every visitor is none), `'self'` scripts */
12
+ export function staticPolicy(policy) {
13
+ return policy
14
+ .split(';')
15
+ .map((directive) => {
16
+ const [name, ...sources] = directive.trim().split(/\s+/);
17
+ if (!name)
18
+ return '';
19
+ const kept = sources.filter((s) => !s.startsWith("'nonce-"));
20
+ if (/^script-src(-elem)?$/i.test(name) && kept.length === 0)
21
+ kept.push("'self'");
22
+ return [name, ...kept].join(' ');
23
+ })
24
+ .filter(Boolean)
25
+ .join('; ');
26
+ }
27
+ /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
28
+ export function headerRules(headers) {
29
+ const lines = Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`);
30
+ return `\n/*\n${lines.join('\n')}\n${PAGE_DATA}/*\n X-Inertia: true\n`;
31
+ }
32
+ /**
33
+ * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/index.js`), started with
34
+ * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
35
+ * a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
36
+ * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
37
+ */
38
+ export async function prerender(start, clientDir, logger, headersFile) {
39
+ const fail = (lines) => {
40
+ for (const line of lines)
41
+ logger.error(`fondu: ${line}`);
42
+ throw new Error(`fondu: prerendering failed (${lines.length === 1 ? lines[0] : `${lines.length} problems, above`})`);
43
+ };
44
+ const server = await start().catch((error) => fail([error.message]));
45
+ try {
46
+ const get = server.fetch;
47
+ const listing = await get('/__fondu/prerender');
48
+ if (!listing.ok)
49
+ return fail([`the server did not list the pages (${listing.status})`]);
50
+ const { version, paths, problems } = (await listing.json());
51
+ if (problems.length)
52
+ return fail(problems);
53
+ if (paths.length === 0) {
54
+ logger.warn('fondu: prerender is on, and no route has `export const prerender`');
55
+ return;
56
+ }
57
+ let security;
58
+ const errors = [];
59
+ for (const path of paths) {
60
+ const doc = await get(path, { Accept: 'text/html' });
61
+ const visit = await get(path, { 'X-Inertia': 'true', ...(version && { 'X-Inertia-Version': version }) });
62
+ if (doc.status !== 200 || visit.status !== 200) {
63
+ const to = doc.headers.get('location');
64
+ errors.push(`${path}: ${doc.status}${to ? ` → ${to}` : ''} (a prerendered page must answer 200 to anyone)`);
65
+ continue;
66
+ }
67
+ const page = (await visit.json());
68
+ const later = ['deferredProps', 'scrollProps'].filter((key) => page[key]);
69
+ if (later.length) {
70
+ errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
71
+ continue;
72
+ }
73
+ const headers = Object.fromEntries([...doc.headers]
74
+ .filter(([name]) => SECURITY_HEADERS.test(name))
75
+ .map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value) : value]));
76
+ if (headersFile && security && JSON.stringify(headers) !== JSON.stringify(security)) {
77
+ errors.push(`${path}: its security headers differ from ${paths[0]}'s; one set is written for all`);
78
+ continue;
79
+ }
80
+ security = headers;
81
+ const files = staticFiles(path);
82
+ write(clientDir, files.html, await doc.text());
83
+ write(clientDir, files.json, JSON.stringify(page));
84
+ logger.info(`fondu: prerendered ${path}`);
85
+ }
86
+ if (errors.length)
87
+ return fail(errors);
88
+ if (headersFile)
89
+ appendFileSync(join(clientDir, '_headers'), headerRules(security ?? {}));
90
+ }
91
+ finally {
92
+ await server.dispose();
93
+ }
94
+ }
95
+ /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
96
+ export const worker = (root, workerConfig) => async () => {
97
+ let wrangler;
98
+ try {
99
+ const entry = createRequire(resolve(root, 'package.json')).resolve('wrangler');
100
+ wrangler = (await import(pathToFileURL(entry).href));
101
+ }
102
+ catch {
103
+ throw new Error('wrangler is not installed: `npm install -D wrangler` (or bun / pnpm / yarn)');
104
+ }
105
+ const started = await wrangler.unstable_startWorker({
106
+ config: workerConfig,
107
+ bindings: { FONDU_PRERENDER: { type: 'plain_text', value: '1' } },
108
+ dev: { server: { port: 0 }, inspector: false, logLevel: 'error' },
109
+ });
110
+ await started.ready;
111
+ return {
112
+ fetch: (path, headers = {}) => started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
113
+ dispose: () => started.dispose(),
114
+ };
115
+ };
116
+ /** Node / Bun: `node dist/index.js` (or `bun`), on a free port, until it answers */
117
+ export const nodeServer = (root, runtime) => async () => {
118
+ const port = await freePort();
119
+ const child = spawn(runtime, ['dist/index.js'], {
120
+ cwd: root,
121
+ env: { ...process.env, PORT: String(port), FONDU_PRERENDER: '1', NODE_ENV: 'production' },
122
+ stdio: ['ignore', 'pipe', 'pipe'],
123
+ });
124
+ let output = '';
125
+ child.stdout.on('data', (d) => (output += d));
126
+ child.stderr.on('data', (d) => (output += d));
127
+ const base = `http://127.0.0.1:${port}`;
128
+ const server = {
129
+ fetch: (path, headers = {}) => fetch(base + path, { headers, redirect: 'manual' }),
130
+ dispose: async () => {
131
+ if (child.exitCode !== null)
132
+ return;
133
+ const exited = new Promise((r) => child.once('exit', r));
134
+ child.kill();
135
+ const force = setTimeout(() => child.kill('SIGKILL'), 3000);
136
+ await exited;
137
+ clearTimeout(force);
138
+ },
139
+ };
140
+ for (let tries = 0;; tries++) {
141
+ if (child.exitCode !== null || tries === 200)
142
+ throw new Error(`the server (${runtime} dist/index.js) did not start:\n${output.trim()}`);
143
+ try {
144
+ await fetch(base + '/__fondu/prerender');
145
+ return server;
146
+ }
147
+ catch {
148
+ await new Promise((r) => setTimeout(r, 50));
149
+ }
150
+ }
151
+ };
152
+ const freePort = () => new Promise((resolve, reject) => {
153
+ const s = createServer();
154
+ s.on('error', reject);
155
+ s.listen(0, '127.0.0.1', () => {
156
+ const { port } = s.address();
157
+ s.close(() => resolve(port));
158
+ });
159
+ });
160
+ function write(dir, file, content) {
161
+ const to = join(dir, file);
162
+ mkdirSync(dirname(to), { recursive: true });
163
+ writeFileSync(to, content);
164
+ }
@@ -1,5 +1,8 @@
1
1
  import type { Plugin } from 'vite';
2
- /** The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s. */
2
+ /**
3
+ * The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
4
+ * MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
5
+ */
3
6
  export declare function generateTypes(root: string): string;
4
7
  export declare function writeTypes(root: string): void;
5
8
  export declare function typegen(): Plugin;
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join, relative, sep } from 'node:path';
3
- import { isRouteFile, routePattern } from '../paths.js';
3
+ import { isPageFile, isRouteFile, routePattern } from '../paths.js';
4
4
  const OUT = 'app/fondu.gen.d.ts';
5
5
  function walk(dir, out = [], base = dir) {
6
6
  if (!existsSync(dir))
@@ -14,18 +14,19 @@ function walk(dir, out = [], base = dir) {
14
14
  }
15
15
  return out;
16
16
  }
17
- /** The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s. */
17
+ /**
18
+ * The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
19
+ * MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
20
+ */
18
21
  export function generateTypes(root) {
19
- const pages = walk(join(root, 'app/pages'))
20
- .filter((f) => /\.[jt]sx$/.test(f))
21
- .sort();
22
+ const pages = walk(join(root, 'app/pages')).filter(isPageFile).sort();
22
23
  const routes = walk(join(root, 'app/routes')).filter(isRouteFile).sort();
23
24
  const line = (key, path) => ` ${JSON.stringify(key)}: typeof import(${JSON.stringify(path)})`;
24
25
  return `// Generated by fondu (vite dev / vite build). Commit it; do not edit.
25
26
  declare module 'fondu' {
26
27
  interface Register {
27
28
  pages: {
28
- ${pages.map((f) => line(f.replace(/\.[jt]sx$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
29
+ ${pages.map((f) => line(f.replace(/\.(?:[jt]sx|mdx)$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
29
30
  }
30
31
  routes: {
31
32
  ${routes.map((f) => line(routePattern(f), `./routes/${f.replace(/\.ts$/, '')}`)).join('\n')}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.1.2",
4
- "description": "Inertia v3 on Hono, with file routes (loader, action, actions) and pages. Node, Bun and Cloudflare Workers.",
5
- "homepage": "https://github.com/fondujs/fondu#readme",
3
+ "version": "0.2.0",
4
+ "description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. Node, Bun and Cloudflare Workers.",
5
+ "homepage": "https://fondu.dev",
6
6
  "bugs": "https://github.com/fondujs/fondu/issues",
7
7
  "license": "MIT",
8
8
  "repository": {
@@ -36,10 +36,10 @@
36
36
  "typecheck": "tsc -p tsconfig.json"
37
37
  },
38
38
  "dependencies": {
39
- "@hono/vite-build": "1.11.1",
40
- "@hono/vite-dev-server": "0.26.1",
41
- "@inertiajs/vite": "3.9.1",
42
- "@vitejs/plugin-react": "6.1.2"
39
+ "@hono/vite-build": "^1.11.1",
40
+ "@hono/vite-dev-server": "^0.26.1",
41
+ "@inertiajs/vite": "^3.9.1",
42
+ "@vitejs/plugin-react": "^6.1.2"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@inertiajs/core": "3.9.1",