@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/src/exec.ts ADDED
@@ -0,0 +1,400 @@
1
+ // The server's executor for queries and mutations (research 27 §3–§4). No runtime imports beyond data.ts, so the
2
+ // same code runs in the request handler (server.tsx, which finds the scope through AsyncLocalStorage) and in
3
+ // @kerf-js/core/test's in-process fake transport.
4
+ //
5
+ // request scope key → entry (promise, then value and tags): a query runs at most once per request; loaders, every
6
+ // render pass of a streamed page and a mutation's refreshes share it. Its resolved entries are the
7
+ // page's `#kerf-cache`.
8
+ // shared store only for `cache: { life }`: a value is valid while every tag's version still matches (a mutation
9
+ // bumps the versions of the tags it invalidates).
10
+
11
+ import { shapeTree } from './shape.mjs'
12
+ import {
13
+ enter,
14
+ fns,
15
+ isRedirect,
16
+ keyOf,
17
+ runtime,
18
+ StartError,
19
+ type Answer,
20
+ type Context,
21
+ type Fn,
22
+ type Wire,
23
+ type Life,
24
+ } from './data'
25
+
26
+ import {
27
+ createScope,
28
+ finishScope,
29
+ finishing,
30
+ rereads,
31
+ frame,
32
+ memoryStore,
33
+ defaultStore,
34
+ type Scope,
35
+ type ScopeEntry,
36
+ type Touched,
37
+ } from './exec/scope'
38
+ import { guard, dbError, signedIn } from './exec/errors'
39
+ import {
40
+ tracker,
41
+ untouched,
42
+ missedTags,
43
+ reads,
44
+ liveQueries,
45
+ missedPokes,
46
+ missedFeed,
47
+ } from './exec/touch'
48
+ import { validate, formInput, checked, checkTags } from './exec/validation'
49
+ import { landed, shown, said } from './exec/landing'
50
+ import { remember, rewarm, warms } from './exec/warm'
51
+ import { callImpl } from './exec/impl'
52
+ import { once } from './exec/once'
53
+ import { limitCall } from './exec/limit'
54
+ export {
55
+ createScope,
56
+ finishScope,
57
+ finishing,
58
+ frame,
59
+ memoryStore,
60
+ defaultStore,
61
+ guard,
62
+ signedIn,
63
+ dbError,
64
+ liveQueries,
65
+ missedFeed,
66
+ validate,
67
+ checkTags,
68
+ shown,
69
+ said,
70
+ }
71
+ export type {
72
+ Scope,
73
+ ScopeEntry,
74
+ ScopeOptions,
75
+ Touched,
76
+ FormFailure,
77
+ MediaServer,
78
+ Store,
79
+ Stored,
80
+ } from './exec/scope'
81
+
82
+ const LIFE: Record<Exclude<Life, number>, number> = {
83
+ seconds: 1,
84
+ minutes: 60,
85
+ hours: 3600,
86
+ days: 86_400,
87
+ max: Infinity,
88
+ }
89
+ const seconds = (life: Life = 'minutes') => (typeof life === 'number' ? life : LIFE[life])
90
+ const storeOf = (scope: Scope) => scope.options.store ?? defaultStore
91
+
92
+ // ---- queries --------------------------------------------------------------------------------------------------
93
+
94
+ /** The value now if this request already has it, else the promise: what a query resource's fetcher returns in SSR. */
95
+ export function readQuery(scope: Scope, fn: Fn, input: unknown): unknown {
96
+ const e = fetchEntry(scope, fn, input)
97
+ if (!e.done) return landed(scope, e)
98
+ if (e.e !== undefined) throw shown(e.e, scope)
99
+ return e.v
100
+ }
101
+
102
+ const trees = new WeakMap<Fn, { tree: unknown }>()
103
+ /** A query's shape tree, once per definition. */
104
+ export function shapeOf(fn: Fn): unknown {
105
+ let t = trees.get(fn)
106
+ if (!t) trees.set(fn, (t = { tree: shapeTree(fn.def) }))
107
+ return t.tree
108
+ }
109
+
110
+ export const fetchQuery = (scope: Scope, fn: Fn, input: unknown): Promise<ScopeEntry> => {
111
+ const e = fetchEntry(scope, fn, input)
112
+ const tags = scope.tags
113
+ return e.p.then((x) => (tags && x.tags.forEach((t) => tags.add(t)), x))
114
+ }
115
+
116
+ function fetchEntry(scope: Scope, fn: Fn, input: unknown): ScopeEntry {
117
+ if (fn.kind !== 'query')
118
+ throw new StartError(
119
+ 'Q009',
120
+ `\`${fn.$id}\` is a mutation, not a query`,
121
+ 'call it as a function, from a handler',
122
+ )
123
+ const key = keyOf(fn.$id, input)
124
+ const e = scope.entries.get(key)
125
+ if (e) return e
126
+ const entry: ScopeEntry = { id: fn.$id, input, tags: [], p: undefined as never }
127
+ entry.p = (async () => {
128
+ const valid = await validate(fn, input)
129
+ entry.tags = await tagsOf(fn, valid, scope)
130
+ // a preview's reads are its own: never served from the shared store, never written to it
131
+ const cached = scope.preview ? undefined : fn.def.cache
132
+ const store = storeOf(scope)
133
+ // Checked before the shared cache, so a value stored for one user is never answered to no one.
134
+ const early = signedIn(fn) || cached?.scope ? await scope.ctx() : undefined
135
+ if (early) await guard(fn, cached ? shared(early, fn, scope) : early)
136
+ const stored = cached?.scope
137
+ ? `${key}@${String((early as { user?: { id?: string | number } } | undefined)?.user?.id ?? '')}`
138
+ : key
139
+ /** Run the query and store what it returns. */
140
+ const compute = async () => {
141
+ const versions = cached ? await store.versions(entry.tags) : []
142
+ const ctx = early ?? (await scope.ctx())
143
+ const touched = tracker(scope)
144
+ const added: string[] = []
145
+ const v = await call(scope, fn, valid, cached ? shared(ctx, fn, scope) : ctx, {
146
+ touched,
147
+ added,
148
+ })
149
+ const fresh = [...new Set(added)].filter((t) => !entry.tags.includes(t))
150
+ if (fresh.length) {
151
+ entry.tags.push(...fresh)
152
+ if (cached) versions.push(...(await store.versions(fresh)))
153
+ }
154
+ if (scope.options.dev) await checked(v, fn, scope)
155
+ if (touched) {
156
+ untouched(fn, touched.read, entry.tags, scope)
157
+ missedTags(fn, 'read', touched.read, entry.tags, scope)
158
+ reads.set(fn.$id, touched.read)
159
+ }
160
+ if (cached) {
161
+ await store.set(stored, {
162
+ v,
163
+ tags: entry.tags,
164
+ versions,
165
+ expires: Date.now() + seconds(cached.life) * 1000,
166
+ })
167
+ if (warms(fn)) remember(stored, fn, input, entry.tags)
168
+ }
169
+ return v
170
+ }
171
+ if (!cached) return compute()
172
+ const hit = await store.get(stored)
173
+ if (hit && hit.expires > Date.now() && same(hit.versions, await store.versions(hit.tags)))
174
+ return hit.v
175
+ const done = await once(stored, async () => ({ v: await compute(), tags: entry.tags }))
176
+ entry.tags = [...done.tags]
177
+ return done.v
178
+ })().then(
179
+ (v) => Object.assign(entry, { done: true, v }),
180
+ (err) => {
181
+ err = afterStart(err, scope, fn)
182
+ Object.assign(entry, { done: true, e: err })
183
+ throw err
184
+ },
185
+ )
186
+ entry.p.catch(() => {}) // a failure surfaces where the value is read
187
+ scope.entries.set(key, entry)
188
+ return entry
189
+ }
190
+
191
+ /** A `redirect()` after the page started streaming can't change the status: Q007 says so, with where to move it. */
192
+ function afterStart(err: unknown, scope: Scope, fn: Fn): unknown {
193
+ if (isRedirect(err) && scope.started) {
194
+ const message = `\`${fn.$id}\` called \`redirect('${err.href}')\` after the page started streaming: the status is already sent`
195
+ scope.options.onDiagnostic?.({ code: 'Q007', severity: 'error', message })
196
+ err = new StartError(
197
+ 'Q007',
198
+ message,
199
+ `call \`${fn.$id.replace(/\..*$/, '')}.fetch()\` in the route's \`load\`, which runs before the first byte`,
200
+ )
201
+ }
202
+ return err
203
+ }
204
+
205
+ /** A query's tags. One that takes `ctx` is one user's, so it reads `ctx`; a signed-out caller fails here, as `guard` would. */
206
+ export async function tagsOf(fn: Fn, input: unknown, scope: Pick<Scope, 'ctx'>): Promise<string[]> {
207
+ const tags = fn.def.tags
208
+ if (typeof tags !== 'function') return [...(tags ?? [])]
209
+ if (tags.length < 2) return [...tags(input)]
210
+ const ctx = await scope.ctx()
211
+ await guard(fn, ctx)
212
+ return [...tags(input, ctx)]
213
+ }
214
+
215
+ const same = (a: number[], b: number[]) => a.length === b.length && a.every((x, i) => x === b[i])
216
+
217
+ const OWN = new Set([
218
+ '$id',
219
+ 'auth',
220
+ 'cache',
221
+ 'errors',
222
+ 'impl',
223
+ 'input',
224
+ 'invalidates',
225
+ 'live',
226
+ 'optimistic',
227
+ 'output',
228
+ 'run',
229
+ 'shape',
230
+ 'tags',
231
+ ])
232
+
233
+ /** An option from `FnOptions` is a promise to enforce something: with the plugin gone, the call stops rather than runs open. */
234
+ function claimed(fn: Fn, scope: Scope) {
235
+ for (const k in fn.def) {
236
+ if (OWN.has(k) || scope.options.extensions?.some((e) => e.options?.includes(k))) continue
237
+ throw new StartError(
238
+ 'P101',
239
+ `\`${fn.$id}\` sets \`${k}\`, and no \`server.extension\` enforces it`,
240
+ 'add the plugin that provides it to `plugins`, with its `src/<key>.server.ts`',
241
+ { status: 500 },
242
+ )
243
+ }
244
+ }
245
+
246
+ async function call(
247
+ scope: Scope,
248
+ fn: Fn,
249
+ input: unknown,
250
+ ctx: Context,
251
+ track: { touched?: Touched | undefined; added?: string[] } = {},
252
+ ) {
253
+ const { touched } = track
254
+ const added = track.added ?? []
255
+ await guard(fn, ctx)
256
+ await limitCall(fn, ctx, scope, storeOf(scope))
257
+ claimed(fn, scope)
258
+ try {
259
+ for (const e of scope.options.extensions ?? [])
260
+ await e.guard?.({ id: fn.$id, kind: fn.kind, def: fn.def }, ctx)
261
+ } catch (e) {
262
+ throw dbError(e)
263
+ }
264
+ const replaced = scope.options.handlers?.get(fn.$id)
265
+ // Awaited inside the frame: a Drizzle query is a thenable, and only runs when something awaits it.
266
+ const run = async () =>
267
+ await (replaced
268
+ ? replaced(input, ctx)
269
+ : fn.def.impl
270
+ ? callImpl(fn, input, ctx, scope, { touched, added })
271
+ : fn.def.run!({ input, ctx }))
272
+ let v: unknown
273
+ try {
274
+ v = await (touched ? enter(Object.create(scope, { touched: { value: touched } }), run) : run())
275
+ } catch (e) {
276
+ throw dbError(e)
277
+ }
278
+ // oxlint-disable-next-line typescript/only-throw-error -- a returned redirect takes the same path as a thrown one
279
+ if (isRedirect(v)) throw v
280
+ return v
281
+ }
282
+
283
+ /** A cached query's ctx: no request, response or user. Its value is shared by every user (Q006). With `scope: 'user'`, one value per user: `ctx.user` is allowed. */
284
+ function shared(ctx: Context, fn: Fn, scope: Scope): Context {
285
+ const own = fn.def.cache?.scope === 'user'
286
+ return new Proxy(ctx, {
287
+ get(t, k, r) {
288
+ const personal = scope.options.extensions?.some((e) => e.personal?.includes(String(k)))
289
+ if (own && (k === 'user' || k === 'session' || personal)) return Reflect.get(t, k, r)
290
+ if (k === 'request' || k === 'response' || k === 'user' || k === 'session' || personal)
291
+ throw new StartError(
292
+ 'Q006',
293
+ `\`${fn.$id}\` is cached (\`cache: { life }\`) and reads \`ctx.${String(k)}\`: its value would be shared by every user`,
294
+ 'drop `cache`, or pass the value as input',
295
+ )
296
+ return Reflect.get(t, k, r)
297
+ },
298
+ })
299
+ }
300
+
301
+ // ---- mutations --------------------------------------------------------------------------------------------------
302
+
303
+ /** Run a mutation; then refresh the listed queries whose tags it invalidated (single-flight, research 27 §3). */
304
+ export async function runMutation(
305
+ scope: Scope,
306
+ fn: Fn,
307
+ input: unknown,
308
+ refresh: [string, unknown][],
309
+ form?: boolean,
310
+ ): Promise<Answer> {
311
+ if (fn.kind !== 'mutation')
312
+ throw new StartError(
313
+ 'Q009',
314
+ `\`${fn.$id}\` is a query, not a mutation`,
315
+ `\`${fn.$id.replace(/\..*$/, '')}.fetch(input)\``,
316
+ )
317
+ if (scope.request.method === 'GET' || scope.request.method === 'HEAD')
318
+ throw new StartError(
319
+ 'Q004',
320
+ `mutation \`${fn.$id}\` called while the server handles a GET (\`load\`, a page render or a query)`,
321
+ 'call mutations from handlers or other mutations; GET handlers must be side-effect free',
322
+ { status: 500 },
323
+ )
324
+ const valid = await (form ? formInput(fn, input) : validate(fn, input))
325
+ const touched = tracker(scope)
326
+ const added: string[] = []
327
+ const v = await call(scope, fn, valid, await scope.ctx(), { touched, added })
328
+ if (scope.options.dev) await checked(v, fn, scope)
329
+ const declared =
330
+ typeof fn.def.invalidates === 'function'
331
+ ? fn.def.invalidates(valid, v)
332
+ : (fn.def.invalidates ?? [])
333
+ await invalidate(scope, [...declared, ...added])
334
+ const tags = [...scope.invalidated]
335
+ if (touched) {
336
+ missedTags(fn, 'write', touched.write, tags, scope)
337
+ missedPokes(fn, touched.write, tags, scope)
338
+ }
339
+ // in a preview, refreshes read as the next page will: with the preview this response leaves on (or turned off)
340
+ const next = rereads(scope)
341
+ const reader = next ? createScope(next, scope.options) : scope
342
+ try {
343
+ return { v, t: tags, c: await enter(reader, () => refreshed(reader, refresh, tags)) }
344
+ } finally {
345
+ if (reader !== scope) await finishScope(reader)
346
+ }
347
+ }
348
+
349
+ async function refreshed(scope: Scope, refresh: [string, unknown][], tags: string[]) {
350
+ const c: Wire[] = []
351
+ for (const [id, inp] of refresh) {
352
+ const q = fns.get(id)
353
+ if (!q || q.kind !== 'query') continue
354
+ let qtags: string[]
355
+ try {
356
+ const vi = await validate(q, inp)
357
+ qtags = await tagsOf(q, vi, scope)
358
+ } catch {
359
+ continue
360
+ }
361
+ if (!qtags.some((t) => tags.includes(t))) continue
362
+ try {
363
+ const e = await fetchQuery(scope, q, inp)
364
+ c.push([id, inp, e.v, e.tags])
365
+ } catch {} // the client refetches it and sees the error there
366
+ }
367
+ return c
368
+ }
369
+
370
+ /** Drop `tags` for the rest of this request and bump them in the shared store. */
371
+ /** Run a query or mutation by id as this scope's caller, guards and all, as a browser call would (`@kerf-js/agent`). */
372
+ export async function callById(scope: Scope, id: string, input: unknown): Promise<unknown> {
373
+ const fn = fns.get(id)
374
+ if (!fn || (fn.kind !== 'query' && fn.kind !== 'mutation'))
375
+ throw new StartError('Q019', `no query or mutation \`${id}\``, 'call one by its `$id`', {
376
+ status: 404,
377
+ })
378
+ return fn.kind === 'query'
379
+ ? (await fetchQuery(scope, fn, input)).v
380
+ : (await runMutation(scope, fn, input, [])).v
381
+ }
382
+
383
+ export async function invalidate(scope: Scope, tags: string[]) {
384
+ if (!tags.length) return
385
+ for (const t of tags) scope.invalidated.add(t)
386
+ for (const [k, e] of scope.entries)
387
+ if (e.tags.some((t) => tags.includes(t))) scope.entries.delete(k)
388
+ await storeOf(scope).bump(tags)
389
+ if (!scope.preview)
390
+ rewarm(scope, tags, fetchQuery, (request) => createScope(request, scope.options))
391
+ // After the bump, and after `run`: a refetch reads committed data and misses the shared cache (research 30 §5).
392
+ // A bus that's down costs open pages a refresh, not this request its result.
393
+ await runtime.poke?.(tags, scope.request.headers.get('x-kerf-conn')).catch((e) =>
394
+ scope.options.onDiagnostic?.({
395
+ code: 'E_RT',
396
+ severity: 'error',
397
+ message: `poke of ${tags.join(', ')} failed: ${e instanceof Error ? e.message : e}`,
398
+ }),
399
+ )
400
+ }
@@ -0,0 +1,48 @@
1
+ // `server.extension@1`: how a plugin reaches the server without a private path. One provider per key adds what it needs,
2
+ // and only an app with `src/<key>.server.ts` runs it, so nothing arrives behind the app's back (P118). The provider exports
3
+ // a function from that file's default export to a `ServerExtension`; `kerf docs plugins` has a worked example.
4
+ //
5
+ // Four things, each optional. Routes live under `/_kerf/x/<key>/`. `context` adds to `ctx`. `guard` runs before every server
6
+ // function, and options it reads come from augmenting `FnOptions`. `check` runs before the first request.
7
+
8
+ import type { Context } from './data'
9
+
10
+ /** The path prefix an extension's routes answer under. */
11
+ export const EXTENSION = '/_kerf/x/'
12
+
13
+ /** What a server extension is handed. */
14
+ export interface ExtensionApi {
15
+ /** Drop these tags, as a mutation would: live readers refetch. */
16
+ invalidate(tags: string[]): Promise<void>
17
+ /** The server log. */
18
+ report(d: { code: string; severity: string; message: string }): void
19
+ /** This request's `ctx`, with every extension's part. */
20
+ ctx(): Promise<Context>
21
+ /** Run a query or mutation by `$id` as this request's caller, with its schema, `auth` and every `guard`. */
22
+ call(id: string, input: unknown): Promise<unknown>
23
+ }
24
+
25
+ /** A plugin's server half: its routes, what it adds to `ctx`, and what it guards. */
26
+ export interface ServerExtension {
27
+ /** Serves `/_kerf/x/<key>/<path>`. It sees the raw request: nothing has read the body. */
28
+ handle?(request: Request, path: string, api: ExtensionApi): Promise<Response> | Response
29
+ /** Merged into `ctx`, after the app's own. It may replace `user` (a caller with a token) and may look things up first. */
30
+ context?(ctx: Context): object | Promise<object>
31
+ /** Before a function's `run`. Throw to refuse: an error with `answer: { code, message, status }` reaches the client as it is. */
32
+ guard?(
33
+ fn: { id: string; kind: string; def: Record<string, unknown> },
34
+ ctx: Context,
35
+ ): void | Promise<void>
36
+ /** The `FnOptions` keys it enforces. One no extension claims refuses the call: a guard that isn't there mustn't pass. */
37
+ options?: readonly string[]
38
+ /** The `ctx` keys that differ per user, which a shared cache may not read (Q006). */
39
+ personal?: readonly string[]
40
+ /** Before the first request, never in a build: throw for a server that can't run safely. */
41
+ check?(dev?: boolean): void
42
+ }
43
+
44
+ /** One extension in the generated list, loaded when first asked for. */
45
+ export interface ExtensionEntry {
46
+ key: string
47
+ load(): Promise<ServerExtension>
48
+ }
@@ -0,0 +1,74 @@
1
+ // The first-paint CSS of whatever HTML is passed in, by lookups: the build's `pieces` table, nothing parsed here. It reads
2
+ // the HTML rather than a list kept while rendering, so a cached or prerendered page, a static level and a streamed chunk
3
+ // take one path, nothing is shared between requests, and the same HTML always gets the same CSS.
4
+ import { markup } from '@kerf-js/core/markup'
5
+
6
+ export interface Pieces {
7
+ names: string[]
8
+ layers: string
9
+ wraps: string[]
10
+ pieces: [number, number, string, string][]
11
+ always: number[]
12
+ alts: ([string[], string[][]][] | null)[]
13
+ deps: number[][]
14
+ index: Record<string, number[]>
15
+ }
16
+
17
+ const GATE =
18
+ '[data-kerf=styled]{visibility:hidden;animation:kerf-gate 0s 3s forwards}@keyframes kerf-gate{to{visibility:visible}}'
19
+ const depth = (open: string) => open.split('{').length - 1
20
+
21
+ /**
22
+ * One response's tracker: each call gives the CSS `html` needs that this response hasn't sent, from `sheets` alone, so
23
+ * another route's rules never reach this page. `extra`: what the page's head sets, in `markup`'s words.
24
+ */
25
+ export function firstPaint(table: Pieces, sheets: string[], head = '') {
26
+ const rank = new Map(sheets.map((name, i) => [table.names.indexOf(name), i]))
27
+ const sent = new Set<number>()
28
+ const headHas = markup('')
29
+ for (const [, name, value] of head.matchAll(/dataset\.(\w+)\s*=\s*['"]([^'"]+)['"]/g))
30
+ headHas.add(`[data-${name}=${value}]`)
31
+ let gated = false
32
+ return (html: string) => {
33
+ const has = markup(html)
34
+ for (const k of headHas) has.add(k)
35
+ const fresh: number[] = []
36
+ const take = (id: number) => {
37
+ if (sent.has(id) || !rank.has(table.pieces[id]![0])) return
38
+ sent.add(id)
39
+ fresh.push(id)
40
+ table.deps[id]!.forEach(take)
41
+ }
42
+ table.always.forEach(take)
43
+ for (const key of has)
44
+ table.index[key]?.forEach((id) => {
45
+ const need = table.alts[id]
46
+ if (
47
+ !need ||
48
+ need.some(
49
+ ([all, any]) =>
50
+ all.every((k) => has.has(k)) && any.every((l) => l.some((k) => has.has(k))),
51
+ )
52
+ )
53
+ take(id)
54
+ })
55
+ let css = !gated && has.has('[data-kerf=styled]') ? ((gated = true), GATE) : ''
56
+ fresh.sort((a, b) => rank.get(table.pieces[a]![0])! - rank.get(table.pieces[b]![0])! || a - b)
57
+ let open = 0,
58
+ rule = ''
59
+ for (const id of fresh) {
60
+ const [, wrap, selector, body] = table.pieces[id]!
61
+ if (wrap !== open) {
62
+ css += (rule && '}') + '}'.repeat(depth(table.wraps[open]!)) + table.wraps[wrap]
63
+ open = wrap
64
+ rule = ''
65
+ }
66
+ if (selector === rule && selector[0] !== '@') css += `;${body}` // a token block: one head, however many of its tokens are in
67
+ else {
68
+ css += `${rule && '}'}${selector}{${body}`
69
+ rule = selector
70
+ }
71
+ }
72
+ return css + (rule && '}') + '}'.repeat(depth(table.wraps[open]!))
73
+ }
74
+ }
@@ -0,0 +1,15 @@
1
+ /** The raw values restored after a failed form submission. */
2
+ export type FormValue = string | string[] | undefined
3
+
4
+ /** A field's restoration mode. Omit it to retain the raw value. */
5
+ export type FieldKind = 'text' | 'email' | 'multiple' | 'raw'
6
+
7
+ /** Project a restored value to the declared field kind. */
8
+ export function fieldValue(value: FormValue, kind: 'text' | 'email'): string | undefined
9
+ export function fieldValue(value: FormValue, kind: 'multiple'): string[] | undefined
10
+ export function fieldValue(value: FormValue, kind?: FieldKind): FormValue
11
+ export function fieldValue(value: FormValue, kind?: FieldKind): FormValue {
12
+ if (kind === 'text' || kind === 'email') return Array.isArray(value) ? value[0] : value
13
+ if (kind === 'multiple') return value === undefined ? undefined : [value].flat()
14
+ return value
15
+ }