@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201

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 (148) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2184 -54
  3. package/dist/index.js +11515 -2399
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +276 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +421 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +434 -0
  11. package/dist/types.d.ts +688 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +35 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/events/index.ts +2 -1
  25. package/src/modules/auth/index.ts +59 -20
  26. package/src/modules/cache/index.ts +112 -32
  27. package/src/modules/cache/types.ts +2 -2
  28. package/src/modules/crdt/crdt-field.ts +294 -0
  29. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  30. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  31. package/src/modules/crdt/index.ts +463 -0
  32. package/src/modules/crdt/loro-loader.ts +25 -0
  33. package/src/modules/data/data.hydration.test.ts +142 -0
  34. package/src/modules/data/data.membership.test.ts +462 -0
  35. package/src/modules/data/data.rebind.test.ts +147 -0
  36. package/src/modules/data/data.run.test.ts +113 -0
  37. package/src/modules/data/data.settled-writes.test.ts +206 -0
  38. package/src/modules/data/data.status.test.ts +249 -0
  39. package/src/modules/data/id-set-plan.test.ts +122 -0
  40. package/src/modules/data/index.ts +1580 -130
  41. package/src/modules/data/mutation-id.test.ts +25 -0
  42. package/src/modules/data/mutation-id.ts +35 -0
  43. package/src/modules/data/window-query.test.ts +52 -0
  44. package/src/modules/data/window-query.ts +194 -0
  45. package/src/modules/devtools/flags.ts +349 -0
  46. package/src/modules/devtools/index.ts +386 -37
  47. package/src/modules/devtools/notify-throttle.test.ts +149 -0
  48. package/src/modules/devtools/storage-info.test.ts +79 -0
  49. package/src/modules/devtools/storage-info.ts +168 -0
  50. package/src/modules/devtools/versions.test.ts +74 -0
  51. package/src/modules/devtools/versions.ts +110 -0
  52. package/src/modules/feature-flag/index.test.ts +251 -0
  53. package/src/modules/feature-flag/index.ts +308 -0
  54. package/src/modules/ref-tables.test.ts +91 -0
  55. package/src/modules/ref-tables.ts +88 -0
  56. package/src/modules/sync/engine.ts +101 -37
  57. package/src/modules/sync/events/index.ts +9 -2
  58. package/src/modules/sync/queue/queue-down.test.ts +107 -0
  59. package/src/modules/sync/queue/queue-down.ts +35 -6
  60. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  61. package/src/modules/sync/queue/queue-up.ts +241 -57
  62. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  63. package/src/modules/sync/scheduler.retry.test.ts +156 -0
  64. package/src/modules/sync/scheduler.ts +158 -11
  65. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  66. package/src/modules/sync/sync.health.test.ts +149 -0
  67. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  68. package/src/modules/sync/sync.live-removal.test.ts +134 -0
  69. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  70. package/src/modules/sync/sync.subquery.test.ts +82 -0
  71. package/src/modules/sync/sync.ts +1558 -99
  72. package/src/modules/sync/utils.test.ts +269 -2
  73. package/src/modules/sync/utils.ts +201 -17
  74. package/src/otel/index.ts +13 -10
  75. package/src/services/blobs/blob-cache.test.ts +359 -0
  76. package/src/services/blobs/blob-cache.ts +603 -0
  77. package/src/services/blobs/blob-manifest.ts +227 -0
  78. package/src/services/blobs/blob-store.test.ts +77 -0
  79. package/src/services/blobs/blob-store.ts +359 -0
  80. package/src/services/blobs/blob.fixture.ts +90 -0
  81. package/src/services/blobs/index.ts +70 -0
  82. package/src/services/database/cache-engine.ts +160 -0
  83. package/src/services/database/connection-supervisor.test.ts +289 -0
  84. package/src/services/database/connection-supervisor.ts +415 -0
  85. package/src/services/database/database.query-timeout.test.ts +83 -0
  86. package/src/services/database/database.ts +32 -12
  87. package/src/services/database/engine-factory.ts +33 -0
  88. package/src/services/database/events/index.ts +2 -1
  89. package/src/services/database/index.ts +7 -0
  90. package/src/services/database/local-migrator.ts +30 -27
  91. package/src/services/database/local.test.ts +64 -0
  92. package/src/services/database/local.ts +478 -67
  93. package/src/services/database/plan-render.test.ts +159 -0
  94. package/src/services/database/plan-render.ts +108 -0
  95. package/src/services/database/relation-resolver.test.ts +413 -0
  96. package/src/services/database/relation-resolver.ts +0 -0
  97. package/src/services/database/remote.ts +110 -14
  98. package/src/services/database/sqlite-cache-engine.test.ts +558 -0
  99. package/src/services/database/sqlite-cache-engine.ts +1257 -0
  100. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  101. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  102. package/src/services/database/sqlite-open.test.ts +150 -0
  103. package/src/services/database/sqlite-open.ts +164 -0
  104. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  105. package/src/services/database/sqlite-plan-sql.ts +106 -0
  106. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  107. package/src/services/database/sqlite-select.test.ts +246 -0
  108. package/src/services/database/sqlite-select.ts +121 -0
  109. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  110. package/src/services/database/sqlite-transport.ts +221 -0
  111. package/src/services/database/sqlite-worker.ts +437 -0
  112. package/src/services/database/surql-translate.ts +416 -0
  113. package/src/services/database/surreal-cache-engine.ts +141 -0
  114. package/src/services/logger/index.ts +3 -2
  115. package/src/services/persistence/localstorage.ts +2 -2
  116. package/src/services/persistence/resilient.ts +11 -4
  117. package/src/services/persistence/surrealdb.ts +10 -10
  118. package/src/services/stream-processor/index.ts +444 -52
  119. package/src/services/stream-processor/permissions.test.ts +47 -0
  120. package/src/services/stream-processor/permissions.ts +53 -0
  121. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  122. package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
  123. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  124. package/src/services/stream-processor/wasm-types.ts +23 -2
  125. package/src/services/tabs/broker-client.ts +283 -0
  126. package/src/services/tabs/broker.test.ts +278 -0
  127. package/src/services/tabs/coordinator.test.ts +244 -0
  128. package/src/services/tabs/coordinator.ts +576 -0
  129. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  130. package/src/services/tabs/leader-locks.ts +75 -0
  131. package/src/services/tabs/protocol.ts +242 -0
  132. package/src/services/tabs/support.ts +36 -0
  133. package/src/services/tabs/tabs-broker-worker.ts +586 -0
  134. package/src/sp00ky.auth-order.test.ts +92 -0
  135. package/src/sp00ky.init-query.test.ts +183 -0
  136. package/src/sp00ky.ts +1543 -0
  137. package/src/types.ts +496 -13
  138. package/src/utils/blurhash.ts +90 -0
  139. package/src/utils/error-classification.test.ts +44 -0
  140. package/src/utils/error-classification.ts +7 -0
  141. package/src/utils/index.ts +73 -13
  142. package/src/utils/parser.ts +3 -2
  143. package/src/utils/semver.test.ts +32 -0
  144. package/src/utils/semver.ts +30 -0
  145. package/src/utils/surql.ts +30 -18
  146. package/src/utils/withRetry.test.ts +1 -1
  147. package/tsdown.config.ts +86 -1
  148. package/src/spooky.ts +0 -395
