@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

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 (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  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/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -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 +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -0,0 +1,921 @@
1
+ import type { QueryPlan, WhereNode } from '@spooky-sync/query-builder';
2
+ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
3
+ import type { StorageHealth } from '../../types';
4
+ import type { Id, OrderBy, RelationFetch, Row, SnapshotMeta, StoredSnapshot } from './cache-engine';
5
+ import { stableKey } from './relation-resolver';
6
+ import { fromBase64, serializeMergeRow, serializeRow } from './sqlite-plan-sql';
7
+ import { COLUMNS_ROW_ID, planColumnReset } from './sqlite-column-reset';
8
+ import {
9
+ SNAPSHOT_TABLE,
10
+ SqliteCacheEngine,
11
+ normalizePlanForClone,
12
+ normalizeWhereForClone,
13
+ toCloneSafe,
14
+ } from './sqlite-cache-engine';
15
+ import { WorkerSqliteTransport, type SqliteTransport } from './sqlite-transport';
16
+ import { tableOf, type SqlOp } from './surql-translate';
17
+ import { ROWS_PROTOCOL, ROWS_READER_OPS, parseRowBytes, type WireOp } from './rows-exec';
18
+ import { FLAG_RAW, FLAG_U8, bucketDirName, type StoreStats } from './rows-store';
19
+ import {
20
+ ROWS_AHEAD_OPS,
21
+ ROWS_PREWARM_KEY,
22
+ ReadAhead,
23
+ aheadKey,
24
+ jsonSafe,
25
+ takePrewarmed,
26
+ type PrewarmRecord,
27
+ } from './rows-prewarm';
28
+
29
+ export { ROWS_PREWARM_KEY, ROWS_PREWARM_SNIPPET, prewarmRows } from './rows-prewarm';
30
+
31
+ /**
32
+ * Tables whose rows exist nowhere else: writes the user made that the server
33
+ * has not confirmed. A batch that touches one is flushed to disk before the
34
+ * write resolves. Everything else is a copy of server state and is flushed a
35
+ * moment later, in the worker's own time: losing it to a power cut costs a
36
+ * refetch, not a user's work.
37
+ */
38
+ export const ROWS_DURABLE_TABLES: ReadonlySet<string> = new Set([
39
+ '_00_pending_mutations',
40
+ '_00_pending_writes',
41
+ '_00_failed_mutations',
42
+ '_00_crdt_local',
43
+ ]);
44
+
45
+ const SCHEMA_TABLE = '_00_schema';
46
+
47
+ /** How long after connecting a read counts as one the app makes at startup. */
48
+ const PAINT_CAPTURE_MS = 3000;
49
+
50
+ // What the next page load asks the worker ahead of the app (see `rows-prewarm.ts`).
51
+ // Bounded: the answers wait in the page's memory until the app asks or writes.
52
+ const AHEAD_MAX_READS = 24;
53
+ const AHEAD_MAX_REPLY_BYTES = 512 << 10;
54
+ const AHEAD_MAX_TOTAL_BYTES = 2 << 20;
55
+ const AHEAD_MAX_REQUEST_CHARS = 32_000;
56
+ /** How long a read waits for an answer that was asked ahead before asking again itself. */
57
+ const AHEAD_WAIT_MS = 250;
58
+ /** How long a follower's own reader may take over one read before the leader is asked instead. */
59
+ const READER_OP_TIMEOUT_MS = 2000;
60
+
61
+ /** A timer nothing should wait for (a Node process, a test run). */
62
+ function background<T>(timer: T): T {
63
+ (timer as { unref?: () => void }).unref?.();
64
+ return timer;
65
+ }
66
+
67
+ /** Worker ops that leave the store as it was: none of them makes an answer read ahead stale. */
68
+ const ROWS_READ_OPS: ReadonlySet<string> = new Set([
69
+ 'select',
70
+ 'by-ids',
71
+ 'get',
72
+ 'relation',
73
+ 'select-table',
74
+ 'count',
75
+ 'versions',
76
+ 'tables',
77
+ 'blob-get',
78
+ 'diag',
79
+ 'warm',
80
+ ]);
81
+ const PAINT_MAX_KEYS = 64;
82
+ const PAINT_MAX_ENTRY_CHARS = 256_000;
83
+ const PAINT_FLUSH_MS = 1500;
84
+
85
+ interface PaintEntry {
86
+ tables: string[];
87
+ /** `0` or `1` (bytes to revive), then the rows as JSON text. */
88
+ text: string;
89
+ dirty: boolean;
90
+ }
91
+
92
+ function hashKey(text: string): string {
93
+ let a = 0x811c9dc5;
94
+ let b = 0x01000193;
95
+ for (let i = 0; i < text.length; i++) {
96
+ const c = text.charCodeAt(i);
97
+ a = Math.imul(a ^ c, 0x01000193);
98
+ b = Math.imul(b + c, 0x85ebca6b) ^ (b >>> 13);
99
+ }
100
+ return (a >>> 0).toString(36) + (b >>> 0).toString(36);
101
+ }
102
+
103
+ /**
104
+ * The rows the app read at startup last time, kept in localStorage: the one
105
+ * place a page can read synchronously, before a worker exists or a file is
106
+ * open. {@link RowsCacheEngine.peekByIds} and `peekSelect` answer from it in
107
+ * a fraction of a millisecond, so a screen can paint what it showed before
108
+ * while the store opens.
109
+ *
110
+ * What it holds is a copy, and the contract says so: a peek is something to
111
+ * paint from, the read that follows is the answer. The copy is dropped the
112
+ * moment this tab writes to a table it came from, and written again from the
113
+ * next read of the same thing, so in practice the two agree; when they do not
114
+ * (another tab wrote, the browser died before the drop reached the disk) the
115
+ * read that follows corrects the screen a few milliseconds later.
116
+ */
117
+ export class PaintCache {
118
+ private entries = new Map<string, PaintEntry>();
119
+ /** Reads this session made at startup: the ones worth keeping a copy of, whenever they run again. */
120
+ private known = new Set<string>();
121
+ /** table -> keys, for the entries of earlier sessions too. */
122
+ private byTable: Map<string, Set<string>> | null = null;
123
+ /** table -> writes this tab made to it, to tell a read sent before a write from one sent after. */
124
+ private writes = new Map<string, number>();
125
+ private timer: ReturnType<typeof setTimeout> | null = null;
126
+ private bucket = '';
127
+ private since = 0;
128
+
129
+ constructor(private maxChars: number) {
130
+ if (typeof addEventListener === 'function') {
131
+ // localStorage is synchronous, so the last state can still be saved as the page goes.
132
+ addEventListener('pagehide', () => this.flush());
133
+ }
134
+ }
135
+
136
+ /** The bucket about to be opened: peeks answer from it until `start` says which one it is. */
137
+ expect(bucket: string): void {
138
+ if (!this.bucket) this.bucket = bucket;
139
+ }
140
+
141
+ /** A new session on `bucket`: reads from now on are startup reads for a while. */
142
+ start(bucket: string): void {
143
+ if (bucket !== this.bucket) {
144
+ this.flush();
145
+ this.entries.clear();
146
+ this.known.clear();
147
+ this.byTable = null;
148
+ }
149
+ this.bucket = bucket;
150
+ this.since = Date.now();
151
+ }
152
+
153
+ private name(key: string): string {
154
+ return `sp00ky.paint.${this.bucket}.${key}`;
155
+ }
156
+
157
+ private index(): Map<string, Set<string>> {
158
+ if (this.byTable) return this.byTable;
159
+ this.byTable = new Map();
160
+ try {
161
+ const saved = JSON.parse(localStorage.getItem(`sp00ky.paint.${this.bucket}`) ?? '{}') as Record<string, string[]>;
162
+ for (const [key, tables] of Object.entries(saved)) this.link(key, tables);
163
+ } catch {
164
+ /* an unreadable index only means nothing gets dropped that is not there */
165
+ }
166
+ return this.byTable;
167
+ }
168
+
169
+ private link(key: string, tables: string[]): void {
170
+ const index = this.byTable!;
171
+ for (const table of tables) {
172
+ let keys = index.get(table);
173
+ if (!keys) index.set(table, (keys = new Set()));
174
+ keys.add(key);
175
+ }
176
+ }
177
+
178
+ get(key: string, revive: (b64: string) => Uint8Array): Row[] | null {
179
+ if (!this.bucket) return null;
180
+ try {
181
+ const text = this.entries.get(key)?.text ?? localStorage.getItem(this.name(key));
182
+ if (!text) return null;
183
+ if (text[0] === '0') return JSON.parse(text.slice(1)) as Row[];
184
+ return JSON.parse(text.slice(1), (_k, v) =>
185
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
186
+ ) as Row[];
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ /** How many writes `tables` have seen: taken when a read is sent, checked when it answers. */
193
+ stamp(tables: string[]): number {
194
+ let n = 0;
195
+ for (const table of tables) n += this.writes.get(table) ?? 0;
196
+ return n;
197
+ }
198
+
199
+ /**
200
+ * A read just answered: keep its text if it is a startup read, or one kept
201
+ * before. `sentAt` is {@link stamp} from when it was sent; a write to its
202
+ * tables since then means the answer may already be old, and it is let go.
203
+ */
204
+ note(key: string, tables: string[], rows: string, u8: boolean, sentAt: number): void {
205
+ if (!this.bucket || sentAt !== this.stamp(tables)) return;
206
+ if (!this.known.has(key)) {
207
+ if (Date.now() - this.since > PAINT_CAPTURE_MS || this.known.size >= PAINT_MAX_KEYS) return;
208
+ this.known.add(key);
209
+ }
210
+ if (rows.length > PAINT_MAX_ENTRY_CHARS) return;
211
+ this.entries.set(key, { tables, text: (u8 ? '1' : '0') + rows, dirty: true });
212
+ this.timer ??= setTimeout(() => this.flush(), PAINT_FLUSH_MS);
213
+ }
214
+
215
+ /** This tab is about to write to `tables`: what was read from them is no longer what they hold. */
216
+ touch(tables: Iterable<string>): void {
217
+ if (!this.bucket) return;
218
+ const index = this.index();
219
+ for (const table of tables) {
220
+ this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
221
+ const keys = index.get(table);
222
+ if (!keys || keys.size === 0) continue;
223
+ for (const key of keys) {
224
+ this.entries.delete(key);
225
+ try {
226
+ localStorage.removeItem(this.name(key));
227
+ } catch {
228
+ /* ignore */
229
+ }
230
+ }
231
+ keys.clear();
232
+ }
233
+ }
234
+
235
+ /** Write what changed, newest reads first, up to the budget. */
236
+ flush(): void {
237
+ if (this.timer) clearTimeout(this.timer);
238
+ this.timer = null;
239
+ if (!this.bucket) return;
240
+ const index = this.index();
241
+ try {
242
+ let used = 0;
243
+ const kept: Record<string, string[]> = {};
244
+ for (const [key, entry] of [...this.entries].reverse()) {
245
+ if (used + entry.text.length > this.maxChars) {
246
+ this.entries.delete(key);
247
+ localStorage.removeItem(this.name(key));
248
+ continue;
249
+ }
250
+ used += entry.text.length;
251
+ kept[key] = entry.tables;
252
+ if (entry.dirty) {
253
+ localStorage.setItem(this.name(key), entry.text);
254
+ entry.dirty = false;
255
+ this.link(key, entry.tables);
256
+ }
257
+ }
258
+ // Entries of earlier sessions that this one never read again stay until a write drops them.
259
+ for (const [table, keys] of index) {
260
+ for (const key of keys) {
261
+ const tables = (kept[key] ??= []);
262
+ if (!tables.includes(table)) tables.push(table);
263
+ }
264
+ }
265
+ localStorage.setItem(`sp00ky.paint.${this.bucket}`, JSON.stringify(kept));
266
+ } catch {
267
+ // Out of quota, or no storage: painting from the cache is a bonus, not a need.
268
+ }
269
+ }
270
+
271
+ /** Forget everything kept for `bucket`. */
272
+ static drop(bucket: string): void {
273
+ try {
274
+ const prefix = `sp00ky.paint.${bucket}`;
275
+ const mine: string[] = [];
276
+ for (let i = 0; i < localStorage.length; i++) {
277
+ const key = localStorage.key(i);
278
+ if (key !== null && (key === prefix || key.startsWith(prefix + '.'))) mine.push(key);
279
+ }
280
+ for (const key of mine) localStorage.removeItem(key);
281
+ } catch {
282
+ /* ignore */
283
+ }
284
+ }
285
+ }
286
+
287
+ /** Every table a plan reads: its own and its relations'. */
288
+ function tablesOf(plan: QueryPlan): string[] {
289
+ const out = new Set<string>([plan.table]);
290
+ const walk = (relations: QueryPlan['relations']): void => {
291
+ for (const relation of relations ?? []) {
292
+ out.add(relation.table);
293
+ walk(relation.relations);
294
+ }
295
+ };
296
+ walk(plan.relations);
297
+ return [...out];
298
+ }
299
+
300
+ const encoder = new TextEncoder();
301
+ const decoder = new TextDecoder();
302
+
303
+ type RowsReply = { buf: ArrayBuffer | null; u8?: boolean };
304
+
305
+ const byIdsKey = (table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): string =>
306
+ hashKey('i' + JSON.stringify([table, ids.map(stableKey), opts?.select ?? null, opts?.orderBy ?? null]));
307
+
308
+ function parseRowText(text: string, u8: boolean): Row[] {
309
+ if (!u8) return JSON.parse(text) as Row[];
310
+ return JSON.parse(text, (_k, v) =>
311
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? fromBase64((v as { __u8: string }).__u8) : v
312
+ ) as Row[];
313
+ }
314
+ type OpenReply = { persisted: boolean; opfsError?: string; proto?: number; workerUrl?: string };
315
+
316
+ /** One write, with the table and key already resolved. */
317
+ export type WriteItem =
318
+ | { kind: 'upsert'; table: string; key: string; data: Row; mode: 'replace' | 'merge' }
319
+ | { kind: 'delete'; table: string; key: string }
320
+ | { kind: 'clear'; table: string };
321
+
322
+ /** The writes of a translated statement list; the table is the id's own. */
323
+ function itemsOf(ops: SqlOp[]): WriteItem[] {
324
+ const items: WriteItem[] = [];
325
+ for (const op of ops) {
326
+ if (op.kind === 'noop') continue;
327
+ if (op.kind === 'deleteAll') items.push({ kind: 'clear', table: op.table });
328
+ else if (op.kind === 'delete') items.push({ kind: 'delete', table: tableOf(op.id), key: stableKey(op.id) });
329
+ else if (op.kind === 'upsert') {
330
+ items.push({ kind: 'upsert', table: tableOf(op.id), key: stableKey(op.id), data: op.data, mode: op.mode });
331
+ } else throw new Error(`RowsCacheEngine: ${op.kind} is not a write`);
332
+ }
333
+ return items;
334
+ }
335
+
336
+ /**
337
+ * Serialize a batch of writes for the worker: every row's JSON text in one
338
+ * buffer, which is transferred, and one small tuple per op saying where its
339
+ * text lies. The text is what `SqliteCacheEngine` stores, byte for byte.
340
+ */
341
+ export function packWrites(items: WriteItem[]): { wire: WireOp[]; buf: ArrayBuffer | null; sync: boolean } {
342
+ const wire: WireOp[] = [];
343
+ let bytes = new Uint8Array(0);
344
+ let at = 0;
345
+ let sync = false;
346
+ const append = (text: string): [off: number, len: number] => {
347
+ // `encodeInto` needs room for the worst case, three bytes per UTF-16 unit.
348
+ const need = at + text.length * 3;
349
+ if (bytes.length < need) {
350
+ const grown = new Uint8Array(Math.max(need, bytes.length * 2, 1024));
351
+ grown.set(bytes.subarray(0, at));
352
+ bytes = grown;
353
+ }
354
+ const written = encoder.encodeInto(text, bytes.subarray(at)).written;
355
+ const off = at;
356
+ at += written;
357
+ return [off, written];
358
+ };
359
+ for (const op of items) {
360
+ const table = op.table;
361
+ if (ROWS_DURABLE_TABLES.has(table)) sync = true;
362
+ if (op.kind === 'clear') {
363
+ wire.push(['clear', table]);
364
+ continue;
365
+ }
366
+ const key = op.key;
367
+ if (op.kind === 'delete') {
368
+ wire.push(['del', table, key]);
369
+ continue;
370
+ }
371
+ const row: Row = { ...op.data, id: key };
372
+ const rv = Number(row._00_rv) || 0;
373
+ if (op.mode === 'replace') {
374
+ const text = serializeRow(row);
375
+ const [off, len] = append(text);
376
+ wire.push(['put', table, key, rv, text.includes('"__u8"') ? FLAG_U8 : 0, off, len]);
377
+ continue;
378
+ }
379
+ const { insert, patch } = serializeMergeRow(row);
380
+ const [off, len] = append(insert);
381
+ // The patch differs from the row only when a field is being cleared.
382
+ const [patchOff, patchLen] = patch === insert ? [0, 0] : append(patch);
383
+ wire.push(['merge', table, key, rv, insert.includes('"__u8"') ? FLAG_U8 : 0, off, len, patchOff, patchLen]);
384
+ }
385
+ return { wire, buf: at > 0 ? (bytes.buffer as ArrayBuffer) : null, sync };
386
+ }
387
+
388
+ /**
389
+ * Local cache backend on sp00ky's own row store (`rows-store.ts`), in a
390
+ * dedicated Worker (`rows-worker.ts`) on OPFS.
391
+ *
392
+ * It answers every verb the way {@link SqliteCacheEngine} does (same stored
393
+ * JSON, same filter and ordering rules, checked against real SQLite in
394
+ * `rows-exec.integration.test.ts`), so an app can switch between the two with
395
+ * `localEngine` alone. What differs is underneath: no SQL is rendered, rows
396
+ * cross the worker boundary as JSON text in a transferred buffer and are
397
+ * parsed once, on the side that reads them.
398
+ *
399
+ * It extends the SQLite engine for everything that is about the worker rather
400
+ * than about SQL: the serialized op queue, epoch fencing, bucket switches, the
401
+ * shared-tabs roles, the SurrealQL-vocabulary shim. Every method that renders
402
+ * SQL there is replaced here by a message to the row worker.
403
+ */
404
+ export class RowsCacheEngine extends SqliteCacheEngine {
405
+ override readonly engineKind = 'rows' as const;
406
+ /** The transport in use wraps a worker `prewarmRows` started. */
407
+ private adopted = false;
408
+ /** Last-seen startup reads, for {@link peekByIds} / {@link peekSelect}. Off for a memory store. */
409
+ private paint: PaintCache | null =
410
+ this.useOpfs && this.config.paintCache !== false && typeof localStorage !== 'undefined' ? new PaintCache(1_000_000) : null;
411
+
412
+ protected override createTransport(): SqliteTransport {
413
+ const pre = takePrewarmed();
414
+ if (pre?.failed) pre.worker.terminate();
415
+ this.adopted = pre !== null && !pre.failed;
416
+ const transport = new WorkerSqliteTransport(
417
+ this.logger,
418
+ this.adopted
419
+ ? () => pre!.worker
420
+ : // Same shape as the SQLite worker's URL: `.ts` for bundlers that build
421
+ // from source, rewritten to `./rows-worker.js` in the published build.
422
+ (this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' })))
423
+ );
424
+ // What the worker was asked ahead of the app, for as long as it holds true.
425
+ let ahead = this.adopted ? new ReadAhead(pre!, AHEAD_WAIT_MS) : null;
426
+ const forget = (): void => {
427
+ ahead?.drop();
428
+ ahead = null;
429
+ };
430
+ if (ahead) background(setTimeout(forget, PAINT_CAPTURE_MS));
431
+ let opens = 0;
432
+ // Every open is checked: a worker from another release must not be talked to.
433
+ const call = transport.call.bind(transport);
434
+ transport.call = async <T>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> => {
435
+ if (type === 'open') {
436
+ // The prewarm's work stands only for the first open, of the store it
437
+ // was started on, with nothing more asked of the worker (under a
438
+ // role's lock other tabs write through this worker too).
439
+ const asked = payload as { dbName: string; useOpfs: boolean; workerLockName?: string; share?: boolean };
440
+ // A leader whose followers read the file themselves opens it for sharing.
441
+ if (asked.workerLockName && asked.useOpfs && this.config.followerReads === 'direct') {
442
+ asked.share = true;
443
+ }
444
+ const mine = ahead !== null && opens++ === 0 && asked.useOpfs && asked.dbName === pre!.bucket && !asked.workerLockName;
445
+ const answered = pre?.opened as (OpenReply & { ok?: boolean }) | undefined;
446
+ if (pre) pre.opened = undefined;
447
+ if (!mine) forget();
448
+ else if (answered?.persisted) {
449
+ // The worker answered this very open already: no need to ask again.
450
+ this.opened(transport, asked, answered);
451
+ return answered as T;
452
+ }
453
+ } else if (ahead && ROWS_AHEAD_OPS.has(type)) {
454
+ const early = ahead.take(type, payload);
455
+ const got = early ? await early : null;
456
+ if (got) {
457
+ const { id: _id, ok: _ok, error: _error, ...rest } = got;
458
+ return rest as T;
459
+ }
460
+ } else if (!ROWS_READ_OPS.has(type)) forget();
461
+ const reply = await call<T>(type, payload, transfer);
462
+ if (type === 'open') this.opened(transport, payload as { dbName: string; useOpfs: boolean }, reply as OpenReply);
463
+ return reply;
464
+ };
465
+ return transport;
466
+ }
467
+
468
+ private opened(transport: SqliteTransport, asked: { dbName: string; useOpfs: boolean }, reply: OpenReply): void {
469
+ if (reply.proto !== ROWS_PROTOCOL) {
470
+ transport.close('row worker speaks another protocol');
471
+ throw new Error(`RowsCacheEngine: worker protocol ${String(reply.proto)}, expected ${ROWS_PROTOCOL}`);
472
+ }
473
+ // Leave the next page load what it needs to start this worker ahead of the app.
474
+ try {
475
+ if (asked.useOpfs && reply.persisted && reply.workerUrl) {
476
+ const old = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
477
+ const record: PrewarmRecord = { url: reply.workerUrl, bucket: asked.dbName };
478
+ // The reads to ask ahead belong to a bucket: another user's are not kept.
479
+ if (old?.bucket === asked.dbName && Array.isArray(old.reads)) record.reads = old.reads;
480
+ localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify(record));
481
+ }
482
+ } catch {
483
+ // No localStorage (a worker, a locked-down page): nothing to prewarm from.
484
+ }
485
+ }
486
+
487
+ /**
488
+ * A prewarmed worker is a guess. When it turns out wrong (it failed to
489
+ * load, or it is another release's), drop it and connect again with a
490
+ * worker of our own.
491
+ */
492
+ override async connect(bucketId: string): Promise<void> {
493
+ // Known before the worker answers, so a peek can be asked for right away.
494
+ this.bucketId = bucketId;
495
+ this.paint?.start(bucketId);
496
+ try {
497
+ await super.connect(bucketId);
498
+ this.beginStartupReads();
499
+ } catch (error) {
500
+ if (!this.adopted) throw error;
501
+ this.adopted = false;
502
+ try {
503
+ localStorage.removeItem(ROWS_PREWARM_KEY);
504
+ } catch {
505
+ /* ignore */
506
+ }
507
+ this.logger.warn(
508
+ { error, Category: 'sp00ky-client::RowsCacheEngine::connect' },
509
+ 'Prewarmed row worker was unusable; starting a fresh one'
510
+ );
511
+ await this.close();
512
+ await super.connect(bucketId);
513
+ this.beginStartupReads();
514
+ }
515
+ }
516
+
517
+ override async switchBucket(bucketId: string): Promise<void> {
518
+ this.dropReader('bucket switch');
519
+ await super.switchBucket(bucketId);
520
+ this.paint?.start(bucketId);
521
+ this.beginStartupReads();
522
+ }
523
+
524
+ /** A follower reads through the leader's worker; one started ahead for this tab is not needed. */
525
+ override async adoptAttached(
526
+ dbPort: MessagePort,
527
+ snapshot: { bucketId: string; storageHealth: StorageHealth },
528
+ onPortDead: (reason: string) => void
529
+ ): Promise<void> {
530
+ takePrewarmed()?.worker.terminate();
531
+ this.dropReader('attaching to a leader');
532
+ await super.adoptAttached(dbPort, snapshot, onPortDead);
533
+ if (this.config.followerReads === 'direct' && this.useOpfs && snapshot.storageHealth.status === 'persistent') {
534
+ await this.startReader(snapshot.bucketId);
535
+ }
536
+ }
537
+
538
+ // ---- a follower's own reader ------------------------------------------------
539
+ // With `followerReads: 'direct'` a follower answers its reads from a worker
540
+ // of its own, on a reader of the store's file (`RowStore` reader mode). The
541
+ // reader is an optimization and nothing depends on it: when it cannot be
542
+ // had, or fails, the read goes to the leader as it would have.
543
+
544
+ /** The follower's reader worker, while this engine follows and has one. */
545
+ private reader: SqliteTransport | null = null;
546
+
547
+ private async startReader(bucketId: string): Promise<void> {
548
+ let transport: SqliteTransport | null = null;
549
+ // Every change of role bumps the epoch: the same epoch later means still this follower.
550
+ const asFollower = this.epoch;
551
+ try {
552
+ transport = new WorkerSqliteTransport(
553
+ this.logger,
554
+ this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' }))
555
+ );
556
+ const reply = await transport.call<OpenReply>('open', {
557
+ dbName: bucketId,
558
+ useOpfs: true,
559
+ reader: true,
560
+ openOptions: { maxAttempts: 2, disallowMemoryFallback: true },
561
+ });
562
+ if (reply.proto !== ROWS_PROTOCOL || !reply.persisted) throw new Error('reader worker is not this release\'s');
563
+ // The role may have moved on while the worker started.
564
+ if (this.epoch !== asFollower || this.bucketId !== bucketId) throw new Error('no longer a follower of this store');
565
+ this.reader = transport;
566
+ } catch (error) {
567
+ transport?.close('reader unavailable');
568
+ this.logger.info(
569
+ { error: String(error), Category: 'sp00ky-client::RowsCacheEngine::reader' },
570
+ 'No direct reads for this follower tab; it reads through the leader'
571
+ );
572
+ }
573
+ }
574
+
575
+ private dropReader(reason: string): void {
576
+ const reader = this.reader;
577
+ this.reader = null;
578
+ reader?.close(reason);
579
+ }
580
+
581
+ /** True while this follower answers its reads from the store's file itself. */
582
+ get readsDirectly(): boolean {
583
+ return this.reader !== null;
584
+ }
585
+
586
+ protected override rawCall<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
587
+ const reader = this.reader;
588
+ if (!reader || !ROWS_READER_OPS.has(type)) return super.rawCall<T>(type, payload, transfer);
589
+ let timer: ReturnType<typeof setTimeout> | undefined;
590
+ const late = new Promise<never>((_resolve, reject) => {
591
+ timer = setTimeout(() => reject(new Error('reader timed out')), READER_OP_TIMEOUT_MS);
592
+ });
593
+ return Promise.race([reader.call<T>(type, payload), late])
594
+ .catch((error: unknown) => {
595
+ if (this.reader === reader) {
596
+ this.dropReader('read failed');
597
+ this.logger.warn(
598
+ { error: String(error), type, Category: 'sp00ky-client::RowsCacheEngine::reader' },
599
+ 'Direct read failed; this tab reads through the leader from here on'
600
+ );
601
+ }
602
+ return super.rawCall<T>(type, payload, transfer);
603
+ })
604
+ .finally(() => clearTimeout(timer));
605
+ }
606
+
607
+ override async adoptOwner(...args: Parameters<SqliteCacheEngine['adoptOwner']>): ReturnType<SqliteCacheEngine['adoptOwner']> {
608
+ this.dropReader('becoming the leader');
609
+ return super.adoptOwner(...args);
610
+ }
611
+
612
+ override async releaseOwnership(): Promise<void> {
613
+ this.dropReader('releasing the store');
614
+ return super.releaseOwnership();
615
+ }
616
+
617
+ override onLeaderLost(reason: string): void {
618
+ // The file is still there and still whole, but writes have nowhere to go:
619
+ // read through the next leader, with a reader started against it.
620
+ this.dropReader('leader lost');
621
+ super.onLeaderLost(reason);
622
+ }
623
+
624
+ override async close(): Promise<void> {
625
+ this.dropReader('engine closed');
626
+ return super.close();
627
+ }
628
+
629
+ /** Tables need no creating: a table is the rows written to it. */
630
+ protected override async ensureTable(): Promise<void> {}
631
+
632
+ // ---- read ahead -----------------------------------------------------------
633
+ // The reads of a session's first seconds are saved, and the next page load's
634
+ // prewarm asks them again before the app exists (`rows-prewarm.ts`).
635
+
636
+ private startupReads: Map<string, [string, unknown]> | null = null;
637
+ private startupBytes = 0;
638
+ private startupUntil = 0;
639
+ private startupTimer: ReturnType<typeof setTimeout> | null = null;
640
+ private startupHooked = false;
641
+
642
+ private beginStartupReads(): void {
643
+ // Not with shared tabs: other tabs write through the leader's worker, and
644
+ // an answer read ahead of them could be older than what they wrote.
645
+ if (!this.useOpfs || this.shared || typeof localStorage === 'undefined') return;
646
+ if (!this.startupHooked && typeof addEventListener === 'function') {
647
+ // localStorage is synchronous, so the list can still be saved as the page goes.
648
+ addEventListener('pagehide', () => this.saveStartupReads());
649
+ this.startupHooked = true;
650
+ }
651
+ this.startupReads = new Map();
652
+ this.startupBytes = 0;
653
+ this.startupUntil = performance.now() + PAINT_CAPTURE_MS;
654
+ if (this.startupTimer) clearTimeout(this.startupTimer);
655
+ this.startupTimer = background(setTimeout(() => this.saveStartupReads(), PAINT_CAPTURE_MS + 50));
656
+ }
657
+
658
+ private noteStartupRead(type: string, payload: unknown, replyBytes: number): void {
659
+ const reads = this.startupReads;
660
+ if (!reads || performance.now() > this.startupUntil || !ROWS_AHEAD_OPS.has(type)) return;
661
+ if (reads.size >= AHEAD_MAX_READS || replyBytes > AHEAD_MAX_REPLY_BYTES) return;
662
+ if (this.startupBytes + replyBytes > AHEAD_MAX_TOTAL_BYTES || !jsonSafe(payload)) return;
663
+ const key = aheadKey(type, payload);
664
+ if (key.length > AHEAD_MAX_REQUEST_CHARS || reads.has(key)) return;
665
+ reads.set(key, [type, payload]);
666
+ this.startupBytes += replyBytes;
667
+ }
668
+
669
+ /** Leave this session's startup reads for the next page load. Also runs as the page goes. */
670
+ private saveStartupReads(): void {
671
+ const reads = this.startupReads;
672
+ if (!reads) return;
673
+ try {
674
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
675
+ if (!saved?.url || saved.bucket !== this.bucketId) return;
676
+ localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify({ url: saved.url, bucket: saved.bucket, reads: [...reads.values()] }));
677
+ } catch {
678
+ // No storage, or no room: the next load asks nothing ahead.
679
+ }
680
+ }
681
+
682
+ /** A read that answers rows. `paint` names it for the paint cache, when it is worth keeping. */
683
+ private async rows(type: string, payload: unknown, paint?: { key: string; tables: string[] }): Promise<Row[]> {
684
+ const sentAt = paint && this.paint ? this.paint.stamp(paint.tables) : 0;
685
+ const reply = await this.call<RowsReply>(type, payload);
686
+ this.noteStartupRead(type, payload, reply.buf?.byteLength ?? 0);
687
+ if (!reply.buf) return [];
688
+ const text = decoder.decode(new Uint8Array(reply.buf));
689
+ if (paint) this.paint?.note(paint.key, paint.tables, text, reply.u8 === true, sentAt);
690
+ return parseRowText(text, reply.u8 === true);
691
+ }
692
+
693
+ // ---- reads ---------------------------------------------------------------
694
+
695
+ private selectPayload(plan: QueryPlan, params: Record<string, unknown>): { plan: QueryPlan; params: Record<string, unknown> } {
696
+ // Class instances (RecordId) do not survive structured clone; see the
697
+ // SQLite engine's `select` for why the KEYS of `params` must all stay.
698
+ const normParams: Record<string, unknown> = {};
699
+ for (const [k, v] of Object.entries(params)) normParams[k] = toCloneSafe(v);
700
+ return { plan: normalizePlanForClone(plan), params: normParams };
701
+ }
702
+
703
+ /**
704
+ * The paint cache's name for a select. A caller that reads the same thing
705
+ * again and again under changing arguments (a query whose id set moves)
706
+ * names it itself with `paintKey`, so the copy kept is always its latest
707
+ * answer; without one a read is told apart by its plan and parameters.
708
+ */
709
+ private selectKey(payload: unknown, opts?: { paintKey?: string }): string {
710
+ return opts?.paintKey === undefined ? hashKey('s' + JSON.stringify(payload)) : hashKey('q' + opts.paintKey);
711
+ }
712
+
713
+ override async select(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Promise<Row[]> {
714
+ const payload = this.selectPayload(plan, params);
715
+ return this.rows('select', payload, this.paint ? { key: this.selectKey(payload, opts), tables: tablesOf(plan) } : undefined);
716
+ }
717
+
718
+ /**
719
+ * What `select(plan, params)` answered the last time the app asked at
720
+ * startup, synchronously, or `null`. Available as soon as `connect` was
721
+ * CALLED: it reads localStorage, not the store. Paint from it, then run the
722
+ * real `select`, which is the answer; they differ only when something wrote
723
+ * to these tables that this tab did not see.
724
+ */
725
+ peekSelect(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Row[] | null {
726
+ if (!this.paint) return null;
727
+ // A named read needs no payload to find its copy.
728
+ const payload = opts?.paintKey === undefined ? this.selectPayload(plan, params) : null;
729
+ return this.paint.get(this.selectKey(payload, opts), fromBase64);
730
+ }
731
+
732
+ /**
733
+ * See `LocalStore.expectBucket`. Not with shared tabs: the paint cache is
734
+ * not kept there (other tabs write to the store unseen by this one).
735
+ */
736
+ expectBucket(bucketId: string): void {
737
+ if (!this.shared) this.paint?.expect(bucketId);
738
+ }
739
+
740
+ /** {@link peekSelect} for `selectByIds`. */
741
+ peekByIds(table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): Row[] | null {
742
+ return this.paint?.get(byIdsKey(table, ids, opts), fromBase64) ?? null;
743
+ }
744
+
745
+ override async fetchRelation(req: RelationFetch): Promise<Row[]> {
746
+ return this.rows('relation', {
747
+ table: req.table,
748
+ matchField: req.matchField,
749
+ keys: req.keys.map(stableKey),
750
+ where: normalizeWhereForClone(req.where),
751
+ orderBy: req.orderBy,
752
+ select: req.select,
753
+ });
754
+ }
755
+
756
+ override async selectByIds(
757
+ table: string,
758
+ ids: Id[],
759
+ opts?: { select?: string[]; orderBy?: OrderBy }
760
+ ): Promise<Row[]> {
761
+ if (ids.length === 0) return [];
762
+ return this.rows(
763
+ 'by-ids',
764
+ { table, ids: ids.map(stableKey), select: opts?.select, orderBy: opts?.orderBy },
765
+ this.paint ? { key: byIdsKey(table, ids, opts), tables: [table] } : undefined
766
+ );
767
+ }
768
+
769
+ override async getById(table: string, id: Id): Promise<Row | null> {
770
+ return parseRowBytes<Row | null>(await this.call<RowsReply>('get', { table, id: stableKey(id) }), fromBase64);
771
+ }
772
+
773
+ override async scanVersions(tables: string[]): Promise<Record<string, [string, number][]>> {
774
+ return (await this.call<{ versions: Record<string, [string, number][]> }>('versions', { tables })).versions;
775
+ }
776
+
777
+ /**
778
+ * See `sqlite-column-reset.ts`. The recorded column sets live in one raw row
779
+ * of `_00_schema`, which no row read ever returns.
780
+ */
781
+ override async resetChangedTables(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]> {
782
+ const { bytes } = await this.call<{ bytes: ArrayBuffer | null }>('blob-get', { table: SCHEMA_TABLE, key: COLUMNS_ROW_ID });
783
+ let stored: Record<string, string> | null = null;
784
+ try {
785
+ if (bytes) stored = JSON.parse(decoder.decode(new Uint8Array(bytes))) as Record<string, string>;
786
+ } catch {
787
+ stored = null;
788
+ }
789
+ const tables = await this.listTables();
790
+ const plan = planColumnReset(stored, fingerprints, new Set(tables), keep);
791
+ if (plan.statements.length === 0) return plan.changed;
792
+ this.paint?.touch(plan.changed);
793
+ if (plan.changed.length > 0) await this.call('reset-versions', { tables: plan.changed, keep: [...keep] });
794
+ // Recorded last: a tab that dies between the two redoes the reset, which is harmless.
795
+ const body = encoder.encode(JSON.stringify(fingerprints));
796
+ const buf = body.buffer as ArrayBuffer;
797
+ await this.call(
798
+ 'write',
799
+ { ops: [['put', SCHEMA_TABLE, COLUMNS_ROW_ID, 0, FLAG_RAW, 0, body.length]] satisfies WireOp[], buf, sync: false },
800
+ [buf]
801
+ );
802
+ return plan.changed;
803
+ }
804
+
805
+ override async getSnapshot(key: string): Promise<StoredSnapshot | null> {
806
+ const { bytes, meta } = await this.call<{ bytes: ArrayBuffer | null; meta: string | null }>('blob-get', {
807
+ table: SNAPSHOT_TABLE,
808
+ key,
809
+ });
810
+ if (!bytes || !meta) return null;
811
+ try {
812
+ return { bytes: new Uint8Array(bytes), meta: JSON.parse(meta) as SnapshotMeta };
813
+ } catch {
814
+ return null;
815
+ }
816
+ }
817
+
818
+ override async putSnapshot(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void> {
819
+ // A copy, so the transfer does not take the caller's buffer away.
820
+ const buf = bytes.slice().buffer as ArrayBuffer;
821
+ await this.call('blob-put', { table: SNAPSHOT_TABLE, key, bytes: buf, meta: JSON.stringify(meta) }, [buf]);
822
+ }
823
+
824
+ override async deleteSnapshot(key: string): Promise<void> {
825
+ await this.call('blob-del', { table: SNAPSHOT_TABLE, key });
826
+ }
827
+
828
+ // ---- writes --------------------------------------------------------------
829
+
830
+ override async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
831
+ await this.write([{ kind: 'upsert', table, key: stableKey(id), data, mode }]);
832
+ }
833
+
834
+ override async delete(table: string, id: Id): Promise<void> {
835
+ await this.write([{ kind: 'delete', table, key: stableKey(id) }]);
836
+ }
837
+
838
+ /** One message, one atomic batch in the store, however many rows. */
839
+ private async write(items: WriteItem[]): Promise<void> {
840
+ const { wire, buf, sync } = packWrites(items);
841
+ if (wire.length === 0) return;
842
+ this.paint?.touch(new Set(items.map((item) => item.table)));
843
+ await this.call('write', { ops: wire, buf, sync }, buf ? [buf] : undefined);
844
+ }
845
+
846
+ protected override runWriteBatch(ops: SqlOp[]): Promise<void> {
847
+ return this.write(itemsOf(ops));
848
+ }
849
+
850
+ protected override async rawSelectTable(
851
+ table: string,
852
+ where?: WhereNode[],
853
+ orderBy?: OrderBy,
854
+ window?: { limit?: number; start?: number }
855
+ ): Promise<Row[]> {
856
+ return this.rows('select-table', {
857
+ table,
858
+ where: normalizeWhereForClone(where),
859
+ orderBy,
860
+ limit: window?.limit,
861
+ start: window?.start,
862
+ });
863
+ }
864
+
865
+ protected override async countRows(table: string, where?: WhereNode[]): Promise<number> {
866
+ return (await this.call<{ n: number }>('count', { table, where: normalizeWhereForClone(where) })).n;
867
+ }
868
+
869
+ protected override async listTables(): Promise<string[]> {
870
+ return (await this.call<{ tables: string[] }>('tables')).tables;
871
+ }
872
+
873
+ protected override async deleteAllRows(table: string): Promise<void> {
874
+ await this.write([{ kind: 'clear', table }]);
875
+ }
876
+
877
+ // ---- housekeeping --------------------------------------------------------
878
+
879
+ override async getStorageDiagnostics(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics> {
880
+ const diag: EngineStorageDiagnostics = {
881
+ engine: 'rows',
882
+ bucketId: this.bucketId,
883
+ useOpfs: this.useOpfs,
884
+ workerSelectConfigured: true,
885
+ workerSelectEffective: true,
886
+ };
887
+ try {
888
+ const { stats, tableCounts } = await this.call<{
889
+ stats: StoreStats;
890
+ tableCounts?: { table: string; rows: number }[];
891
+ }>('diag', { tableCounts: opts?.tableCounts === true });
892
+ diag.dbSizeBytes = stats.fileBytes;
893
+ diag.freelistBytes = stats.garbageBytes;
894
+ if (tableCounts) diag.tableCounts = tableCounts.filter((t) => t.table !== SNAPSHOT_TABLE);
895
+ } catch (e) {
896
+ diag.error = e instanceof Error ? e.message : String(e);
897
+ }
898
+ return diag;
899
+ }
900
+
901
+ /** See `LocalStore.dropBucket`. Fails harmlessly while a worker holds the files. */
902
+ override async dropBucket(bucketId: string): Promise<void> {
903
+ if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
904
+ PaintCache.drop(bucketId);
905
+ try {
906
+ // Nothing to start ahead for a store that is gone.
907
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
908
+ if (saved?.bucket === bucketId) localStorage.removeItem(ROWS_PREWARM_KEY);
909
+ } catch {
910
+ /* no storage */
911
+ }
912
+ const storage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
913
+ if (!storage?.getDirectory) return;
914
+ const root = await storage.getDirectory();
915
+ try {
916
+ await root.removeEntry(bucketDirName(bucketId), { recursive: true });
917
+ } catch (error) {
918
+ if ((error as DOMException)?.name !== 'NotFoundError') throw error;
919
+ }
920
+ }
921
+ }