@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.11

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 (55) hide show
  1. package/AGENTS.md +4 -3
  2. package/dist/index.d.ts +170 -9
  3. package/dist/index.js +5398 -2968
  4. package/dist/rows-worker.d.ts +1 -0
  5. package/dist/rows-worker.js +2731 -0
  6. package/dist/sqlite-open.js +1 -1
  7. package/dist/sqlite-worker.js +1 -1
  8. package/dist/types.d.ts +131 -13
  9. package/package.json +9 -4
  10. package/scripts/check-worker-entries.mjs +15 -2
  11. package/skills/sp00ky-core/SKILL.md +2 -0
  12. package/src/client/bucket-handle.ts +21 -1
  13. package/src/client/eager-paint.test.ts +82 -0
  14. package/src/client/services.ts +4 -1
  15. package/src/client/sp00ky-client.test.ts +143 -1
  16. package/src/client/sp00ky-client.ts +158 -19
  17. package/src/index.ts +9 -0
  18. package/src/kernel/effects.ts +12 -2
  19. package/src/kernel/interpreter.test.ts +17 -0
  20. package/src/kernel/interpreter.ts +5 -2
  21. package/src/modules/channel/hub.test.ts +223 -0
  22. package/src/modules/channel/hub.ts +355 -0
  23. package/src/modules/channel/index.ts +358 -14
  24. package/src/modules/channel/room.test.ts +340 -0
  25. package/src/modules/channel/room.ts +367 -0
  26. package/src/modules/channel/rooms.fixture.ts +383 -0
  27. package/src/modules/channel/share.test.ts +535 -0
  28. package/src/modules/channel/webrtc.ts +2 -2
  29. package/src/modules/devtools/storage-info.ts +4 -3
  30. package/src/query/materialize.saga.test.ts +16 -0
  31. package/src/query/materialize.saga.ts +7 -26
  32. package/src/query/materialize.ts +79 -3
  33. package/src/query/register.saga.test.ts +61 -0
  34. package/src/query/register.saga.ts +39 -2
  35. package/src/services/database/cache-engine.ts +17 -3
  36. package/src/services/database/engine-factory.ts +7 -0
  37. package/src/services/database/index.ts +1 -0
  38. package/src/services/database/rows-cache-engine.test.ts +1584 -0
  39. package/src/services/database/rows-cache-engine.ts +1203 -0
  40. package/src/services/database/rows-exec.integration.test.ts +589 -0
  41. package/src/services/database/rows-exec.ts +1027 -0
  42. package/src/services/database/rows-prewarm.ts +251 -0
  43. package/src/services/database/rows-store.test.ts +635 -0
  44. package/src/services/database/rows-store.ts +1208 -0
  45. package/src/services/database/rows-transport.fixture.ts +151 -0
  46. package/src/services/database/rows-worker.ts +607 -0
  47. package/src/services/database/rows-yield.test.ts +141 -0
  48. package/src/services/database/rows-yield.ts +92 -0
  49. package/src/services/database/sqlite-cache-engine.test.ts +22 -1
  50. package/src/services/database/sqlite-cache-engine.ts +55 -34
  51. package/src/services/database/sqlite-transport.ts +7 -5
  52. package/src/services/tabs/support.ts +6 -4
  53. package/src/types.ts +41 -6
  54. package/tsdown.config.ts +42 -1
  55. package/vitest.config.ts +4 -0