@@ -0,0 +1,437 @@
1
+ /// <reference lib="webworker" />
2
+ /**
3
+ * Dedicated Web Worker that owns the SQLite-WASM handle. All DB access is
4
+ * funnelled through here (the main thread never touches the wasm module), which
5
+ * is also what the OPFS VFS requires — file access must happen off the main
6
+ * thread. Persistence uses the **OPFS SAHPool VFS**: durable, and (unlike the
7
+ * classic OPFS VFS) it does NOT require COOP/COEP cross-origin isolation
8
+ * headers, so host apps embedding the client need no server changes. When OPFS
9
+ * is unavailable it retries, then falls back to an in-memory DB and REPORTS the
10
+ * loss of durability (see `sqlite-open.ts`) instead of degrading silently.
11
+ *
12
+ * Message protocol (request/response keyed by `id`; replies go to the channel
13
+ * the request arrived on):
14
+ * { id, type: 'open', payload: { dbName, useOpfs, workerLockName? } }
15
+ * -> { id, ok, persisted, opfsError? }
16
+ * { id, type: 'exec', payload: { sql, bind } } -> { id, ok, rows }
17
+ * { id, type: 'run', payload: { sql, bind } } -> { id, ok }
18
+ * { id, type: 'batch', payload: [{ sql, bind }] } (atomic BEGIN/COMMIT)
19
+ * { id, type: 'select', payload: { plan, params } } -> { id, ok, rows, relationFetches }
20
+ * { id, type: 'close' }
21
+ * { id, type: 'shutdown' } (owner only: close + pauseVfs + self.close)
22
+ * { id, type: 'relock', payload: { workerLockName } } (owner only)
23
+ * { id, type: 'add-client', payload: { clientId } } + ev.ports[0] (owner only)
24
+ * { id, type: 'remove-client', payload: { clientId } } (owner only)
25
+ *
26
+ * Multi-client (shared-tabs mode): the OWNER (the leader tab's engine) speaks
27
+ * on the worker's own channel and controls the lifecycle. Follower tabs get a
28
+ * MessagePort each (`add-client`) and may only issue data ops
29
+ * (exec/run/batch/select). Every op, from any channel, runs through ONE op
30
+ * chain so an async `select` from one client can never interleave with another
31
+ * client's `batch` at the VFS layer.
32
+ *
33
+ * Leader fencing (shared-tabs mode): `open` may carry `workerLockName`, a Web
34
+ * Lock this worker acquires BEFORE opening the pool and holds for the DB's
35
+ * lifetime. The name is unique per leadership, so the lock being gone has
36
+ * exactly one meaning: the broker stole it because this tab was presumed dead
37
+ * (usually frozen). When that happens the worker FENCES itself: closes the DB,
38
+ * releases the OPFS sync access handles (pauseVfs), tells the owner, and
39
+ * refuses every further op. A frozen-then-thawed ex-leader therefore can never
40
+ * write the durable file after a new leader took over. The thaw gate below
41
+ * closes the wake-up ordering race where a queued write could run before the
42
+ * lock-loss callback fires.
43
+ *
44
+ * `select` executes a whole QueryPlan — table creation, base select, the full
45
+ * `.related()` tree (shared `resolveRelations`), and JSON row parsing — in ONE
46
+ * round-trip, returning structured-clone row objects. This is the first-load
47
+ * hot path; the per-statement ops remain for the write/shim paths.
48
+ */
49
+ import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
50
+ import {
51
+ openDb,
52
+ type OpenDbOptions,
53
+ type SqliteDbHandle,
54
+ type SqlitePoolHandle,
55
+ } from './sqlite-open';
56
+ import { executeSelect, type SelectDb } from './sqlite-select';
57
+
58
+ interface Stmt {
59
+ sql: string;
60
+ bind?: unknown[];
61
+ }
62
+
63
+ interface PostTarget {
64
+ postMessage: (msg: unknown) => void;
65
+ }
66
+
67
+ let db: SqliteDbHandle | null = null;
68
+ let pool: SqlitePoolHandle | null = null;
69
+
70
+ // ==================== leader fencing (worker web lock) ====================
71
+
72
+ /** Once fenced, every op is refused and the DB stays closed. Terminal. */
73
+ let fenced = false;
74
+
75
+ interface HeldLock {
76
+ name: string;
77
+ /** Release on purpose; the closure-local flag keeps the steal handler from
78
+ * mistaking it for a takeover. Idempotent. */
79
+ release: () => void;
80
+ }
81
+
82
+ /** The per-leadership lock currently held (null = no fencing active). A
83
+ * relock (same-leader re-promotion after a broker restart) briefly holds two
84
+ * locks: the new one is installed here first, then the old one's own release
85
+ * is called, so there is no window where neither is held. */
86
+ let currentLock: HeldLock | null = null;
87
+
88
+ function workerLocks(): LockManager | null {
89
+ const nav = (globalThis as { navigator?: { locks?: LockManager } }).navigator;
90
+ return nav?.locks && typeof nav.locks.request === 'function' ? nav.locks : null;
91
+ }
92
+
93
+ /**
94
+ * Acquire `name` exclusively without waiting. Resolves with a handle when
95
+ * granted, null when someone else holds it. If the request settles while the
96
+ * holder still believes it owns the lock, the broker stole it: fence.
97
+ */
98
+ function acquireWorkerLock(name: string): Promise<HeldLock | null> {
99
+ const locks = workerLocks();
100
+ // No Web Locks (non-browser test env): no fencing, behave as before.
101
+ if (!locks) return Promise.resolve({ name, release() {} });
102
+ return new Promise<HeldLock | null>((resolve) => {
103
+ let granted = false;
104
+ let intentional = false;
105
+ let releaseGrant: (() => void) | null = null;
106
+ locks
107
+ .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
108
+ if (!lock) {
109
+ resolve(null);
110
+ return;
111
+ }
112
+ granted = true;
113
+ resolve({
114
+ name,
115
+ release() {
116
+ intentional = true;
117
+ releaseGrant?.();
118
+ },
119
+ });
120
+ return new Promise<void>((release) => {
121
+ releaseGrant = release;
122
+ });
123
+ })
124
+ .then(
125
+ () => {
126
+ if (granted && !intentional) void fence('worker lock stolen');
127
+ },
128
+ () => {
129
+ if (granted && !intentional) void fence('worker lock request failed');
130
+ }
131
+ );
132
+ });
133
+ }
134
+
135
+ function releaseHeldLock(): void {
136
+ currentLock?.release();
137
+ currentLock = null;
138
+ }
139
+
140
+ /**
141
+ * Terminal teardown after leadership loss. Closing the DB first makes
142
+ * pauseVfs legal (it throws while files are open); pausing releases the sync
143
+ * access handles so the NEW leader's open succeeds without waiting for this
144
+ * worker to be garbage collected.
145
+ */
146
+ async function fence(reason: string): Promise<void> {
147
+ if (fenced) return;
148
+ fenced = true;
149
+ // Deliberately console, not a logger: this must be visible in any host app
150
+ // regardless of its configured log level.
151
+ // oxlint-disable-next-line no-console
152
+ console.error(
153
+ `[sp00ky] sqlite worker fenced (${reason}): leadership was taken over, ` +
154
+ 'closing the database and refusing further ops.'
155
+ );
156
+ try {
157
+ db?.close();
158
+ } catch {
159
+ /* already closed */
160
+ }
161
+ db = null;
162
+ try {
163
+ pool?.pauseVfs?.();
164
+ } catch {
165
+ /* pool already torn down or files still open; new leader retries anyway */
166
+ }
167
+ pool = null;
168
+ try {
169
+ (self as unknown as Worker).postMessage({ type: 'lock-lost', reason });
170
+ } catch {
171
+ /* owner gone */
172
+ }
173
+ releaseHeldLock();
174
+ self.close();
175
+ }
176
+
177
+ // ==================== thaw gate ====================
178
+
179
+ /**
180
+ * A frozen tab's worker resumes with its message queue intact, and a queued
181
+ * write could run BEFORE the lock-steal callback fires. Both the 1s interval
182
+ * and every op call `noteTick()`; whichever runs first after a long gap kicks
183
+ * off a lock verification, and ops await it before touching the DB. The gap
184
+ * threshold must stay BELOW the broker's pong timeout: a freeze shorter than
185
+ * the threshold cannot have triggered a steal yet, so skipping the check for
186
+ * small gaps is safe.
187
+ */
188
+ const FREEZE_SUSPECT_MS = 10_000;
189
+ let lastTickAt = performance.now();
190
+ let thawVerification: Promise<void> | null = null;
191
+
192
+ function noteTick(): void {
193
+ const now = performance.now();
194
+ const gap = now - lastTickAt;
195
+ lastTickAt = now;
196
+ if (gap > FREEZE_SUSPECT_MS && currentLock && !fenced && !thawVerification) {
197
+ thawVerification = verifyLockStillHeld().finally(() => {
198
+ thawVerification = null;
199
+ });
200
+ }
201
+ }
202
+ setInterval(noteTick, 1000);
203
+
204
+ async function verifyLockStillHeld(): Promise<void> {
205
+ const locks = workerLocks();
206
+ const name = currentLock?.name;
207
+ if (!locks || !name || typeof locks.query !== 'function') return;
208
+ try {
209
+ const state = await locks.query();
210
+ const stillHeld = (state.held ?? []).some((l) => l.name === name);
211
+ if (!stillHeld) await fence('lock missing after suspected freeze');
212
+ } catch {
213
+ /* query unavailable: fall back to the steal callback */
214
+ }
215
+ }
216
+
217
+ // ==================== db ops ====================
218
+
219
+ async function open(
220
+ dbName: string,
221
+ useOpfs: boolean,
222
+ systemTables: readonly string[] = [],
223
+ workerLockName?: string,
224
+ openOptions?: OpenDbOptions
225
+ ): Promise<{ persisted: boolean; opfsError?: string }> {
226
+ if (workerLockName) {
227
+ const handle = await acquireWorkerLock(workerLockName);
228
+ if (!handle) throw new Error('worker-lock-unavailable');
229
+ releaseHeldLock();
230
+ currentLock = handle;
231
+ }
232
+ const sqlite3: any = await sqlite3InitModule();
233
+ // Retry/fallback policy (and the loud report when persistence is lost) lives
234
+ // in `sqlite-open.ts` so it can be unit tested off-worker.
235
+ const result = await openDb(sqlite3, dbName, useOpfs, openOptions ?? {});
236
+ db = result.db;
237
+ pool = result.pool ?? null;
238
+ // Physically create the internal `_00_*` tables the client reads before any
239
+ // write (DEFINE is a noop on this engine, so the migrator can't). Prevents
240
+ // "no such table: _00_query" on a fresh bucket right after signup.
241
+ for (const t of systemTables) {
242
+ db!.exec({ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
243
+ }
244
+ // Retry (rather than instantly failing with SQLITE_BUSY=5) if a lock is held.
245
+ // Combined with the single-flight op chain, overlap is avoided.
246
+ // `cache_size` is negated → KiB (here 32 MiB) so SQLite's page cache can't
247
+ // grow unbounded and starve a wasm-heavy renderer.
248
+ try {
249
+ db!.exec({ sql: 'PRAGMA busy_timeout = 5000; PRAGMA cache_size = -32000;' });
250
+ } catch {
251
+ /* pragma best-effort */
252
+ }
253
+ return { persisted: result.persisted, opfsError: result.opfsError };
254
+ }
255
+
256
+ function closeDb(): void {
257
+ db?.close();
258
+ db = null;
259
+ pool = null;
260
+ selectDb.knownTables.clear();
261
+ // The lock is scoped to (bucket, leadership); a same-worker bucket switch
262
+ // closes then reopens under a NEW name, so the old one must go now.
263
+ releaseHeldLock();
264
+ }
265
+
266
+ function exec(sql: string, bind?: unknown[]): unknown[] {
267
+ if (!db) throw new Error('sqlite: DB not open');
268
+ return db.exec({ sql, bind, rowMode: 'object', returnValue: 'resultRows' }) as unknown[];
269
+ }
270
+
271
+ function run(sql: string, bind?: unknown[]): void {
272
+ if (!db) throw new Error('sqlite: DB not open');
273
+ db.exec({ sql, bind });
274
+ }
275
+
276
+ function batch(stmts: Stmt[]): void {
277
+ if (!db) throw new Error('sqlite: DB not open');
278
+ db.exec({ sql: 'BEGIN' });
279
+ try {
280
+ for (const s of stmts) db.exec({ sql: s.sql, bind: s.bind });
281
+ db.exec({ sql: 'COMMIT' });
282
+ } catch (e) {
283
+ try {
284
+ db.exec({ sql: 'ROLLBACK' });
285
+ } catch {
286
+ /* ignore */
287
+ }
288
+ throw e;
289
+ }
290
+ }
291
+
292
+ // ==================== worker-side plan execution ('select') ====================
293
+
294
+ /** DB handle for `executeSelect` (see `sqlite-select.ts`, the unit-testable
295
+ * plan executor). `knownTables` is cleared on open/close, which covers both
296
+ * the solo fresh-worker path and the shared-mode same-worker bucket switch. */
297
+ const selectDb: SelectDb = {
298
+ exec: (sql, bind) => exec(sql, bind) as { data: string }[],
299
+ run,
300
+ knownTables: new Set<string>(),
301
+ };
302
+
303
+ // ==================== dispatch ====================
304
+
305
+ /** Follower client ports, keyed by the clientId the owner assigned. */
306
+ const clients = new Map<string, MessagePort>();
307
+
308
+ /** Data ops a follower client port may issue; lifecycle stays owner-only. */
309
+ const CLIENT_OPS = new Set(['exec', 'run', 'batch', 'select']);
310
+
311
+ /**
312
+ * ONE chain for every op from every channel. The handlers for `open` and
313
+ * `select` are async; without this, a follower's select could interleave with
314
+ * the owner's batch mid-transaction at the VFS layer. (Solo mode kept this
315
+ * invariant on the main thread via the engine's opQueue; with multiple client
316
+ * ports only the worker can.)
317
+ */
318
+ let opChain: Promise<void> = Promise.resolve();
319
+
320
+ async function handle(type: string, payload: any, source: 'owner' | 'client'): Promise<unknown> {
321
+ if (fenced) throw new Error('sqlite: fenced, leadership was taken over');
322
+ if (source === 'client' && !CLIENT_OPS.has(type)) {
323
+ throw new Error(`sqlite worker: op ${type} is not allowed on a client port`);
324
+ }
325
+ switch (type) {
326
+ case 'open':
327
+ selectDb.knownTables.clear();
328
+ {
329
+ const result = await open(
330
+ payload.dbName,
331
+ payload.useOpfs,
332
+ payload.systemTables,
333
+ payload.workerLockName,
334
+ payload.openOptions
335
+ );
336
+ // The freshly seeded system tables exist — record them so the select
337
+ // path doesn't redundantly re-issue CREATE TABLE for each.
338
+ for (const t of (payload.systemTables ?? []) as string[]) selectDb.knownTables.add(t);
339
+ return result;
340
+ }
341
+ case 'relock': {
342
+ // Same-leader re-promotion after a broker restart: the DB stays open,
343
+ // only the per-leadership lock name rolls forward. Acquire the new lock
344
+ // BEFORE releasing the old one so there is no unfenced window.
345
+ const handle = await acquireWorkerLock(payload.workerLockName);
346
+ if (!handle) throw new Error('worker-lock-unavailable');
347
+ releaseHeldLock();
348
+ currentLock = handle;
349
+ return {};
350
+ }
351
+ case 'select':
352
+ return executeSelect(payload.plan, payload.params ?? {}, selectDb);
353
+ case 'exec':
354
+ return { rows: exec(payload.sql, payload.bind) };
355
+ case 'run':
356
+ run(payload.sql, payload.bind);
357
+ return {};
358
+ case 'batch':
359
+ batch(payload as Stmt[]);
360
+ return {};
361
+ case 'close':
362
+ closeDb();
363
+ return {};
364
+ case 'shutdown':
365
+ // Graceful pagehide path: pausing the VFS releases the sync access
366
+ // handles NOW instead of whenever this worker gets garbage collected,
367
+ // so the next leader's open does not race the browser's GC.
368
+ try {
369
+ db?.close();
370
+ } catch {
371
+ /* ignore */
372
+ }
373
+ db = null;
374
+ try {
375
+ pool?.pauseVfs?.();
376
+ } catch {
377
+ /* ignore */
378
+ }
379
+ pool = null;
380
+ releaseHeldLock();
381
+ queueMicrotask(() => self.close());
382
+ return {};
383
+ case 'remove-client': {
384
+ const port = clients.get(payload.clientId);
385
+ port?.close();
386
+ clients.delete(payload.clientId);
387
+ return {};
388
+ }
389
+ default:
390
+ throw new Error(`sqlite worker: unknown message ${type}`);
391
+ }
392
+ }
393
+
394
+ function dispatch(target: PostTarget, data: any, source: 'owner' | 'client'): void {
395
+ const { id, type, payload } = data ?? {};
396
+ noteTick();
397
+ const t0 = performance.now();
398
+ const runOp = async () => {
399
+ try {
400
+ if (thawVerification) await thawVerification;
401
+ const result = await handle(type, payload, source);
402
+ // `wt` (worker time) lets the main thread split a round-trip into actual
403
+ // DB work vs postMessage/queue overhead (see `__sqliteStats`).
404
+ target.postMessage({ id, ok: true, wt: performance.now() - t0, ...(result as object) });
405
+ } catch (err) {
406
+ target.postMessage({ id, ok: false, error: err instanceof Error ? err.message : String(err) });
407
+ }
408
+ };
409
+ opChain = opChain.then(runOp, runOp);
410
+ }
411
+
412
+ self.onmessage = (ev: MessageEvent) => {
413
+ const data = ev.data ?? {};
414
+ // `add-client` is handled inline (not on the op chain): it only registers a
415
+ // port and must not wait behind a long select, or the follower's first ops
416
+ // (already queued on that port by the time the ack arrives) would deadlock
417
+ // the attach handshake in the engine.
418
+ if (data.type === 'add-client') {
419
+ const port = ev.ports?.[0];
420
+ const clientId = data.payload?.clientId as string | undefined;
421
+ if (!port || !clientId) {
422
+ (self as unknown as Worker).postMessage({
423
+ id: data.id,
424
+ ok: false,
425
+ error: 'sqlite worker: add-client needs a clientId and a transferred port',
426
+ });
427
+ return;
428
+ }
429
+ clients.get(clientId)?.close();
430
+ clients.set(clientId, port);
431
+ port.onmessage = (pe: MessageEvent) => dispatch(port, pe.data, 'client');
432
+ port.start?.();
433
+ (self as unknown as Worker).postMessage({ id: data.id, ok: true, wt: 0 });
434
+ return;
435
+ }
436
+ dispatch(self as unknown as Worker, data, 'owner');
437
+ };