@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/link.ts ADDED
@@ -0,0 +1,385 @@
1
+ // One browser, one socket (research 45 §5). Every tab gets the same thing it always had, a duplex line of text frames,
2
+ // and only one tab, the leader, holds the WebSocket under them all. `channel.ts`, `live.ts` and `share.ts` ride it and
3
+ // know nothing about tabs: a line is a socket to them, and to the server, which gives each its own connection (mux.ts).
4
+ // That is why `id`, `exceptSelf`, `left`, `limits` and acks all mean what they did: per tab.
5
+ //
6
+ // campaign a Web Lock with a queue, so taking over needs no timer, and a ping for a leader that's frozen, not gone.
7
+ // tab death each tab holds a lock of its own and the leader queues on it: it comes through however the tab went.
8
+ // routing frames go up one BroadcastChannel only the leader reads, and down one per tab, so a frame wakes one tab.
9
+ // wire `f:<line>:<text>`, a prefix and not an envelope: the frame inside is never parsed here.
10
+ // session a socket keeps the cookies of its upgrade, and another tab may have signed in since. A tab that didn't dial
11
+ // asks the server who it is and compares; if they differ, the leader dials again.
12
+ //
13
+ // Without Web Locks every tab leads itself: its own socket, which is what every tab used to have.
14
+
15
+ import {
16
+ NAME,
17
+ campaign,
18
+ freeTab,
19
+ holdTab,
20
+ shareable,
21
+ tab,
22
+ whenGone,
23
+ type Campaign,
24
+ } from './link/election'
25
+ import { arrive, end, endAll, lines, type Mine } from './link/lines'
26
+ export {
27
+ BEAT,
28
+ campaign,
29
+ freeTab,
30
+ holdTab,
31
+ shareable,
32
+ tab,
33
+ whenGone,
34
+ type Campaign,
35
+ } from './link/election'
36
+
37
+ const PING = 20_000,
38
+ DEAD = 45_000,
39
+ BASE = 200,
40
+ CAP = 30_000,
41
+ IDLE = 1000
42
+ /** The line went because the leader did: not the network's fault, so reopen at once. */
43
+ export const HANDOVER = 4900
44
+
45
+ /** What a test reads. */
46
+ export const linkStats = { role: 'none' as 'none' | 'leader' | 'follower', steals: 0, dials: 0 }
47
+
48
+ // ---- lines, as a tab sees them ----------------------------------------------------------------------------------------
49
+
50
+ export interface Line {
51
+ send(text: string): void
52
+ close(): void
53
+ }
54
+
55
+ let nth = 0
56
+
57
+ declare const __KERF_SOCKETS__: boolean | undefined
58
+ /** Whether this deploy can hold a socket. `kerf build` says no for a function host (Netlify, Vercel, Lambda…). */
59
+ export const SOCKETS = typeof __KERF_SOCKETS__ === 'undefined' || __KERF_SOCKETS__
60
+
61
+ /** Sockets that never said hello in a row: the page's way to learn this host has none. */
62
+ export let socketFailures = 0
63
+ /** The one who asked goes round SSE once, and the socket gets another chance after. Where the build said none, always. */
64
+ export const noSockets = () => {
65
+ if (!SOCKETS) return true
66
+ const none = socketFailures >= 2
67
+ if (none) socketFailures = 0
68
+ return none
69
+ }
70
+ export const probeLink = () => election?.probe()
71
+
72
+ /** `c`: a socket's frames (socket.ts). `r`: realtime events, opened with a `/_kerf/rt` body (hub.ts). */
73
+ export function openLine(
74
+ kind: 'c' | 'r',
75
+ hello: string,
76
+ frame: (text: string) => void,
77
+ closed: (code: number, reason?: string) => void,
78
+ ): Line {
79
+ start()
80
+ const id = `${tab}.${++nth}`
81
+ const l: Mine = { id, hello: `o:${id}:${kind}:${hello}`, frame, closed }
82
+ lines.set(id, l)
83
+ say(id, 'o', l.hello)
84
+ if (!election?.leading()) election?.probe()
85
+ return {
86
+ send(text) {
87
+ if (lines.has(id)) say(id, 'f', `f:${id}:${text}`)
88
+ },
89
+ close() {
90
+ if (!lines.has(id)) return
91
+ say(id, 'x', `x:${id}:`)
92
+ end(l, 1000)
93
+ },
94
+ }
95
+ }
96
+
97
+ // ---- up and down the tabs ---------------------------------------------------------------------------------------------
98
+
99
+ type Up = { tab: string; id: string; k: 'o' | 'x' | 'f'; l: string }
100
+ type Note =
101
+ | { t: 'lead' }
102
+ | { t: 'lost'; code: number; never: boolean }
103
+ | { t: 'who'; tab: string }
104
+ | { t: 'you'; to: string; u?: string }
105
+ | { t: 'redial' }
106
+ | { t: 'bye'; tab: string }
107
+
108
+ let running = false
109
+ let notes: BroadcastChannel | undefined
110
+ let down: BroadcastChannel | undefined
111
+ let election: Campaign | undefined
112
+ /** A tab that didn't dial holds its first lines until the session is checked. */
113
+ let gate: Up[] | undefined
114
+
115
+ function say(id: string, k: Up['k'], line: string) {
116
+ const m: Up = { tab, id, k, l: line }
117
+ if (gate) gate.push(m)
118
+ else if (election?.leading()) take(m)
119
+ else if (shareable()) holdTab(() => upTo.postMessage(m))
120
+ // else: this tab leads itself in a moment, and `lead` opens what's here
121
+ }
122
+ let upTo: BroadcastChannel
123
+
124
+ function start() {
125
+ if (running) return
126
+ running = true
127
+ if (shareable()) {
128
+ notes = new BroadcastChannel(NAME)
129
+ notes.onmessage = (e) => note(e.data)
130
+ down = new BroadcastChannel(`${NAME}:down:${tab}`)
131
+ down.onmessage = (e) => arrive(e.data)
132
+ upTo = new BroadcastChannel(`${NAME}:up`)
133
+ }
134
+ listen()
135
+ election = campaign(
136
+ NAME,
137
+ lead,
138
+ () => hangUp(HANDOVER),
139
+ () => void linkStats.steals++,
140
+ )
141
+ linkStats.role = 'follower'
142
+ if (!shareable() || session) return
143
+ gate = []
144
+ checkSession()
145
+ }
146
+
147
+ function note(m: Note) {
148
+ if (m.t === 'lead' && !election?.leading()) {
149
+ linkStats.role = 'follower'
150
+ endAll(HANDOVER)
151
+ } else if (m.t === 'lost') {
152
+ if (election?.leading()) return
153
+ if (m.never) socketFailures++
154
+ endAll(m.code)
155
+ } else if (m.t === 'who') {
156
+ if (election?.leading()) notes!.postMessage({ t: 'you', to: m.tab, u: open ? user : undefined })
157
+ } else if (m.t === 'you' && m.to === tab) theirs?.(m.u)
158
+ else if (m.t === 'redial') {
159
+ if (election?.leading() && ws) lost(ws, HANDOVER, true)
160
+ } else if (m.t === 'bye') dropTab(m.tab)
161
+ }
162
+
163
+ let session: Promise<void> | undefined
164
+ let theirs: ((u: string | undefined) => void) | undefined
165
+
166
+ /** One round trip, once, the first time a tab that didn't dial opens a line: a new socket used to cost the same. */
167
+ function checkSession() {
168
+ const mine = fetch('/_kerf/rt', {
169
+ method: 'POST',
170
+ headers: { 'content-type': 'application/json', 'x-kerf': '1' },
171
+ body: '{"w":1}',
172
+ })
173
+ .then((r) => (r.ok ? r.json() : undefined))
174
+ .then((r) => r?.u as string | undefined)
175
+ .catch(() => undefined)
176
+ const leader = new Promise<string | undefined>((ok) => {
177
+ theirs = ok
178
+ notes!.postMessage({ t: 'who', tab })
179
+ setTimeout(ok, 1000)
180
+ })
181
+ session = Promise.all([mine, leader]).then(([me, them]) => {
182
+ theirs = undefined
183
+ if (me !== undefined && them !== undefined && me !== them) notes!.postMessage({ t: 'redial' })
184
+ const held = gate
185
+ gate = undefined
186
+ for (const m of held ?? []) holdTab(() => (election?.leading() ? take(m) : upTo.postMessage(m)))
187
+ })
188
+ }
189
+
190
+ // ---- the leader -------------------------------------------------------------------------------------------------------
191
+
192
+ let ws: WebSocket | undefined
193
+ let open = false
194
+ let user: string | undefined
195
+ let attempt = 0
196
+ let redialed = 0
197
+ let retry: ReturnType<typeof setTimeout> | undefined
198
+ let ping: ReturnType<typeof setInterval> | undefined
199
+ let dead: ReturnType<typeof setTimeout> | undefined
200
+ let idle: ReturnType<typeof setTimeout> | undefined
201
+ const queue: string[] = []
202
+ /** Which lines each tab has open on this socket. */
203
+ const opened = new Map<string, Set<string>>()
204
+ const ears = new Map<string, BroadcastChannel>()
205
+ let upFrom: BroadcastChannel | undefined
206
+
207
+ const offline = () => !navigator.onLine
208
+ const send = (line: string) => {
209
+ if (open) ws!.send(line)
210
+ else {
211
+ queue.push(line)
212
+ wantSocket()
213
+ }
214
+ }
215
+
216
+ function take(m: Up) {
217
+ let set = opened.get(m.tab)
218
+ if (m.k === 'o') {
219
+ if (!set) {
220
+ opened.set(m.tab, (set = new Set()))
221
+ if (m.tab !== tab) whenGone(m.tab, () => dropTab(m.tab))
222
+ }
223
+ set.add(m.id)
224
+ clearTimeout(idle)
225
+ idle = undefined
226
+ } else if (m.k === 'x') set?.delete(m.id)
227
+ // A line that closed before the socket came never has to be opened.
228
+ if (m.k === 'x' && !open) {
229
+ const hello = queue.findIndex((q) => q.startsWith(`o:${m.id}:`))
230
+ if (hello >= 0) queue.splice(hello, 1)
231
+ } else send(m.l)
232
+ if (![...opened.values()].some((s) => s.size))
233
+ idle ??= setTimeout(() => {
234
+ idle = undefined
235
+ if (ws && ![...opened.values()].some((s) => s.size)) lost(ws, 1000)
236
+ }, IDLE)
237
+ }
238
+
239
+ function dropTab(t: string) {
240
+ const set = opened.get(t)
241
+ if (!set) return
242
+ opened.delete(t)
243
+ ears.get(t)?.close()
244
+ ears.delete(t)
245
+ for (const id of set) take({ tab: t, id, k: 'x', l: `x:${id}:` })
246
+ }
247
+
248
+ function arriveFrom(text: string) {
249
+ clearTimeout(dead)
250
+ dead = setTimeout(() => ws && lost(ws, 1006), DEAD)
251
+ if (text === 'p') return
252
+ if (text[0] === 'h') {
253
+ user = text.slice(2)
254
+ open = true
255
+ attempt = socketFailures = 0
256
+ for (const l of queue.splice(0)) ws!.send(l)
257
+ return
258
+ }
259
+ const owner = text.slice(2, text.indexOf('.', 2))
260
+ // The session this socket has ran out, and the cookies may have moved on: a new socket finds out, once.
261
+ const stale = text[0] === 'x' && text.includes(':4401:') && Date.now() - redialed > 30_000
262
+ if (stale) redialed = Date.now()
263
+ forward(owner, text)
264
+ if (stale && ws) lost(ws, HANDOVER, true)
265
+ }
266
+
267
+ function forward(owner: string, text: string) {
268
+ if (owner === tab) return arrive(text)
269
+ if (text[0] === 'x') opened.get(owner)?.delete(text.slice(2, text.indexOf(':', 2)))
270
+ let ear = ears.get(owner)
271
+ if (!ear) ears.set(owner, (ear = new BroadcastChannel(`${NAME}:down:${owner}`)))
272
+ ear.postMessage(text)
273
+ }
274
+
275
+ function wantSocket() {
276
+ if (!SOCKETS || ws || retry !== undefined || !election?.leading() || offline()) return
277
+ if (!attempt) return dial()
278
+ retry = setTimeout(
279
+ () => {
280
+ retry = undefined
281
+ dial()
282
+ },
283
+ Math.random() * Math.min(CAP, BASE * 2 ** attempt),
284
+ )
285
+ }
286
+
287
+ function dial() {
288
+ if (ws || !election?.leading()) return
289
+ linkStats.dials++
290
+ const s = new WebSocket(
291
+ `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/_kerf/ws?mux=1`,
292
+ )
293
+ ws = s
294
+ s.onmessage = (e) => arriveFrom(e.data)
295
+ s.onclose = () => lost(s, 1006)
296
+ ping = setInterval(() => {
297
+ if (open) s.send('p')
298
+ }, PING)
299
+ dead = setTimeout(() => lost(s, 1006), DEAD)
300
+ }
301
+
302
+ /** Not from the close event alone: offline, that can take as long as it likes, and WebKit's does. */
303
+ function lost(s: WebSocket, code: number, tell = true) {
304
+ if (ws !== s) return
305
+ const never = !open && code === 1006
306
+ ws = undefined
307
+ open = false
308
+ user = undefined
309
+ if (code !== HANDOVER) attempt++
310
+ if (never) socketFailures++
311
+ else if (code === 1006) socketFailures = 0
312
+ s.onmessage = s.onclose = null
313
+ s.close()
314
+ clearInterval(ping)
315
+ clearTimeout(dead)
316
+ queue.length = 0
317
+ opened.clear()
318
+ if (tell) notes?.postMessage({ t: 'lost', code, never })
319
+ endAll(code)
320
+ }
321
+
322
+ /** Offline, close first: a frame queued ahead of the close frame holds it back, and the server never hears. */
323
+ export function socketDown() {
324
+ if (ws) lost(ws, 1006)
325
+ }
326
+
327
+ function hangUp(code: number) {
328
+ clearTimeout(idle)
329
+ clearTimeout(retry)
330
+ idle = retry = undefined
331
+ // Not told: whoever leads next says so, and that ends every line in one go.
332
+ if (ws) lost(ws, code, false)
333
+ else endAll(code)
334
+ upFrom?.close()
335
+ upFrom = undefined
336
+ for (const ear of ears.values()) ear.close()
337
+ ears.clear()
338
+ attempt = 0
339
+ }
340
+
341
+ function lead() {
342
+ linkStats.role = 'leader'
343
+ if (shareable()) {
344
+ upFrom = new BroadcastChannel(`${NAME}:up`)
345
+ upFrom.onmessage = (e) => take(e.data)
346
+ notes!.postMessage({ t: 'lead' })
347
+ }
348
+ // What this tab held for the session check goes straight out, and its lines were waiting on nobody.
349
+ if (gate) {
350
+ const held = gate
351
+ gate = undefined
352
+ for (const m of held) if (m) take(m)
353
+ } else for (const l of lines.values()) take({ tab, id: l.id, k: 'o', l: l.hello })
354
+ }
355
+
356
+ // ---- the page ---------------------------------------------------------------------------------------------------------
357
+
358
+ function halt() {
359
+ if (!running) return
360
+ running = false
361
+ notes?.postMessage({ t: 'bye', tab })
362
+ election?.stop()
363
+ election = undefined
364
+ hangUp(1001)
365
+ for (const bc of [notes, down, upTo]) bc?.close()
366
+ notes = down = undefined
367
+ freeTab()
368
+ gate = undefined
369
+ session = undefined
370
+ linkStats.role = 'none'
371
+ }
372
+
373
+ let listening = false
374
+ function listen() {
375
+ if (listening) return
376
+ listening = true
377
+ addEventListener('pagehide', halt)
378
+ addEventListener('offline', socketDown)
379
+ addEventListener('online', () => {
380
+ clearTimeout(retry)
381
+ retry = undefined
382
+ attempt = 0
383
+ if (queue.length) wantSocket()
384
+ })
385
+ }
@@ -0,0 +1,136 @@
1
+ // The `db.adapter@1` default (research 13 §2.2): a list source over a Drizzle table. `columns` keeps its meaning here,
2
+ // so a table's other columns stay out of what's selected, returned or written.
3
+
4
+ import {
5
+ and,
6
+ asc,
7
+ count,
8
+ desc,
9
+ eq,
10
+ gt,
11
+ inArray,
12
+ isNull,
13
+ lt,
14
+ or,
15
+ sql,
16
+ type Column,
17
+ type SQL,
18
+ } from 'drizzle-orm'
19
+ import {
20
+ likeOf,
21
+ pageOf,
22
+ plan,
23
+ rowOf,
24
+ storedId,
25
+ written,
26
+ type DbAdapter,
27
+ type ListPage,
28
+ type ListParams,
29
+ type ListSource,
30
+ type SourceSpec,
31
+ } from './list'
32
+
33
+ /** The Drizzle client and table a list source runs on. */
34
+ export interface DrizzleTarget {
35
+ db: object
36
+ table: object
37
+ }
38
+
39
+ /** What every dialect's query builders share by name, though no type says so. */
40
+ type Chain = PromiseLike<object[]> & {
41
+ from(t: object): Chain
42
+ where(w?: SQL): Chain
43
+ orderBy(...o: SQL[]): Chain
44
+ limit(n: number): Chain
45
+ offset(n: number): Chain
46
+ values(v: object): Chain
47
+ set(v: object): Chain
48
+ returning(s?: object): Chain
49
+ }
50
+ interface Db {
51
+ select(s: object): Chain
52
+ insert(t: object): Chain
53
+ update(t: object): Chain
54
+ delete(t: object): Chain
55
+ }
56
+
57
+ /** A `ListSource` over a Drizzle table. */
58
+ export function drizzleSource<Row = Record<string, unknown>>(
59
+ { db: handle, table }: DrizzleTarget,
60
+ spec: SourceSpec,
61
+ ): ListSource<Row> {
62
+ const db = handle as Db
63
+ const col = (name: string) => (table as Record<string, Column>)[name]!
64
+ const selection = Object.fromEntries(Object.values(spec.columns).map((c) => [c, col(c)]))
65
+ const public_ = rowOf<Row>(spec)
66
+ const id = col(storedId(spec))
67
+ const reading = (rows: object[]) => rows.map(public_)
68
+ const one = async (query: Chain) => reading(await query)[0] ?? null
69
+ return {
70
+ async list(p: ListParams): Promise<ListPage<Row>> {
71
+ const q = plan(spec, p)
72
+ const filters: (SQL | undefined)[] = q.where.map((w) => {
73
+ const some = w.values.filter((v) => v !== null)
74
+ const hit =
75
+ some.length === 1
76
+ ? eq(col(w.column), some[0])
77
+ : some.length
78
+ ? inArray(col(w.column), some)
79
+ : undefined
80
+ return w.values.includes(null) ? or(hit, isNull(col(w.column))) : hit
81
+ })
82
+ if (q.search)
83
+ filters.push(
84
+ or(
85
+ ...q.search.columns.map(
86
+ (c) => sql`lower(${col(c)}) like ${likeOf(q.search!.text)} escape '!'`,
87
+ ),
88
+ ),
89
+ )
90
+ const where = and(...filters)
91
+ const by = q.sort?.dir === 'desc' ? desc : asc
92
+ const past = q.sort?.dir === 'desc' ? lt : gt
93
+ const keyset = p.after
94
+ ? q.sort
95
+ ? or(
96
+ past(col(q.sort.column), p.after[0]),
97
+ and(eq(col(q.sort.column), p.after[0]), past(id, p.after[1])),
98
+ )
99
+ : past(id, p.after[1])
100
+ : undefined
101
+ const order = q.sort ? [by(col(q.sort.column)), by(id)] : [asc(id)]
102
+ const cursor = p.mode === 'cursor'
103
+ const rows = await db
104
+ .select(selection)
105
+ .from(table)
106
+ .where(and(where, keyset))
107
+ .orderBy(...order)
108
+ .limit(cursor ? p.limit + 1 : p.limit)
109
+ .offset(p.offset)
110
+ const total = cursor
111
+ ? undefined
112
+ : ((await db.select({ n: count() }).from(table).where(where)) as { n: number }[])[0]!.n
113
+ return pageOf(reading(rows), p, { sort: q.sort?.field, id: q.id.field }, total)
114
+ },
115
+ get: (id_) => one(db.select(selection).from(table).where(eq(id, id_)).limit(1)),
116
+ create: async (data) =>
117
+ (await one(
118
+ db
119
+ .insert(table)
120
+ .values(written(spec, data, true))
121
+ .returning(selection),
122
+ ))!,
123
+ update: (id_, patch) => {
124
+ const row = written(spec, patch)
125
+ return one(
126
+ Object.keys(row).length
127
+ ? db.update(table).set(row).where(eq(id, id_)).returning(selection)
128
+ : db.select(selection).from(table).where(eq(id, id_)).limit(1),
129
+ )
130
+ },
131
+ remove: async (id_) => (await db.delete(table).where(eq(id, id_)).returning({ id })).length > 0,
132
+ }
133
+ }
134
+
135
+ /** `db.adapter@1` over a Drizzle table. */
136
+ export const adapter: DbAdapter<DrizzleTarget> = { name: 'drizzle', source: drizzleSource }