@@ -0,0 +1,141 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { AheadStore, type AheadHost, type YieldChannel } from './rows-yield';
3
+ import { ROWS_PREWARM_OPEN_ID } from './rows-prewarm';
4
+
5
+ /** BroadcastChannels of one name: a message reaches every channel but the one that sent it. */
6
+ function hub(): () => YieldChannel {
7
+ const channels: YieldChannel[] = [];
8
+ return () => {
9
+ const channel: YieldChannel = {
10
+ onmessage: null,
11
+ postMessage: (data) => {
12
+ for (const other of channels) if (other !== channel) other.onmessage?.({ data } as MessageEvent);
13
+ },
14
+ };
15
+ channels.push(channel);
16
+ return channel;
17
+ };
18
+ }
19
+
20
+ /** A worker as `AheadStore` sees it: an open bucket, a queue of ops, a page. */
21
+ function worker(channel: (() => YieldChannel) | null, bucket: string | null = 'user_a') {
22
+ const state = {
23
+ bucket,
24
+ queue: [] as (() => void)[],
25
+ closed: 0,
26
+ told: [] as { id: number; ok: false; error: string }[],
27
+ /** Run what waits in the op queue. */
28
+ run() {
29
+ for (const fn of state.queue.splice(0)) fn();
30
+ },
31
+ };
32
+ const host: AheadHost = {
33
+ channel: () => channel?.() ?? null,
34
+ openBucket: () => state.bucket,
35
+ enqueue: (fn) => void state.queue.push(fn),
36
+ closeStore: () => {
37
+ state.closed++;
38
+ state.bucket = null;
39
+ },
40
+ tellPage: (message) => void state.told.push(message),
41
+ };
42
+ return { state, store: new AheadStore(host) };
43
+ }
44
+
45
+ describe('a store opened ahead of its page', () => {
46
+ it('is given to the worker that leads, and the page is told under the open\'s id', () => {
47
+ const channel = hub();
48
+ const held = worker(channel);
49
+ const leader = worker(channel, null);
50
+ held.store.openedAhead();
51
+ leader.store.ask('user_a');
52
+ // In turn with the ops: nothing is closed under a read that is running.
53
+ expect(held.state.closed).toBe(0);
54
+ held.state.run();
55
+ expect(held.state.closed).toBe(1);
56
+ expect(held.state.told).toEqual([{ id: ROWS_PREWARM_OPEN_ID, ok: false, error: expect.stringContaining('gave the store') }]);
57
+ // Asked again (the leader's next attempt): there is nothing left to give.
58
+ leader.store.ask('user_a');
59
+ held.state.run();
60
+ expect(held.state.closed).toBe(1);
61
+ expect(held.state.told.length).toBe(1);
62
+ });
63
+
64
+ it('stays with a page that has claimed it', () => {
65
+ const channel = hub();
66
+ const held = worker(channel);
67
+ const leader = worker(channel, null);
68
+ held.store.openedAhead();
69
+ held.store.claim();
70
+ leader.store.ask('user_a');
71
+ held.state.run();
72
+ expect(held.state.closed).toBe(0);
73
+ expect(held.state.told).toEqual([]);
74
+ });
75
+
76
+ it('stays with a page that claims it while the hand-over waits its turn', () => {
77
+ const channel = hub();
78
+ const held = worker(channel);
79
+ const leader = worker(channel, null);
80
+ held.store.openedAhead();
81
+ leader.store.ask('user_a');
82
+ expect(held.state.queue.length).toBe(1);
83
+ held.store.claim();
84
+ held.state.run();
85
+ expect(held.state.closed).toBe(0);
86
+ expect(held.state.told).toEqual([]);
87
+ });
88
+
89
+ it('is not given up for another bucket, nor by a worker whose page opened it itself', () => {
90
+ const channel = hub();
91
+ const held = worker(channel);
92
+ const owned = worker(channel);
93
+ const leader = worker(channel, null);
94
+ held.store.openedAhead();
95
+ // `owned` never opened ahead: its store was asked for by its page.
96
+ owned.store.claim();
97
+ owned.store.openedAhead();
98
+ leader.store.ask('user_b');
99
+ held.state.run();
100
+ owned.state.run();
101
+ expect(held.state.closed).toBe(0);
102
+ leader.store.ask('user_a');
103
+ held.state.run();
104
+ owned.state.run();
105
+ expect(held.state.closed).toBe(1);
106
+ expect(owned.state.closed).toBe(0);
107
+ });
108
+
109
+ it('is asked for again when the first asking came while it was still being opened', () => {
110
+ const channel = hub();
111
+ const held = worker(channel, null);
112
+ const leader = worker(channel, null);
113
+ // The open is under way: no store yet, and nobody listening.
114
+ held.store.openedAhead();
115
+ leader.store.ask('user_a');
116
+ held.state.run();
117
+ expect(held.state.closed).toBe(0);
118
+ held.state.bucket = 'user_a';
119
+ held.store.openedAhead();
120
+ // The leader's next failed attempt.
121
+ leader.store.ask('user_a');
122
+ held.state.run();
123
+ expect(held.state.closed).toBe(1);
124
+ });
125
+
126
+ it('does nothing where there is no channel to ask on', () => {
127
+ const held = worker(null);
128
+ held.store.openedAhead();
129
+ expect(() => held.store.ask('user_a')).not.toThrow();
130
+ held.state.run();
131
+ expect(held.state.closed).toBe(0);
132
+ // Nor when the channel throws.
133
+ const broken = worker(() => ({
134
+ onmessage: null,
135
+ postMessage: () => {
136
+ throw new Error('closed');
137
+ },
138
+ }));
139
+ expect(() => broken.store.ask('user_a')).not.toThrow();
140
+ });
141
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * A store opened ahead of its page, and how the tab that leads gets it back.
3
+ *
4
+ * `prewarmRows` (rows-prewarm.ts) starts the row worker from the page head and
5
+ * opens the last bucket's store before the app has loaded. With shared tabs
6
+ * the page cannot know then whether it will lead. When another tab does, that
7
+ * tab's worker finds the files held by a worker nobody uses: its page becomes
8
+ * a follower and ends it, but only once its bundle has loaded and it was told
9
+ * its role, and the leader's ten attempts are over by then.
10
+ *
11
+ * So a worker that leads asks for the files each time an open fails, and a
12
+ * worker that holds them unclaimed gives them up and tells its page. A page
13
+ * claims its worker with the first message it sends under an id of its own
14
+ * (everything a prewarm sends goes under a negative one).
15
+ *
16
+ * Kept apart from `rows-worker.ts`, which runs only in a worker on OPFS, so
17
+ * this can be tested.
18
+ */
19
+ import { ROWS_PREWARM_OPEN_ID } from './rows-prewarm';
20
+
21
+ /** What this needs of a BroadcastChannel. A channel never hears its own messages. */
22
+ export interface YieldChannel {
23
+ postMessage(message: unknown): void;
24
+ onmessage: ((ev: MessageEvent) => void) | null;
25
+ }
26
+
27
+ export interface AheadHost {
28
+ /** The channel the workers of an origin ask each other on, or null where there is none. */
29
+ channel(): YieldChannel | null;
30
+ /** The bucket whose store is open in this worker, or null. */
31
+ openBucket(): string | null;
32
+ /** Run `fn` in turn with the worker's ops, so a store is not closed under a read. */
33
+ enqueue(fn: () => void): void;
34
+ closeStore(): void;
35
+ /** Post to the page that started this worker. */
36
+ tellPage(message: { id: number; ok: false; error: string }): void;
37
+ }
38
+
39
+ export class AheadStore {
40
+ /** The open store was opened ahead of the page. */
41
+ private ahead = false;
42
+ /** The page has sent a message of its own: what is open here is its store from now on. */
43
+ private claimed = false;
44
+ private heard: YieldChannel | null = null;
45
+
46
+ constructor(private host: AheadHost) {}
47
+
48
+ /** A message from the page under an id of its own. */
49
+ claim(): void {
50
+ this.claimed = true;
51
+ }
52
+
53
+ /** The open a prewarm asked for has succeeded. */
54
+ openedAhead(): void {
55
+ if (this.claimed || this.host.openBucket() === null || !this.listen()) return;
56
+ this.ahead = true;
57
+ }
58
+
59
+ /** This worker leads `bucket` and could not open its files: whoever holds them unclaimed is asked for them. */
60
+ ask(bucket: string): void {
61
+ try {
62
+ this.listen()?.postMessage({ bucket });
63
+ } catch {
64
+ /* no channel: the retries are all there is */
65
+ }
66
+ }
67
+
68
+ private wanted(bucket: unknown): boolean {
69
+ return this.ahead && !this.claimed && this.host.openBucket() !== null && this.host.openBucket() === bucket;
70
+ }
71
+
72
+ private listen(): YieldChannel | null {
73
+ if (this.heard) return this.heard;
74
+ const channel = this.host.channel();
75
+ if (!channel) return null;
76
+ channel.onmessage = (ev) => {
77
+ const bucket = (ev.data as { bucket?: unknown } | null)?.bucket;
78
+ if (!this.wanted(bucket)) return;
79
+ // The page may claim the store while this waits its turn.
80
+ this.host.enqueue(() => {
81
+ if (!this.wanted(bucket)) return;
82
+ this.ahead = false;
83
+ this.host.closeStore();
84
+ // Under the open's id: the page then takes neither that open as answered
85
+ // nor anything it had read ahead (`prewarmRows`, `ReadAhead`).
86
+ this.host.tellPage({ id: ROWS_PREWARM_OPEN_ID, ok: false, error: 'rows worker: gave the store to the tab that leads' });
87
+ });
88
+ };
89
+ this.heard = channel;
90
+ return channel;
91
+ }
92
+ }
@@ -1,4 +1,4 @@
1
- import { describe, it, expect } from 'vitest';
1
+ import { describe, it, expect, vi } from 'vitest';
2
2
  import { RecordId } from 'surrealdb';
3
3
  import { pureWriteOpResult, SqliteCacheEngine } from './sqlite-cache-engine';
4
4
  import { stubTransport } from './sqlite-transport.fixture';
@@ -570,6 +570,27 @@ describe('create() tx result shaping (fast path parity)', () => {
570
570
  });
571
571
 
572
572
 
573
+ // patch() applies RFC6902 ops through fast-json-patch's default export (a
574
+ // named import broke loading dist/index.js in Node ESM). Exercise the call so
575
+ // a regression to an unusable binding fails here, not only at build time.
576
+ describe('SqliteCacheEngine.patch', () => {
577
+ it('applies RFC6902 ops read-modify-write and stores the result', async () => {
578
+ const engine = new SqliteCacheEngine({ namespace: 'n', database: 'd' } as any, makeLogger());
579
+ vi.spyOn(engine, 'getById').mockResolvedValue({ id: 'game:1', title: 'a', tags: ['x'] });
580
+ const upsert = vi.spyOn(engine, 'upsert').mockResolvedValue(undefined);
581
+ await engine.patch('game', 'game:1', [
582
+ { op: 'replace', path: '/title', value: 'b' },
583
+ { op: 'add', path: '/tags/-', value: 'y' },
584
+ ]);
585
+ expect(upsert).toHaveBeenCalledWith(
586
+ 'game',
587
+ 'game:1',
588
+ { id: 'game:1', title: 'b', tags: ['x', 'y'] },
589
+ 'replace'
590
+ );
591
+ });
592
+ });
593
+
573
594
  // The circuit snapshot + version scan the boot-time prime reads through this
574
595
  // engine. Bytes and meta must round-trip as ONE batch (a reader must never see
575
596
  // new bytes with old meta) and a table that does not exist yet scans as empty.
@@ -1,4 +1,9 @@
1
- import { applyPatch, type Operation } from 'fast-json-patch';
1
+ // Default import, not `{ applyPatch }`: fast-json-patch 3.x is CommonJS for
2
+ // Node (its ESM build is reachable only through the `module` field bundlers
3
+ // read) and fills `module.exports` via Object.assign, which Node's CJS export
4
+ // lexer cannot see. A named import makes `dist/index.js` throw a SyntaxError on
5
+ // load in Node ESM (SSR, Vitest). Same pattern as `pino` in services/logger.
6
+ import jsonPatch, { type Operation } from 'fast-json-patch';
2
7
  import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
3
8
  import { withTimeout } from '../../utils/index';
4
9
  import type { QueryPlan, RelationPlan, WhereNode } from '@spooky-sync/query-builder';
@@ -55,7 +60,7 @@ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-in
55
60
  * on a fresh bucket throws "no such table". Keep in sync with the systemSchema
56
61
  * block in `local-migrator.ts`.
57
62
  */
58
- const SNAPSHOT_TABLE = '_00_circuit_snapshot';
63
+ export const SNAPSHOT_TABLE = '_00_circuit_snapshot';
59
64
 
60
65
  const SYSTEM_TABLES = [
61
66
  '_00_stream_processor_state',
@@ -116,7 +121,7 @@ export class SqliteCacheEngine implements LocalStore {
116
121
  private transport: SqliteTransport | null = null;
117
122
  private storeEpoch = 0;
118
123
  private knownTables = new Set<string>();
119
- private useOpfs: boolean;
124
+ protected useOpfs: boolean;
120
125
  /** Whether `select` runs as one worker round-trip (plan executed in-worker).
121
126
  * Flipped off at runtime if the worker script predates the `select` op
122
127
  * (stale cached bundle) — degrade to the legacy multi-hop path, don't break. */
@@ -125,7 +130,7 @@ export class SqliteCacheEngine implements LocalStore {
125
130
  * downgrade (configured true, effective false) from a configured-off. */
126
131
  private workerSelectConfigured: boolean;
127
132
  private events: DatabaseEventSystem = createDatabaseEventSystem();
128
- private bucketId = 'anon';
133
+ protected bucketId = 'anon';
129
134
  /** Deadline for one worker round trip; see `localOpTimeoutMs`. */
130
135
  private readonly localOpTimeoutMs: number;
131
136
  /** Durability of the local store, set on every open. A plain Set of callbacks
@@ -136,19 +141,19 @@ export class SqliteCacheEngine implements LocalStore {
136
141
  /** Schemaless — tables are created lazily on first write; no migrator. */
137
142
  readonly usesSurqlSchema = false;
138
143
 
139
- readonly engineKind = 'sqlite' as const;
144
+ readonly engineKind: 'sqlite' | 'rows' = 'sqlite';
140
145
 
141
146
  /** Shared-tabs mode: the engine's transport is swapped at runtime by the
142
147
  * TabsCoordinator (owner worker as leader, leader's port as follower). */
143
- private shared: boolean;
148
+ protected shared: boolean;
144
149
  /** Leaderless parking (shared mode): ops entering the opQueue await this
145
150
  * gate until a new role lands or the timeout rejects them. */
146
151
  private roleGate: { promise: Promise<void>; release: () => void } | null = null;
147
152
  private roleGateTimer: ReturnType<typeof setTimeout> | null = null;
148
153
 
149
154
  constructor(
150
- private config: Sp00kyConfig<any>['database'],
151
- private logger: Logger,
155
+ protected config: Sp00kyConfig<any>['database'],
156
+ protected logger: Logger,
152
157
  opts: { useOpfs?: boolean; workerSelect?: boolean; shared?: boolean } = {}
153
158
  ) {
154
159
  this.localOpTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
@@ -279,7 +284,7 @@ export class SqliteCacheEngine implements LocalStore {
279
284
  * the boot/switch atomicity below.) */
280
285
  private opQueue: Promise<unknown> = Promise.resolve();
281
286
 
282
- private call<T = any>(type: string, payload?: unknown): Promise<T> {
287
+ protected call<T = any>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
283
288
  const enqueuedAt = performance.now();
284
289
  const run = async () => {
285
290
  // Leaderless window (shared mode): park behind the role gate instead of
@@ -287,7 +292,7 @@ export class SqliteCacheEngine implements LocalStore {
287
292
  if (this.roleGate) await this.roleGate.promise;
288
293
  // Time spent waiting behind other ops in the queue, not doing work.
289
294
  getStats().queueWaitMs += performance.now() - enqueuedAt;
290
- return this.rawCall<T>(type, payload);
295
+ return this.rawCall<T>(type, payload, transfer);
291
296
  };
292
297
  const result = this.opQueue.then(run, run);
293
298
  // Keep the chain alive regardless of individual failures.
@@ -325,7 +330,7 @@ export class SqliteCacheEngine implements LocalStore {
325
330
  }
326
331
  }
327
332
 
328
- private rawCall<T = any>(type: string, payload?: unknown): Promise<T> {
333
+ protected rawCall<T = any>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
329
334
  if (!this.transport) throw new Error('SqliteCacheEngine: not connected');
330
335
  // --- instrumentation: live, inspectable via `globalThis.__sqliteStats` ---
331
336
  const s = getStats();
@@ -360,7 +365,7 @@ export class SqliteCacheEngine implements LocalStore {
360
365
  // one, and killing it mid-write would cost more than the wait.
361
366
  const timeoutMs = this.localOpTimeoutMs;
362
367
  const result = withTimeout(
363
- this.transport.call<T>(type, payload),
368
+ this.transport.call<T>(type, payload, transfer),
364
369
  timeoutMs,
365
370
  () => new LocalOpTimeoutError(type, timeoutMs)
366
371
  ).then(
@@ -735,7 +740,7 @@ export class SqliteCacheEngine implements LocalStore {
735
740
  this.transport = null;
736
741
  }
737
742
 
738
- private async ensureTable(table: string): Promise<void> {
743
+ protected async ensureTable(table: string): Promise<void> {
739
744
  if (this.knownTables.has(table)) return;
740
745
  await this.call('run', {
741
746
  sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
@@ -758,7 +763,8 @@ export class SqliteCacheEngine implements LocalStore {
758
763
 
759
764
  // ---- reads ---------------------------------------------------------------
760
765
 
761
- async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
766
+ // `_opts.paintKey` names the read for a store that keeps answers to paint from; this one keeps none.
767
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}, _opts?: { paintKey?: string }): Promise<Row[]> {
762
768
  if (this.workerSelect) {
763
769
  // ONE round-trip: the worker executes the whole plan (table creation,
764
770
  // base select, relation tree, JSON parse) and returns structured-clone
@@ -998,7 +1004,7 @@ export class SqliteCacheEngine implements LocalStore {
998
1004
  // RFC6902 (fast-json-patch) applied read-modify-write — SQLite's json_patch
999
1005
  // is RFC7396 merge-patch and would misinterpret op arrays.
1000
1006
  const existing = (await this.getById(table, id)) ?? { id: stableKey(id) };
1001
- const next = applyPatch(existing, patches as Operation[]).newDocument as Row;
1007
+ const next = jsonPatch.applyPatch(existing, patches as Operation[]).newDocument as Row;
1002
1008
  await this.upsert(table, id, next, 'replace');
1003
1009
  }
1004
1010
 
@@ -1125,25 +1131,16 @@ export class SqliteCacheEngine implements LocalStore {
1125
1131
  if (op.value) return rows.map((r) => r[op.value!]);
1126
1132
  return op.select ? rows.map((r) => project(r, op.select!)) : rows;
1127
1133
  }
1128
- case 'count': {
1129
- await this.ensureTable(op.table);
1130
- const bind: unknown[] = [];
1131
- let sql = `SELECT COUNT(*) AS n FROM "${op.table}"`;
1132
- if (op.where && op.where.length > 0) sql += ` WHERE ${renderWhereSql(op.where, bind, {})}`;
1133
- const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1134
+ case 'count':
1134
1135
  // `GROUP ALL` collapses to a single `{ count }` row on SurrealDB; match
1135
1136
  // it exactly so callers can read `rows[0].count` on either engine.
1136
- return [{ count: rows?.[0]?.n ?? 0 }];
1137
- }
1137
+ return [{ count: await this.countRows(op.table, op.where) }];
1138
1138
  case 'infoForDb': {
1139
- const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1140
- sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1141
- });
1142
1139
  // SurrealDB answers with the DEFINE statement per table. Nothing here
1143
1140
  // parses it (the DevTools explorer only reads the keys), so a truthful
1144
1141
  // schemaless stand-in beats inventing field definitions.
1145
1142
  const tables: Record<string, string> = {};
1146
- for (const r of rows ?? []) tables[r.name] = `DEFINE TABLE ${r.name} SCHEMALESS`;
1143
+ for (const name of await this.listTables()) tables[name] = `DEFINE TABLE ${name} SCHEMALESS`;
1147
1144
  return { tables, analyzers: {}, functions: {}, params: {}, users: {} };
1148
1145
  }
1149
1146
  case 'upsert':
@@ -1172,8 +1169,7 @@ export class SqliteCacheEngine implements LocalStore {
1172
1169
  await this.delete(tableOf(op.id), op.id);
1173
1170
  return pureWriteOpResult(op);
1174
1171
  case 'deleteAll':
1175
- await this.ensureTable(op.table);
1176
- await this.call('run', { sql: `DELETE FROM "${op.table}"` });
1172
+ await this.deleteAllRows(op.table);
1177
1173
  return pureWriteOpResult(op);
1178
1174
  case 'let': {
1179
1175
  let result = await this.execOp(op.inner, scope, vars);
@@ -1198,12 +1194,37 @@ export class SqliteCacheEngine implements LocalStore {
1198
1194
  }
1199
1195
  }
1200
1196
 
1197
+ // The three statements `execOp` needs beyond the verbs. Methods of their own
1198
+ // so an engine that stores rows differently (`RowsCacheEngine`) answers them
1199
+ // its own way.
1200
+
1201
+ protected async countRows(table: string, where?: WhereNode[]): Promise<number> {
1202
+ await this.ensureTable(table);
1203
+ const bind: unknown[] = [];
1204
+ let sql = `SELECT COUNT(*) AS n FROM "${table}"`;
1205
+ if (where && where.length > 0) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
1206
+ const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1207
+ return rows?.[0]?.n ?? 0;
1208
+ }
1209
+
1210
+ protected async listTables(): Promise<string[]> {
1211
+ const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1212
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1213
+ });
1214
+ return (rows ?? []).map((r) => r.name);
1215
+ }
1216
+
1217
+ protected async deleteAllRows(table: string): Promise<void> {
1218
+ await this.ensureTable(table);
1219
+ await this.call('run', { sql: `DELETE FROM "${table}"` });
1220
+ }
1221
+
1201
1222
  /**
1202
1223
  * Compile a pure-write op list to ONE worker `batch` (single SQLite
1203
1224
  * transaction). Ensures each touched table exists, then one statement per op.
1204
1225
  * Merges happen in-SQL via json_patch — no read-back round-trips.
1205
1226
  */
1206
- private async runWriteBatch(ops: SqlOp[]): Promise<void> {
1227
+ protected async runWriteBatch(ops: SqlOp[]): Promise<void> {
1207
1228
  const stmts: { sql: string; bind?: unknown[] }[] = [];
1208
1229
  const tables = new Set<string>();
1209
1230
  const ensure = (t: string) => {
@@ -1249,7 +1270,7 @@ export class SqliteCacheEngine implements LocalStore {
1249
1270
  if (stmts.length > 0) await this.call('batch', stmts);
1250
1271
  }
1251
1272
 
1252
- private async rawSelectTable(
1273
+ protected async rawSelectTable(
1253
1274
  table: string,
1254
1275
  where?: WhereNode[],
1255
1276
  orderBy?: OrderBy,
@@ -1364,7 +1385,7 @@ function getStats(): SqliteStats {
1364
1385
  * `stableKey` string (the exact value `scalar()` would bind on the main
1365
1386
  * thread), leave everything clone-representable untouched.
1366
1387
  */
1367
- function toCloneSafe(v: unknown): unknown {
1388
+ export function toCloneSafe(v: unknown): unknown {
1368
1389
  if (v === null || typeof v !== 'object') return v;
1369
1390
  if (Array.isArray(v) || v instanceof Uint8Array || v instanceof Date) return v;
1370
1391
  const proto = Object.getPrototypeOf(v);
@@ -1372,7 +1393,7 @@ function toCloneSafe(v: unknown): unknown {
1372
1393
  return stableKey(v);
1373
1394
  }
1374
1395
 
1375
- function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1396
+ export function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1376
1397
  if (!nodes) return nodes;
1377
1398
  return nodes.map((n) =>
1378
1399
  'or' in n
@@ -1391,7 +1412,7 @@ function normalizeRelationForClone(r: RelationPlan): RelationPlan {
1391
1412
 
1392
1413
  /** Normalize every baked value a plan carries (where trees, window ids) for
1393
1414
  * the postMessage to the worker's `select` op. */
1394
- function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1415
+ export function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1395
1416
  return {
1396
1417
  ...plan,
1397
1418
  ids: plan.ids?.map(stableKey),
@@ -19,7 +19,8 @@ export interface SqliteTransport {
19
19
  readonly kind: 'worker' | 'port';
20
20
  /** True while the transport can carry a request. */
21
21
  readonly connected: boolean;
22
- call<T = unknown>(type: string, payload?: unknown): Promise<T>;
22
+ /** `transfer` hands the listed buffers over instead of copying them. */
23
+ call<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T>;
23
24
  /** Reject every pending request with `reason`. Safe to call repeatedly. */
24
25
  failAll(reason: string): void;
25
26
  /** failAll + release the underlying channel. Terminal. `err` overrides the
@@ -69,13 +70,13 @@ abstract class BaseTransport implements SqliteTransport {
69
70
  else p.reject(new Error(error));
70
71
  }
71
72
 
72
- call<T = unknown>(type: string, payload?: unknown): Promise<T> {
73
+ call<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
73
74
  if (this.closed) return Promise.reject(this.makeError('transport closed'));
74
75
  const id = ++this.seq;
75
76
  return new Promise<T>((resolve, reject) => {
76
77
  this.pending.set(id, { resolve, reject });
77
78
  try {
78
- this.post({ id, type, payload });
79
+ this.post({ id, type, payload }, transfer);
79
80
  } catch (e) {
80
81
  this.pending.delete(id);
81
82
  reject(e);
@@ -215,8 +216,9 @@ export class PortSqliteTransport extends BaseTransport {
215
216
  this.onPortDead(reason);
216
217
  }
217
218
 
218
- protected post(msg: unknown): void {
219
- this.port.postMessage(msg);
219
+ protected post(msg: unknown, transfer?: Transferable[]): void {
220
+ if (transfer) this.port.postMessage(msg, transfer);
221
+ else this.port.postMessage(msg);
220
222
  }
221
223
 
222
224
  protected makeError(reason: string): Error {
@@ -19,10 +19,12 @@ export type SharedTabsSupport =
19
19
 
20
20
  export function detectSharedTabsSupport(config: Sp00kyConfig<any>): SharedTabsSupport {
21
21
  if (config.sharedTabs !== true) return { supported: false, reason: 'flag-off' };
22
- // Shared-tabs only makes sense for the SQLite engine: it is the one whose
23
- // OPFS pool is single-holder. The SurrealDB engine and custom engines keep
24
- // their existing per-tab behavior.
25
- if (config.localEngine !== 'sqlite') return { supported: false, reason: 'engine-not-sqlite' };
22
+ // Shared-tabs only makes sense for the engines whose OPFS files are
23
+ // single-holder: SQLite and the row store. The SurrealDB engine and custom
24
+ // engines keep their existing per-tab behavior.
25
+ if (config.localEngine !== 'sqlite' && config.localEngine !== 'rows') {
26
+ return { supported: false, reason: 'engine-not-sqlite' };
27
+ }
26
28
  if (typeof window === 'undefined') return { supported: false, reason: 'not-browser' };
27
29
  if (typeof SharedWorker === 'undefined') return { supported: false, reason: 'no-shared-worker' };
28
30
  if (typeof MessageChannel === 'undefined') {
package/src/types.ts CHANGED
@@ -126,6 +126,8 @@ export interface LocalWorkers {
126
126
  surreal?: () => Worker;
127
127
  /** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
128
128
  sqlite?: () => Worker;
129
+ /** The row store's worker (`localEngine: 'rows'`): runs `@spooky-sync/core/rows-worker`. */
130
+ rows?: () => Worker;
129
131
  }
130
132
 
131
133
  /**
@@ -168,6 +170,30 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
168
170
  * failure the queue retries. `0` disables. Defaults to `60_000`.
169
171
  */
170
172
  queryTimeoutMs?: number;
173
+ /**
174
+ * `localEngine: 'rows'` only. Keep a copy of the rows the app reads at
175
+ * startup in localStorage (up to about 1 MB), so `peekSelect` / `peekByIds`
176
+ * can hand a screen what it showed last time before the store is open.
177
+ * Works with `sharedTabs`: a copy is dropped for every tab as soon as any
178
+ * tab writes to a table it was read from.
179
+ * Default `true` for a durable store; `false` turns it off.
180
+ */
181
+ paintCache?: boolean;
182
+ /**
183
+ * `localEngine: 'rows'` with `sharedTabs` only. Where a follower tab's
184
+ * reads are answered.
185
+ * - `'leader'` (default): by the leader tab's worker, over a port.
186
+ * - `'direct'`: by a worker of the follower's own that reads the store's
187
+ * file beside the leader. A read then never waits for the leader's
188
+ * work (a sync-down in another tab), and crosses no tab boundary.
189
+ * Writes still go to the leader. Needs shared OPFS access handles
190
+ * (Chrome 121+); elsewhere, and whenever its worker fails, a follower
191
+ * reads through the leader as before. The price: nothing but the
192
+ * leader's lock stands between two writers of the file, where the
193
+ * default has the browser refuse a second one, and each follower
194
+ * holds the store's index in memory.
195
+ */
196
+ followerReads?: 'leader' | 'direct';
171
197
  /**
172
198
  * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
173
199
  * or a query on the in-process surrealdb engine). Local ops are serialized
@@ -200,9 +226,13 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
200
226
  /**
201
227
  * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
202
228
  * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
203
- * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
204
- * is a passive queryable store — reactivity is driven by the remote SSP, not
205
- * this engine. See `services/database/cache-engine.ts`.
229
+ * OPFS persistence; `'rows'` (experimental) uses sp00ky's own row store in a
230
+ * Worker, also on OPFS: an append-only file per bucket with a flat index,
231
+ * built for this client's reads and writes and nothing else, and answering
232
+ * every query the way `'sqlite'` does; or pass a custom
233
+ * {@link LocalCacheEngine}. The local cache is a passive queryable store —
234
+ * reactivity is driven by the remote SSP, not this engine. See
235
+ * `services/database/cache-engine.ts` and `services/database/rows-store.ts`.
206
236
  */
207
237
  localEngine?: LocalEngineChoice;
208
238
  /**
@@ -233,7 +263,7 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
233
263
  };
234
264
  /**
235
265
  * Share ONE durable local store across all tabs of this origin (default
236
- * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
266
+ * `false`). Requires `localEngine: 'sqlite'` or `'rows'`. A SharedWorker broker elects a
237
267
  * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
238
268
  * worker and the sync loop, and follower tabs read/write the same store over
239
269
  * MessagePorts, so every tab is durable instead of only the first one.
@@ -252,8 +282,8 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
252
282
  /**
253
283
  * Persist the in-browser SSP circuit's store as a snapshot in the local
254
284
  * store, so a reload restores it and only steps in what changed since.
255
- * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
256
- * can hold the bytes) and `false` otherwise.
285
+ * Defaults to `true` under `localEngine: 'sqlite'` and `'rows'` (the
286
+ * OPFS-backed stores can hold the bytes) and `false` otherwise.
257
287
  *
258
288
  * Without a snapshot the circuit is primed by reading every cached row back
259
289
  * out of the local store; either way a reload never re-downloads the working
@@ -318,6 +348,11 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
318
348
  * apply. `iceServers` configures the default WebRTC transport (a public
319
349
  * STUN server when omitted; add TURN for networks that block direct
320
350
  * connections), `transport` replaces it.
351
+ *
352
+ * `share` sends this user's optimistic writes straight to their other
353
+ * devices, per table (`share: { tables: { game: true, note: (row) =>
354
+ * !row.draft } }`), through the room relay named by `relay` (the
355
+ * `sp00ky-relay` server, one socket per browser). Off unless set.
321
356
  */
322
357
  channels?: ChannelsConfig;
323
358
  /**