@kerf-js/start 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
package/README.md CHANGED
@@ -1,3 +1,1469 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/Ravonus/kerf">
3
+ <img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">@kerf-js/start</h1>
8
+
9
+ <p align="center">
10
+ <strong>Kerf's full-stack layer: file routes, typed server functions, streaming SSR, a database, auth and live data.</strong><br>
11
+ Pages ship only the islands that need the client, and one build runs on Node, Bun or Deno.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kerf-js/start"><img src="https://img.shields.io/npm/v/@kerf-js/start?color=145c3c&label=npm" alt="npm version"></a>
16
+ <a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
17
+ <a href="https://github.com/Ravonus/kerf/actions"><img src="https://img.shields.io/github/actions/workflow/status/Ravonus/kerf/quality.yml?branch=main&label=checks" alt="checks"></a>
18
+ <img src="https://img.shields.io/node/v/@kerf-js/start?color=145c3c" alt="node version">
19
+ </p>
20
+
21
+ <p align="center">
22
+ <a href="#quick-start">Quick start</a> ·
23
+ <a href="https://github.com/Ravonus/kerf/tree/main/docs">Docs</a> ·
24
+ <a href="https://github.com/Ravonus/kerf/tree/main/examples">Examples</a> ·
25
+ <a href="https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md">Changelog</a> ·
26
+ <a href="https://github.com/Ravonus/kerf">GitHub</a>
27
+ </p>
28
+
29
+ > [!IMPORTANT]
30
+ > **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
31
+ > [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
32
+
33
+ `@kerf-js/start` turns a folder of Kerf components into a server-rendered app. Files in `src/routes` become pages,
34
+ exports in `src/server` become typed functions the client calls over HTTP, and the server streams each page as its
35
+ data arrives. A database, sign-in and realtime updates plug into the same `ctx` every server function gets. It runs on
36
+ Node, Bun or Deno and needs no Rust. An app made with `npm create kerf` already has it, wired up.
37
+
38
+ ## Highlights
39
+
40
+ - **Routes from files.** `src/routes/shop/[id].tsx` is `/shop/:id`, with `_layout.tsx` for layouts, `404.tsx` and
41
+ `_error.tsx` for failures, and typed `params` generated from the file names.
42
+ - **Server functions with a contract.** `query` and `mutation` validate input with any Standard Schema (Zod, Valibot…),
43
+ run with `ctx`, return typed results, and name the cache tags they read and invalidate.
44
+ - **Streaming SSR.** The head and shell go first, then each `<Boundary>` as its data resolves. A `load` field left as a
45
+ promise streams into the page instead of holding up the first byte.
46
+ - **Islands by default.** The compiler works out which components need the browser. The rest stays server HTML with no
47
+ JavaScript, and an island loads when it is seen or used, with events before then replayed.
48
+ - **Forms that work without JavaScript.** `<Form of={mutation}>` posts to the mutation, shows schema errors by field,
49
+ and restores what was typed when a no-JS submit comes back with errors.
50
+ - **A database and auth on `ctx`.** Drizzle over SQLite (`node:sqlite` or `bun:sqlite`, no native binary), Postgres or
51
+ MySQL; migrations apply on the next request. Better Auth by default, or any provider with two functions.
52
+ - **Live data without polling code.** `query.live()` refetches whenever a mutation on any tab invalidates one of its
53
+ tags, and `dbChanges` brings in writes from cron jobs, `psql` or other services.
54
+ - **Deploy targets checked before you deploy.** `kerf deploy hosts` says which of Netlify, Vercel, Cloudflare, Fly and
55
+ Render can run what the app uses, then `kerf deploy init` writes their files and a GitHub workflow.
56
+
57
+ ## Contents
58
+
59
+ - [Install](#install)
60
+ - [Quick start](#quick-start)
61
+ - [Project layout](#project-layout)
62
+ - [File routes](#file-routes)
63
+ - [Data loading](#data-loading)
64
+ - [Server functions](#server-functions)
65
+ - [Forms](#forms)
66
+ - [Streaming SSR and islands](#streaming-ssr-and-islands)
67
+ - [Navigation, view transitions and speculation rules](#navigation-view-transitions-and-speculation-rules)
68
+ - [Head, SEO and share cards](#head-seo-and-share-cards)
69
+ - [Database](#database)
70
+ - [Auth](#auth)
71
+ - [Realtime](#realtime)
72
+ - [Configuration](#configuration)
73
+ - [Runtimes, deploy targets and adapters](#runtimes-deploy-targets-and-adapters)
74
+ - [API reference](#api-reference)
75
+ - [Troubleshooting](#troubleshooting)
76
+ - [Related packages](#related-packages)
77
+ - [Contributing](#contributing)
78
+ - [License](#license)
79
+
80
+ ## Install
81
+
82
+ Start a new app. The wizard asks for a UI kit, a database, a data layer and auth, and installs everything:
83
+
84
+ ```bash
85
+ npm create kerf my-app
86
+ # or
87
+ pnpm create kerf my-app
88
+ # or
89
+ bun create kerf my-app
90
+ # or (Deno)
91
+ deno run -A npm:create-kerf my-app
92
+ ```
93
+
94
+ Each one scaffolds for its own runtime and package manager. To add Start to an existing Kerf project:
95
+
96
+ ```bash
97
+ npm install @kerf-js/start @kerf-js/core
98
+ # or
99
+ pnpm add @kerf-js/start @kerf-js/core
100
+ # or
101
+ bun add @kerf-js/start @kerf-js/core
102
+ ```
103
+
104
+ Start needs Node 24 or later (the `engines` field), Bun or Deno. Drizzle, Better Auth, Zod and the database drivers are
105
+ optional peer dependencies: install the ones your app uses, or let `kerf add db` and `kerf add auth` do it.
106
+
107
+ ## Quick start
108
+
109
+ A server function in `src/server/` runs on the server. The client gets a stub that calls it:
110
+
111
+ ```ts
112
+ // src/server/greeting.ts
113
+ import { query } from '@kerf-js/start'
114
+
115
+ export const greeting = query({
116
+ run: () => {
117
+ const time = new Date().toISOString()
118
+ return `Hello at ${time}`
119
+ },
120
+ })
121
+ ```
122
+
123
+ A route in `src/routes/` reads it. Calling the query in a component gives a `Resource`, a box that fills when the data
124
+ arrives:
125
+
126
+ ```tsx
127
+ // src/routes/hello.tsx
128
+ import type { Meta } from '@kerf-js/start'
129
+ import { greeting } from '#/server/greeting'
130
+
131
+ export const meta: Meta = {
132
+ title: 'Hello',
133
+ description:
134
+ 'A greeting from the server, with the time it was made.',
135
+ }
136
+
137
+ export default function Hello() {
138
+ const text = greeting()
139
+ return <p>{text.value ?? 'Loading…'}</p>
140
+ }
141
+ ```
142
+
143
+ ```bash
144
+ npx kerf dev # serves it at http://localhost:5173/hello
145
+ npx kerf build # writes .output/ and .kerf/contract.json
146
+ npx kerf start # runs .output/ on the configured runtime
147
+ ```
148
+
149
+ `#/server/greeting` is `src/server/greeting`. That alias is `paths` in `tsconfig.json`: change it or add your own there,
150
+ and Vite and `kerf check` follow.
151
+
152
+ ## Project layout
153
+
154
+ ```text
155
+ src/routes/** file routes: _layout.tsx, index.tsx,
156
+ [id].tsx, [...rest].tsx, 404.tsx,
157
+ _error.tsx, x.og.tsx
158
+ src/server/** queries, mutations, streams and channels
159
+ (the client gets stubs); also any *.server.ts
160
+ src/db/schema.ts Drizzle tables; safe to import anywhere
161
+ src/db/index.server.ts the database client
162
+ src/auth.server.ts the auth provider, mounted at /api/auth/*
163
+ src/context.server.ts what `ctx` holds
164
+ src/realtime.server.ts bus, origins and change feed for realtime
165
+ kerf.config.ts site metadata, runtime, hydration, deploy
166
+ drizzle/ generated migrations (never edit by hand)
167
+ ```
168
+
169
+ `load` and `meta` never ship to the client, and neither does anything under `src/server` beyond a stub per function.
170
+ Importing `@kerf-js/start/db*` or `@kerf-js/start/auth` from code the client reaches is an error (Q012).
171
+
172
+ ## File routes
173
+
174
+ The router reads `src/routes` into a manifest that the server, the client, the Vite plugin and `kerf routes` share.
175
+
176
+ | File | URL | Notes |
177
+ | ---------------------------- | -------------------- | ------------------------------------------------------------------ |
178
+ | `index.tsx` | `/` | |
179
+ | `about.tsx` | `/about` | |
180
+ | `users/[id].tsx` | `/users/:id` | `params.id` |
181
+ | `users/index.tsx` | `/users` | |
182
+ | `docs/[...rest].tsx` | `/docs/*` | `params.rest` is the rest of the path; must be the last segment |
183
+ | `_layout.tsx` | wraps its folder | the root one wraps the whole app |
184
+ | `404.tsx` | any unmatched path | root only; rendered inside the root layout with status 404 |
185
+ | `_error.tsx` | any thrown error | root only; rendered inside the root layout with status 500 |
186
+ | `users/[id].og.tsx` | that route's card | `_default.og.tsx` replaces the built-in card for every route |
187
+ | `_anything`, `*.test.tsx` | ignored | so are folders that start with `_` |
188
+
189
+ Static segments outrank params, and params outrank a splat, so `users/new.tsx` wins over `users/[id].tsx`. A segment
190
+ that mixes text and a param (`user-[id].tsx`) is refused: use a whole segment.
191
+
192
+ A route module may export:
193
+
194
+ | Export | What it is |
195
+ | ----------- | -------------------------------------------------------------------------------------------------- |
196
+ | `default` | The component. Gets `params`, `data` and, in a layout, `children`. |
197
+ | `load` | Async data for the page, run on the server before render. See [Data loading](#data-loading). |
198
+ | `meta` | Title, description and tags, as an object or a function of `data` and `params`. |
199
+ | `prerender` | The params `kerf build` writes as static pages with their cards; `true` on a route without params. |
200
+ | `skeleton` | A function of plain markup shown while the route's data loads, or `false` to keep the old page up. |
201
+
202
+ ### A param route
203
+
204
+ ```tsx
205
+ // src/routes/users/[id].tsx
206
+ import {
207
+ notFound,
208
+ type LoadArgs,
209
+ type Meta,
210
+ type RouteProps,
211
+ } from '@kerf-js/start'
212
+ import { getUser } from '#/server/users'
213
+
214
+ export const load = async ({ params }: LoadArgs<'/users/[id]'>) => {
215
+ const user = await getUser.fetch({ id: params.id })
216
+ return user ?? notFound()
217
+ }
218
+
219
+ export const meta: Meta<typeof load> = ({ data }) => ({
220
+ title: data.name,
221
+ description: data.bio,
222
+ })
223
+
224
+ export default function User(
225
+ props: RouteProps<typeof load, '/users/[id]'>,
226
+ ) {
227
+ const { data } = props
228
+ return <h1>{data.name}</h1>
229
+ }
230
+ ```
231
+
232
+ `LoadArgs<'/users/[id]'>` types `params` as `{ id: string }`, and `RouteProps<typeof load, …>` types `data` from what
233
+ `load` returns, without `notFound()`. Route paths come from `.kerf/routes.d.ts`, which Start's Vite plugin writes during `kerf dev` and `kerf build`.
234
+
235
+ `props.data` and `const { data } = props` stay live across navigations: compute from them in JSX or `derived`, not
236
+ once in the component body (W001).
237
+
238
+ ### Layouts
239
+
240
+ A `_layout.tsx` wraps every route in its folder and below. It renders `props.children` where the page goes:
241
+
242
+ ```tsx
243
+ // src/routes/_layout.tsx
244
+ import { Link, type RouteProps } from '@kerf-js/start'
245
+
246
+ export const meta = {
247
+ extra: [{ name: 'theme-color', content: '#0b0b0f' }],
248
+ }
249
+
250
+ export default function Root(props: RouteProps) {
251
+ return (
252
+ <div class="root">
253
+ <nav>
254
+ <Link href="/">Home</Link>
255
+ <Link
256
+ href="/users"
257
+ match="section"
258
+ >
259
+ Users
260
+ </Link>
261
+ </nav>
262
+ {props.children}
263
+ </div>
264
+ )
265
+ }
266
+ ```
267
+
268
+ - A layout's `load` runs before its children's, so it is where a guard goes:
269
+ `export const load = ({ ctx }: LoadArgs) => ctx.user ?? redirect('/login')`.
270
+ - A layout's `params` are its page's, a `[...rest]` included, so a layout can mark the page it shows.
271
+ - Chrome shared by several sections (a sidebar, section tabs) goes in the one layout above them, following the URL with
272
+ `currentPath()`. A `_layout.tsx` per section is replaced, chrome and all, whenever you move between sections, so the
273
+ sidebar flashes and is rebuilt. Keep `{props.children}` in the same parent on every page.
274
+
275
+ ### 404 and error pages
276
+
277
+ Until you add them, an app gets built-in pages. Your own get the path, or the status and message, as `data`:
278
+
279
+ ```tsx
280
+ // src/routes/404.tsx
281
+ import type { RouteProps } from '@kerf-js/start'
282
+
283
+ export const meta = {
284
+ title: 'Page not found',
285
+ description: 'There is nothing here.',
286
+ }
287
+
288
+ export default function NotFound(props: RouteProps) {
289
+ return (
290
+ <h1>Nothing lives at {(props.data as { path: string }).path}</h1>
291
+ )
292
+ }
293
+ ```
294
+
295
+ ```tsx
296
+ // src/routes/_error.tsx
297
+ export const meta = { title: 'Something broke' }
298
+
299
+ export default function Failed(props: {
300
+ data: { status: number; message: string }
301
+ }) {
302
+ return (
303
+ <h1>
304
+ Error {props.data.status}: {props.data.message}
305
+ </h1>
306
+ )
307
+ }
308
+ ```
309
+
310
+ `notFound()` returned or thrown from any `load` renders `404.tsx` with status 404, and `meta` isn't called. Both files
311
+ are read only at the routes root; one in a subfolder is reported and ignored.
312
+
313
+ ### Skeletons
314
+
315
+ Navigation is instant: the URL and `aria-current` change on click, kept layouts stay, and the level that changes shows a
316
+ skeleton made from its own markup until its data arrives. Don't build a loading state for a route change yourself. When
317
+ the generated one doesn't fit, export a function of plain markup:
318
+
319
+ ```tsx
320
+ function HomeSkeleton() {
321
+ return (
322
+ <section data-site="hero">
323
+ <h1>Your headline</h1>
324
+ <p data-skeleton></p>
325
+ </section>
326
+ )
327
+ }
328
+ export const skeleton = HomeSkeleton
329
+ ```
330
+
331
+ It runs before the page's code loads, so it may use only `div span section article main header footer p h1`–`h6
332
+ ul ol li`, string `class` and `data-*` attributes, and text. Anything else warns and leaves no skeleton.
333
+
334
+ ## Data loading
335
+
336
+ `load` runs on the server for the first request and for each client navigation (the client fetches the route's data as
337
+ JSON). It gets:
338
+
339
+ | Argument | What it is |
340
+ | --------- | -------------------------------------------------------------------------- |
341
+ | `params` | The route's params, typed from the path |
342
+ | `request` | The incoming `Request` (headers, cookies, URL) |
343
+ | `signal` | Aborts with the request |
344
+ | `ctx` | What server functions get: `ctx.db`, `ctx.user`, whatever your context adds |
345
+
346
+ Call queries with `await q.fetch(input)` here. It shares the request cache with the page's `q()`, so a query that `load`
347
+ and a component both read runs once.
348
+
349
+ ### Deferred fields stream
350
+
351
+ Return a promise as a top-level field and it isn't awaited before the first byte. It streams into the `<Boundary>` that
352
+ reads it:
353
+
354
+ ```tsx
355
+ // src/routes/product/[id].tsx
356
+ import { Boundary, resource } from '@kerf-js/core'
357
+ import type { LoadArgs, RouteProps } from '@kerf-js/start'
358
+ import { getProduct, getReviews } from '#/server/products'
359
+
360
+ export const load = async ({
361
+ params,
362
+ }: LoadArgs<'/product/[id]'>) => ({
363
+ // Awaited: in the first byte
364
+ product: await getProduct.fetch({ id: params.id }),
365
+ // A promise: streams later
366
+ reviews: getReviews.fetch({ id: params.id }),
367
+ })
368
+
369
+ export const meta = ({
370
+ data,
371
+ }: {
372
+ data: { product: { name: string } }
373
+ }) => ({
374
+ title: data.product.name,
375
+ })
376
+
377
+ function Reviews(props: { list: Promise<string[]> }) {
378
+ const r = resource(() => props.list)
379
+ return (
380
+ <ul>
381
+ {(r.value ?? []).map((t) => (
382
+ <li>{t}</li>
383
+ ))}
384
+ </ul>
385
+ )
386
+ }
387
+
388
+ export default function Product(
389
+ props: RouteProps<typeof load, '/product/[id]'>,
390
+ ) {
391
+ return (
392
+ <main>
393
+ <h1>{props.data.product.name}</h1>
394
+ <Boundary pending={<p>Loading reviews</p>}>
395
+ <Reviews list={props.data.reviews} />
396
+ </Boundary>
397
+ </main>
398
+ )
399
+ }
400
+ ```
401
+
402
+ `meta` and share cards only see settled fields. Reading a deferred one there is H007, an error, because it is still
403
+ streaming. On a client navigation the deferred fields arrive resolved in the route's JSON.
404
+
405
+ ### Redirects and errors in `load`
406
+
407
+ - `redirect('/x')` answers 307 (or pass `301 | 302 | 303 | 308`).
408
+ - `notFound()` renders the 404 route.
409
+ - Anything else thrown renders `_error.tsx` with status 500.
410
+
411
+ ## Server functions
412
+
413
+ Any module under `src/server/` (or named `*.server.ts`) can export queries and mutations. The `kerf:start` Vite plugin
414
+ gives each an id and replaces it in the client build with a stub that calls `/_kerf/fn/<id>`. Only `optimistic` ships to
415
+ the client.
416
+
417
+ ```ts
418
+ // src/server/todos.ts
419
+ import { mutation, query } from '@kerf-js/start'
420
+ import { schemasOf } from '@kerf-js/start/db'
421
+ import { and, eq } from 'drizzle-orm'
422
+ import { z } from 'zod'
423
+ import * as schema from '#/db/schema'
424
+
425
+ const { todos } = schema
426
+ const schemas = schemasOf(schema, {
427
+ todos: { title: (s: z.ZodString) => s.trim().min(1) },
428
+ })
429
+
430
+ export const listTodos = query({
431
+ tags: ['todos'], // what invalidates it
432
+ auth: 'user', // anyone else gets A002; ctx.user is non-null
433
+ run: ({ ctx }) =>
434
+ ctx.db.select().from(todos).where(eq(todos.userId, ctx.user.id)),
435
+ })
436
+
437
+ export const addTodo = mutation({
438
+ input: schemas.todos.insert.pick({ title: true }),
439
+ auth: 'user',
440
+ invalidates: ['todos'], // tagged queries come back in the response
441
+ optimistic: ({ input }, cache) =>
442
+ cache.update(
443
+ listTodos,
444
+ undefined,
445
+ (list) =>
446
+ void list.push({
447
+ id: `tmp:${input.title}`,
448
+ title: input.title,
449
+ done: false,
450
+ userId: '',
451
+ createdAt: 0,
452
+ }),
453
+ ),
454
+ run: async ({ input, ctx }) => {
455
+ const [row] = await ctx.db
456
+ .insert(todos)
457
+ .values({
458
+ id: crypto.randomUUID(),
459
+ userId: ctx.user.id,
460
+ createdAt: Date.now(),
461
+ ...input,
462
+ })
463
+ .returning()
464
+ return row
465
+ },
466
+ })
467
+
468
+ export const removeTodo = mutation({
469
+ input: z.object({ id: z.string() }),
470
+ auth: 'user',
471
+ invalidates: ({ id }) => ['todos', `todo:${id}`],
472
+ run: async ({ input, ctx }) => {
473
+ // auth: 'user' says who is calling, not what they may touch:
474
+ // check ownership in the where.
475
+ await ctx.db
476
+ .delete(todos)
477
+ .where(
478
+ and(eq(todos.id, input.id), eq(todos.userId, ctx.user.id)),
479
+ )
480
+ },
481
+ })
482
+ ```
483
+
484
+ ### Calling them
485
+
486
+ | Where | How | You get |
487
+ | --------------------------------------------- | ------------------------------------------ | ------------------------------------------ |
488
+ | A component or `defineState` setup | `listTodos()` | a `Resource`: `.value`, `.pending`, `.error` |
489
+ | With tracked input | `q(() => (id.value ? { id: id.value } : skip))` | refetches when `id` changes; `skip` waits |
490
+ | `load`, handlers, other server functions, tests | `await listTodos.fetch(input)` | a promise (Q001 if you call `q()` there) |
491
+ | An event handler | `await addTodo({ title })` | the result, or a rejected `FnError` |
492
+ | Mutation state | `addTodo.pending.value`, `addTodo.error.value` | every caller's state |
493
+
494
+ A query created inside a `<Boundary pending={…}>` streams from the server; created outside one, the first byte waits for
495
+ it. Read results in JSX as `(q().value ?? []).map(…)`; never copy query results into `state`.
496
+
497
+ ### Options
498
+
499
+ | Option | On | What it does |
500
+ | ------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |
501
+ | `input` | both | A Standard Schema. Validated on the server before `run`; issues come back on `FnError.issues`. |
502
+ | `output` | both | Checked in dev and tests (C002), and written to `.kerf/contract.json`. |
503
+ | `auth` | both | `'user'` refuses a call with no session (A002) and types `ctx.user` as non-null. |
504
+ | `tags` | query | Strings, or `(input, ctx) => string[]`. Every cache (client, request, shared) goes by these. |
505
+ | `invalidates` | mutation | Tags whose queries the response refreshes in one round trip, or `(input, result) => string[]`. |
506
+ | `optimistic` | mutation | `({ input }, cache) => void`. Runs on the client; `cache.update(query, input, draft => …)` edits a cached value until the server answers. |
507
+ | `limit` | both | `{ max, window, by? }`: at most `max` calls per `window` seconds per signed-in user (or per address, `by: 'ip'`); the next is 429 (Q019) with `Retry-After`. Counted in the cache store, so `redisStore()` shares it. |
508
+ | `cache` | query | `{ life: 'seconds' \| 'minutes' \| 'hours' \| 'days' \| 'max' \| number }` shares one value across requests. It can't read `ctx.user` (Q006) unless you add `scope: 'user'`. |
509
+ | `live` | query | `{ required: true }` fails the build on a target with no real change feed; `verify` proves it. See [Realtime](#realtime). |
510
+ | `errors` | both | Named failures, raised with `raise(code, data)`; the client sees `FnError.code` and `.data`. |
511
+ | `shape` | query | An example result that sizes a pending view. |
512
+
513
+ A table a function touches must be named in its `tags` or `invalidates` (Q011, checked at run time in `kerf dev`): a
514
+ tag named after the table, or `table:…`.
515
+
516
+ ### Failing on purpose
517
+
518
+ ```ts
519
+ import { FnError, invalid, raise, redirect } from '@kerf-js/start'
520
+
521
+ // A user-facing message and a status
522
+ throw new FnError({ message: 'Not yours' }, 403)
523
+ // A field error, shown next to the field by <Form>
524
+ invalid({ email: 'That address is taken' })
525
+ // A declared error: FnError.code and .data on the client
526
+ raise('out_of_stock', { sku })
527
+ redirect('/todos') // in run, the client follows it
528
+ ```
529
+
530
+ On the client, a failed call rejects with an `FnError` carrying `.message`, `.code`, `.status` and `.issues`.
531
+
532
+ ### Invalidating by hand
533
+
534
+ `invalidate('todos')` drops those tags: on the server for this response and the shared cache, on the client by
535
+ refetching what reads them. Tags can name one row: `tags: ({ id }) => ['todos', `todo:${id}`]`.
536
+
537
+ ### Where the shared cache lives
538
+
539
+ `cache: { life }` values live in one process's memory by default. It keeps up to 10,000 values (the least recently
540
+ used go first) and drops an expired one when it's read. When several requests miss the same value at once, the first
541
+ runs the query and the rest wait for its answer instead of each running it.
542
+
543
+ With more than one server instance, put the cache in Redis so they all read the same values and an invalidation on one
544
+ reaches the others:
545
+
546
+ ```ts
547
+ // src/cache.server.ts
548
+ import { redisStore } from '@kerf-js/realtime-redis'
549
+
550
+ // REDIS_URL, or redisStore({ url, prefix })
551
+ export default redisStore()
552
+ ```
553
+
554
+ Any object with `get`, `set`, `versions` and `bump` works (the `Store` type from `@kerf-js/start/cache`), and
555
+ `memoryStore({ values, tags })` changes the memory store's limits.
556
+
557
+ ## Forms
558
+
559
+ `<Form of={mutation}>` renders a real `<form>` that posts to the mutation. Before JavaScript loads, it is a plain POST
560
+ and the page comes back with errors and typed values restored. After, it submits with `fetch`, keeps focus on the first
561
+ invalid field, and never reloads.
562
+
563
+ ```tsx
564
+ import { Form, type FormApi } from '@kerf-js/start'
565
+ import { joinWaitlist } from '#/server/waitlist'
566
+
567
+ export function WaitlistForm() {
568
+ return (
569
+ <Form
570
+ of={joinWaitlist}
571
+ class="waitlist"
572
+ >
573
+ {(form: FormApi) => (
574
+ <>
575
+ {form.message.value && (
576
+ <p role="alert">That didn't go through.</p>
577
+ )}
578
+ <label>
579
+ Email
580
+ <input
581
+ type="email"
582
+ required
583
+ {...form.field('email', 'email')}
584
+ />
585
+ </label>
586
+ <form.Error name="email" />
587
+ <button
588
+ type="submit"
589
+ disabled={form.pending.value}
590
+ >
591
+ Join
592
+ </button>
593
+ </>
594
+ )}
595
+ </Form>
596
+ )
597
+ }
598
+ ```
599
+
600
+ | Prop | Default | What it does |
601
+ | ----------- | ------- | -------------------------------------------------------------------- |
602
+ | `of` | | The mutation (F001 if it isn't one) |
603
+ | `id` | | Tells two forms for one mutation apart on the no-JS path |
604
+ | `reset` | `true` | Empty the fields after a success |
605
+ | `onSuccess` | | `(result) => void` |
606
+ | `onError` | | `(error) => void` |
607
+
608
+ The `FormApi` gives `pending`, `errors`, `message`, `result`, `error(name)`, `value(name)`, `field(name, kind?)` and an
609
+ `Error` component that renders a live region. `field(name)` restores the raw submitted value; pass `'text'` or
610
+ `'email'` for a string, or `'multiple'` for an array. Field names with dots nest (`address.city`), and `x[]` or repeated
611
+ names become arrays.
612
+
613
+ ## Streaming SSR and islands
614
+
615
+ ### What a response looks like
616
+
617
+ The server matches the path, runs every `load` in the chain, merges the metadata, then streams:
618
+
619
+ 1. The `<head>` with every tag and the critical CSS, and the page shell.
620
+ 2. Each `<Boundary>`'s content as its resources resolve, one chunk each.
621
+ 3. The page data the client needs to take over.
622
+
623
+ ```tsx
624
+ import { Boundary } from '@kerf-js/core'
625
+
626
+ ;<Boundary
627
+ pending={<p>Loading…</p>}
628
+ error={(e, retry) => <button onClick={retry}>Retry</button>}
629
+ >
630
+ <Orders />
631
+ </Boundary>
632
+ ```
633
+
634
+ A `<Boundary>` covers every resource created while its children are built. Its fallback shows after 150 ms and stays
635
+ at least 400 ms, and a refetch keeps the current content. `kerf docs async` has the details.
636
+
637
+ ### Islands
638
+
639
+ Most of a page has nothing to do in the browser. Kerf's compiler follows each route's component graph and marks a
640
+ component as client only when it has a reason: an event handler, a `ref` or spread on an element, a read of reactive
641
+ state or a query, an `import()` outside a handler, or a top-level side effect. Each call site of such a component from
642
+ static code is an island. Everything else stays server HTML and ships no JavaScript.
643
+
644
+ Each island then loads when it is needed:
645
+
646
+ | Timing | When it loads | What earns it |
647
+ | ------------- | -------------------------------- | --------------------------------------------------------------------------------- |
648
+ | `interaction` | on the first event inside it | only handlers: every change starts with an event, and events replay |
649
+ | `visible` | when it scrolls into view | work that starts by itself but stays inside the island |
650
+ | `load` | with the page | anything else: `autofocus`, a module that runs as it loads, a box at module level |
651
+
652
+ A small inline script captures clicks, input and submits on an island whose code hasn't arrived, holds the default of a
653
+ click or submit, and replays them in order once the code is there. If the code never comes, the defaults run late. When
654
+ the visitor asks for less data (`prefers-reduced-data` or Save-Data), pointer hover doesn't start a load early.
655
+
656
+ When the compiler can't prove what you know, say it with a comment above the component:
657
+
658
+ ```tsx
659
+ /* @kerf visible */
660
+ export function Chart(props: { points: number[] }) {
661
+ // measures and draws once it's on screen
662
+ }
663
+ ```
664
+
665
+ | Comment | Means |
666
+ | -------------------------- | -------------------------------------------------------------- |
667
+ | `/* @kerf client */` | always ship this component and load it with the page |
668
+ | `/* @kerf static */` | this component needs no client code |
669
+ | `/* @kerf visible */` | its work only matters once it's on screen |
670
+ | `/* @kerf interaction */` | its work only matters to someone using it |
671
+
672
+ `.kerf/hydration.json` says why each island loads when it does, and H010 points out islands that load with the page for
673
+ a reason their code could avoid. An island's props cross from server to client as JSON: a function, a `Date` or a class
674
+ instance there is H009. A prop that is a function over local names can't cross either, so the component around it
675
+ hydrates whole (H017).
676
+
677
+ Set `hydration` in `kerf.config.ts` to change the policy: `'lazy'` (the default), `'partial'` (every island loads with
678
+ the page) or `'full'` (every route hydrates whole).
679
+
680
+ ### CSS on a page
681
+
682
+ A built page carries the CSS its first paint needs in a `<style>`, found by matching the page's HTML against a table from
683
+ the build, and links the rest at the end of its shell. The links are at most two hashed files: one with what every route
684
+ shares, one with the rest of that route. Hover and focus rules aren't in the first paint, so they work once the late
685
+ sheet lands. Mark a region that must not show before then with `data-kerf="styled"`: it keeps its room, stays hidden,
686
+ and shows anyway after 3 s.
687
+
688
+ `site.criticalCss: false` goes back to one sheet per chunk, inlined up to 48 KB. `site.inlineCss: false` keeps plain
689
+ links, as a strict CSP needs. `kerf build` keeps old combined sheets for 30 days in `.kerf/sheets`, so a page cached
690
+ before a deploy still finds its sheets: keep that folder between builds.
691
+
692
+ ## Navigation, view transitions and speculation rules
693
+
694
+ Links are `<Link href>`, or any same-origin `<a href>`: once the client has started, clicks on either navigate without a
695
+ page load. Code navigates with `navigate(href, { replace?, scroll? })`. `<Link match="section">` sets
696
+ `aria-current="page"` on any page under its `href`, for a site's top links.
697
+
698
+ **View transitions.** A client navigation swaps the page inside `document.startViewTransition` when the browser has it,
699
+ the tab is visible and has painted, and the visitor hasn't asked for reduced motion. On a device with four cores or
700
+ fewer it skips the fade, and it stops fading after one transition takes over 100 ms to start. Style it with the usual
701
+ `::view-transition-*` pseudo-elements.
702
+
703
+ **Prefetch on intent.** Hovering a link (after 80 ms, on a 4G connection) or focusing it fetches that route's data, not
704
+ its code, within a byte budget per connection type (64 KB per response on 4G, 16 KB otherwise, 8 KB on 2G). Nothing is
705
+ prefetched offline or with Save-Data. Put `data-preload="off"` on a link or a container to opt out.
706
+
707
+ **Speculation rules.** A page that runs no client code until it's needed follows its links with full page loads. So the
708
+ server adds a `<script type="speculationrules">` that asks the browser to prefetch the link the pointer rests on
709
+ (`eagerness: 'moderate'`). It is a prefetch, not a prerender, which would run the next page's code unseen. It leaves out
710
+ island links, `/_kerf/*`, downloads and anything under `data-preload="off"`, and the router removes the rules when it
711
+ takes over, so nothing is fetched twice.
712
+
713
+ ## Head, SEO and share cards
714
+
715
+ Every page gets a title, a description, a canonical URL, Open Graph and Twitter tags and a share card in the first
716
+ response, where a crawler can read them. Most of it is automatic; the words are yours.
717
+
718
+ ```tsx
719
+ import type { Meta } from '@kerf-js/start'
720
+
721
+ export const meta: Meta = {
722
+ title: 'Pricing',
723
+ description:
724
+ 'Three plans, billed monthly, and what each one includes.',
725
+ }
726
+ ```
727
+
728
+ `meta` is plain data, computed once per request after the loaders and before the first byte. It can't read a box (H006)
729
+ or a deferred field (H007). It also takes `title: { absolute: 'Home' }` to skip the site template, `og`, `twitter`,
730
+ `extra` for other tags, and `jsonLd` for structured data. Layers merge in this order, later winning: `site` in
731
+ `kerf.config.ts`, what the page rendered, each layout's `meta`, the route's `meta`.
732
+
733
+ With no `meta`, or a field left out:
734
+
735
+ - **Title**: the page's `h1` (or its first `h2`/`h3`), through `site.title`'s `%s` template.
736
+ - **Description**: the first prose paragraph after the `h1` inside `<main>`, cut at a sentence by 155 characters.
737
+ - **Share card**: a 1200×630 PNG of the title, description, app name and address. `routes/x.og.tsx` replaces one route's
738
+ card and `_default.og.tsx` every card; `og: { image: '/x.png' }` or `image: false` skips it. The card URL holds a
739
+ hash of what it draws, so it is cached forever and changes when the page does.
740
+ - **Canonical and `og:url`** from `site.url`, `KERF_SITE_URL`, or the host's own variable (Vercel, Netlify, Cloudflare
741
+ Pages, Render, Railway, Fly). With none, the server uses the request's origin and warns once in production (H001).
742
+
743
+ `kerf check` reports metadata for every route from what the routes really produce (H001–H016), and
744
+ `kerf routes --meta` prints a table of each page's tags and where each came from. Full details:
745
+ [`kerf docs meta`](https://github.com/Ravonus/kerf/blob/main/packages/cli/docs/meta.md).
746
+
747
+ ## Database
748
+
749
+ `ctx.db` is a Drizzle client, async on every driver. `@kerf-js/start` ships three, each a `createDb` that connects on
750
+ the first statement, so `kerf build` and a page with no queries need no database:
751
+
752
+ | Import | Driver | Options |
753
+ | ------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------- |
754
+ | `@kerf-js/start/db/sqlite` | `node:sqlite` on Node and Deno, `bun:sqlite` on Bun; no native binary | `schema`, `url` (default `file:.data/app.db`, or `:memory:`), `migrate` |
755
+ | `@kerf-js/start/db/postgres` | postgres.js | `schema`, `url`, `migrate`, `max` (pool, default 10), `prepare` (default `true`; off behind a pooler in transaction mode) |
756
+ | `@kerf-js/start/db/mysql` | mysql2 | `schema`, `url`, `migrate`, `max` (pool, default 10) |
757
+
758
+ `migrate` defaults to `true`: pending migrations apply before the first statement a request runs. Postgres and MySQL hold
759
+ a lock while they do, so instances starting together apply each file once.
760
+
761
+ ```ts
762
+ // src/db/index.server.ts
763
+ import { createDb } from '@kerf-js/start/db/postgres'
764
+ import { env } from '../env.server'
765
+ import * as schema from './schema'
766
+
767
+ export const db = createDb({ schema, url: env.DATABASE_URL })
768
+ ```
769
+
770
+ ```ts
771
+ // src/context.server.ts
772
+ import { db } from '#/db/index.server'
773
+
774
+ export default () => ({ db })
775
+
776
+ declare module '@kerf-js/start' {
777
+ interface Context {
778
+ db: typeof db
779
+ }
780
+ }
781
+ ```
782
+
783
+ ### Migrations
784
+
785
+ Change `src/db/schema.ts`, run `kerf db generate` (Q015 warns until you do), reload. The new migration in `drizzle/`
786
+ applies before the next statement. There is no `kerf db migrate`. Never edit `drizzle/` by hand.
787
+
788
+ ```bash
789
+ # Drizzle-kit generate, then records the schema hash
790
+ npx kerf db generate add_due_dates
791
+ # A migration with change triggers for realtime
792
+ npx kerf db live
793
+ # The change feed as its own process
794
+ npx kerf db listen
795
+ ```
796
+
797
+ A request that hits a missing table gets Q014, which names it. If the database is down, a request that uses it answers
798
+ 503 with Q016, pages with no queries still serve, and the next statement tries again once it is back, with no restart.
799
+
800
+ ### Validating input from tables
801
+
802
+ `schemasOf(schema, refine?)` from `@kerf-js/start/db` gives a Zod `select`, `insert` and `update` schema per table
803
+ (through drizzle-zod), so a table is its own validator:
804
+
805
+ ```ts
806
+ const schemas = schemasOf(schema, {
807
+ todos: { title: (s: z.ZodString) => s.trim().min(1) },
808
+ })
809
+ export const addTodo = mutation({
810
+ input: schemas.todos.insert.pick({ title: true }) /* … */,
811
+ })
812
+ ```
813
+
814
+ ### Other data layers
815
+
816
+ Prisma, or plain SQL with no ORM, come from [`@kerf-js/db`](https://www.npmjs.com/package/@kerf-js/db) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/db)</sup>:
817
+
818
+ ```bash
819
+ npx kerf add db postgres --layer native # ctx.db.sql`select …`
820
+ # Ctx.db is your Prisma client
821
+ npx kerf add db sqlite --layer prisma
822
+ ```
823
+
824
+ Paged, filtered and searchable lists over any of them (`listInput` and a list source) are covered in the `@kerf-js/db`
825
+ README. A Drizzle table's source is `drizzleSource({ db, table }, spec)` from `@kerf-js/start/list/drizzle`.
826
+
827
+ ## Auth
828
+
829
+ Auth is a provider in `src/auth.server.ts` with two jobs: `handler(request)` serves everything under `/api/auth`, and
830
+ `session(request)` says who a request is. `ctx.user`, `ctx.session` and `auth: 'user'` come from those.
831
+
832
+ ### Better Auth (the default)
833
+
834
+ ```ts
835
+ // src/auth.server.ts
836
+ import { createAuth } from '@kerf-js/start/auth/better-auth'
837
+ import { drizzleAuth } from '@kerf-js/start/auth/drizzle'
838
+ import { db } from '#/db/index.server'
839
+ import * as schema from './db/schema'
840
+ import { env } from './env.server'
841
+
842
+ export default createAuth({
843
+ db,
844
+ secret: env.BETTER_AUTH_SECRET,
845
+ options: { database: drizzleAuth(db, schema) },
846
+ })
847
+ ```
848
+
849
+ ```ts
850
+ // src/context.server.ts
851
+ import { session } from '@kerf-js/start/auth'
852
+ import auth from '#/auth.server'
853
+ import { db } from '#/db/index.server'
854
+
855
+ export default async ({ request }: { request: Request }) => ({
856
+ db,
857
+ ...(await session(auth, request)),
858
+ })
859
+
860
+ type Session = Awaited<ReturnType<typeof auth.session>>
861
+
862
+ declare module '@kerf-js/start' {
863
+ interface Context {
864
+ db: typeof db
865
+ user: Session['user']
866
+ session: Session['session']
867
+ }
868
+ }
869
+ ```
870
+
871
+ `createAuth` takes `db`, `secret` (32+ characters; A001 in production), `options` (any Better Auth option, which wins
872
+ over Kerf's defaults) and `api`. `options.database` is required (A005): `drizzleAuth(db, schema)`, `nativeAuth(db)` from
873
+ `@kerf-js/db/plugin-native/auth`, or Better Auth's Prisma adapter. `kerf add auth` sets all of this up.
874
+
875
+ Sign-in is a mutation. `forward` puts the provider's cookies on the response and turns its failure into an `FnError`:
876
+
877
+ ```ts
878
+ // src/server/session.ts
879
+ import { mutation, redirect } from '@kerf-js/start'
880
+ import { forward } from '@kerf-js/start/auth'
881
+ import { z } from 'zod'
882
+ import auth from '#/auth.server'
883
+
884
+ export const signIn = mutation({
885
+ auth: 'public',
886
+ input: z.object({ email: z.email(), password: z.string().min(8) }),
887
+ run: async ({ input, ctx }) => {
888
+ await forward(
889
+ ctx,
890
+ auth.api.signInEmail({
891
+ body: input,
892
+ headers: ctx.request.headers,
893
+ asResponse: true,
894
+ }),
895
+ )
896
+ // A new session needs a full load (A004 without one)
897
+ redirect('/todos')
898
+ },
899
+ })
900
+ ```
901
+
902
+ **Who may call a function.** `auth` takes four forms:
903
+
904
+ | `auth` | Who gets through | Everyone else |
905
+ | ------------------------------- | --------------------------------------------------- | ------------------------- |
906
+ | `'user'` | Anyone signed in | Q019 (429) | A function's `limit` ran out for this caller | Wait `Retry-After` seconds, or raise `limit` |
907
+ | J001 | A cron job threw | Fix the job; it runs again when next due |
908
+ | J002 | A cron schedule that doesn't parse | Five fields: `minute hour day month weekday` |
909
+ | J003 | A queued job threw and will run again after its backoff | Fix the job; it retries until `retries` runs out |
910
+ | J004 | A queued job is dead: out of retries, or no job by its name | Fix it and enqueue again; the queue keeps the dead job and its error |
911
+ | J006 | `enqueue` got input the job's schema rejects (400) | Enqueue what the schema accepts |
912
+ | E001 | `sendEmail` in production with no mailer | Set `RESEND_API_KEY` or `SMTP_URL`, or export a mailer |
913
+ | E002 | An email with no sender | Set `EMAIL_FROM`, or pass `from` |
914
+ | E003 | Resend refused the message | Check the key and that the sending domain is verified |
915
+ | E004 | SMTP failed, or nodemailer is missing | Check `SMTP_URL`; `pnpm add nodemailer` |
916
+ | A002 (401) |
917
+ | `{ role: 'admin' }` or an array | A signed-in user with one of the roles | A002 (401) or A006 (403) |
918
+ | `{ can: (ctx) => boolean }` | A signed-in user your check passes (it may be async) | A002 (401) or A006 (403) |
919
+ | `'public'` | Anyone | |
920
+
921
+ Roles are read from `ctx.user.role`, as Better Auth's `admin` plugin writes it (`'admin'`, or `'admin,user'`); an
922
+ array works too.
923
+
924
+ **In an app with auth, a mutation needs someone signed in unless it says otherwise.** When `ctx` has a `user` field
925
+ (it does once `session(auth, request)` is in `src/context.server.ts`), a mutation with no `auth` acts as `auth: 'user'`.
926
+ Sign-in, sign-up, sign-out and anything else a visitor may send say `auth: 'public'`. Queries stay open unless they say
927
+ otherwise, since a page's data is usually for anyone. An app without auth is unchanged.
928
+
929
+ **Behind a proxy.** Better Auth rate-limits sign-in by the client's address. Behind a load balancer or CDN, every
930
+ request comes from the proxy, so set `site.trustProxy` (`true` for one proxy, or how many) and the address comes from
931
+ `X-Forwarded-For` instead. With several instances, give it one store: `rateLimit: { customStorage: redisRateLimit() }` from
932
+ `@kerf-js/realtime-redis`. In production `createAuth` also needs its own URL (`BETTER_AUTH_URL` or `options.baseURL`,
933
+ A007): without it Better Auth trusts each request's `Host` header for the links in its emails. The JWT signing key
934
+ rotates every 30 days (`api: { jwks: { rotationInterval } }` changes it).
935
+
936
+ > [!WARNING]
937
+ > **`auth: 'user'` says who is calling, not what they may touch.** A `run` that takes a row's id must check that row
938
+ > belongs to `ctx.user`, usually with `and(eq(todos.id, input.id), eq(todos.userId, ctx.user.id))` in the `where`.
939
+
940
+ **Sessions are opaque tokens in the database, not JWTs.** The HTTP-only cookie holds a random token, so deleting the
941
+ row revokes the session. `createAuth` turns on Better Auth's cookie cache, which spares pages and queries their session
942
+ reads for **5 minutes**. A revoked session can still see pages for up to that long, but it can't write: mutations,
943
+ realtime connections and Better Auth's own routes always read the database. Shorten it with
944
+ `options: { session: { cookieCache: { maxAge: 60 } } }`, or turn it off with `{ cookieCache: { enabled: false } }`.
945
+
946
+ **API access.** `GET /api/auth/token` gives a signed-in user a JWT good for 15 minutes, and `GET /api/auth/jwks` is
947
+ public, so another service verifies it with no database. A function takes a bearer token only if you list it:
948
+
949
+ ```ts
950
+ createAuth({
951
+ db,
952
+ secret,
953
+ options,
954
+ api: {
955
+ functions: () => [orders, shipOrder],
956
+ jwt: {
957
+ audience: 'https://api.example.com',
958
+ expirationTime: '15m',
959
+ },
960
+ },
961
+ })
962
+ ```
963
+
964
+ ```text
965
+ GET /_kerf/fn/<id>?i=<json>
966
+ authorization: Bearer <token>
967
+
968
+ POST /_kerf/fn/<id>
969
+ authorization: Bearer <token>
970
+ content-type: application/json
971
+ x-kerf: 1
972
+ body: {"i": input}
973
+ ```
974
+
975
+ With no `BETTER_AUTH_URL` or fixed `baseURL`, no token is accepted, since nothing could check `iss` and `aud`.
976
+ `api: false` removes all of it.
977
+
978
+ ### Any other provider
979
+
980
+ ```ts
981
+ // src/auth.server.ts
982
+ import { defineAuth } from '@kerf-js/start/auth'
983
+
984
+ export default defineAuth<{ id: string }, { id: string }>({
985
+ async session(request) {
986
+ return { user: null, session: null } // who this request is
987
+ },
988
+ async handler(request) {
989
+ // Everything under /api/auth
990
+ return new Response('Not found', { status: 404 })
991
+ },
992
+ })
993
+ ```
994
+
995
+ A provider that caches sessions may answer a GET from the cache, and must ask its store for any other method. Set
996
+ `basePath` to mount `handler` somewhere other than `/api/auth`.
997
+
998
+ ## Realtime
999
+
1000
+ Don't poll, and don't open a socket yourself (R007, T013). A live query, a `stream` and a `channel` reconnect, resume
1001
+ and clean up for you.
1002
+
1003
+ ### Live queries
1004
+
1005
+ Live queries need no server code. Tags are the contract: any mutation that invalidates one of a query's tags, on any
1006
+ tab, refetches it for every reader. Unchanged rows keep their identity, so the page writes only what changed.
1007
+
1008
+ ```tsx
1009
+ const todos = listTodos.live()
1010
+ todos.value // the rows, as with listTodos()
1011
+ // 'connecting' | 'live' | 'degraded' | 'reconnecting' | 'offline'
1012
+ todos.live.value
1013
+ ```
1014
+
1015
+ A live query needs `tags` (W053), and its mutations need one of them in `invalidates` (R003 in dev).
1016
+
1017
+ ### Writes from outside the app
1018
+
1019
+ Give the database's writes to `realtime` and a cron job, `psql` or another service reaches the same queries:
1020
+
1021
+ ```ts
1022
+ // src/realtime.server.ts
1023
+ import { realtime } from '@kerf-js/start'
1024
+ import { dbChanges } from '@kerf-js/start/changes'
1025
+ import { db } from '#/db/index.server'
1026
+ import { notes } from '#/db/schema'
1027
+
1028
+ export default realtime({ changes: dbChanges(db, [notes]) })
1029
+ ```
1030
+
1031
+ Then `kerf db live` writes the trigger migration and it applies on the next request. A notification carries a table and
1032
+ primary keys, never a column: each client refetches through its own `query`, so `auth` and every filter still apply.
1033
+
1034
+ | Database | How it hears changes | Limits |
1035
+ | -------- | ------------------------------------------------------------ | ----------------------------------------------------------------------- |
1036
+ | Postgres | triggers and NOTIFY on one held connection | a transaction-mode pooler breaks LISTEN: pass `{ listenUrl }` for a direct connection |
1037
+ | SQLite | `PRAGMA data_version` every 100 ms, then the triggers' log | same host only |
1038
+ | MySQL | the triggers' log, read every 500 ms | a row in the log per row written |
1039
+ | MongoDB | a change stream (`mongoChanges` from `@kerf-js/db/mongo`) | needs a replica set |
1040
+
1041
+ `notes.liveMode.value` says what the server settled on (`'feed'`, `'external'`, `'poll'`, `'app'` or `'off'`), and
1042
+ `kerf doctor --preset vercel` says what a target can do before you deploy. `live: { required: true }` on a query fails
1043
+ `kerf check` and `kerf build` (R013) on a target that can't deliver it, and `liveHealth()` reports it for a health route.
1044
+
1045
+ ### Streams and topics
1046
+
1047
+ ```ts
1048
+ // src/server/prices.ts
1049
+ import { stream, topic } from '@kerf-js/start'
1050
+ import { z } from 'zod'
1051
+
1052
+ const Price = z.object({ symbol: z.string(), price: z.number() })
1053
+
1054
+ export const priceTopic = topic('prices', {
1055
+ key: z.string().max(12),
1056
+ message: Price,
1057
+ })
1058
+
1059
+ export const prices = stream({
1060
+ // Bound the input (R005)
1061
+ input: z.object({ symbols: z.array(z.string().max(12)).max(50) }),
1062
+ message: Price,
1063
+ auth: 'user', // re-checked every 5 minutes
1064
+ async *run({ input, signal, lastEventId }) {
1065
+ yield* priceTopic.subscribe(input.symbols, {
1066
+ signal,
1067
+ after: lastEventId,
1068
+ })
1069
+ },
1070
+ })
1071
+ // anywhere on the server: await priceTopic.publish('AAPL', { symbol:
1072
+ // 'AAPL', price: 1 })
1073
+ ```
1074
+
1075
+ ```tsx
1076
+ // The latest message: tick.value
1077
+ const tick = prices({ symbols: ['AAPL'] })
1078
+ const board = prices(() => ({ symbols: syms.value }), {
1079
+ fold: (acc, m) => ({ ...acc, [m.symbol]: m }),
1080
+ initial: {},
1081
+ keep: '30s',
1082
+ })
1083
+ ```
1084
+
1085
+ ### Channels and shared state
1086
+
1087
+ `channel` is a WebSocket with named, validated messages each way, for what the client sends often (chat, typing,
1088
+ cursors). `authorize` is required (R001) and runs on every join and every 5 minutes.
1089
+
1090
+ ```ts
1091
+ // src/server/chat.ts
1092
+ import { channel } from '@kerf-js/start'
1093
+ import { z } from 'zod'
1094
+ import { insertMessage, isMember, Message } from '#/server/messages'
1095
+
1096
+ export const room = channel({
1097
+ params: z.object({ roomId: z.string().max(64) }),
1098
+ authorize: ({ ctx, params }) => isMember(ctx.user, params.roomId),
1099
+ client: { say: z.object({ text: z.string().min(1).max(2000) }) },
1100
+ server: { said: Message },
1101
+ on: {
1102
+ say: async ({ msg, ctx, params, room }) => {
1103
+ const row = await insertMessage(ctx, params.roomId, msg.text)
1104
+ await room.publish('said', row)
1105
+ },
1106
+ },
1107
+ limits: { perSecond: 10 }, // default 20 a second per socket
1108
+ })
1109
+ ```
1110
+
1111
+ ```tsx
1112
+ const chat = room.connect(() => ({ roomId: props.roomId }))
1113
+ const said = chat.collect('said', { max: 200, key: (m) => m.id })
1114
+ await chat.send('say', { text }) // resolves on the server's ack
1115
+ // 'connecting' | 'open' | 'reconnecting' | 'closed' | 'unauthorized'
1116
+ chat.status.value
1117
+ ```
1118
+
1119
+ A channel is a wire, not a log: a reconnect replays the last 60 s or 256 messages per instance, so what must last goes
1120
+ in the database. `sharedState(name, { key, value, initial, authorize: { read, write } })` is one last-writer-wins value
1121
+ per key, held in server memory.
1122
+
1123
+ ### More than one instance
1124
+
1125
+ One instance needs nothing. Several need a bus, and `kerf build` refuses the in-memory bus on a multi-instance preset
1126
+ (R002):
1127
+
1128
+ ```ts
1129
+ // src/realtime.server.ts
1130
+ import { realtime } from '@kerf-js/start'
1131
+ import { postgresBus } from '@kerf-js/start/bus/postgres'
1132
+
1133
+ export default realtime({
1134
+ bus: postgresBus({ url: process.env.DATABASE_URL! }),
1135
+ // Exact; the app's own origin is always allowed
1136
+ origins: ['https://other.example'],
1137
+ // The platform's response limit: streams end 10 s earlier and
1138
+ // resume
1139
+ maxDuration: 300,
1140
+ })
1141
+ ```
1142
+
1143
+ On function hosts (Vercel, Netlify, Lambda, Azure Functions, Firebase, Cloudflare Workers, Deno Deploy) a process ends
1144
+ with its request, so `.live()` shows `degraded` for outside writes (R014). Deploy to a server preset, or run
1145
+ `kerf db listen` on any always-on host with a bus both can reach and `dbChanges(db, tables, { listener: 'external' })`
1146
+ in the app.
1147
+
1148
+ The full realtime reference, including `verify` round trips against staging and the test helpers in
1149
+ `@kerf-js/core/test`, is [`kerf docs start`](https://github.com/Ravonus/kerf/blob/main/packages/cli/docs/start.md).
1150
+
1151
+ ## Configuration
1152
+
1153
+ Start reads these keys from `kerf.config.ts` (or `.json` / `.yaml`). `kerf check` validates them and writes
1154
+ `.kerf/config.schema.json` for editor completion.
1155
+
1156
+ ```ts
1157
+ // kerf.config.ts
1158
+ import { defineConfig } from '@kerf-js/core/config'
1159
+
1160
+ export default defineConfig({
1161
+ site: {
1162
+ name: 'Acme',
1163
+ url: 'https://acme.dev',
1164
+ title: '%s · Acme',
1165
+ description: 'Tools for builders.',
1166
+ headers: { '/admin/**': { 'x-frame-options': 'DENY' } },
1167
+ },
1168
+ runtime: 'node',
1169
+ hydration: 'lazy',
1170
+ deploy: {
1171
+ target: 'fly',
1172
+ fly: {
1173
+ app: 'acme',
1174
+ region: 'iad',
1175
+ volume: { name: 'data', sizeGb: 1 },
1176
+ },
1177
+ },
1178
+ live: {
1179
+ targets: {
1180
+ staging: {
1181
+ url: 'https://staging.acme.dev',
1182
+ db: 'STAGING_DATABASE_URL',
1183
+ production: false,
1184
+ },
1185
+ },
1186
+ },
1187
+ })
1188
+ ```
1189
+
1190
+ | Key | Values | Default | What it does |
1191
+ | -------------------- | ---------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------- |
1192
+ | `site` | object | | Metadata defaults: `name`, `url`, `title` (with `%s`), `description`, `locale`, `image`, `twitter`, `card` |
1193
+ | `site.headers` | `{ [pattern]: headers }` | | Response headers by route pattern, static files included |
1194
+ | `site.security` | `false` \| `{ [header]: string \| false }` | see below | Headers every response gets unless it sets its own; name one to change it, `false` drops it |
1195
+ | `site.trustProxy` | `boolean` \| `number` | `false` | Proxies in front: the client's address comes from `X-Forwarded-For` (rate limits) |
1196
+ | `site.log` | `'text'` \| `'json'` | `'text'` | The server log's lines: readable, or JSON objects for a log collector |
1197
+ | `site.limits` | `{ body, upload }` (bytes) | 1 MB, 25 MB | Largest JSON and multipart (file) request body; past it, 413 (Q018) before the rest is read |
1198
+ | `site.inlineCss` | `boolean` | `true` | First-paint CSS in a `<style>`; `false` for plain links (strict CSP) |
1199
+ | `site.criticalCss` | `boolean` | `true` | One hashed sheet plus first-paint CSS; `false` splits by chunk and inlines up to 48 KB |
1200
+ | `site.criticalKeep` | `string[]` | | Classes a head script sets, kept in the first paint |
1201
+ | `site.head` | `string` | | Raw HTML before the stylesheets on every page |
1202
+ | `runtime` | `'node'` \| `'bun'` \| `'deno'` | the one running the CLI | What `kerf build` targets |
1203
+ | `hydration` | `'lazy'` \| `'partial'` \| `'full'` | `'lazy'` | When islands load, or hydrate every route whole |
1204
+ | `deploy` | `{ target, <host>, ci, branch, cdn }` | | The host `kerf build` and `kerf deploy` target |
1205
+ | `live.targets` | `{ [name]: { url, db, production } }` | | Where a live query's `verify` runs its round trip |
1206
+ | `rust` | `{ unions, services }` | | Server functions with a Rust body (`kerf docs rust`) |
1207
+
1208
+ Every response Start sends carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`,
1209
+ `X-Frame-Options: SAMEORIGIN` and `Cross-Origin-Opener-Policy: same-origin-allow-popups`, plus
1210
+ `Strict-Transport-Security: max-age=31536000` over https outside dev. None of them can break a page. A
1211
+ Content-Security-Policy is left to the app (it lists the app's own sources): set it in `site.security` or `site.headers`.
1212
+
1213
+ Pages are sent `private, no-cache`, so no shared cache or CDN keeps one user's page for another. A route that sets its
1214
+ own `cache-control` (`ctx.response.headers.set(...)` in `load`) replaces that default; server function answers stay
1215
+ `no-store`.
1216
+
1217
+ The full key list is [`kerf docs config`](https://github.com/Ravonus/kerf/blob/main/packages/cli/docs/config.md).
1218
+
1219
+ ## Running in production
1220
+
1221
+ **Health.** `GET /_kerf/health` answers 200 when every database answers `select 1` (within 2 s) and live data is
1222
+ delivered as `live: { required }` needs, and 503 otherwise, as JSON: `{ ok, db: [{ dialect, ok, ms }], live }`. It
1223
+ runs before migrations, so a failed one still reports. Point a load balancer or uptime check at it.
1224
+
1225
+ **Logs.** Problems the server finds go to stderr, one line each. `site.log: 'json'` makes them JSON objects (`time`,
1226
+ `level`, `code`, `message`, `route`, `requestId`) for a log collector. Every response carries `x-request-id`, and every
1227
+ line from that request names it, so a user's report leads to the line. Behind `site.trustProxy`, a proxy's own
1228
+ `x-request-id` is kept.
1229
+
1230
+ **Shutdown.** On SIGTERM (a deploy or scale-down) the server stops taking requests and finishes the ones it has, the
1231
+ schedule stops, queued jobs that are running finish, and realtime connections close as "going away", so open pages reconnect to an instance that's staying.
1232
+
1233
+ **Scheduled jobs.** `src/cron.server.ts` default-exports the jobs:
1234
+
1235
+ ```ts
1236
+ // src/cron.server.ts
1237
+ import { defineCron } from '@kerf-js/start/cron'
1238
+
1239
+ export default defineCron({
1240
+ // 03:00 UTC every day
1241
+ cleanup: {
1242
+ schedule: '0 3 * * *',
1243
+ run: ({ ctx }) => ctx.db.delete(sessions).where(expired()),
1244
+ },
1245
+ })
1246
+ ```
1247
+
1248
+ Schedules are five fields in UTC (`*`, `*/n`, `a-b` and lists), checked when the server starts (J002). A job runs with
1249
+ the app's `ctx` and no signed-in user; a failure is logged (J001) and the job runs again when it's next due. With
1250
+ several instances and `redisStore()` in `src/cache.server.ts`, each job runs on one of them per minute; with the memory
1251
+ store, every instance runs it. Jobs run on server presets (`node`, `bun`, `deno`), not on function hosts, which only
1252
+ wake for requests: there, call a mutation from the host's own scheduler.
1253
+
1254
+ **Email.** `sendEmail()` from `@kerf-js/start/email` sends through whichever is set: `RESEND_API_KEY` (Resend's API,
1255
+ no package needed) or `SMTP_URL` (`smtps://user:pass@smtp.example.com:465`, through `nodemailer`, which you add). The
1256
+ sender is `EMAIL_FROM` unless a message passes `from`. In dev with neither, each message is printed to the server log,
1257
+ links and all. Better Auth's password-reset and verification emails go through it too, unless you pass your own.
1258
+
1259
+ ```ts
1260
+ import { sendEmail } from '@kerf-js/start/email'
1261
+
1262
+ await sendEmail({
1263
+ to: user.email,
1264
+ subject: 'Your export is ready',
1265
+ text: url,
1266
+ })
1267
+ ```
1268
+
1269
+ To choose in code (another provider, a test double), default-export a mailer from `src/email.server.ts`:
1270
+ `resendMailer({ apiKey })`, `smtpMailer({ url })`, or any `{ name, send(message) }`.
1271
+
1272
+ **Queued jobs.** Work that shouldn't hold up a response (emails, webhooks, image processing) goes on a queue.
1273
+ `src/jobs.server.ts` default-exports the jobs, and server code enqueues them:
1274
+
1275
+ ```ts
1276
+ // src/jobs.server.ts
1277
+ import { defineJobs, job } from '@kerf-js/start/jobs'
1278
+ import { redisQueue } from '@kerf-js/realtime-redis'
1279
+ import { z } from 'zod'
1280
+
1281
+ export default defineJobs(
1282
+ {
1283
+ welcome: job({
1284
+ input: z.object({ userId: z.string() }),
1285
+ run: ({ ctx, input }) =>
1286
+ sendWelcome(ctx.db, input.userId),
1287
+ }),
1288
+ },
1289
+ { queue: redisQueue() }, // leave out for the in-memory queue
1290
+ )
1291
+
1292
+ // in a mutation (import jobs from './jobs.server')
1293
+ await jobs.welcome.enqueue(
1294
+ { userId },
1295
+ { key: `welcome:${userId}` },
1296
+ )
1297
+ ```
1298
+
1299
+ `enqueue` checks the input against the schema (J006) and returns the job's id; `delay` holds it back, and `key` keeps one
1300
+ job per key until it has run. A job runs with the app's `ctx` and no signed-in user. When it throws it's logged (J003)
1301
+ and tried again after 2, 4, 8… seconds (`backoff`), up to `retries` more times (5); then it's dead (J004) and kept with
1302
+ its error. Jobs run at least once: a job whose instance dies is claimed again when its lease (5 minutes) ends, so make
1303
+ them safe to repeat. The memory queue loses its jobs on restart and isn't shared; `redisQueue()` keeps them in Redis,
1304
+ and every instance works the same queue. Like cron, the queue is worked on server presets (`node`, `bun`, `deno`).
1305
+
1306
+ ## Runtimes, deploy targets and adapters
1307
+
1308
+ `kerf build` runs Vite with Start's plugin and Nitro, and writes `.output/` and `.kerf/contract.json`. The Nitro preset
1309
+ comes from, in order: `--preset`, `--runtime`, `deploy.target`, `runtime` in the config, then the runtime running the
1310
+ CLI.
1311
+
1312
+ | Runtime | Nitro preset | Run it with |
1313
+ | ------- | -------------- | ------------------------------ |
1314
+ | `node` | `node` | `kerf start` |
1315
+ | `bun` | `bun` | `kerf start --runtime bun` |
1316
+ | `deno` | `deno_server` | `kerf start --runtime deno` |
1317
+
1318
+ The CLI itself runs on whichever runtime starts it (`bun --bun`, or `deno run -A npm:@kerf-js/cli`). Server code that
1319
+ uses `node:` modules and web APIs works on all three; `Bun.*`, `Deno.*` or `better-sqlite3` break the others. Built
1320
+ assets ship with `.br` and `.gz` copies, and the server picks by `Accept-Encoding`.
1321
+
1322
+ ### Hosts
1323
+
1324
+ `kerf deploy` knows five hosts. It reads what the app uses and says which can run it, before a build:
1325
+
1326
+ | What the app uses | Netlify / Vercel | Cloudflare | Fly / Render |
1327
+ | ---------------------------------------------------- | ---------------- | --------------------- | ----------------------------- |
1328
+ | pages, queries, mutations, forms, `stream()` | yes | yes | yes |
1329
+ | `channel`, `sharedState` | no (E001) | yes, Durable Objects | yes |
1330
+ | `.live({ required })`, Rust `remote()` sidecars | no (E002) | no (E002) | yes |
1331
+ | a SQLite file, media uploads | no (E003) | no (E003) | with a volume or disk |
1332
+ | `changes` without an external listener | degraded (R014) | degraded | yes |
1333
+
1334
+ | Target | Preset | Files `kerf deploy init` writes | Secrets it reads |
1335
+ | ------------ | -------------------- | ------------------------------------------- | -------------------------------------------------- |
1336
+ | `netlify` | `netlify` | `netlify.toml` | `NETLIFY_AUTH_TOKEN`, `NETLIFY_SITE_ID` |
1337
+ | `vercel` | `vercel` | `vercel.json` | `VERCEL_TOKEN`, `VERCEL_ORG_ID`, `VERCEL_PROJECT_ID` |
1338
+ | `cloudflare` | `cloudflare_durable` | `wrangler.toml` | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` |
1339
+ | `fly` | the runtime's server | `fly.toml`, `Dockerfile`, `.dockerignore` | `FLY_API_TOKEN` |
1340
+ | `render` | the runtime's server | `render.yaml`, `Dockerfile`, `.dockerignore` | `RENDER_DEPLOY_HOOK_URL` |
1341
+
1342
+ ```bash
1343
+ npx kerf deploy hosts # fit, cost and a suggestion
1344
+ # Host files, a GitHub workflow and `deploy` in the config
1345
+ npx kerf deploy init
1346
+ # Dry run: prints the build and commands --yes would run
1347
+ npx kerf deploy
1348
+ npx kerf deploy --yes # deploy a preview; add --prod for production
1349
+ ```
1350
+
1351
+ Every target also gets `.github/workflows/kerf-deploy.yml`, which runs `kerf check` then deploys on push. Tokens come
1352
+ from the environment only: one written into the config or a host file is E008. Any other Nitro preset works with
1353
+ `kerf build --preset <name>`; `kerf doctor --preset <name>` says what live data does there. Full details:
1354
+ [`kerf docs deploy`](https://github.com/Ravonus/kerf/blob/main/packages/cli/docs/deploy.md).
1355
+
1356
+ ## API reference
1357
+
1358
+ ### `@kerf-js/start`
1359
+
1360
+ | Export | What it is |
1361
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------ |
1362
+ | `query(def)`, `mutation(def)` | Define server functions |
1363
+ | `stream(def)`, `topic(name, def)`, `tracked(id, value)` | Server-to-client message streams |
1364
+ | `channel(def)`, `sharedState(name, def)` | WebSocket rooms and shared per-key values |
1365
+ | `realtime(options)` | The default export of `src/realtime.server.ts`: bus, origins, limits, changes |
1366
+ | `dbChanges(db, tables, options?)` | A change feed from Postgres, SQLite or MySQL triggers |
1367
+ | `memoryBus()` | The one-process bus (the default) |
1368
+ | `liveHealth()`, `realtimeStats()` | Feed status for a health route; hub counters |
1369
+ | `redirect(href, status?)`, `notFound()` | Leave a `load` or `run` early |
1370
+ | `raise(code, data?)`, `invalid(fields)` | A declared error; a field error for `<Form>` |
1371
+ | `FnError`, `StartError`, `isRedirect(v)` | Error types, and a redirect check |
1372
+ | `invalidate(...tags)`, `cache`, `skip`, `stale` | Drop tags; the client cache; skip a tracked input; "a newer build is running" |
1373
+ | `listInput(spec)` | A query `input` for paged, sorted, filtered lists |
1374
+ | `Link`, `currentPath()`, `navigate(href, options?)` | Links with `aria-current`, the current path, and code navigation |
1375
+ | `Form` | A form that posts to a mutation, with or without JavaScript |
1376
+ | Types: `LoadArgs`, `RouteProps`, `Meta`, `OgProps`, `Prerender`, `ParamsOf`, `Context`, `Query`, `Mutation`, `LiveQuery`, `ListSource`, … | Typing routes, cards and functions |
1377
+
1378
+ <details>
1379
+ <summary>Every subpath</summary>
1380
+
1381
+ | Import | What it has |
1382
+ | ------------------------------------- | ------------------------------------------------------------------------------------- |
1383
+ | `@kerf-js/start/db` | `schemasOf(schema, refine?)`, `getTableName`, and the `DbHandle` type |
1384
+ | `@kerf-js/start/db/sqlite` | `createDb` on `node:sqlite` or `bun:sqlite` |
1385
+ | `@kerf-js/start/db/postgres` | `createDb` on postgres.js |
1386
+ | `@kerf-js/start/db/mysql` | `createDb` on mysql2 |
1387
+ | `@kerf-js/start/db/core` | The migration gate and handle that data layers build on (used by `@kerf-js/db`) |
1388
+ | `@kerf-js/start/auth` | `defineAuth`, `session`, `forward`, and the `AuthProvider` type |
1389
+ | `@kerf-js/start/auth/better-auth` | `createAuth`: Better Auth with Kerf's defaults |
1390
+ | `@kerf-js/start/auth/drizzle` | `drizzleAuth(db, schema?)`: Better Auth's store on a Drizzle client |
1391
+ | `@kerf-js/start/list` | `listInput` and the list contract that sources implement |
1392
+ | `@kerf-js/start/list/drizzle` | `drizzleSource({ db, table }, spec)` |
1393
+ | `@kerf-js/start/changes` | `dbChanges` and the `Source` interface for your own change feed |
1394
+ | `@kerf-js/start/bus/postgres` | `postgresBus({ url })`: LISTEN/NOTIFY as the realtime bus |
1395
+ | `@kerf-js/start/bus` | The `Bus` interface and `memoryBus` |
1396
+ | `@kerf-js/start/media` | `z`, Zod with `z.media()` for upload records `<Media>` takes |
1397
+ | `@kerf-js/start/rust` | `remote()` and `native()`: server functions with a Rust body (`kerf docs rust`) |
1398
+ | `@kerf-js/start/extension` | `server.extension@1`: how a plugin adds a server route |
1399
+ | `@kerf-js/start/og` | The share-card renderer |
1400
+ | `@kerf-js/start/client` | `start()`: the client entry |
1401
+ | `@kerf-js/start/server` | `createHandler()`: the request handler |
1402
+ | `@kerf-js/start/vite` | `kerfStart()`, the Vite plugin, and `scanRoutes` |
1403
+ | `@kerf-js/start/app` | `dev()` and `build()`, as `kerf dev` and `kerf build` call them |
1404
+ | `@kerf-js/start/data`, `/hub`, `/live`, `/channel`, `/share`, `/listen`, `/verify`, `/live-target`, `/changes-sql`, `/routes`, `/inspect`, `/contract`, `/derive`, `/sidecar` | Internals the CLI, the build and sibling packages use. Not a stable API |
1405
+
1406
+ </details>
1407
+
1408
+ ## Troubleshooting
1409
+
1410
+ `kerf docs <code>` explains any diagnostic below, with its fix.
1411
+
1412
+ | Code / symptom | Cause | Fix |
1413
+ | ------------------------------------ | ------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
1414
+ | Q001 | `q()` called outside a component or `defineState` setup | `await q.fetch(input)` in `load`, handlers and server code |
1415
+ | Q006 | A query with `cache` read `ctx.user` | Add `cache: { scope: 'user' }`, or drop the shared cache |
1416
+ | Q011 | A function touched a table its `tags`/`invalidates` don't name | Add the table's name (or `table:…`) |
1417
+ | Q012 | `@kerf-js/start/db*` or `/auth` reached the client | Import it only from server modules or `load` |
1418
+ | Q013 | A database URL the driver can't open | Use the matching `createDb` (`postgres://` needs `/db/postgres`) |
1419
+ | Q014 | A table or column is missing | `kerf db generate`, then reload |
1420
+ | Q015 | `src/db/schema.ts` changed since the last generate | `kerf db generate` |
1421
+ | Q016 (503) | The database is down, or a migration failed | Start it, check `DATABASE_URL`, or fix the migration; no restart needed |
1422
+ | Q018 (413) | A request body over `site.limits` | Send less, or raise `site.limits.body` / `.upload` |
1423
+ | Q019 (404) | `api.call` / `serverCall` named no query or mutation | Call one by its `$id` |
1424
+ | Q020 (500) | `serverCall` outside a request | Call it from a query, mutation, `load` or extension route |
1425
+ | A001 | The auth secret is missing or under 32 characters in production | Set `BETTER_AUTH_SECRET` |
1426
+ | A002 (401) | `auth: 'user'` (or a mutation in an app with auth) called with no session | Sign in first, or guard the route in a layout's `load` |
1427
+ | A006 (403) | A signed-in user without the `role`, or `can` said no | Sign in as a user it allows, or change the rule |
1428
+ | A007 | No `BETTER_AUTH_URL` or `options.baseURL` in production | Set `BETTER_AUTH_URL` to the site's https URL |
1429
+ | A004 | A mutation changed the session cookie without a redirect | `redirect()` after sign-in or sign-out |
1430
+ | A005 | `createAuth` has no store | Pass `options.database` |
1431
+ | H007 (500) | `meta` or a card read a deferred `load` field | Await it in `load`, or leave it out of `meta` |
1432
+ | H009 | An island prop JSON can't carry | Pass plain data, or `/* @kerf client */` on the parent |
1433
+ | R002 | The memory bus on a multi-instance preset | Set `bus` in `realtime()` |
1434
+ | R014, `.live` shows `degraded` | Outside writes on a function host | A server preset, or `kerf db listen` with a shared bus |
1435
+ | W053 | `.live()` on a query with no `tags` | Add `tags` |
1436
+ | Sign-in answers `INVALID_ORIGIN` | `BETTER_AUTH_URL` doesn't match where the app runs (`kerf dev --port`) | Update `BETTER_AUTH_URL` in `.env` |
1437
+ | `postgresBus` or `.live` goes quiet | pgBouncer in transaction mode breaks LISTEN | Give it a direct connection |
1438
+ | A native addon fails after deploy (E004) | Built on a Mac, deployed to Linux | Build where the host runs; the generated workflow builds on Linux |
1439
+
1440
+ ## Related packages
1441
+
1442
+ | Package | What it is |
1443
+ | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
1444
+ | [`@kerf-js/core`](https://www.npmjs.com/package/@kerf-js/core) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/core)</sup> | The reactive runtime, compiler binding, Vite plugin, SSR and test utilities Start is built on |
1445
+ | [`@kerf-js/cli`](https://www.npmjs.com/package/@kerf-js/cli) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/cli)</sup> | The `kerf` command: `dev`, `build`, `check`, `db`, `deploy`, `docs` and the MCP server |
1446
+ | [`create-kerf`](https://www.npmjs.com/package/create-kerf) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/create-kerf)</sup> | `npm create kerf`: scaffolds an app with Start, a database and auth |
1447
+ | [`@kerf-js/db`](https://www.npmjs.com/package/@kerf-js/db) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/db)</sup> | Prisma and no-ORM data layers, and list sources for SQL, Kysely, Prisma, MongoDB, DynamoDB and Firestore |
1448
+ | [`@kerf-js/veneer`](https://www.npmjs.com/package/@kerf-js/veneer) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/veneer)</sup> | The UI toolkit; its `Table` reads list sources |
1449
+ | [`@kerf-js/realtime-redis`](https://www.npmjs.com/package/@kerf-js/realtime-redis) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/realtime-redis)</sup>, [`-nats`](https://www.npmjs.com/package/@kerf-js/realtime-nats), [`-durable-object`](https://www.npmjs.com/package/@kerf-js/realtime-durable-object) | Realtime buses for Redis, NATS and Cloudflare Durable Objects |
1450
+
1451
+ ## Contributing
1452
+
1453
+ See [CONTRIBUTING.md](https://github.com/Ravonus/kerf/blob/main/CONTRIBUTING.md). From the repository root:
1454
+
1455
+ ```bash
1456
+ pnpm install
1457
+ # Unit and integration tests (Vitest)
1458
+ pnpm --filter @kerf-js/start test
1459
+ # The runtime matrix against a built app
1460
+ pnpm --filter @kerf-js/start test:e2e <built-app>
1461
+ ```
1462
+
1463
+ `test:e2e` takes `--e2e <path>` to pick another scenario in `test/e2e`. The live database scripts in that folder run
1464
+ directly with Node and need the database environment named in each script. They stay `.mjs` because Node and the
1465
+ runtime matrix load them without a test transform.
1466
+
1467
+ ## License
1468
+
1469
+ [MIT](https://github.com/Ravonus/kerf/blob/main/LICENSE)