@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/list.ts ADDED
@@ -0,0 +1,315 @@
1
+ // The list contract: one way to ask for a page or a cursor, whatever holds
2
+ // the rows. `listInput` is a schema a `query` takes as its `input`, and a source is what the `@kerf-js/db` subpaths build.
3
+ //
4
+ // export const tasks = query({
5
+ // input: listInput({ sort: ['rank', 'title'], filter: ['status'], search: ['title'], pageSize: { default: 25, max: 100 } }),
6
+ // run: ({ input }) => Tasks.list(input),
7
+ // })
8
+ //
9
+ // Every name a client sends is checked against an allowlist twice, here and against the source's `columns`, so no
10
+ // request reaches an identifier. A filter value is a scalar or a list of them: an object is refused, which
11
+ // is what stops `{ $ne: null }` reaching a document store. Only `columns` are selected, returned or written.
12
+
13
+ import { StartError, type StandardSchemaV1 } from './data'
14
+
15
+ /** One value a filter can hold. */
16
+ export type Scalar = string | number | boolean | null
17
+ /** Which way a sort runs. */
18
+ export type Dir = 'asc' | 'desc'
19
+ /** One field and a direction. */
20
+ export interface Sort {
21
+ field: string
22
+ dir: Dir
23
+ }
24
+
25
+ /** A checked request, as a source takes it. */
26
+ export interface ListParams {
27
+ mode: 'page' | 'cursor'
28
+ limit: number
29
+ /** Rows to skip, in `page` mode. */
30
+ offset: number
31
+ /** The position to continue after, in `cursor` mode: the last row's sort value and id. */
32
+ after: [value: unknown, id: unknown] | null
33
+ sort: Sort | null
34
+ search?: string
35
+ /** A list means any of them. `null` means the field is empty. */
36
+ filter: Record<string, Scalar | Scalar[]>
37
+ }
38
+
39
+ /** The envelope Veneer's `Table` reads. `next` and `prev` go back in as `cursor` or `page`; absent means no such page. */
40
+ export interface ListPage<T> {
41
+ items: T[]
42
+ total?: number
43
+ next?: string | number
44
+ prev?: string | number
45
+ }
46
+
47
+ /** What a list lets a client ask for. */
48
+ export interface ListSpec {
49
+ /** Required, even empty: nothing is sortable, filterable or searchable by default. */
50
+ sort: readonly string[]
51
+ filter: readonly string[]
52
+ search?: readonly string[]
53
+ defaultSort?: Sort
54
+ pageSize?: { default?: number; max?: number }
55
+ }
56
+
57
+ /** What a client sends: every field is checked by `listInput`. */
58
+ export interface ListRequest {
59
+ mode?: 'page' | 'cursor'
60
+ page?: number
61
+ pageSize?: number
62
+ cursor?: string | null
63
+ sort?: Sort | null
64
+ search?: string
65
+ filter?: Record<string, Scalar | Scalar[]>
66
+ }
67
+
68
+ const SEARCH_MAX = 200,
69
+ IN_MAX = 100,
70
+ CURSOR_MAX = 1024
71
+
72
+ const scalar = (v: unknown): v is Scalar =>
73
+ v === null ||
74
+ typeof v === 'boolean' ||
75
+ typeof v === 'string' ||
76
+ (typeof v === 'number' && Number.isFinite(v))
77
+
78
+ const pack = (v: unknown) => (v instanceof Date ? { $d: v.toISOString() } : v)
79
+ const stamped = (v: unknown): v is { $d: string } =>
80
+ typeof (v as { $d?: unknown } | null)?.$d === 'string'
81
+ const unpack = (v: unknown) => (stamped(v) ? new Date(v.$d) : v)
82
+
83
+ /** Opaque to a client, and read with the same care as any other input. */
84
+ export function encodeCursor(value: unknown, id: unknown): string {
85
+ const bytes = new TextEncoder().encode(JSON.stringify([pack(value), pack(id)]))
86
+ return btoa(String.fromCharCode(...bytes))
87
+ .replaceAll('+', '-')
88
+ .replaceAll('/', '_')
89
+ .replace(/=+$/, '')
90
+ }
91
+
92
+ /** The other way from `encodeCursor`: null for anything that isn't a cursor of ours. */
93
+ export function decodeCursor(text: string): [unknown, unknown] | null {
94
+ if (text.length > CURSOR_MAX) return null
95
+ try {
96
+ const bytes = Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), (c) =>
97
+ c.charCodeAt(0),
98
+ )
99
+ const list: unknown = JSON.parse(new TextDecoder().decode(bytes))
100
+ const fits = (v: unknown) => scalar(v) || (stamped(v) && !Number.isNaN(Date.parse(v.$d)))
101
+ return Array.isArray(list) && list.length === 2 && list.every(fits)
102
+ ? [unpack(list[0]), unpack(list[1])]
103
+ : null
104
+ } catch {
105
+ return null
106
+ }
107
+ }
108
+
109
+ /** A `query`'s `input`. Takes a `ListRequest` from the client, and hands `run` the `ListParams` a source takes. */
110
+ export function listInput(spec: ListSpec): StandardSchemaV1<ListRequest | undefined, ListParams> {
111
+ const fallback = spec.pageSize?.default ?? 25,
112
+ max = spec.pageSize?.max ?? 100
113
+ const sorts = new Set(spec.sort),
114
+ filters = new Set(spec.filter)
115
+ const validate = (input: unknown) => {
116
+ const issues: { message: string; path?: string[] }[] = []
117
+ const no = (message: string, ...path: string[]) => void issues.push({ message, path })
118
+ const r = (input ?? {}) as ListRequest
119
+ if (typeof r !== 'object' || Array.isArray(r))
120
+ return { issues: [{ message: 'a list request is an object' }] }
121
+ const mode = r.mode ?? (r.cursor !== undefined ? 'cursor' : 'page')
122
+ if (mode !== 'page' && mode !== 'cursor') no('`mode` is `page` or `cursor`', 'mode')
123
+ const size = r.pageSize ?? fallback
124
+ if (!Number.isInteger(size) || size < 1 || size > max)
125
+ no(`\`pageSize\` is a whole number up to ${max}`, 'pageSize')
126
+ const page = r.page ?? 1
127
+ if (!Number.isInteger(page) || page < 1 || page > 1e6)
128
+ no('`page` is a whole number from 1', 'page')
129
+ let after: ListParams['after'] = null
130
+ if (r.cursor != null) {
131
+ after = typeof r.cursor === 'string' ? decodeCursor(r.cursor) : null
132
+ if (!after) no('that cursor is not one of ours', 'cursor')
133
+ }
134
+ const sort = r.sort ?? spec.defaultSort ?? null
135
+ if (
136
+ sort &&
137
+ !(
138
+ typeof sort === 'object' &&
139
+ sorts.has(sort.field) &&
140
+ (sort.dir === 'asc' || sort.dir === 'desc')
141
+ )
142
+ )
143
+ no('that sort is not allowed', 'sort')
144
+ if (r.search !== undefined && (typeof r.search !== 'string' || r.search.length > SEARCH_MAX))
145
+ no(`\`search\` is text up to ${SEARCH_MAX} characters`, 'search')
146
+ if (r.search && !spec.search?.length) no('this list has no search', 'search')
147
+ const filter: ListParams['filter'] = Object.create(null)
148
+ if (
149
+ r.filter !== undefined &&
150
+ (typeof r.filter !== 'object' || r.filter === null || Array.isArray(r.filter))
151
+ )
152
+ no('`filter` is an object', 'filter')
153
+ else
154
+ for (const key of Object.keys(r.filter ?? {})) {
155
+ const v = r.filter![key]!
156
+ if (!filters.has(key)) no(`\`${key}\` can't be filtered on`, 'filter', key)
157
+ else if (
158
+ Array.isArray(v) ? !(v.length && v.length <= IN_MAX && v.every(scalar)) : !scalar(v)
159
+ )
160
+ no(`\`${key}\` takes a value or a list of up to ${IN_MAX}, not an object`, 'filter', key)
161
+ else filter[key] = v
162
+ }
163
+ if (issues.length) return { issues }
164
+ const params: ListParams = {
165
+ mode,
166
+ limit: size,
167
+ offset: mode === 'page' ? (page - 1) * size : 0,
168
+ after,
169
+ sort,
170
+ filter,
171
+ ...(r.search ? { search: r.search } : {}),
172
+ }
173
+ return { value: params }
174
+ }
175
+ return { '~standard': { version: 1, vendor: 'kerf', validate } }
176
+ }
177
+
178
+ // ---- sources --------------------------------------------------------------------------------------------------------
179
+
180
+ /** The allowlist a source reads and writes through. */
181
+ export interface SourceSpec {
182
+ /** Public name → stored name. Required: only these are selected, returned or written. */
183
+ columns: Record<string, string>
184
+ /** The public name of the row's id. Default `id`. */
185
+ id?: string
186
+ /** Public names `search` scans. */
187
+ search?: readonly string[]
188
+ /** Public names a write may set. Default every column but the id. */
189
+ write?: readonly string[]
190
+ }
191
+
192
+ /** One table or collection, read and written the same way whatever holds it. */
193
+ export interface ListSource<Row = Record<string, unknown>> {
194
+ list(params: ListParams): Promise<ListPage<Row>>
195
+ get(id: unknown): Promise<Row | null>
196
+ create(data: Record<string, unknown>): Promise<Row>
197
+ /** Null when there's no such row. */
198
+ update(id: unknown, patch: Record<string, unknown>): Promise<Row | null>
199
+ remove(id: unknown): Promise<boolean>
200
+ /** What it can't do, so a page can leave the control out. */
201
+ readonly limits?: { page?: false; search?: 'prefix' | 'cased' | false; sort?: readonly string[] }
202
+ }
203
+
204
+ /** `db.adapter@1`: what a provider exports. `target` is the driver's handle: a collection, a table, a query function. */
205
+ export interface DbAdapter<T = unknown> {
206
+ readonly name: string
207
+ source<Row = Record<string, unknown>>(target: T, spec: SourceSpec): ListSource<Row>
208
+ }
209
+
210
+ const refuse = (what: string) =>
211
+ new StartError(
212
+ 'Q002',
213
+ `the list source refused ${what}`,
214
+ "add it to the source's `columns`, and to `listInput`",
215
+ { status: 400 },
216
+ )
217
+
218
+ /** A request checked against the source and put in stored names. Throws on any name outside `columns`. */
219
+ export interface Plan {
220
+ sort: { column: string; dir: Dir; field: string } | null
221
+ /** The last thing to order by, so rows that tie keep one order across pages. */
222
+ id: { column: string; field: string }
223
+ where: { column: string; values: Scalar[] }[]
224
+ search?: { columns: string[]; text: string }
225
+ }
226
+
227
+ /** Stored name of the row's id. A spec without one can't address a row, so a write can't go nowhere in silence. */
228
+ export function storedId(spec: SourceSpec): string {
229
+ const id = spec.id ?? 'id'
230
+ if (!Object.hasOwn(spec.columns, id)) throw refuse(`\`${id}\` as the id`)
231
+ return spec.columns[id]!
232
+ }
233
+
234
+ /** Check a request against `spec`, for a source to run. */
235
+ export function plan(spec: SourceSpec, p: ListParams): Plan {
236
+ const stored = (field: string) =>
237
+ Object.hasOwn(spec.columns, field)
238
+ ? spec.columns[field]!
239
+ : (() => {
240
+ throw refuse(`\`${field}\``)
241
+ })()
242
+ const id = spec.id ?? 'id'
243
+ const where = Object.keys(p.filter).map((field) => ({
244
+ column: stored(field),
245
+ values: [p.filter[field]!].flat(),
246
+ }))
247
+ if (where.some((w) => !w.values.every(scalar)))
248
+ throw refuse('a filter value that is not a scalar')
249
+ const searching = p.search ? (spec.search ?? []) : []
250
+ if (p.search && !searching.length) throw refuse('a search')
251
+ return {
252
+ sort: p.sort ? { column: stored(p.sort.field), dir: p.sort.dir, field: p.sort.field } : null,
253
+ id: { column: stored(id), field: id },
254
+ where,
255
+ ...(p.search ? { search: { columns: searching.map(stored), text: p.search } } : {}),
256
+ }
257
+ }
258
+
259
+ /** A stored row in public names, with only `columns` in it. */
260
+ export const rowOf = <Row = Record<string, unknown>>(spec: SourceSpec) => {
261
+ const pairs = Object.entries(spec.columns)
262
+ return (row: object) =>
263
+ Object.fromEntries(
264
+ pairs.filter(([, c]) => c in row).map(([f, c]) => [f, (row as Record<string, unknown>)[c]]),
265
+ ) as Row
266
+ }
267
+
268
+ /** A write in stored names. Refuses anything outside `write`, so a client can't set `role` or move an id. */
269
+ export function written(
270
+ spec: SourceSpec,
271
+ data: Record<string, unknown>,
272
+ creating = false,
273
+ ): Record<string, unknown> {
274
+ const id = spec.id ?? 'id'
275
+ const allowed = new Set(spec.write ?? Object.keys(spec.columns).filter((f) => f !== id))
276
+ if (creating) allowed.add(id)
277
+ const out: Record<string, unknown> = {}
278
+ for (const field of Object.keys(data)) {
279
+ if (!allowed.has(field) || !Object.hasOwn(spec.columns, field))
280
+ throw refuse(`a write to \`${field}\``)
281
+ out[spec.columns[field]!] = data[field]
282
+ }
283
+ return out
284
+ }
285
+
286
+ /** `rows` are in public names, with one more than `limit` in cursor mode when there is a next page. */
287
+ export function pageOf<R>(
288
+ rows: R[],
289
+ p: ListParams,
290
+ field: { sort?: string | undefined; id: string },
291
+ total?: number,
292
+ ): ListPage<R> {
293
+ if (p.mode === 'page') {
294
+ const page = p.offset / p.limit + 1
295
+ return {
296
+ items: rows,
297
+ ...(total === undefined ? {} : { total }),
298
+ ...(total !== undefined && p.offset + p.limit < total ? { next: page + 1 } : {}),
299
+ ...(page > 1 ? { prev: page - 1 } : {}),
300
+ }
301
+ }
302
+ const more = rows.length > p.limit
303
+ const items = more ? rows.slice(0, p.limit) : rows
304
+ const last = items.at(-1) as R & Record<string, unknown>
305
+ return {
306
+ items,
307
+ ...(total === undefined ? {} : { total }),
308
+ ...(more
309
+ ? { next: encodeCursor(field.sort ? last[field.sort] : last[field.id], last[field.id]) }
310
+ : {}),
311
+ }
312
+ }
313
+
314
+ /** `LIKE` with `!` as the escape: the one character that means the same on SQLite, Postgres and MySQL. */
315
+ export const likeOf = (text: string) => `%${text.replace(/[!%_]/g, '!$&')}%`.toLowerCase()
package/src/listen.ts ADDED
@@ -0,0 +1,54 @@
1
+ // `kerf db listen`: the change feed as a process of its own, for an app on functions, which can't hold a connection. It
2
+ // publishes pokes to the app's bus, so it needs a bus every instance reads, and its heartbeat is how the app knows it's up.
3
+
4
+ import type { Bus } from './bus'
5
+ import { createFeed, type Source } from './changes'
6
+ import { StartError } from './data'
7
+
8
+ const BEAT = 10_000
9
+
10
+ /** Listens until the returned `stop`. Run one: two listeners poke twice, which costs a refetch and loses nothing. */
11
+ export async function listen({
12
+ changes,
13
+ bus,
14
+ say = console.info,
15
+ beat = BEAT,
16
+ }: {
17
+ changes: Source
18
+ bus: Bus
19
+ say?: (line: string) => void
20
+ beat?: number
21
+ }) {
22
+ if (bus.name === 'memory')
23
+ throw new StartError(
24
+ 'R017',
25
+ '`kerf db listen` publishes to the bus, and the memory bus stops at this process',
26
+ 'set `bus` in `src/realtime.server.ts`',
27
+ )
28
+ const how = await changes.probe()
29
+ say(`kerf live: ${how.mode} (${how.via})${how.why ? `: ${how.why}` : ''}`)
30
+ if (how.mode !== 'feed')
31
+ throw new StartError(
32
+ 'R015',
33
+ `this listener has no real feed${how.why ? `: ${how.why}` : ''}`,
34
+ how.fix,
35
+ )
36
+ const feed = createFeed(changes, {
37
+ emit: (p) =>
38
+ void bus
39
+ .publish('kerf:poke', JSON.stringify(p))
40
+ .catch((e) => say(`kerf live: publish failed: ${e?.message ?? e}`)),
41
+ status: (down) => say(down ? `kerf live: down: ${down}` : 'kerf live: back'),
42
+ })
43
+ await feed.start(how)
44
+ const beats = setInterval(
45
+ () => void bus.publish('kerf:poke', '{"v":1,"b":1}').catch(() => {}),
46
+ beat,
47
+ )
48
+ await bus.publish('kerf:poke', '{"v":1,"b":1}')
49
+ return async () => {
50
+ clearInterval(beats)
51
+ await feed.stop()
52
+ await bus.close?.()
53
+ }
54
+ }
@@ -0,0 +1,18 @@
1
+ import type { LiveApi } from '../data'
2
+
3
+ // `data.ts` hands these over (`use`). A static import would close a cycle with its `import('./live')`, and the bundler
4
+ // would then keep this chunk, the hub and the split they force in apps that never read `.live`.
5
+ export let cache: LiveApi['cache'],
6
+ currentScope: LiveApi['currentScope'],
7
+ fns: LiveApi['fns'],
8
+ FnError: LiveApi['FnError'],
9
+ keyOf: LiveApi['keyOf'],
10
+ net: LiveApi['net'],
11
+ rt: LiveApi['rt'],
12
+ runtime: LiveApi['runtime'],
13
+ skip: LiveApi['skip'],
14
+ StartError: LiveApi['StartError'],
15
+ track: LiveApi['track']
16
+ export const use = (api: LiveApi) =>
17
+ void ({ cache, currentScope, fns, FnError, keyOf, net, rt, runtime, skip, StartError, track } =
18
+ api)
@@ -0,0 +1,6 @@
1
+ const BASE = 500
2
+ export const CAP = 30_000
3
+
4
+ /** Full jitter: anywhere from 0 to 0.5 s, 1 s, 2 s … 30 s. */
5
+ export const backoff = (attempt: number, random = Math.random) =>
6
+ random() * Math.min(CAP, BASE * 2 ** attempt)
@@ -0,0 +1,42 @@
1
+ import { DEV } from '@kerf-js/core'
2
+ import { cache, FnError } from './api'
3
+ import type { Sub } from './sub-types'
4
+
5
+ export type Row = { 0: number; 1: never; 2: unknown }
6
+
7
+ export function ack(d: Row, byN: Map<number, Sub>, seeded: () => boolean) {
8
+ const s = byN.get(d[0])
9
+ if (!s) return
10
+ s.tags = d[1]
11
+ s.error.value = undefined
12
+ if (DEV && !s.tags.length)
13
+ console.warn(
14
+ `kerf: W053 \`${s.fn.$id}\` is read with \`.live()\` but declares no \`tags\`: no mutation can ever poke it.\n fix: add \`tags\` to the query`,
15
+ )
16
+ // Data older than the subscription may have missed a write. A page's first connect is covered by its cursor.
17
+ if (!s.acked && !seeded() && s.tags.length) void cache.invalidate(...s.tags)
18
+ s.acked = true
19
+ }
20
+
21
+ export function update(event: string, d: Row, byN: Map<number, Sub>) {
22
+ if (event === 'm') {
23
+ const s = byN.get(d[0])
24
+ if (!s) return
25
+ if (d[1] !== null) s.cursor = d[1]
26
+ s.error.value = undefined
27
+ for (const v of s.views.values())
28
+ v.box.value = v.fold ? v.fold(v.box.value as never, d[2] as never) : d[2]
29
+ } else if (event === 'r') {
30
+ const s = byN.get(d[0])
31
+ if (!s) return
32
+ s.cursor = undefined
33
+ for (const v of s.views.values()) v.box.value = v.initial
34
+ } else if (event === 'f') {
35
+ const s = byN.get(d[0])
36
+ if (s) s.done.value = true
37
+ } else if (event === 'e') {
38
+ const s = byN.get(d[0])
39
+ if (s)
40
+ s.error.value = new FnError(d[1], (d[1] as { code?: string }).code === 'A002' ? 401 : 500)
41
+ }
42
+ }
@@ -0,0 +1,77 @@
1
+ import {
2
+ DEV,
3
+ createRoot,
4
+ derived,
5
+ effect,
6
+ getOwner,
7
+ onCleanup,
8
+ state,
9
+ untrack,
10
+ } from '@kerf-js/core'
11
+ import type { Fn } from '../data'
12
+ import { currentScope, rt, skip, StartError } from './api'
13
+ import type { Sub, View } from './sub-types'
14
+ import type { Stream, StreamOptions } from './types'
15
+
16
+ export function read(
17
+ fn: Fn,
18
+ input: unknown,
19
+ o: StreamOptions<never, unknown> = {},
20
+ acquire: (fn: Fn, input: unknown) => Sub,
21
+ held: (s: Sub, keep?: string | number) => () => void,
22
+ ): Stream<unknown> {
23
+ if (!getOwner())
24
+ throw new StartError(
25
+ 'W051',
26
+ DEV
27
+ ? `\`${fn.$id}()\` (a stream) was called outside a component or scope: nothing would close it`
28
+ : fn.$id,
29
+ DEV
30
+ ? 'call it in a component, a `defineState` setup or `createRoot(dispose => …)`'
31
+ : undefined,
32
+ )
33
+ const scope = currentScope()
34
+ if (scope) {
35
+ scope.live = true // the server renders `initial`, and the client hydrates to the same
36
+ return { value: o.initial, status: rt.status, error: undefined }
37
+ }
38
+ const view = state<{ s: Sub; v: View } | undefined>(undefined)
39
+ const fold = o.fold ? String(o.fold) : ''
40
+ effect(
41
+ () => {
42
+ const arg = typeof input === 'function' ? (input as () => unknown)() : input
43
+ if (arg === skip) return undefined
44
+ return untrack(() => {
45
+ const s = acquire(fn, arg)
46
+ if (o.fold) s.buffer ??= o.buffer ?? 256
47
+ else if (o.buffer) s.buffer ??= o.buffer
48
+ let v = s.views.get(fold)
49
+ if (!v)
50
+ s.views.set(
51
+ fold,
52
+ (v = createRoot(
53
+ () => ({ fold: o.fold, initial: o.initial, box: state<unknown>(o.initial) }),
54
+ null,
55
+ )),
56
+ )
57
+ v.fold = o.fold
58
+ onCleanup(held(s, o.keep))
59
+ return { s, v }
60
+ })
61
+ },
62
+ (now) => {
63
+ view.value = now
64
+ },
65
+ )
66
+ const status = derived(() => (view.value?.s.done.value ? 'done' : rt.status.value))
67
+ return {
68
+ get value() {
69
+ const now = view.value
70
+ return now ? now.v.box.value : o.initial
71
+ },
72
+ status,
73
+ get error() {
74
+ return view.value?.s.error.value
75
+ },
76
+ }
77
+ }
@@ -0,0 +1,24 @@
1
+ import type { State } from '@kerf-js/core'
2
+ import type { Fn } from '../data'
3
+
4
+ export interface View {
5
+ fold?: ((acc: never, m: never) => unknown) | undefined
6
+ initial: unknown
7
+ box: State<unknown>
8
+ }
9
+ export interface Sub {
10
+ n: number
11
+ key: string
12
+ fn: Fn
13
+ input: unknown
14
+ refs: number
15
+ timer?: ReturnType<typeof setTimeout> | undefined
16
+ /** Stream: the last id, sent back on a resume. Query: its tags, from the ack. */
17
+ cursor?: string | undefined
18
+ tags: string[]
19
+ buffer?: number
20
+ acked: boolean
21
+ views: Map<string, View>
22
+ error: State<unknown>
23
+ done: State<boolean>
24
+ }
@@ -0,0 +1,86 @@
1
+ import type { Body } from '../hub'
2
+ import { HANDOVER, openLine, type Line } from '../link'
3
+ import { FnError } from './api'
4
+
5
+ /** How the client reaches `/_kerf/rt`: SSE, a shared socket, or a fake under test. */
6
+ export interface Link {
7
+ /** Resolves when the connection ends. */
8
+ open(
9
+ body: Body,
10
+ frame: (event: string, data: unknown) => void,
11
+ signal: AbortSignal,
12
+ alive: () => void,
13
+ ): Promise<void>
14
+ change(body: Body): Promise<void>
15
+ }
16
+
17
+ export function transports(handover: () => void) {
18
+ const post = (body: Body, signal?: AbortSignal) =>
19
+ fetch('/_kerf/rt', {
20
+ method: 'POST',
21
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream', 'x-kerf': '1' },
22
+ body: JSON.stringify(body),
23
+ ...(signal && { signal }),
24
+ })
25
+
26
+ const http: Link = {
27
+ async open(body, heard, signal, alive) {
28
+ const res = await post(body, signal)
29
+ if (!res.ok) {
30
+ const { e } = await res.json().catch(() => ({ e: {} }))
31
+ throw new FnError(e, res.status)
32
+ }
33
+ const reader = res.body!.getReader()
34
+ const decoder = new TextDecoder()
35
+ let buf = ''
36
+ for (;;) {
37
+ const { done, value } = await reader.read()
38
+ if (done) return
39
+ alive()
40
+ buf += decoder.decode(value, { stream: true })
41
+ for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) {
42
+ if (buf[0] === ':') continue
43
+ const line = buf.indexOf('\n')
44
+ heard(buf.slice(7, line), JSON.parse(buf.slice(line + 7, i)))
45
+ }
46
+ }
47
+ },
48
+ async change(body) {
49
+ const res = await post(body)
50
+ if (!res.ok) throw new FnError({}, res.status)
51
+ },
52
+ }
53
+
54
+ /** A line on the browser's one socket (link.ts): the same events, and `/_kerf/rt`'s SSE is for a host with no sockets. */
55
+ let line: Line | undefined
56
+ const socket: Link = {
57
+ open(body, heard, signal, alive) {
58
+ return new Promise<void>((done, fail) => {
59
+ const l = (line = openLine(
60
+ 'r',
61
+ JSON.stringify(body),
62
+ (text) => {
63
+ alive()
64
+ const at = text.indexOf(':'),
65
+ event = text.slice(0, at)
66
+ if (event !== 'ping') heard(event, JSON.parse(text.slice(at + 1)))
67
+ },
68
+ (code, reason) => {
69
+ if (line === l) line = undefined
70
+ if (code === HANDOVER) handover()
71
+ if (code === 4000 && reason) fail(new FnError(JSON.parse(reason), 429))
72
+ else done()
73
+ },
74
+ ))
75
+ signal.addEventListener('abort', () => l.close())
76
+ })
77
+ },
78
+ change(body) {
79
+ if (!line) return Promise.reject(new FnError({}, 503))
80
+ line.send(JSON.stringify(body))
81
+ return Promise.resolve()
82
+ },
83
+ }
84
+
85
+ return { http, socket }
86
+ }
@@ -0,0 +1,52 @@
1
+ import type { Derived } from '@kerf-js/core'
2
+ import type { Context, LiveOptions, LiveStatus, Skip, StandardSchemaV1 } from '../data'
3
+ import type { Tracked } from '../hub'
4
+
5
+ export type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : void
6
+ type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : undefined
7
+
8
+ /** Where a stream stands; `done` is the end of a generator. */
9
+ export type StreamStatus = LiveStatus | 'done'
10
+
11
+ /** `stream()`: the input, the message schema and the generator. */
12
+ export interface StreamDef<S, M, A = undefined> {
13
+ input?: S
14
+ /** Checked in dev and tests (C002), and the contract's `message`. */
15
+ message?: StandardSchemaV1<unknown, M>
16
+ auth?: A
17
+ /** `lastEventId`: the last `tracked` id the client saw, on a resume. Stop when `signal` aborts. */
18
+ run: (args: {
19
+ input: Out<S>
20
+ ctx: Context
21
+ signal: AbortSignal
22
+ lastEventId?: string
23
+ }) => AsyncIterable<M | Tracked<M>>
24
+ $id?: string
25
+ }
26
+
27
+ /** `.live()` on a stream: what the value starts as, and how messages fold into it. */
28
+ export interface StreamOptions<M, T> extends LiveOptions {
29
+ /** Keep every message: `fold(acc, message)`. Its state lives in the cache, so a remount finds it. */
30
+ fold?: (acc: T, message: M) => T
31
+ initial?: T
32
+ /** Messages the server holds for a slow client. A fold defaults to 256; without one, the latest wins. */
33
+ buffer?: number
34
+ }
35
+
36
+ /** A stream as a page reads it. */
37
+ export interface Stream<T> {
38
+ /** The latest message, or the fold. */
39
+ readonly value: T
40
+ readonly status: Derived<StreamStatus>
41
+ readonly error: unknown
42
+ }
43
+
44
+ /** What `stream()` returns. */
45
+ export interface StreamFn<I, M> {
46
+ (input: Arg<I>): Stream<M | undefined>
47
+ <T>(input: Arg<I>, options: StreamOptions<M, T> & { initial: T }): Stream<T>
48
+ (input: Arg<I>, options: StreamOptions<M, M>): Stream<M | undefined>
49
+ readonly kind: 'stream'
50
+ readonly $id: string
51
+ }
52
+ type Arg<I> = I | (() => I | Skip)