@spooky-sync/core 0.0.1-canary.32 → 0.0.1-canary.321

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