@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/share.ts ADDED
@@ -0,0 +1,397 @@
1
+ // `interaction({ share })` past this page (research 45 §4, §5). The only layer that knows tabs and the network, and only
2
+ // an app that shares loads it: the `kerf()` plugin imports it where `share:` is used.
3
+ //
4
+ // tabs every tab posts its bits to one BroadcastChannel and keeps every sibling's, so there's no relay to run.
5
+ // leader one tab holds a Web Lock and the `$share` join, on the same socket and lifecycle as this tab's `channel`s.
6
+ // It sends the OR of the tabs' bits, at most one frame per GAP_NET, each carrying every key that changed.
7
+ // death each tab holds a lock of its own and siblings queue on it: it comes through the moment the tab is gone,
8
+ // crash included, with no heartbeat. Without Web Locks every tab is its own client and ages out by beat.
9
+ // stall a frozen leader keeps its lock, so a tab that gets no pong steals it. Two sockets, briefly, is the failure mode.
10
+ // remote other tabs, plus other clients. Cleared by a zero from the server, by a link down past GRACE, or by TTL.
11
+ //
12
+ // Everything here writes `remote` through `heard`, and only this page's three boxes come in through `set`: an echo has
13
+ // no path. A tab is a pure function of `tabs` and `clients`, and the socket a pure diff against them (`reconcile`), so a
14
+ // new leader runs the code an old one ran.
15
+
16
+ import { tabQueue } from './share/tab-queue'
17
+ import { network, upstream as upstreamOf, wanted as wantedKeys } from './share/network'
18
+ import { receiver } from './share/receive'
19
+ import { render, renderAll, hear, dropClients } from './share/display'
20
+ import { createRoot, effect, untrack } from '@kerf-js/core'
21
+ import { seams, type ShareLine } from '@kerf-js/core/interaction'
22
+ import { connectBuiltIn, keepOpen, wakeSocket } from './channel'
23
+ import {
24
+ lines,
25
+ shown,
26
+ tabs,
27
+ tabAt,
28
+ visible,
29
+ mine,
30
+ watched,
31
+ clients,
32
+ type Triple,
33
+ type Msg,
34
+ } from './share/state'
35
+ import { BEAT, campaign, freeTab, holdTab, probeLink, tab, whenGone, type Campaign } from './link'
36
+
37
+ /** Ms between flushes to the other tabs. */
38
+ export const GAP_TAB = 16
39
+ /** Ms between flushes to the server. */
40
+ export const GAP_NET = 60
41
+ /** Ms a held key stands without being said again. */
42
+ export const TTL = 15_000
43
+ /** Ms what's held stands after the link drops, so a handover doesn't flash. */
44
+ export const GRACE = 1500
45
+ /** Entries one frame carries. */
46
+ export const BATCH = 400
47
+ /** Ms without a change before the socket may close. */
48
+ export const IDLE = 5000
49
+
50
+ /** Bump when a message below changes shape: tabs of two shapes then share nothing, and each is its own client. */
51
+ const WIRE = 1
52
+ const CHANNEL = `kerf:ui:${WIRE}`
53
+
54
+ /** What a test reads: `role`, and how much went where. */
55
+ export const shareStats = {
56
+ role: 'none' as 'none' | 'leader' | 'follower',
57
+ tab,
58
+ conn: undefined as string | undefined,
59
+ handed: 0,
60
+ steals: 0,
61
+ frames: 0,
62
+ keysSent: 0,
63
+ bc: 0,
64
+ }
65
+
66
+ const noLocks = () => typeof navigator === 'undefined' || !navigator.locks
67
+
68
+ const locks = () => !noLocks()
69
+ const leading = () => shareStats.role === 'leader'
70
+ const looking = () => typeof document === 'undefined' || document.visibilityState !== 'hidden'
71
+
72
+ let bc: BroadcastChannel | undefined
73
+ let running = false
74
+ let lockReady = false
75
+ const early: Msg[] = []
76
+ let election: Campaign | undefined
77
+ let timer: ReturnType<typeof setInterval> | undefined
78
+
79
+ function post(m: Msg) {
80
+ if (locks() && !lockReady) return void early.push(m)
81
+ shareStats.bc++
82
+ bc?.postMessage(m)
83
+ }
84
+
85
+ // ---- what a tab shows ------------------------------------------------------------------------------------------------
86
+
87
+ function dropTab(t: string) {
88
+ visible.delete(t)
89
+ if (!tabs.delete(t)) return
90
+ tabAt.delete(t)
91
+ watched.delete(t)
92
+ renderAll()
93
+ reconcile()
94
+ }
95
+
96
+ /** It comes through when the tab is gone, however it went. The tab held it before it first said anything. */
97
+ function watch(t: string) {
98
+ if (t === tab || watched.has(t) || !locks()) return
99
+ watched.add(t)
100
+ whenGone(t, () => dropTab(t))
101
+ }
102
+
103
+ /** Down: what's held stands for GRACE, so a handover doesn't flash. Up: holders re-say, and what nobody re-says goes. */
104
+ let settling: ReturnType<typeof setTimeout> | undefined
105
+ function link(on: boolean) {
106
+ clearTimeout(settling)
107
+ if (on) for (const held of clients.values()) for (const e of held.values()) e.stale = true
108
+ settling = setTimeout(() => dropClients((e) => !on || !!e.stale), GRACE)
109
+ }
110
+
111
+ const wakeIfLeading = () => {
112
+ if (leading()) wakeSocket()
113
+ }
114
+
115
+ function announce() {
116
+ post({
117
+ t: 'tab',
118
+ tab,
119
+ keys: [...mine],
120
+ shown: looking(),
121
+ ...(locks() ? {} : { k: shareStats.conn }),
122
+ })
123
+ }
124
+
125
+ /** 200 rows mounting are one post and one frame. */
126
+ let queued = false
127
+ function changedKeys() {
128
+ if (queued) return
129
+ queued = true
130
+ queueMicrotask(() => {
131
+ queued = false
132
+ if (!running) return
133
+ announce()
134
+ reconcile()
135
+ })
136
+ }
137
+
138
+ // ---- to the other tabs, once a frame ----------------------------------------------------------------------------------
139
+
140
+ const dirtyTab = new Set<string>()
141
+ const queueTab = tabQueue(dirtyTab, mine, post, tab, GAP_TAB)
142
+
143
+ // ---- the leader: the OR of every tab, on one join ---------------------------------------------------------------------
144
+
145
+ type Conn = ReturnType<typeof connectBuiltIn>
146
+ let conn: Conn | undefined
147
+ let stopConn: (() => void) | undefined
148
+ let open = false
149
+ /** key → what the server was last told. In here means asked for. */
150
+ const sent = new Map<string, number>()
151
+ const refused = new Set<string>()
152
+ const dirtyNet = new Set<string>()
153
+ const toAdd = new Set<string>()
154
+ const toDrop = new Set<string>()
155
+ let idle: ReturnType<typeof setTimeout> | undefined
156
+
157
+ const upstream = (key: string) => upstreamOf(key, locks())
158
+ const wanted = () => wantedKeys(locks())
159
+
160
+ const net = network({
161
+ connection: () => conn,
162
+ isOpen: () => open,
163
+ sent,
164
+ refused,
165
+ dirtyNet,
166
+ toAdd,
167
+ toDrop,
168
+ upstream,
169
+ shareStats,
170
+ GAP_NET,
171
+ BATCH,
172
+ })
173
+ const netSoon = net.netSoon
174
+
175
+ /** Whatever changed in `tabs`, the socket follows. Nothing wanted for a while, no socket: a page left its rows behind. */
176
+ function reconcile() {
177
+ if (!leading()) return
178
+ const want = wanted()
179
+ if (want.size) {
180
+ clearTimeout(idle)
181
+ idle = undefined
182
+ dial()
183
+ } else
184
+ idle ??= setTimeout(() => {
185
+ idle = undefined
186
+ if (leading() && !wanted().size) hangUp()
187
+ }, IDLE)
188
+ if (!open) return
189
+ for (const key of want) {
190
+ if (sent.has(key)) {
191
+ if (upstream(key) !== sent.get(key)) dirtyNet.add(key)
192
+ continue
193
+ }
194
+ sent.set(key, 0)
195
+ toDrop.delete(key)
196
+ if (!refused.has(key)) toAdd.add(key)
197
+ if (upstream(key)) dirtyNet.add(key)
198
+ }
199
+ for (const key of Array.from(sent.keys())) {
200
+ if (want.has(key)) continue
201
+ sent.delete(key)
202
+ dirtyNet.delete(key)
203
+ clients.delete(key)
204
+ if (!toAdd.delete(key)) toDrop.add(key)
205
+ }
206
+ if (toAdd.size || toDrop.size || dirtyNet.size) netSoon()
207
+ }
208
+
209
+ function linked(live: boolean) {
210
+ if (live === open) return
211
+ open = live
212
+ if (!live) {
213
+ sent.clear()
214
+ toAdd.clear()
215
+ toDrop.clear()
216
+ dirtyNet.clear()
217
+ refused.clear()
218
+ net.clear()
219
+ }
220
+ link(live)
221
+ post({ t: 'link', up: live })
222
+ if (live) reconcile()
223
+ }
224
+
225
+ function dial() {
226
+ if (conn) return
227
+ stopConn = createRoot((dispose) => {
228
+ conn = connectBuiltIn('$share')
229
+ conn.on('b', ({ s }: { s: Triple[] }) => {
230
+ hear(s, leading())
231
+ if (locks()) post({ t: 'net', s })
232
+ })
233
+ conn.on('ok', (m: { id: string; no: string[] }) => {
234
+ shareStats.conn = m.id
235
+ const lost: Triple[] = []
236
+ for (const k of m.no) {
237
+ refused.add(k)
238
+ dirtyNet.delete(k)
239
+ for (const id of clients.get(k)?.keys() ?? []) lost.push([id, k, 0])
240
+ }
241
+ if (lost.length) {
242
+ hear(lost, leading())
243
+ if (locks()) post({ t: 'net', s: lost })
244
+ }
245
+ if (!locks()) announce()
246
+ })
247
+ effect(
248
+ () => conn!.status.value,
249
+ (s) => linked(s === 'open'),
250
+ )
251
+ return dispose
252
+ }, null)
253
+ }
254
+
255
+ function hangUp() {
256
+ linked(false)
257
+ stopConn?.()
258
+ stopConn = conn = undefined
259
+ shareStats.conn = undefined
260
+ }
261
+
262
+ function lead() {
263
+ shareStats.role = 'leader'
264
+ shareStats.handed++
265
+ link(false)
266
+ post({ t: 'link', up: false })
267
+ post({ t: 'roll' })
268
+ reconcile()
269
+ }
270
+
271
+ // ---- the page --------------------------------------------------------------------------------------------------------
272
+
273
+ function up() {
274
+ if (running) return
275
+ running = true
276
+ bc = new BroadcastChannel(CHANNEL)
277
+ bc.onmessage = (e) => receive(e.data)
278
+ tabs.set(tab, mine)
279
+ holdTab(() => {
280
+ lockReady = true
281
+ for (const m of early.splice(0)) post(m)
282
+ })
283
+ shareStats.role = 'follower'
284
+ election = campaign(
285
+ CHANNEL,
286
+ lead,
287
+ () => {
288
+ hangUp()
289
+ shareStats.role = 'follower'
290
+ },
291
+ () => void shareStats.steals++,
292
+ )
293
+ election.pinged = sayHeld // a hidden leader's own beat is throttled; a sibling's ping isn't
294
+ announce()
295
+ post({ t: 'roll' })
296
+ timer = setInterval(beat, BEAT)
297
+ }
298
+
299
+ function beat() {
300
+ const now = Date.now()
301
+ dropClients((e) => now - e.at > TTL)
302
+ if (!locks()) {
303
+ announce()
304
+ for (const [t, at] of tabAt) if (now - at > TTL) dropTab(t)
305
+ }
306
+ if (leading()) sayHeld()
307
+ }
308
+
309
+ /** A held bit is said again, so that if this instance's server dies, peers age it out. Nothing held, nothing sent. */
310
+ let saidAt = 0
311
+ function sayHeld() {
312
+ if (Date.now() - saidAt < BEAT - 1000) return
313
+ saidAt = Date.now()
314
+ for (const [key, bits] of sent)
315
+ if (bits) {
316
+ sent.set(key, -1)
317
+ dirtyNet.add(key)
318
+ }
319
+ if (dirtyNet.size) netSoon()
320
+ }
321
+
322
+ function halt() {
323
+ if (!running) return
324
+ post({ t: 'bye', tab })
325
+ running = false
326
+ lockReady = false
327
+ hangUp()
328
+ shareStats.role = 'none'
329
+ clearInterval(timer)
330
+ clearTimeout(settling)
331
+ clearTimeout(idle)
332
+ idle = undefined
333
+ election?.stop()
334
+ election = undefined
335
+ freeTab()
336
+ bc?.close()
337
+ bc = undefined
338
+ tabs.clear()
339
+ tabAt.clear()
340
+ visible.clear()
341
+ watched.clear()
342
+ clients.clear()
343
+ }
344
+
345
+ const receive = receiver({
346
+ dropClients,
347
+ watch,
348
+ reconcile,
349
+ wakeIfLeading,
350
+ leading,
351
+ post,
352
+ announce,
353
+ dropTab,
354
+ link,
355
+ })
356
+
357
+ if (typeof window !== 'undefined') {
358
+ addEventListener('pagehide', halt)
359
+ addEventListener('pageshow', (e) => {
360
+ if (!e.persisted || !lines.size) return
361
+ up()
362
+ renderAll()
363
+ })
364
+ document.addEventListener('visibilitychange', () => {
365
+ if (running) post({ t: 'shown', tab, shown: looking() })
366
+ })
367
+ keepOpen.stay = () => [...visible.values()].some(Boolean)
368
+ }
369
+
370
+ seams.line = (key, heard): ShareLine => {
371
+ lines.set(key, heard)
372
+ mine.set(key, 0)
373
+ if (!running) up()
374
+ changedKeys()
375
+ untrack(() => render(key))
376
+ return {
377
+ set(bits) {
378
+ mine.set(key, bits)
379
+ queueTab(key)
380
+ if (!running) return
381
+ reconcile()
382
+ if (bits && !leading()) {
383
+ election?.probe()
384
+ probeLink()
385
+ }
386
+ },
387
+ leave() {
388
+ lines.delete(key)
389
+ shown.delete(key)
390
+ mine.delete(key)
391
+ dirtyTab.delete(key)
392
+ if (!running) return
393
+ if (!leading()) clients.delete(key)
394
+ changedKeys()
395
+ },
396
+ }
397
+ }
package/src/sheets.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // A page's stylesheets as two files: what every route shares, and what its own route adds, each hashed and cached for
2
+ // good. A build splits CSS by chunk, so a page would link 5 to 11 sheets. Only what's on every route is shared, so no
3
+ // route's CSS can reach a page it wasn't written for. The chunks' own sheets stay: a client route change fetches those.
4
+
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { dirname, resolve } from 'node:path'
8
+
9
+ /** A relative `url()` means something else from another file, and that file keeps its own link. */
10
+ const movable = (css) =>
11
+ !/url\(\s*(?!["']?(?:\/|data:|https?:|#|%23))/.test(css) && !/@import\b/.test(css)
12
+
13
+ /**
14
+ * @param {string[][]} routes each route's sheets, in cascade order
15
+ * @param {(name: string) => string} text
16
+ */
17
+ export function planSheets(routes, text) {
18
+ const files = {}
19
+ const join = (has) => {
20
+ if (!has.length) return undefined
21
+ const css = has.map(text).join('')
22
+ const file = `assets/sheet-${createHash('sha256').update(css).digest('base64url').slice(0, 8)}.css`
23
+ files[file] = css
24
+ return { file, has }
25
+ }
26
+ const everywhere = (n) => routes.every((r) => r.includes(n))
27
+ const shared = join([...new Set(routes.flat())].filter((n) => everywhere(n) && movable(text(n))))
28
+ const seen = new Map()
29
+ for (const list of routes) {
30
+ const route = join([...new Set(list)].filter((n) => !everywhere(n) && movable(text(n))))
31
+ if (route) seen.set(route.file, route)
32
+ }
33
+ return { shared, routes: [...seen.values()], files }
34
+ }
35
+
36
+ const FROM = /(?:^|\n)\s*(?:import|export)\s[^'"\n]*?from\s+['"](\.[^'"]+)['"]/g
37
+ const EXTS = ['', '.tsx', '.ts', '.jsx', '.js', '/index.tsx', '/index.ts']
38
+
39
+ /** The app's own source files `files` import: where the islands a route can show are declared. */
40
+ export function reach(files) {
41
+ const seen = new Set()
42
+ const walk = (f) => {
43
+ if (seen.has(f)) return
44
+ seen.add(f)
45
+ for (const [, spec] of readFileSync(f, 'utf8').matchAll(FROM)) {
46
+ const to = EXTS.map((e) => resolve(dirname(f), spec) + e).find(
47
+ (c) => /\.[jt]sx?$/.test(c) && existsSync(c),
48
+ )
49
+ if (to) walk(to)
50
+ }
51
+ }
52
+ files.filter(existsSync).forEach(walk)
53
+ return seen
54
+ }
55
+
56
+ /** Which of the plan's sheets a page's list goes in. What neither holds keeps its own link. */
57
+ export function pick(plan, list) {
58
+ const left = new Set(list)
59
+ const out = []
60
+ if (plan.shared?.has.some((n) => left.has(n))) {
61
+ out.push(plan.shared)
62
+ plan.shared.has.forEach((n) => left.delete(n))
63
+ }
64
+ let best,
65
+ most = 0
66
+ for (const r of plan.routes) {
67
+ const hits = r.has.filter((n) => left.has(n)).length
68
+ if (hits > most && r.has.every((n) => list.includes(n) || left.has(n))) {
69
+ best = r
70
+ most = hits
71
+ }
72
+ }
73
+ if (!best)
74
+ for (const r of plan.routes) {
75
+ // a route's sheet may hold a little more than this page showed: never another route's
76
+ const hits = r.has.filter((n) => left.has(n)).length
77
+ if (hits > most) {
78
+ best = r
79
+ most = hits
80
+ }
81
+ }
82
+ if (best) {
83
+ out.push(best)
84
+ best.has.forEach((n) => left.delete(n))
85
+ }
86
+ return { sheets: out, rest: list.filter((n) => left.has(n)) }
87
+ }
@@ -0,0 +1,170 @@
1
+ import {
2
+ copyFileSync,
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { randomBytes } from 'node:crypto'
12
+ import { basename, join, relative, resolve } from 'node:path'
13
+ import { cargo, checkWasm } from './cargo.mjs'
14
+ import { launch, stop } from './process.mjs'
15
+ import { buildable, crateDir, isNative, stem, urlVariable } from './common.mjs'
16
+
17
+ // ---- build --------------------------------------------------------------------------------------------------------
18
+
19
+ const BUILT = ['.kerf', 'sidecars'] // a build empties `.output`, and these have to run during it
20
+ const SHIPPED = ['.output', 'rust']
21
+ const SHIPPED_NATIVE = ['.output', 'server', 'rust'] // with the server, so a host that moves it moves these
22
+
23
+ /** Release binaries into `.kerf/sidecars/`, and what `kerf start` needs to run them. */
24
+ export async function buildSidecars({ root, contract, rust, preset, log = () => {} }) {
25
+ root = resolve(root)
26
+ const out = join(root, ...BUILT)
27
+ const services = buildable(contract, rust)
28
+ rmSync(out, { recursive: true, force: true })
29
+ if (!services.length) return { services: [], diagnostics: [] }
30
+ mkdirSync(out, { recursive: true })
31
+ const manifest = {}
32
+ const diagnostics = []
33
+ for (const service of services) {
34
+ const dir = crateDir(root, rust, service)
35
+ if (!existsSync(dir)) {
36
+ diagnostics.push({
37
+ code: 'R109',
38
+ severity: 'error',
39
+ file: 'kerf.config.ts',
40
+ span: [1, 1, 1, 1],
41
+ why: `\`rust://${service}\` has no crate at \`${relative(root, dir)}\`. Create it, point \`rust.services.${service}.crate\` at it, or set \`external: true\`.`,
42
+ })
43
+ continue
44
+ }
45
+ log(`building ${service}…`)
46
+ const built = await cargo('build', { root, dir, service, contract, release: true })
47
+ if (!built.ok || !(built.exe || built.lib)) {
48
+ diagnostics.push(...built.diagnostics)
49
+ continue
50
+ }
51
+ if (isNative(contract, service)) {
52
+ const addon = `${stem(service)}.${process.platform}-${process.arch}.node`
53
+ copyFileSync(built.lib, join(out, addon))
54
+ manifest[service] = {
55
+ kind: 'native',
56
+ addon,
57
+ hash: contract.services[service].hash,
58
+ bytes: statSync(built.lib).size,
59
+ }
60
+ const wasm = await checkWasm({ root, dir, service, contract, preset, rust, build: true })
61
+ diagnostics.push(...wasm.diagnostics)
62
+ if (wasm.lib) {
63
+ copyFileSync(wasm.lib, join(out, `${stem(service)}.wasm`))
64
+ Object.assign(manifest[service], {
65
+ wasm: `${stem(service)}.wasm`,
66
+ wasmBytes: statSync(wasm.lib).size,
67
+ })
68
+ }
69
+ continue
70
+ }
71
+ const bin = basename(built.exe)
72
+ copyFileSync(built.exe, join(out, bin))
73
+ manifest[service] = {
74
+ bin,
75
+ hash: contract.services[service].hash,
76
+ bytes: statSync(built.exe).size,
77
+ }
78
+ }
79
+ writeFileSync(join(out, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n')
80
+ return { services: Object.keys(manifest), diagnostics }
81
+ }
82
+
83
+ /** Into the output, once the server is built. */
84
+ export function shipSidecars(root) {
85
+ const from = join(resolve(root), ...BUILT)
86
+ if (!existsSync(from)) return
87
+ const manifest = JSON.parse(readFileSync(join(from, 'manifest.json'), 'utf8'))
88
+ const natives = Object.entries(manifest).filter(([, m]) => m.kind === 'native')
89
+ const sidecars = Object.entries(manifest).filter(([, m]) => m.kind !== 'native')
90
+ const copy = (list, to, names) => {
91
+ if (!list.length) return
92
+ mkdirSync(to, { recursive: true })
93
+ for (const [, m] of list) for (const f of names(m)) cpSync(join(from, f), join(to, f))
94
+ writeFileSync(
95
+ join(to, 'manifest.json'),
96
+ JSON.stringify(Object.fromEntries(list), null, 2) + '\n',
97
+ )
98
+ }
99
+ copy(sidecars, join(resolve(root), ...SHIPPED), (m) => [m.bin])
100
+ copy(natives, join(resolve(root), ...SHIPPED_NATIVE), (m) => [m.addon, m.wasm].filter(Boolean))
101
+ }
102
+
103
+ // ---- start --------------------------------------------------------------------------------------------------------
104
+
105
+ /**
106
+ * Run `.output/rust/`'s binaries for `kerf start` (or `built`'s, while `kerf build` prerenders). A service with `KERF_RUST_<NAME>_URL` already set is someone else's.
107
+ * Each keeps its port across restarts, so the server's address stays good.
108
+ * @returns {Promise<{ env: Record<string, string>, close(): void }>} `env` for the server process
109
+ */
110
+ export async function startSidecars({ root, built = false, log = console.log }) {
111
+ const dir = join(resolve(root), ...(built ? BUILT : SHIPPED))
112
+ const file = join(dir, 'manifest.json')
113
+ if (!existsSync(file)) return { env: {}, close() {} }
114
+ const manifest = JSON.parse(readFileSync(file, 'utf8'))
115
+ const names = Object.keys(manifest).filter(
116
+ (s) => manifest[s].kind !== 'native' && !process.env[urlVariable(s)],
117
+ )
118
+ // While a build prerenders, the libraries aren't next to a server yet.
119
+ const paths =
120
+ built && Object.values(manifest).some((m) => m.kind === 'native')
121
+ ? { KERF_NATIVE_DIR: dir }
122
+ : {}
123
+ if (!names.length) return { env: paths, close() {} }
124
+ const secret = process.env.KERF_RUST_SECRET || randomBytes(32).toString('hex')
125
+ const env = { ...paths, KERF_RUST_SECRET: secret }
126
+ let closed = false
127
+ const live = new Map()
128
+
129
+ const supervise = (service) => {
130
+ const { bin, hash } = manifest[service]
131
+ let listen = '127.0.0.1:0',
132
+ tries = 0,
133
+ up
134
+ const begin = async () => {
135
+ up = Date.now()
136
+ const p = await launch({
137
+ exe: join(dir, bin),
138
+ service,
139
+ hash,
140
+ listen,
141
+ secret,
142
+ log,
143
+ onExit: (code, signal) => again(`exited (${signal ?? code})`),
144
+ })
145
+ listen = `127.0.0.1:${p.port}` // restarts rebind what the first start got
146
+ live.set(service, p)
147
+ return p
148
+ }
149
+ const again = (why) => {
150
+ if (closed) return
151
+ // One that ran for a while starts over; one that dies at once backs off.
152
+ tries = Date.now() - up > 30_000 ? 1 : tries + 1
153
+ const wait = Math.min(100 * 2 ** tries, 5_000)
154
+ log(`[kerf] ${service} ${why}: restarting in ${wait} ms`)
155
+ setTimeout(() => {
156
+ if (!closed) begin().catch((e) => again(e.message.split('\n')[0]))
157
+ }, wait)
158
+ }
159
+ return begin()
160
+ }
161
+
162
+ for (const service of names) env[urlVariable(service)] = (await supervise(service)).url
163
+
164
+ const killAll = () => {
165
+ closed = true
166
+ for (const p of live.values()) stop(p, 1_000)
167
+ }
168
+ process.once('exit', killAll)
169
+ return { env, close: killAll }
170
+ }