@spooky-sync/core 0.0.1-canary.33 → 0.0.1-canary.331

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 (266) hide show
  1. package/AGENTS.md +84 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2080 -142
  4. package/dist/index.js +16009 -2480
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +373 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +392 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +477 -0
  18. package/dist/types.d.ts +1857 -38
  19. package/dist/worker-edges.js +480 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +48 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +28 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +173 -0
  27. package/skills/sp00ky-core/SKILL.md +32 -7
  28. package/skills/sp00ky-core/references/config.md +7 -1
  29. package/src/boot/auth-flip.saga.test.ts +135 -0
  30. package/src/boot/auth-flip.saga.ts +77 -0
  31. package/src/boot/boot.saga.test.ts +203 -0
  32. package/src/boot/boot.saga.ts +146 -0
  33. package/src/boot/bucket-switch.saga.test.ts +187 -0
  34. package/src/boot/bucket-switch.saga.ts +133 -0
  35. package/src/boot/preload.saga.test.ts +80 -0
  36. package/src/boot/preload.saga.ts +40 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +352 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +195 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.test.ts +74 -0
  46. package/src/client/services.ts +434 -0
  47. package/src/client/sp00ky-client.test.ts +341 -0
  48. package/src/client/sp00ky-client.ts +625 -0
  49. package/src/events/events.test.ts +2 -1
  50. package/src/events/index.ts +3 -0
  51. package/src/index.ts +69 -1
  52. package/src/kernel/constants.test.ts +19 -0
  53. package/src/kernel/constants.ts +80 -0
  54. package/src/kernel/effects.test.ts +40 -0
  55. package/src/kernel/effects.ts +167 -0
  56. package/src/kernel/events.ts +57 -0
  57. package/src/kernel/interpreter.test.ts +116 -0
  58. package/src/kernel/interpreter.ts +148 -0
  59. package/src/kernel/saga.test.ts +89 -0
  60. package/src/kernel/saga.ts +73 -0
  61. package/src/live/index.test.ts +512 -0
  62. package/src/live/index.ts +1059 -0
  63. package/src/modules/app-release/index.test.ts +125 -0
  64. package/src/modules/app-release/index.ts +209 -0
  65. package/src/modules/auth/auth.local-first.test.ts +228 -0
  66. package/src/modules/auth/events/index.ts +9 -2
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +205 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +476 -22
  72. package/src/modules/crdt/acceptance.ts +75 -0
  73. package/src/modules/crdt/bytes.ts +50 -0
  74. package/src/modules/crdt/crdt-field.ts +125 -0
  75. package/src/modules/crdt/crdt.test.ts +469 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +757 -0
  78. package/src/modules/crdt/loro-loader.ts +25 -0
  79. package/src/modules/crdt/mirror.ts +37 -0
  80. package/src/modules/devtools/flags.ts +349 -0
  81. package/src/modules/devtools/index.ts +746 -95
  82. package/src/modules/devtools/mutations.test.ts +92 -0
  83. package/src/modules/devtools/mutations.ts +160 -0
  84. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  85. package/src/modules/devtools/state-shape.test.ts +263 -0
  86. package/src/modules/devtools/storage-info.test.ts +79 -0
  87. package/src/modules/devtools/storage-info.ts +168 -0
  88. package/src/modules/devtools/versions.test.ts +74 -0
  89. package/src/modules/devtools/versions.ts +110 -0
  90. package/src/modules/feature-flag/index.test.ts +298 -0
  91. package/src/modules/feature-flag/index.ts +316 -0
  92. package/src/modules/ref-tables.test.ts +93 -0
  93. package/src/modules/ref-tables.ts +91 -0
  94. package/src/modules/web-push/index.test.ts +824 -0
  95. package/src/modules/web-push/index.ts +1027 -0
  96. package/src/mutation/jobs.test.ts +25 -0
  97. package/src/mutation/jobs.ts +41 -0
  98. package/src/mutation/mutation-id.test.ts +37 -0
  99. package/src/mutation/mutation-id.ts +35 -0
  100. package/src/mutation/pending-writes.integration.test.ts +175 -0
  101. package/src/mutation/push.saga.test.ts +301 -0
  102. package/src/mutation/push.saga.ts +225 -0
  103. package/src/mutation/rows.test.ts +231 -0
  104. package/src/mutation/rows.ts +427 -0
  105. package/src/mutation/tray.saga.test.ts +63 -0
  106. package/src/mutation/tray.saga.ts +48 -0
  107. package/src/mutation/write.saga.test.ts +316 -0
  108. package/src/mutation/write.saga.ts +268 -0
  109. package/src/otel/index.ts +10 -7
  110. package/src/pure.ts +66 -0
  111. package/src/push/types.ts +174 -0
  112. package/src/query/anon-query-isolation.integration.test.ts +527 -0
  113. package/src/query/env.test.ts +23 -0
  114. package/src/query/env.ts +65 -0
  115. package/src/query/fetch.saga.test.ts +199 -0
  116. package/src/query/fetch.saga.ts +120 -0
  117. package/src/query/hash.test.ts +14 -0
  118. package/src/query/hash.ts +18 -0
  119. package/src/query/id-set-plan.test.ts +132 -0
  120. package/src/query/lifecycle.saga.test.ts +274 -0
  121. package/src/query/lifecycle.saga.ts +186 -0
  122. package/src/query/list-ref-live.integration.test.ts +203 -0
  123. package/src/query/materialize.saga.test.ts +115 -0
  124. package/src/query/materialize.saga.ts +84 -0
  125. package/src/query/materialize.test.ts +58 -0
  126. package/src/query/materialize.ts +57 -0
  127. package/src/query/membership.saga.test.ts +407 -0
  128. package/src/query/membership.saga.ts +282 -0
  129. package/src/query/membership.test.ts +118 -0
  130. package/src/query/membership.ts +201 -0
  131. package/src/query/register.saga.test.ts +311 -0
  132. package/src/query/register.saga.ts +235 -0
  133. package/src/query/render-set.test.ts +47 -0
  134. package/src/query/render-set.ts +71 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +157 -0
  137. package/src/query/window-query.test.ts +70 -0
  138. package/src/query/window-query.ts +208 -0
  139. package/src/services/blobs/blob-cache.test.ts +359 -0
  140. package/src/services/blobs/blob-cache.ts +603 -0
  141. package/src/services/blobs/blob-manifest.ts +227 -0
  142. package/src/services/blobs/blob-store.test.ts +77 -0
  143. package/src/services/blobs/blob-store.ts +359 -0
  144. package/src/services/blobs/blob.fixture.ts +90 -0
  145. package/src/services/blobs/index.ts +70 -0
  146. package/src/services/database/cache-engine.ts +209 -0
  147. package/src/services/database/connection-supervisor.test.ts +318 -0
  148. package/src/services/database/connection-supervisor.ts +422 -0
  149. package/src/services/database/database.query-timeout.test.ts +140 -0
  150. package/src/services/database/database.responses.test.ts +43 -0
  151. package/src/services/database/database.ts +156 -61
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/events/index.ts +2 -1
  155. package/src/services/database/index.ts +7 -0
  156. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  157. package/src/services/database/local-migrator.integration.test.ts +110 -0
  158. package/src/services/database/local-migrator.ts +61 -16
  159. package/src/services/database/local.test.ts +150 -0
  160. package/src/services/database/local.ts +508 -63
  161. package/src/services/database/plan-render.test.ts +159 -0
  162. package/src/services/database/plan-render.ts +108 -0
  163. package/src/services/database/relation-resolver.test.ts +484 -0
  164. package/src/services/database/relation-resolver.ts +0 -0
  165. package/src/services/database/remote.ts +285 -6
  166. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  167. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  168. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  169. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  170. package/src/services/database/sqlite-column-reset.ts +91 -0
  171. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  172. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  173. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  174. package/src/services/database/sqlite-lock-verify.ts +45 -0
  175. package/src/services/database/sqlite-open.test.ts +150 -0
  176. package/src/services/database/sqlite-open.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  178. package/src/services/database/sqlite-plan-sql.ts +196 -0
  179. package/src/services/database/sqlite-projection.test.ts +121 -0
  180. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  181. package/src/services/database/sqlite-select.test.ts +261 -0
  182. package/src/services/database/sqlite-select.ts +131 -0
  183. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  184. package/src/services/database/sqlite-transport.ts +224 -0
  185. package/src/services/database/sqlite-worker.ts +437 -0
  186. package/src/services/database/surql-translate.ts +417 -0
  187. package/src/services/database/surreal-cache-engine.ts +163 -0
  188. package/src/services/logger/index.test.ts +132 -0
  189. package/src/services/logger/index.ts +189 -7
  190. package/src/services/persistence/localstorage.ts +2 -2
  191. package/src/services/persistence/resilient.ts +10 -3
  192. package/src/services/persistence/surrealdb.ts +4 -4
  193. package/src/services/stream-processor/index.ts +806 -67
  194. package/src/services/stream-processor/permissions.test.ts +47 -0
  195. package/src/services/stream-processor/permissions.ts +53 -0
  196. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  197. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  198. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  199. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  200. package/src/services/stream-processor/wasm-types.ts +58 -2
  201. package/src/services/tabs/broker-client.ts +284 -0
  202. package/src/services/tabs/broker.test.ts +381 -0
  203. package/src/services/tabs/coordinator.test.ts +386 -0
  204. package/src/services/tabs/coordinator.ts +646 -0
  205. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  206. package/src/services/tabs/leader-locks.ts +75 -0
  207. package/src/services/tabs/protocol.ts +262 -0
  208. package/src/services/tabs/support.ts +36 -0
  209. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  210. package/src/sp00ky.ts +5 -395
  211. package/src/state/client-state.ts +208 -0
  212. package/src/state/lifecycle.test.ts +141 -0
  213. package/src/state/lifecycle.ts +99 -0
  214. package/src/state/reducers.test.ts +306 -0
  215. package/src/state/reducers.ts +531 -0
  216. package/src/state/selectors.test.ts +188 -0
  217. package/src/state/selectors.ts +258 -0
  218. package/src/sw/index.test.ts +582 -0
  219. package/src/sw/index.ts +607 -0
  220. package/src/sw/store.ts +96 -0
  221. package/src/sync/connection.saga.test.ts +97 -0
  222. package/src/sync/connection.saga.ts +89 -0
  223. package/src/sync/live.saga.test.ts +178 -0
  224. package/src/sync/live.saga.ts +107 -0
  225. package/src/sync/policy.health.test.ts +56 -0
  226. package/src/sync/policy.test.ts +663 -0
  227. package/src/sync/policy.ts +515 -0
  228. package/src/sync/poll.saga.test.ts +51 -0
  229. package/src/sync/poll.saga.ts +36 -0
  230. package/src/sync/tabs.saga.test.ts +78 -0
  231. package/src/sync/tabs.saga.ts +96 -0
  232. package/src/testing/adapters.ts +137 -0
  233. package/src/testing/build.ts +63 -0
  234. package/src/testing/fake-services.ts +63 -0
  235. package/src/testing/run-pure.test.ts +92 -0
  236. package/src/testing/run-pure.ts +128 -0
  237. package/src/testing/services.ts +17 -0
  238. package/src/types.ts +633 -10
  239. package/src/utils/blurhash.ts +90 -0
  240. package/src/utils/edges.ts +39 -0
  241. package/src/utils/error-classification.test.ts +54 -0
  242. package/src/utils/error-classification.ts +25 -0
  243. package/src/utils/index.ts +89 -12
  244. package/src/utils/parser.test.ts +67 -102
  245. package/src/utils/parser.ts +64 -2
  246. package/src/utils/semver.test.ts +32 -0
  247. package/src/utils/semver.ts +30 -0
  248. package/src/utils/sha256.ts +15 -0
  249. package/src/utils/surql.ts +29 -18
  250. package/src/utils/utils.test.ts +3 -2
  251. package/tsdown.config.ts +117 -3
  252. package/vitest.config.ts +48 -0
  253. package/src/modules/cache/index.ts +0 -241
  254. package/src/modules/cache/types.ts +0 -19
  255. package/src/modules/data/data.test.ts +0 -58
  256. package/src/modules/data/index.ts +0 -879
  257. package/src/modules/sync/engine.ts +0 -173
  258. package/src/modules/sync/events/index.ts +0 -77
  259. package/src/modules/sync/index.ts +0 -3
  260. package/src/modules/sync/queue/index.ts +0 -2
  261. package/src/modules/sync/queue/queue-down.ts +0 -89
  262. package/src/modules/sync/queue/queue-up.ts +0 -223
  263. package/src/modules/sync/scheduler.ts +0 -84
  264. package/src/modules/sync/sync.ts +0 -421
  265. package/src/modules/sync/utils.test.ts +0 -311
  266. package/src/modules/sync/utils.ts +0 -167
@@ -0,0 +1,1401 @@
1
+ import { applyPatch, type Operation } from 'fast-json-patch';
2
+ import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
3
+ import { withTimeout } from '../../utils/index';
4
+ import type { QueryPlan, RelationPlan, WhereNode } from '@spooky-sync/query-builder';
5
+ import {
6
+ renderOrderSql,
7
+ renderWhereSql,
8
+ reviveRow,
9
+ serializeMergeRow,
10
+ serializeRow,
11
+ project,
12
+ projectedDataSql,
13
+ } from './sqlite-plan-sql';
14
+ import type { Logger } from '../logger/index';
15
+ import type { Sp00kyConfig, StorageHealth } from '../../types';
16
+ import type { SnapshotMeta, StoredSnapshot } from './cache-engine';
17
+ import type { SealedQuery } from '../../utils/surql';
18
+ import { resolveRelations, stableKey } from './relation-resolver';
19
+ import {
20
+ createDatabaseEventSystem,
21
+ DatabaseEventTypes,
22
+ type DatabaseEventSystem,
23
+ } from './events/index';
24
+ import { StaleEpochError } from './local';
25
+ import { translateSurql, tableOf, setPath, getPath, type SqlOp } from './surql-translate';
26
+ import {
27
+ BrokerPortClosedError,
28
+ PortSqliteTransport,
29
+ WorkerSqliteTransport,
30
+ type SqliteTransport,
31
+ } from './sqlite-transport';
32
+ import { PROMOTION_OPEN_OPTIONS } from './sqlite-open';
33
+ import { COLUMNS_ROW_ID, planColumnReset } from './sqlite-column-reset';
34
+ import type { EngineTx, Id, LocalStore, OrderBy, RelationFetch, Row } from './cache-engine';
35
+ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
36
+
37
+ /**
38
+ * The statement result a pure-write op contributes to a query's results array.
39
+ * Single source of truth shared by the per-op path (`execOp`) and the batched
40
+ * fast path in `query()`, so the two can never diverge: a caller that reads a
41
+ * statement's output sees the same shape whether or not the transaction took the
42
+ * batch fast path. In particular `create()` compiles to an all-upsert tx
43
+ * (`createSet` + `createMutation`) and reads `resultIndex:0` for the new row and
44
+ * its id — the fast path previously returned empty arrays there, so the row (and
45
+ * its id) was lost and the reconcile crashed in `encodeRecordId`.
46
+ *
47
+ * An upsert echoes the written row (`{...data, id}`) with no read-back — the
48
+ * full merged row is only materialized for a LET-wrapped upsert (see the 'let'
49
+ * case). delete/deleteAll yield `[]`; noop yields `null`.
50
+ */
51
+ /**
52
+ * The `_00_*` internal tables the client relies on. The LocalMigrator DEFINEs
53
+ * them, but every DEFINE lowers to a noop on the SQLite engine, so they must be
54
+ * created physically at open (see `openInternal`) or a read-before-first-write
55
+ * on a fresh bucket throws "no such table". Keep in sync with the systemSchema
56
+ * block in `local-migrator.ts`.
57
+ */
58
+ const SNAPSHOT_TABLE = '_00_circuit_snapshot';
59
+
60
+ const SYSTEM_TABLES = [
61
+ '_00_stream_processor_state',
62
+ // In-browser circuit snapshot: one BLOB row (`circuit`) + a JSON meta row.
63
+ // Excluded from DevTools' table listing, since its data column is not JSON.
64
+ '_00_circuit_snapshot',
65
+ '_00_view',
66
+ '_00_window',
67
+ '_00_failed_mutations',
68
+ '_00_schema',
69
+ '_00_pending_mutations',
70
+ // Debounced patches still inside their delay; read on every boot.
71
+ '_00_pending_writes',
72
+ // Blob cache manifest. Read before its first write on every boot (reconcile
73
+ // asks for the ids it found in OPFS), so it has to exist up front like the
74
+ // rest — otherwise the very first reconcile throws and the cache runs cold.
75
+ '_00_blob',
76
+ // CRDT documents per open field, with edits not yet in the outbox.
77
+ '_00_crdt_local',
78
+ // Server-written, synced-down meta tables (see meta_tables_client.surql).
79
+ // DEFINE is a noop on this engine, so without seeding them here their synced
80
+ // rows have no local table to land in: feature flags silently fall back to
81
+ // defaults and app-release update notifications never show.
82
+ '_00_user_feature',
83
+ '_00_app_release',
84
+ ] as const;
85
+
86
+ export function pureWriteOpResult(op: SqlOp): unknown {
87
+ switch (op.kind) {
88
+ case 'upsert':
89
+ return { ...op.data, id: stableKey(op.id) };
90
+ case 'noop':
91
+ return null;
92
+ default:
93
+ return [];
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Local cache backend on official SQLite-WASM in a dedicated Worker (see
99
+ * `sqlite-worker.ts`), with OPFS SAHPool persistence. Storage model: one table
100
+ * per schema table, `id TEXT PRIMARY KEY, data TEXT` where `data` is the row as
101
+ * JSON. Filtering/ordering use `json_extract`. Relations are decomposed by the
102
+ * shared {@link resolveRelations} — identical to the SurrealDB backend.
103
+ *
104
+ * Value normalization (JSON round-trip):
105
+ * - Bytes in any shape (`Uint8Array`, the SDK's `ArrayBuffer`) →
106
+ * `{ "__u8": <base64> }`, read back as `Uint8Array` (CRDT data survives).
107
+ * - Record links / ids → their `table:id` string form (so `json_extract`
108
+ * comparisons and `IN` matching are consistent). NOTE: link fields therefore
109
+ * read back as strings, not `RecordId` instances — the one shape difference
110
+ * from the SurrealDB backend, to be closed with schema-driven revival + an
111
+ * oracle E2E in the browser.
112
+ */
113
+ export class SqliteCacheEngine implements LocalStore {
114
+ /** The wire to the SQLite worker: an owned dedicated Worker (solo/leader) or
115
+ * a MessagePort into another tab's worker (follower). See sqlite-transport. */
116
+ private transport: SqliteTransport | null = null;
117
+ private storeEpoch = 0;
118
+ private knownTables = new Set<string>();
119
+ private useOpfs: boolean;
120
+ /** Whether `select` runs as one worker round-trip (plan executed in-worker).
121
+ * Flipped off at runtime if the worker script predates the `select` op
122
+ * (stale cached bundle) — degrade to the legacy multi-hop path, don't break. */
123
+ private workerSelect: boolean;
124
+ /** What `workerSelect` was at construction, so DevTools can tell a runtime
125
+ * downgrade (configured true, effective false) from a configured-off. */
126
+ private workerSelectConfigured: boolean;
127
+ private events: DatabaseEventSystem = createDatabaseEventSystem();
128
+ private bucketId = 'anon';
129
+ /** Deadline for one worker round trip; see `localOpTimeoutMs`. */
130
+ private readonly localOpTimeoutMs: number;
131
+ /** Durability of the local store, set on every open. A plain Set of callbacks
132
+ * rather than a `DatabaseEventSystem` event: this changes at most once per
133
+ * open, and the typed event map is about query traffic. */
134
+ private storageHealthValue: StorageHealth = { status: 'unknown', fallback: false };
135
+ private storageHealthSubs = new Set<(health: StorageHealth) => void>();
136
+ /** Schemaless — tables are created lazily on first write; no migrator. */
137
+ readonly usesSurqlSchema = false;
138
+
139
+ readonly engineKind = 'sqlite' as const;
140
+
141
+ /** Shared-tabs mode: the engine's transport is swapped at runtime by the
142
+ * TabsCoordinator (owner worker as leader, leader's port as follower). */
143
+ private shared: boolean;
144
+ /** Leaderless parking (shared mode): ops entering the opQueue await this
145
+ * gate until a new role lands or the timeout rejects them. */
146
+ private roleGate: { promise: Promise<void>; release: () => void } | null = null;
147
+ private roleGateTimer: ReturnType<typeof setTimeout> | null = null;
148
+
149
+ constructor(
150
+ private config: Sp00kyConfig<any>['database'],
151
+ private logger: Logger,
152
+ opts: { useOpfs?: boolean; workerSelect?: boolean; shared?: boolean } = {}
153
+ ) {
154
+ this.localOpTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
155
+ this.useOpfs = opts.useOpfs ?? true;
156
+ this.workerSelect = opts.workerSelect ?? config.workerSelect ?? true;
157
+ this.workerSelectConfigured = this.workerSelect;
158
+ this.shared = opts.shared ?? false;
159
+ }
160
+
161
+ get epoch(): number {
162
+ return this.storeEpoch;
163
+ }
164
+
165
+ get currentBucketId(): string {
166
+ return this.bucketId;
167
+ }
168
+
169
+ get storageHealth(): StorageHealth {
170
+ return this.storageHealthValue;
171
+ }
172
+
173
+ /** Fires immediately with the current snapshot (the store opens during
174
+ * `connect()`, before app components mount, so a late subscriber must still
175
+ * learn a fallback happened), then on every change. */
176
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {
177
+ cb(this.storageHealthValue);
178
+ this.storageHealthSubs.add(cb);
179
+ return () => {
180
+ this.storageHealthSubs.delete(cb);
181
+ };
182
+ }
183
+
184
+ private setStorageHealth(health: StorageHealth): void {
185
+ this.storageHealthValue = health;
186
+ for (const cb of this.storageHealthSubs) cb(health);
187
+ }
188
+
189
+ getConfig(): Sp00kyConfig<any>['database'] {
190
+ return this.config;
191
+ }
192
+
193
+ /**
194
+ * Storage numbers for the DevTools Storage tab. Uses {@link call} so the
195
+ * reads serialize with regular traffic (no SQLITE_BUSY). Never throws — the
196
+ * worker may be mid bucket-switch; a failure lands in `error` instead.
197
+ */
198
+ async getStorageDiagnostics(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics> {
199
+ const diag: EngineStorageDiagnostics = {
200
+ engine: 'sqlite',
201
+ bucketId: this.bucketId,
202
+ useOpfs: this.useOpfs,
203
+ workerSelectConfigured: this.workerSelectConfigured,
204
+ workerSelectEffective: this.workerSelect,
205
+ };
206
+ try {
207
+ const { rows } = await this.call<{ rows: { bytes: number; freelist: number }[] }>('exec', {
208
+ sql:
209
+ 'SELECT (SELECT * FROM pragma_page_count()) * (SELECT * FROM pragma_page_size()) AS bytes, ' +
210
+ '(SELECT * FROM pragma_freelist_count()) * (SELECT * FROM pragma_page_size()) AS freelist',
211
+ });
212
+ diag.dbSizeBytes = rows?.[0]?.bytes;
213
+ diag.freelistBytes = rows?.[0]?.freelist;
214
+ if (opts?.tableCounts) {
215
+ const { rows: tables } = await this.call<{ rows: { name: string }[] }>('exec', {
216
+ sql: "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",
217
+ });
218
+ const names = (tables ?? []).map((r) => r.name).filter((n) => n !== SNAPSHOT_TABLE);
219
+ if (names.length) {
220
+ // Names come from sqlite_master itself; double-quoting is enough.
221
+ const sql = names
222
+ .map((n) => `SELECT '${n.replace(/'/g, "''")}' AS t, COUNT(*) AS n FROM "${n.replace(/"/g, '""')}"`)
223
+ .join(' UNION ALL ');
224
+ const { rows: counts } = await this.call<{ rows: { t: string; n: number }[] }>('exec', {
225
+ sql,
226
+ });
227
+ diag.tableCounts = (counts ?? []).map((r) => ({ table: r.t, rows: r.n }));
228
+ } else {
229
+ diag.tableCounts = [];
230
+ }
231
+ }
232
+ } catch (e) {
233
+ diag.error = e instanceof Error ? e.message : String(e);
234
+ }
235
+ return diag;
236
+ }
237
+
238
+ getEvents(): DatabaseEventSystem {
239
+ return this.events;
240
+ }
241
+
242
+ getClient(): unknown {
243
+ throw new Error('SqliteCacheEngine has no SurrealDB client (getClient is unavailable).');
244
+ }
245
+
246
+ /**
247
+ * See `LocalStore.dropBucket`. Each bucket is its own OPFS SAH pool, whose
248
+ * directory sqlite-wasm names `.<pool name>` (`sp00ky-<bucket>`, see
249
+ * sqlite-open.ts). Fails harmlessly while a worker still holds its handles.
250
+ */
251
+ async dropBucket(bucketId: string): Promise<void> {
252
+ if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
253
+ const storage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
254
+ if (!storage?.getDirectory) return;
255
+ const root = await storage.getDirectory();
256
+ try {
257
+ await root.removeEntry(`.sp00ky-${bucketId}`, { recursive: true });
258
+ } catch (error) {
259
+ if ((error as DOMException)?.name !== 'NotFoundError') throw error;
260
+ }
261
+ }
262
+
263
+ /** LocalStore alias; SQLite has no in-flight gate, so this maps to a rebuild. */
264
+ switchStore(bucketId: string): Promise<void> {
265
+ return this.switchBucket(bucketId);
266
+ }
267
+
268
+ /** SQLite has no switch gate window; the epoch bump alone fences stale writes. */
269
+ beginSwitch(): () => void {
270
+ return () => {};
271
+ }
272
+
273
+ // ---- worker plumbing -----------------------------------------------------
274
+
275
+ /** Serializes every worker op so reads/writes never overlap at the VFS layer
276
+ * (overlapping ops trip SQLITE_BUSY). Mirrors the SurrealDB engine's
277
+ * single-flight query queue. (The worker keeps its own chain too, for
278
+ * multi-client mode; this one additionally provides the queue-wait stat and
279
+ * the boot/switch atomicity below.) */
280
+ private opQueue: Promise<unknown> = Promise.resolve();
281
+
282
+ private call<T = any>(type: string, payload?: unknown): Promise<T> {
283
+ const enqueuedAt = performance.now();
284
+ const run = async () => {
285
+ // Leaderless window (shared mode): park behind the role gate instead of
286
+ // failing; a new leader releases it, the timeout rejects it.
287
+ if (this.roleGate) await this.roleGate.promise;
288
+ // Time spent waiting behind other ops in the queue, not doing work.
289
+ getStats().queueWaitMs += performance.now() - enqueuedAt;
290
+ return this.rawCall<T>(type, payload);
291
+ };
292
+ const result = this.opQueue.then(run, run);
293
+ // Keep the chain alive regardless of individual failures.
294
+ this.opQueue = result.then(
295
+ () => undefined,
296
+ () => undefined
297
+ );
298
+ return result;
299
+ }
300
+
301
+ /**
302
+ * Ops dispatched to the worker and not yet answered. Role transitions run on
303
+ * their own chain (see {@link transitionChain}), so they can start while the
304
+ * opQueue still has an op at the worker; tearing the transport down under it
305
+ * would reject that op — and its caller may be a query whose only fetch this
306
+ * was. {@link drainInFlight} lets a deliberate teardown wait them out.
307
+ */
308
+ private inFlightCalls = new Set<Promise<unknown>>();
309
+
310
+ /** Wait for dispatched ops to answer before a deliberate transport teardown.
311
+ * Bounded: a wedged worker must not block the role change forever. */
312
+ private async drainInFlight(timeoutMs = 2_000): Promise<void> {
313
+ if (this.inFlightCalls.size === 0) return;
314
+ const settled = Promise.all([...this.inFlightCalls].map((p) => p.catch(() => undefined)));
315
+ let timer: ReturnType<typeof setTimeout> | undefined;
316
+ try {
317
+ await Promise.race([
318
+ settled,
319
+ new Promise<void>((resolve) => {
320
+ timer = setTimeout(resolve, timeoutMs);
321
+ }),
322
+ ]);
323
+ } finally {
324
+ if (timer) clearTimeout(timer);
325
+ }
326
+ }
327
+
328
+ private rawCall<T = any>(type: string, payload?: unknown): Promise<T> {
329
+ if (!this.transport) throw new Error('SqliteCacheEngine: not connected');
330
+ // --- instrumentation: live, inspectable via `globalThis.__sqliteStats` ---
331
+ const s = getStats();
332
+ s.roundTrips++;
333
+ s.byType[type] = (s.byType[type] ?? 0) + 1;
334
+ if (type === 'batch' && Array.isArray(payload)) {
335
+ s.batchStatements += payload.length;
336
+ s.maxBatch = Math.max(s.maxBatch, payload.length);
337
+ }
338
+ s.inFlight++;
339
+ s.maxInFlight = Math.max(s.maxInFlight, s.inFlight);
340
+ if (this.transport.kind === 'port') s.proxiedOps = (s.proxiedOps ?? 0) + 1;
341
+ const sentAt = performance.now();
342
+ // Track the dispatch, not the returned promise: attaching a handler to
343
+ // `result` would mark it handled and swallow the unhandled-rejection
344
+ // reports that surface a caller which forgot to catch.
345
+ let settle!: () => void;
346
+ const tracked = new Promise<void>((res) => {
347
+ settle = res;
348
+ });
349
+ this.inFlightCalls.add(tracked);
350
+ const finish = () => {
351
+ this.inFlightCalls.delete(tracked);
352
+ settle();
353
+ };
354
+ // Deadline per op. The transport parks a call until the worker replies,
355
+ // and a worker starved behind a long op (or wedged on an unbounded lock
356
+ // check) answered never; every caller up the stack then waited forever.
357
+ // Reject the CALLER only: the op is still queued in the worker and its
358
+ // late reply is dropped by the transport (no pending entry left to
359
+ // resolve). Deliberately no teardown here - a slow worker is not a dead
360
+ // one, and killing it mid-write would cost more than the wait.
361
+ const timeoutMs = this.localOpTimeoutMs;
362
+ const result = withTimeout(
363
+ this.transport.call<T>(type, payload),
364
+ timeoutMs,
365
+ () => new LocalOpTimeoutError(type, timeoutMs)
366
+ ).then(
367
+ (v: T) => {
368
+ finish();
369
+ s.inFlight--;
370
+ // Split the round-trip: `wt` is time inside the worker's handler,
371
+ // the remainder is postMessage + scheduling overhead.
372
+ const wt = (v as { wt?: unknown } | null)?.wt;
373
+ if (typeof wt === 'number') {
374
+ s.workerMs += wt;
375
+ s.rpcOverheadMs += Math.max(0, performance.now() - sentAt - wt);
376
+ }
377
+ return v;
378
+ },
379
+ (e: unknown) => {
380
+ finish();
381
+ s.inFlight--;
382
+ if (e instanceof LocalOpTimeoutError) {
383
+ s.timeouts = (s.timeouts ?? 0) + 1;
384
+ this.logger.error(
385
+ { type, timeoutMs, Category: 'sp00ky-client::SqliteCacheEngine::rawCall' },
386
+ 'Local store op did not answer within its deadline; rejecting the caller'
387
+ );
388
+ }
389
+ throw e;
390
+ }
391
+ );
392
+ return result;
393
+ }
394
+
395
+ /**
396
+ * Spawn the worker and open `bucketId`'s DB. Uses {@link rawCall} (NOT
397
+ * {@link call}) so it can run as the body of an already-queued opQueue entry
398
+ * without re-queuing onto itself. Callers must run it through the opQueue.
399
+ */
400
+ /** Seam for tests: swap in a fake transport instead of a real Worker. */
401
+ protected createTransport(): SqliteTransport {
402
+ return new WorkerSqliteTransport(this.logger);
403
+ }
404
+
405
+ private async openInternal(
406
+ bucketId: string,
407
+ extras?: {
408
+ workerLockName?: string;
409
+ openOptions?: { maxAttempts?: number; backoffMs?: number[]; disallowMemoryFallback?: boolean };
410
+ }
411
+ ): Promise<void> {
412
+ if (!this.transport || this.transport.kind !== 'worker' || !this.transport.connected) {
413
+ this.transport = this.createTransport();
414
+ if (this.transport instanceof WorkerSqliteTransport) {
415
+ // The worker fencing itself (leadership stolen from a frozen tab that
416
+ // thawed) is a leader-loss: park ops until the broker re-adopts us.
417
+ this.transport.onLockLost = (reason) => {
418
+ this.transport = null;
419
+ this.storeEpoch++;
420
+ this.openRoleGate(`worker fenced: ${reason}`);
421
+ };
422
+ }
423
+ }
424
+ // Seed the `_00_*` system tables as part of `open` (worker-side, one round
425
+ // trip). The LocalMigrator DEFINEs them, but `translateSurql` lowers every
426
+ // DEFINE to a noop on this engine (SQLite has no DDL vocabulary), so
427
+ // provisioning never actually creates them — they were only made lazily on
428
+ // first WRITE. A fresh bucket (e.g. right after signup) that READS one first
429
+ // (the sync layer selects `_00_query` before any row lands) hit
430
+ // "no such table: _00_query" and the client wedged on "Loading database".
431
+ // Creating them inside `open` guarantees any access order is safe without
432
+ // adding ops to the engine's queue.
433
+ // `opfsError` is absent from a worker bundle older than this field, which
434
+ // just reads as "no reason given" rather than breaking the open.
435
+ const { persisted, opfsError } = await this.rawCall<{
436
+ persisted: boolean;
437
+ opfsError?: string;
438
+ }>('open', {
439
+ dbName: bucketId,
440
+ useOpfs: this.useOpfs,
441
+ systemTables: SYSTEM_TABLES,
442
+ ...(extras?.workerLockName ? { workerLockName: extras.workerLockName } : {}),
443
+ ...(extras?.openOptions ? { openOptions: extras.openOptions } : {}),
444
+ });
445
+ this.knownTables.clear();
446
+ for (const t of SYSTEM_TABLES) this.knownTables.add(t);
447
+ this.bucketId = bucketId;
448
+ // Durability was requested but could not be had: the store is in RAM, so it
449
+ // loses local writes on reload and can OOM a wasm-heavy renderer. Report it
450
+ // (the worker also console.errors, since host apps may run pino at `fatal`)
451
+ // and publish it so the app can warn the user.
452
+ const fellBack = this.useOpfs && !persisted;
453
+ // Omit `error` rather than setting it to `undefined`: the devtools
454
+ // serializer renders an undefined value as the STRING 'undefined'.
455
+ const health: StorageHealth = {
456
+ status: persisted ? 'persistent' : 'memory',
457
+ fallback: fellBack,
458
+ };
459
+ if (fellBack && opfsError) health.error = opfsError;
460
+ if (this.shared) health.role = this.roleLabel;
461
+ this.setStorageHealth(health);
462
+ const stats = getStats();
463
+ stats.persisted = persisted;
464
+ if (fellBack && opfsError) stats.opfsError = opfsError;
465
+ else delete stats.opfsError;
466
+ if (fellBack) {
467
+ this.logger.error(
468
+ { bucketId, opfsError, Category: 'sp00ky-client::SqliteCacheEngine::connect' },
469
+ 'SQLite OPFS persistence failed; store is IN MEMORY and will not survive reload'
470
+ );
471
+ } else {
472
+ this.logger.info(
473
+ { bucketId, persisted, Category: 'sp00ky-client::SqliteCacheEngine::connect' },
474
+ persisted ? 'SQLite OPFS store opened' : 'SQLite in-memory store opened (as configured)'
475
+ );
476
+ }
477
+ }
478
+
479
+ /** Enqueue `fn` as a single serialized opQueue entry (mirrors {@link call}'s
480
+ * chaining) so it can't interleave with reads/writes at the worker. */
481
+ private enqueue<T>(fn: () => Promise<T>): Promise<T> {
482
+ const result = this.opQueue.then(fn, fn);
483
+ this.opQueue = result.then(
484
+ () => undefined,
485
+ () => undefined
486
+ );
487
+ return result;
488
+ }
489
+
490
+ async connect(bucketId: string): Promise<void> {
491
+ // Serialize through the opQueue so an op racing boot can't dispatch to a
492
+ // half-open worker.
493
+ await this.enqueue(() => this.openInternal(bucketId));
494
+ }
495
+
496
+ async switchBucket(bucketId: string): Promise<void> {
497
+ this.storeEpoch++;
498
+ // Run close → terminate → reopen as ONE opQueue entry. Previously `close`
499
+ // and the new `open` were separate entries, so a query's `exec` (e.g. the
500
+ // query re-registration fired by an auth/bucket change) could slot in
501
+ // between and dispatch to the just-closed worker → "sqlite: DB not open".
502
+ // As a single entry, every other op runs fully before the close or after
503
+ // the reopen — never against a closed DB.
504
+ await this.enqueue(async () => {
505
+ if (this.transport) {
506
+ try {
507
+ await this.rawCall('close');
508
+ } catch {
509
+ /* ignore */
510
+ }
511
+ this.transport.close('bucket switch');
512
+ this.transport = null;
513
+ }
514
+ await this.openInternal(bucketId);
515
+ });
516
+ }
517
+
518
+ async close(): Promise<void> {
519
+ if (!this.transport) return;
520
+ try {
521
+ await this.call('close');
522
+ } catch {
523
+ /* ignore */
524
+ }
525
+ this.transport.close('engine closed');
526
+ this.transport = null;
527
+ }
528
+
529
+ // ---- shared-tabs role modes ------------------------------------------------
530
+ // The TabsCoordinator drives these; solo mode never touches them. The engine
531
+ // object is never replaced across role changes, so `storeEpoch` stays one
532
+ // monotonic per-tab counter and every existing fencing consumer keeps
533
+ // working unchanged.
534
+
535
+ /** Which role the current transport represents, for StorageHealth. */
536
+ private roleLabel: 'leader' | 'follower' | 'solo' = 'solo';
537
+ /** True once this engine has had a usable store at least once; role changes
538
+ * after that point invalidate in-flight reads and must bump the epoch. */
539
+ private hadStore = false;
540
+
541
+ /**
542
+ * Role transitions run on their OWN chain, never on the opQueue: parked ops
543
+ * sit INSIDE opQueue entries waiting for the role gate, so a transition
544
+ * queued behind them could never run to release them (deadlock). Transitions
545
+ * are safe off-queue because in-flight ops on a dead transport were already
546
+ * rejected, parked ops only resume after the transition completes, and the
547
+ * worker serializes everything worker-side anyway.
548
+ */
549
+ private transitionChain: Promise<unknown> = Promise.resolve();
550
+
551
+ private chainTransition<T>(fn: () => Promise<T>): Promise<T> {
552
+ const result = this.transitionChain.then(fn, fn);
553
+ this.transitionChain = result.then(
554
+ () => undefined,
555
+ () => undefined
556
+ );
557
+ return result;
558
+ }
559
+
560
+ private openRoleGate(reason: string): void {
561
+ if (this.roleGate) return;
562
+ let release!: () => void;
563
+ let rejectFn!: (e: Error) => void;
564
+ const promise = new Promise<void>((res, rej) => {
565
+ release = res;
566
+ rejectFn = rej;
567
+ });
568
+ // Swallow the timeout rejection for waiters that already resolved.
569
+ promise.catch(() => {});
570
+ this.roleGate = { promise, release };
571
+ this.roleGateTimer = setTimeout(() => {
572
+ // Nothing adopted us in time: reject the parked ops (retryable) and drop
573
+ // the gate so later calls fail fast with 'not connected'.
574
+ rejectFn(new BrokerPortClosedError(`no leader adopted this tab: ${reason}`));
575
+ this.roleGate = null;
576
+ this.roleGateTimer = null;
577
+ }, 20_000);
578
+ }
579
+
580
+ private closeRoleGate(): void {
581
+ if (this.roleGateTimer) clearTimeout(this.roleGateTimer);
582
+ this.roleGateTimer = null;
583
+ this.roleGate?.release();
584
+ this.roleGate = null;
585
+ }
586
+
587
+ /**
588
+ * Become the store owner (leader). Boot and failover share this path; a
589
+ * failover (a previous transport existed) bumps the epoch FIRST so every
590
+ * in-flight chain that captured the old epoch fences itself. `resumeHeld`
591
+ * keeps the live worker after a broker restart and only rolls the
592
+ * per-leadership lock forward.
593
+ */
594
+ async adoptOwner(
595
+ bucketId: string,
596
+ opts: {
597
+ workerLockName: string;
598
+ allowMemoryFallback: boolean;
599
+ resumeHeld: boolean;
600
+ }
601
+ ): Promise<StorageHealth> {
602
+ this.roleLabel = 'leader';
603
+ return this.chainTransition(async () => {
604
+ if (
605
+ opts.resumeHeld &&
606
+ this.transport?.kind === 'worker' &&
607
+ this.transport.connected &&
608
+ this.bucketId === bucketId
609
+ ) {
610
+ await this.rawCall('relock', { workerLockName: opts.workerLockName });
611
+ this.closeRoleGate();
612
+ return this.storageHealthValue;
613
+ }
614
+ if (this.transport) await this.drainInFlight();
615
+ if (this.hadStore) this.storeEpoch++;
616
+ if (this.transport) {
617
+ try {
618
+ if (this.transport.kind === 'worker') await this.rawCall('close');
619
+ } catch {
620
+ /* ignore */
621
+ }
622
+ this.transport.close('adopting ownership', new BrokerPortClosedError('adopting ownership'));
623
+ this.transport = null;
624
+ }
625
+ await this.openInternal(bucketId, {
626
+ workerLockName: opts.workerLockName,
627
+ openOptions: {
628
+ ...PROMOTION_OPEN_OPTIONS,
629
+ disallowMemoryFallback: !opts.allowMemoryFallback,
630
+ },
631
+ });
632
+ getStats().roleChanges = (getStats().roleChanges ?? 0) + 1;
633
+ this.hadStore = true;
634
+ this.closeRoleGate();
635
+ return this.storageHealthValue;
636
+ });
637
+ }
638
+
639
+ /** Attach to a leader's worker through `dbPort` (follower). */
640
+ async adoptAttached(
641
+ dbPort: MessagePort,
642
+ snapshot: { bucketId: string; storageHealth: StorageHealth },
643
+ onPortDead: (reason: string) => void
644
+ ): Promise<void> {
645
+ this.roleLabel = 'follower';
646
+ return this.chainTransition(async () => {
647
+ if (this.transport) await this.drainInFlight();
648
+ if (this.hadStore) this.storeEpoch++;
649
+ this.transport?.close(
650
+ 'adopting leader port',
651
+ new BrokerPortClosedError('adopting leader port')
652
+ );
653
+ this.transport = new PortSqliteTransport(dbPort, onPortDead, this.logger);
654
+ this.bucketId = snapshot.bucketId;
655
+ // The shared store exists and is seeded; mirror the owner's bookkeeping.
656
+ this.knownTables.clear();
657
+ for (const t of SYSTEM_TABLES) this.knownTables.add(t);
658
+ const health: StorageHealth = { ...snapshot.storageHealth, role: 'follower' };
659
+ this.setStorageHealth(health);
660
+ const stats = getStats();
661
+ stats.persisted = snapshot.storageHealth.status === 'persistent';
662
+ stats.roleChanges = (stats.roleChanges ?? 0) + 1;
663
+ delete stats.opfsError;
664
+ this.hadStore = true;
665
+ this.closeRoleGate();
666
+ });
667
+ }
668
+
669
+ /** Demoted while owning the store (zombie thaw, stale promotion): tear the
670
+ * worker down so its OPFS handles free up, then park until re-adopted. */
671
+ async releaseOwnership(): Promise<void> {
672
+ await this.chainTransition(async () => {
673
+ if (this.transport) {
674
+ // Let ops already at the worker answer first. Without this they die
675
+ // with the transport — a bucket switch (moveToBucket → teardownLeader)
676
+ // runs while the opQueue may still have a query's fetch in flight, and
677
+ // that fetch's caller is not necessarily prepared to retry.
678
+ await this.drainInFlight();
679
+ try {
680
+ if (this.transport.kind === 'worker') {
681
+ await (this.transport as WorkerSqliteTransport).shutdown();
682
+ }
683
+ } catch {
684
+ /* worker may already be fenced/dead */
685
+ }
686
+ // Anything still pending (drain timed out) is a deliberate teardown,
687
+ // not a crash: fail it the way a follower's lost port does, so the
688
+ // error text is honest and callers can treat it as retryable.
689
+ this.transport.close(
690
+ 'ownership released',
691
+ new BrokerPortClosedError('ownership released')
692
+ );
693
+ this.transport = null;
694
+ }
695
+ this.storeEpoch++;
696
+ this.openRoleGate('ownership released');
697
+ });
698
+ }
699
+
700
+ /** The leader (or its port) died. Called from the port-dead callback and the
701
+ * coordinator; NOT enqueued, so in-flight ops reject immediately instead of
702
+ * waiting behind whatever is stuck. */
703
+ onLeaderLost(reason: string): void {
704
+ if (this.transport?.kind === 'port') {
705
+ this.transport.close(reason);
706
+ this.transport = null;
707
+ }
708
+ this.storeEpoch++;
709
+ this.openRoleGate(reason);
710
+ }
711
+
712
+ /** Leader side: forward a follower's dbPort into the owned worker. */
713
+ async exposeClientPort(clientId: string, port: MessagePort): Promise<void> {
714
+ if (this.transport?.kind !== 'worker') {
715
+ throw new Error('SqliteCacheEngine: not the store owner');
716
+ }
717
+ await (this.transport as WorkerSqliteTransport).addClientPort(clientId, port);
718
+ }
719
+
720
+ async removeClientPort(clientId: string): Promise<void> {
721
+ if (this.transport?.kind !== 'worker') return;
722
+ await (this.transport as WorkerSqliteTransport).removeClientPort(clientId);
723
+ }
724
+
725
+ /** Graceful pagehide as owner: release OPFS handles NOW so the next leader
726
+ * does not race the browser's worker GC. */
727
+ async shutdownOwnedWorker(): Promise<void> {
728
+ if (this.transport?.kind !== 'worker') return;
729
+ try {
730
+ await (this.transport as WorkerSqliteTransport).shutdown();
731
+ } catch {
732
+ /* ignore */
733
+ }
734
+ this.transport.close('shutdown');
735
+ this.transport = null;
736
+ }
737
+
738
+ private async ensureTable(table: string): Promise<void> {
739
+ if (this.knownTables.has(table)) return;
740
+ await this.call('run', {
741
+ sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
742
+ });
743
+ this.knownTables.add(table);
744
+ }
745
+
746
+ private async execRows(sql: string, bind: unknown[]): Promise<Row[]> {
747
+ const { rows } = await this.call<{ rows: { data: string }[] }>('exec', { sql, bind });
748
+ const s = getStats();
749
+ const t0 = performance.now();
750
+ const out = (rows ?? []).map((r) => {
751
+ s.bytesParsed += r.data.length;
752
+ return reviveRow(r.data);
753
+ });
754
+ s.parseMs += performance.now() - t0;
755
+ s.rowsParsed += out.length;
756
+ return out;
757
+ }
758
+
759
+ // ---- reads ---------------------------------------------------------------
760
+
761
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
762
+ if (this.workerSelect) {
763
+ // ONE round-trip: the worker executes the whole plan (table creation,
764
+ // base select, relation tree, JSON parse) and returns structured-clone
765
+ // rows. The legacy path below pays a postMessage hop per table/relation
766
+ // level plus main-thread parsing — the dominant first-load cost.
767
+ //
768
+ // Normalize before postMessage: class-instance VALUES (RecordId & co) →
769
+ // their `stableKey` string. structuredClone strips a class instance to a
770
+ // bare plain object — and surrealdb's RecordId keeps its data behind
771
+ // getters (no own properties), so it clones to `{}`: the worker would
772
+ // filter on garbage. Applies to params AND to values baked inside the
773
+ // plan (where nodes, relation sub-wheres, window ids).
774
+ // Param KEYS must pass through untouched — `comparisonSql` resolves
775
+ // `paramRef` via hasOwnProperty, and a dropped key silently falls back to
776
+ // the baked literal (the crossed-results class fixed in aa4af79b).
777
+ const normPlan = normalizePlanForClone(plan);
778
+ const normParams: Record<string, unknown> = {};
779
+ for (const [k, v] of Object.entries(params)) normParams[k] = toCloneSafe(v);
780
+ try {
781
+ const res = await this.call<{ rows: Row[]; relationFetches?: number }>('select', {
782
+ plan: normPlan,
783
+ params: normParams,
784
+ });
785
+ getStats().relationFetches += res.relationFetches ?? 0;
786
+ return res.rows ?? [];
787
+ } catch (err) {
788
+ // Stale worker script without the 'select' op: fall back for good.
789
+ if (err instanceof Error && err.message.includes('unknown message')) {
790
+ this.workerSelect = false;
791
+ this.logger.warn(
792
+ { err, Category: 'sp00ky-client::SqliteCacheEngine::select' },
793
+ 'Worker lacks select op (stale script?) — falling back to multi-hop select'
794
+ );
795
+ } else {
796
+ throw err;
797
+ }
798
+ }
799
+ }
800
+ return this.selectLegacy(plan, params);
801
+ }
802
+
803
+ /** Pre-worker-select path: one worker round-trip per table/relation level,
804
+ * rows parsed on the main thread. Kept as the `workerSelect:false` escape
805
+ * hatch and the stale-worker fallback. */
806
+ private async selectLegacy(
807
+ plan: QueryPlan,
808
+ params: Record<string, unknown> = {}
809
+ ): Promise<Row[]> {
810
+ // Window materialization: base rows are exactly `plan.ids`, ordered.
811
+ if (plan.ids) {
812
+ const result = await this.selectByIds(plan.table, plan.ids, {
813
+ select: plan.select,
814
+ orderBy: plan.orderBy,
815
+ });
816
+ await resolveRelations(result, plan.relations, this);
817
+ return result;
818
+ }
819
+ await this.ensureTable(plan.table);
820
+ const bind: unknown[] = [];
821
+ // Projection binds land in the SELECT clause, ahead of any WHERE binds.
822
+ const proj = plan.select ? projectedDataSql(plan.select, bind) : 'data';
823
+ let sql = `SELECT ${proj} FROM "${plan.table}"`;
824
+ if (plan.where && plan.where.length > 0) {
825
+ sql += ` WHERE ${renderWhereSql(plan.where, bind, params)}`;
826
+ }
827
+ if (plan.orderBy && plan.orderBy.length > 0) sql += renderOrderSql(plan.orderBy);
828
+ // Deterministic fallback, in parity with `sqlite-select.ts`: without it an
829
+ // unordered query renders in insertion order here and in membership order
830
+ // after the server answers, which reshuffles the list on screen.
831
+ else sql += ` ORDER BY id`;
832
+ if (plan.limit !== undefined) sql += ` LIMIT ${Number(plan.limit)}`;
833
+ if (plan.offset !== undefined) sql += ` OFFSET ${Number(plan.offset)}`;
834
+ const rows = await this.execRows(sql, bind);
835
+ await resolveRelations(rows, plan.relations, this);
836
+ return rows;
837
+ }
838
+
839
+ async fetchRelation(req: RelationFetch): Promise<Row[]> {
840
+ getStats().relationFetches++;
841
+ await this.ensureTable(req.table);
842
+ const keys = req.keys.map(stableKey);
843
+ const placeholders = keys.map(() => '?').join(', ');
844
+ const bind: unknown[] = [...keys];
845
+ const lhs = req.matchField === 'id' ? 'id' : `json_extract(data, '$.${req.matchField}')`;
846
+ let sql = `SELECT data FROM "${req.table}" WHERE ${lhs} IN (${placeholders})`;
847
+ if (req.where && req.where.length > 0) {
848
+ sql += ` AND ${renderWhereSql(req.where, bind, {})}`;
849
+ }
850
+ if (req.orderBy && req.orderBy.length > 0) sql += renderOrderSql(req.orderBy);
851
+ const rows = await this.execRows(sql, bind);
852
+ return req.select ? rows.map((r) => project(r, req.select!)) : rows;
853
+ }
854
+
855
+ async selectByIds(
856
+ table: string,
857
+ ids: Id[],
858
+ opts?: { select?: string[]; orderBy?: OrderBy }
859
+ ): Promise<Row[]> {
860
+ if (ids.length === 0) return [];
861
+ await this.ensureTable(table);
862
+ const keys = ids.map(stableKey);
863
+ const placeholders = keys.map(() => '?').join(', ');
864
+ // Projection binds land in the SELECT clause, so they go first. Must stay
865
+ // byte-identical to the worker path in sqlite-select.ts.
866
+ const bind: unknown[] = [];
867
+ const dataCol = opts?.select ? projectedDataSql(opts.select, bind) : 'data';
868
+ bind.push(...keys);
869
+ let sql = `SELECT ${dataCol} FROM "${table}" WHERE id IN (${placeholders})`;
870
+ if (opts?.orderBy && opts.orderBy.length > 0) sql += renderOrderSql(opts.orderBy);
871
+ let rows = await this.execRows(sql, bind);
872
+ if (!opts?.orderBy || opts.orderBy.length === 0) {
873
+ const pos = new Map(keys.map((k, i) => [k, i]));
874
+ rows = rows.sort((a, b) => (pos.get(stableKey(a.id)) ?? 0) - (pos.get(stableKey(b.id)) ?? 0));
875
+ }
876
+ return rows;
877
+ }
878
+
879
+ async getById(table: string, id: Id): Promise<Row | null> {
880
+ await this.ensureTable(table);
881
+ const rows = await this.execRows(`SELECT data FROM "${table}" WHERE id = ?`, [stableKey(id)]);
882
+ return rows[0] ?? null;
883
+ }
884
+
885
+ /**
886
+ * `(id, _00_rv)` of every row per table, straight off the worker: no body
887
+ * parse, one round trip per table. A table that does not exist yet reads as
888
+ * empty rather than failing the whole scan.
889
+ */
890
+ async scanVersions(tables: string[]): Promise<Record<string, [string, number][]>> {
891
+ const out: Record<string, [string, number][]> = {};
892
+ for (const table of tables) {
893
+ try {
894
+ const { rows } = await this.call<{ rows: { id: string; rv: unknown }[] }>('exec', {
895
+ sql: `SELECT id, json_extract(data, '$._00_rv') AS rv FROM "${table.replace(/"/g, '""')}"`,
896
+ });
897
+ out[table] = (rows ?? []).map((r) => [r.id, Number(r.rv) || 0]);
898
+ } catch {
899
+ out[table] = [];
900
+ }
901
+ }
902
+ return out;
903
+ }
904
+
905
+ /**
906
+ * Reset the cached `_00_rv` of every table whose column set changed since
907
+ * the last boot, so its rows are fetched again whole. See
908
+ * `sqlite-column-reset.ts`. Returns the tables reset.
909
+ */
910
+ async resetChangedTables(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]> {
911
+ const { rows } = await this.call<{ rows: { data: unknown }[] }>('exec', {
912
+ sql: `SELECT data FROM "_00_schema" WHERE id = ?`,
913
+ bind: [COLUMNS_ROW_ID],
914
+ });
915
+ let stored: Record<string, string> | null = null;
916
+ try {
917
+ const raw = rows?.[0]?.data;
918
+ if (typeof raw === 'string') stored = JSON.parse(raw) as Record<string, string>;
919
+ } catch {
920
+ stored = null;
921
+ }
922
+ const { rows: tables } = await this.call<{ rows: { name: string }[] }>('exec', {
923
+ sql: `SELECT name FROM sqlite_master WHERE type = 'table'`,
924
+ });
925
+ const plan = planColumnReset(stored, fingerprints, new Set((tables ?? []).map((t) => t.name)), keep);
926
+ if (plan.statements.length > 0) await this.call('batch', plan.statements);
927
+ return plan.changed;
928
+ }
929
+
930
+ async getSnapshot(key: string): Promise<StoredSnapshot | null> {
931
+ const { rows } = await this.call<{ rows: { id: string; data: unknown }[] }>('exec', {
932
+ sql: `SELECT id, data FROM "${SNAPSHOT_TABLE}" WHERE id IN (?, ?)`,
933
+ bind: [key, `${key}:meta`],
934
+ });
935
+ let bytes: Uint8Array | null = null;
936
+ let meta: SnapshotMeta | null = null;
937
+ for (const r of rows ?? []) {
938
+ if (r.id === key) {
939
+ if (r.data instanceof Uint8Array) bytes = r.data;
940
+ else if (r.data instanceof ArrayBuffer) bytes = new Uint8Array(r.data);
941
+ else if (typeof r.data === 'string') bytes = new TextEncoder().encode(r.data);
942
+ } else if (typeof r.data === 'string') {
943
+ try {
944
+ meta = JSON.parse(r.data) as SnapshotMeta;
945
+ } catch {
946
+ meta = null;
947
+ }
948
+ }
949
+ }
950
+ return bytes && meta ? { bytes, meta } : null;
951
+ }
952
+
953
+ async putSnapshot(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void> {
954
+ // One transaction, so a reader never sees new bytes with old meta.
955
+ await this.call('batch', [
956
+ {
957
+ sql: `INSERT OR REPLACE INTO "${SNAPSHOT_TABLE}" (id, data) VALUES (?, ?)`,
958
+ bind: [key, bytes],
959
+ },
960
+ {
961
+ sql: `INSERT OR REPLACE INTO "${SNAPSHOT_TABLE}" (id, data) VALUES (?, ?)`,
962
+ bind: [`${key}:meta`, JSON.stringify(meta)],
963
+ },
964
+ ]);
965
+ }
966
+
967
+ async deleteSnapshot(key: string): Promise<void> {
968
+ await this.call('run', {
969
+ sql: `DELETE FROM "${SNAPSHOT_TABLE}" WHERE id IN (?, ?)`,
970
+ bind: [key, `${key}:meta`],
971
+ });
972
+ }
973
+
974
+ // ---- writes --------------------------------------------------------------
975
+
976
+ async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
977
+ await this.ensureTable(table);
978
+ const key = stableKey(id);
979
+ if (mode === 'merge') {
980
+ // Merge in-SQL via json_patch (RFC7396 = MERGE semantics): on insert store
981
+ // the row, on conflict shallow-merge. Serialize once, reuse for VALUES and
982
+ // the patch. No read-modify-write round-trip. (RFC7396: null deletes key,
983
+ // which is how a key holding `undefined` clears the stored field.)
984
+ const { insert, patch } = serializeMergeRow({ ...data, id: key });
985
+ await this.call('run', {
986
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
987
+ bind: [key, insert, patch],
988
+ });
989
+ return;
990
+ }
991
+ await this.call('run', {
992
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
993
+ bind: [key, serializeRow({ ...data, id: key })],
994
+ });
995
+ }
996
+
997
+ async patch(table: string, id: Id, patches: unknown[]): Promise<void> {
998
+ // RFC6902 (fast-json-patch) applied read-modify-write — SQLite's json_patch
999
+ // is RFC7396 merge-patch and would misinterpret op arrays.
1000
+ const existing = (await this.getById(table, id)) ?? { id: stableKey(id) };
1001
+ const next = applyPatch(existing, patches as Operation[]).newDocument as Row;
1002
+ await this.upsert(table, id, next, 'replace');
1003
+ }
1004
+
1005
+ async delete(table: string, id: Id): Promise<void> {
1006
+ await this.ensureTable(table);
1007
+ await this.call('run', { sql: `DELETE FROM "${table}" WHERE id = ?`, bind: [stableKey(id)] });
1008
+ }
1009
+
1010
+ // ---- SurrealQL-vocabulary shim (LocalStore compatibility) ---------------
1011
+
1012
+ /**
1013
+ * Execute a raw SurrealQL statement by translating the client's bounded
1014
+ * vocabulary to verbs (see `surql-translate.ts`). Returns results shaped like
1015
+ * SurrealDB's `.query()` (one element per statement; a tx prepends a `null`
1016
+ * begin-result so `surql.seal` extraction lines up). Epoch-fences writes.
1017
+ */
1018
+ async query<T extends unknown[]>(
1019
+ sql: string,
1020
+ vars: Record<string, unknown> = {},
1021
+ opts?: { epoch?: number }
1022
+ ): Promise<T> {
1023
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) throw new StaleEpochError();
1024
+ const start = performance.now();
1025
+ try {
1026
+ const { transaction, ops } = translateSurql(sql, vars);
1027
+ let shaped: unknown[];
1028
+ // FAST PATH: a pure-write transaction (bulk sync-down is one
1029
+ // `tx([upsertMerge…])`) compiles to a SINGLE worker `batch` message run in
1030
+ // one SQLite transaction — instead of 1-2 worker round-trips PER row. This
1031
+ // is the dominant sync-down cost; per-op execution here caused the churn
1032
+ // OOM. Mixed txs (LET/RETURN single-record mutations) keep the per-op path.
1033
+ if (
1034
+ transaction &&
1035
+ ops.every(
1036
+ (o) =>
1037
+ o.kind === 'upsert' ||
1038
+ o.kind === 'delete' ||
1039
+ o.kind === 'deleteAll' ||
1040
+ o.kind === 'noop'
1041
+ )
1042
+ ) {
1043
+ await this.runWriteBatch(ops);
1044
+ // Shape each statement's result the SAME as the per-op path (`execOp`),
1045
+ // so a caller reading a statement's output still works after taking the
1046
+ // batch fast path. A single `create()` compiles to an all-upsert tx
1047
+ // (createSet + createMutation) and reads `resultIndex:0` for the new
1048
+ // row + its id; returning empty arrays here dropped that row (id became
1049
+ // undefined → the reconcile crashed in `encodeRecordId`). The
1050
+ // single-batch write is kept — this only rebuilds the return value.
1051
+ shaped = [null, ...ops.map(pureWriteOpResult)];
1052
+ } else {
1053
+ const results: unknown[] = [];
1054
+ // Per-query scope holds `LET $var = (...)` bindings for later statements
1055
+ // (e.g. `RETURN { target: $updated }`).
1056
+ const scope: Record<string, unknown> = {};
1057
+ for (const op of ops) results.push(await this.execOp(op, scope, vars));
1058
+ shaped = transaction ? [null, ...results] : results;
1059
+ }
1060
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
1061
+ query: sql,
1062
+ vars,
1063
+ duration: performance.now() - start,
1064
+ success: true,
1065
+ timestamp: Date.now(),
1066
+ });
1067
+ return shaped as unknown as T;
1068
+ } catch (err) {
1069
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
1070
+ query: sql,
1071
+ vars,
1072
+ duration: performance.now() - start,
1073
+ success: false,
1074
+ error: err instanceof Error ? err.message : String(err),
1075
+ timestamp: Date.now(),
1076
+ });
1077
+ throw err;
1078
+ }
1079
+ }
1080
+
1081
+ async execute<R>(
1082
+ query: SealedQuery<R>,
1083
+ vars?: Record<string, unknown>,
1084
+ opts?: { epoch?: number }
1085
+ ): Promise<R> {
1086
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
1087
+ return query.extract(raw);
1088
+ }
1089
+
1090
+ queryUngated<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T> {
1091
+ return this.query<T>(sql, vars);
1092
+ }
1093
+
1094
+ private async execOp(
1095
+ op: SqlOp,
1096
+ scope: Record<string, unknown>,
1097
+ vars: Record<string, unknown>
1098
+ ): Promise<unknown> {
1099
+ switch (op.kind) {
1100
+ case 'getById': {
1101
+ const row = await this.getById(tableOf(op.id), op.id);
1102
+ if (op.value) return row ? (row[op.value] ?? null) : null;
1103
+ return row ? (op.select ? project(row, op.select) : row) : null;
1104
+ }
1105
+ case 'selectByIds': {
1106
+ if (op.ids.length === 0) return [];
1107
+ let rows = await this.selectByIds(tableOf(op.ids[0]), op.ids, {
1108
+ select: op.select,
1109
+ orderBy: op.orderBy,
1110
+ });
1111
+ // Windowed in JS, not SQL: the id list is already the whole result set,
1112
+ // and its order is restored after the fetch (see selectByIds).
1113
+ if (op.start !== undefined || op.limit !== undefined) {
1114
+ const from = op.start ?? 0;
1115
+ rows = rows.slice(from, op.limit === undefined ? undefined : from + op.limit);
1116
+ }
1117
+ if (op.value) return rows.map((r) => r[op.value!]);
1118
+ return rows;
1119
+ }
1120
+ case 'selectTable': {
1121
+ const rows = await this.rawSelectTable(op.table, op.where, op.orderBy, {
1122
+ limit: op.limit,
1123
+ start: op.start,
1124
+ });
1125
+ if (op.value) return rows.map((r) => r[op.value!]);
1126
+ return op.select ? rows.map((r) => project(r, op.select!)) : rows;
1127
+ }
1128
+ case 'count': {
1129
+ await this.ensureTable(op.table);
1130
+ const bind: unknown[] = [];
1131
+ let sql = `SELECT COUNT(*) AS n FROM "${op.table}"`;
1132
+ if (op.where && op.where.length > 0) sql += ` WHERE ${renderWhereSql(op.where, bind, {})}`;
1133
+ const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1134
+ // `GROUP ALL` collapses to a single `{ count }` row on SurrealDB; match
1135
+ // it exactly so callers can read `rows[0].count` on either engine.
1136
+ return [{ count: rows?.[0]?.n ?? 0 }];
1137
+ }
1138
+ case 'infoForDb': {
1139
+ const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1140
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1141
+ });
1142
+ // SurrealDB answers with the DEFINE statement per table. Nothing here
1143
+ // parses it (the DevTools explorer only reads the keys), so a truthful
1144
+ // schemaless stand-in beats inventing field definitions.
1145
+ const tables: Record<string, string> = {};
1146
+ for (const r of rows ?? []) tables[r.name] = `DEFINE TABLE ${r.name} SCHEMALESS`;
1147
+ return { tables, analyzers: {}, functions: {}, params: {}, users: {} };
1148
+ }
1149
+ case 'upsert':
1150
+ await this.upsert(tableOf(op.id), op.id, op.data, op.mode);
1151
+ // Cheap return — no read-back. The full merged row is only needed by a
1152
+ // LET-wrapped upsert, which reads it back in the 'let' case below. This
1153
+ // avoids an extra worker round-trip + full-row parse on EVERY sync-down
1154
+ // write (the hot path under rapid churn). Shared with the batch fast
1155
+ // path so the two never drift.
1156
+ return pureWriteOpResult(op);
1157
+ case 'updateSet': {
1158
+ const existing = (await this.getById(tableOf(op.id), op.id)) ?? { id: stableKey(op.id) };
1159
+ for (const { path, op: setOp, value } of op.sets) {
1160
+ if (setOp === '+=' || setOp === '-=') {
1161
+ const cur = Number(getPath(existing, path) ?? 0);
1162
+ const delta = Number(value ?? 0);
1163
+ setPath(existing, path, setOp === '+=' ? cur + delta : cur - delta);
1164
+ } else {
1165
+ setPath(existing, path, value);
1166
+ }
1167
+ }
1168
+ await this.upsert(tableOf(op.id), op.id, existing, 'replace');
1169
+ return op.returnNone ? null : existing;
1170
+ }
1171
+ case 'delete':
1172
+ await this.delete(tableOf(op.id), op.id);
1173
+ return pureWriteOpResult(op);
1174
+ case 'deleteAll':
1175
+ await this.ensureTable(op.table);
1176
+ await this.call('run', { sql: `DELETE FROM "${op.table}"` });
1177
+ return pureWriteOpResult(op);
1178
+ case 'let': {
1179
+ let result = await this.execOp(op.inner, scope, vars);
1180
+ // A LET-bound UPSERT must expose the FULL merged row (e.g.
1181
+ // `RETURN { target: $updated }`), so read it back here — only here,
1182
+ // not on every upsert.
1183
+ if (op.inner.kind === 'upsert') {
1184
+ result = (await this.getById(tableOf(op.inner.id), op.inner.id)) ?? result;
1185
+ }
1186
+ scope[op.var] = result;
1187
+ return result;
1188
+ }
1189
+ case 'return': {
1190
+ const obj: Row = {};
1191
+ for (const { key, var: v } of op.entries) {
1192
+ obj[key] = v in scope ? scope[v] : vars[v];
1193
+ }
1194
+ return obj;
1195
+ }
1196
+ case 'noop':
1197
+ return pureWriteOpResult(op);
1198
+ }
1199
+ }
1200
+
1201
+ /**
1202
+ * Compile a pure-write op list to ONE worker `batch` (single SQLite
1203
+ * transaction). Ensures each touched table exists, then one statement per op.
1204
+ * Merges happen in-SQL via json_patch — no read-back round-trips.
1205
+ */
1206
+ private async runWriteBatch(ops: SqlOp[]): Promise<void> {
1207
+ const stmts: { sql: string; bind?: unknown[] }[] = [];
1208
+ const tables = new Set<string>();
1209
+ const ensure = (t: string) => {
1210
+ if (!tables.has(t)) {
1211
+ tables.add(t);
1212
+ this.knownTables.add(t);
1213
+ stmts.push({
1214
+ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
1215
+ });
1216
+ }
1217
+ };
1218
+ for (const op of ops) {
1219
+ if (op.kind === 'upsert') {
1220
+ const t = tableOf(op.id);
1221
+ const key = stableKey(op.id);
1222
+ ensure(t);
1223
+ if (op.mode === 'merge') {
1224
+ // Serialize ONCE and reuse for both VALUES (fresh insert) and the
1225
+ // json_patch (merge). Patching with `id` is a harmless no-op set, so
1226
+ // the full row doubles as the delta — halves per-row stringify cost.
1227
+ // A key holding `undefined` (a field cleared upstream) rides in the
1228
+ // delta as a `null` member, which json_patch removes.
1229
+ const { insert, patch } = serializeMergeRow({ ...op.data, id: key });
1230
+ stmts.push({
1231
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
1232
+ bind: [key, insert, patch],
1233
+ });
1234
+ } else {
1235
+ stmts.push({
1236
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
1237
+ bind: [key, serializeRow({ ...op.data, id: key })],
1238
+ });
1239
+ }
1240
+ } else if (op.kind === 'delete') {
1241
+ const t = tableOf(op.id);
1242
+ ensure(t);
1243
+ stmts.push({ sql: `DELETE FROM "${t}" WHERE id = ?`, bind: [stableKey(op.id)] });
1244
+ } else if (op.kind === 'deleteAll') {
1245
+ ensure(op.table);
1246
+ stmts.push({ sql: `DELETE FROM "${op.table}"` });
1247
+ }
1248
+ }
1249
+ if (stmts.length > 0) await this.call('batch', stmts);
1250
+ }
1251
+
1252
+ private async rawSelectTable(
1253
+ table: string,
1254
+ where?: WhereNode[],
1255
+ orderBy?: OrderBy,
1256
+ window?: { limit?: number; start?: number }
1257
+ ): Promise<Row[]> {
1258
+ await this.ensureTable(table);
1259
+ const bind: unknown[] = [];
1260
+ let sql = `SELECT data FROM "${table}"`;
1261
+ if (where && where.length > 0) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
1262
+ if (orderBy && orderBy.length > 0) sql += renderOrderSql(orderBy);
1263
+ // SQLite has no bare OFFSET, so a START without a LIMIT needs `LIMIT -1`
1264
+ // (its documented "no limit" sentinel) to stay valid SQL.
1265
+ if (window?.limit !== undefined) sql += ` LIMIT ${Number(window.limit)}`;
1266
+ else if (window?.start !== undefined) sql += ' LIMIT -1';
1267
+ if (window?.start !== undefined) sql += ` OFFSET ${Number(window.start)}`;
1268
+ return this.execRows(sql, bind);
1269
+ }
1270
+
1271
+ async transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T> {
1272
+ // Verbs run in order on the single worker message channel. `patch` needs a
1273
+ // read-modify-write round-trip, so a single BEGIN/COMMIT batch cannot wrap
1274
+ // the whole closure; sequential execution is sufficient for the current
1275
+ // single-record write sites.
1276
+ const tx: EngineTx = {
1277
+ upsert: (t, id, data, mode) => this.upsert(t, id, data, mode),
1278
+ patch: (t, id, p) => this.patch(t, id, p),
1279
+ delete: (t, id) => this.delete(t, id),
1280
+ };
1281
+ return fn(tx);
1282
+ }
1283
+ }
1284
+
1285
+ // ==================== instrumentation ====================
1286
+
1287
+ interface SqliteStats {
1288
+ roundTrips: number;
1289
+ batchStatements: number;
1290
+ maxBatch: number;
1291
+ inFlight: number;
1292
+ maxInFlight: number;
1293
+ byType: Record<string, number>;
1294
+ /** Worker round trips that hit `localOpTimeoutMs` (see rawCall). */
1295
+ timeouts?: number;
1296
+ /** Time ops spent waiting behind the opQueue before dispatch. */
1297
+ queueWaitMs: number;
1298
+ /** Time inside the worker's message handler (actual SQLite work). */
1299
+ workerMs: number;
1300
+ /** Round-trip time minus workerMs: postMessage + scheduling overhead. */
1301
+ rpcOverheadMs: number;
1302
+ /** Main-thread JSON parse/revive of returned rows. */
1303
+ parseMs: number;
1304
+ rowsParsed: number;
1305
+ bytesParsed: number;
1306
+ /** Relation-resolver fan-out fetches (one worker round-trip each). */
1307
+ relationFetches: number;
1308
+ /** Whether the open store is OPFS-backed. `false` here with an `opfsError`
1309
+ * means the whole dataset is sitting in RAM. Optional so it stays absent
1310
+ * until the first open (and is skipped by the backfill loop below). */
1311
+ persisted?: boolean;
1312
+ /** Why OPFS persistence failed, when it did. */
1313
+ opfsError?: string;
1314
+ /** Shared-tabs follower: ops that crossed the leader's MessagePort. */
1315
+ proxiedOps?: number;
1316
+ /** Times this tab's engine changed hands (promotions + attachments). */
1317
+ roleChanges?: number;
1318
+ }
1319
+
1320
+ const EMPTY_STATS: SqliteStats = {
1321
+ roundTrips: 0,
1322
+ batchStatements: 0,
1323
+ maxBatch: 0,
1324
+ inFlight: 0,
1325
+ maxInFlight: 0,
1326
+ byType: {},
1327
+ queueWaitMs: 0,
1328
+ workerMs: 0,
1329
+ rpcOverheadMs: 0,
1330
+ parseMs: 0,
1331
+ rowsParsed: 0,
1332
+ bytesParsed: 0,
1333
+ relationFetches: 0,
1334
+ };
1335
+
1336
+ /** Live stats, inspectable in the browser console via `__sqliteStats`. Counts
1337
+ * worker round-trips (the sync-down cost driver), batch sizes, queue depth
1338
+ * (`maxInFlight`), and the latency split of each round-trip (queue wait vs
1339
+ * worker time vs RPC overhead vs main-thread row parsing) so first-load cost
1340
+ * can be measured rather than guessed. */
1341
+ function getStats(): SqliteStats {
1342
+ const g = globalThis as unknown as { __sqliteStats?: SqliteStats };
1343
+ if (!g.__sqliteStats) {
1344
+ g.__sqliteStats = { ...EMPTY_STATS, byType: {} };
1345
+ } else {
1346
+ // Backfill fields added since the object was created (HMR / older bundle).
1347
+ for (const [k, v] of Object.entries(EMPTY_STATS)) {
1348
+ if ((g.__sqliteStats as any)[k] === undefined) (g.__sqliteStats as any)[k] = v;
1349
+ }
1350
+ }
1351
+ return g.__sqliteStats;
1352
+ }
1353
+
1354
+ // SQL rendering + row (de)serialization live in `sqlite-plan-sql.ts`, shared
1355
+ // with the worker (worker-side plan execution renders the same SQL).
1356
+
1357
+ // ==================== structured-clone normalization ====================
1358
+
1359
+ /**
1360
+ * Make a bind/param value safe to cross the worker boundary. structuredClone
1361
+ * keeps plain data intact but strips a CLASS instance to a bare object — and
1362
+ * surrealdb's `RecordId` stores its fields behind getters (zero own
1363
+ * properties), so it clones to `{}`. Convert such instances to their
1364
+ * `stableKey` string (the exact value `scalar()` would bind on the main
1365
+ * thread), leave everything clone-representable untouched.
1366
+ */
1367
+ function toCloneSafe(v: unknown): unknown {
1368
+ if (v === null || typeof v !== 'object') return v;
1369
+ if (Array.isArray(v) || v instanceof Uint8Array || v instanceof Date) return v;
1370
+ const proto = Object.getPrototypeOf(v);
1371
+ if (proto === Object.prototype || proto === null) return v;
1372
+ return stableKey(v);
1373
+ }
1374
+
1375
+ function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1376
+ if (!nodes) return nodes;
1377
+ return nodes.map((n) =>
1378
+ 'or' in n
1379
+ ? { or: n.or.map((c) => ({ ...c, value: toCloneSafe(c.value) })) }
1380
+ : { ...n, value: toCloneSafe(n.value) }
1381
+ );
1382
+ }
1383
+
1384
+ function normalizeRelationForClone(r: RelationPlan): RelationPlan {
1385
+ return {
1386
+ ...r,
1387
+ where: normalizeWhereForClone(r.where),
1388
+ relations: r.relations?.map(normalizeRelationForClone),
1389
+ };
1390
+ }
1391
+
1392
+ /** Normalize every baked value a plan carries (where trees, window ids) for
1393
+ * the postMessage to the worker's `select` op. */
1394
+ function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1395
+ return {
1396
+ ...plan,
1397
+ ids: plan.ids?.map(stableKey),
1398
+ where: normalizeWhereForClone(plan.where),
1399
+ relations: plan.relations?.map(normalizeRelationForClone),
1400
+ };
1401
+ }