@spooky-sync/core 0.0.1-canary.9 → 0.0.1-canary.91

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 (65) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +907 -339
  3. package/dist/index.js +2837 -402
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/types.d.ts +543 -0
  7. package/package.json +39 -9
  8. package/skills/sp00ky-core/SKILL.md +258 -0
  9. package/skills/sp00ky-core/references/auth.md +98 -0
  10. package/skills/sp00ky-core/references/config.md +76 -0
  11. package/src/build-globals.d.ts +12 -0
  12. package/src/events/events.test.ts +2 -1
  13. package/src/events/index.ts +3 -0
  14. package/src/index.ts +9 -2
  15. package/src/modules/auth/events/index.ts +2 -1
  16. package/src/modules/auth/index.ts +59 -20
  17. package/src/modules/cache/index.ts +41 -29
  18. package/src/modules/cache/types.ts +2 -2
  19. package/src/modules/crdt/crdt-field.ts +281 -0
  20. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  21. package/src/modules/crdt/index.ts +352 -0
  22. package/src/modules/data/data.status.test.ts +108 -0
  23. package/src/modules/data/index.ts +732 -109
  24. package/src/modules/data/window-query.test.ts +52 -0
  25. package/src/modules/data/window-query.ts +130 -0
  26. package/src/modules/devtools/index.ts +115 -21
  27. package/src/modules/devtools/versions.test.ts +74 -0
  28. package/src/modules/devtools/versions.ts +81 -0
  29. package/src/modules/feature-flag/index.ts +166 -0
  30. package/src/modules/ref-tables.test.ts +66 -0
  31. package/src/modules/ref-tables.ts +69 -0
  32. package/src/modules/sync/engine.ts +101 -37
  33. package/src/modules/sync/events/index.ts +9 -2
  34. package/src/modules/sync/queue/queue-down.ts +5 -4
  35. package/src/modules/sync/queue/queue-up.ts +14 -13
  36. package/src/modules/sync/scheduler.ts +40 -3
  37. package/src/modules/sync/sync.ts +893 -59
  38. package/src/modules/sync/utils.test.ts +269 -2
  39. package/src/modules/sync/utils.ts +182 -17
  40. package/src/otel/index.ts +127 -0
  41. package/src/services/database/database.ts +11 -11
  42. package/src/services/database/events/index.ts +2 -1
  43. package/src/services/database/local-migrator.ts +21 -21
  44. package/src/services/database/local.test.ts +33 -0
  45. package/src/services/database/local.ts +192 -32
  46. package/src/services/database/remote.ts +13 -13
  47. package/src/services/logger/index.ts +6 -101
  48. package/src/services/persistence/localstorage.ts +2 -2
  49. package/src/services/persistence/resilient.ts +41 -0
  50. package/src/services/persistence/surrealdb.ts +9 -9
  51. package/src/services/stream-processor/index.ts +248 -37
  52. package/src/services/stream-processor/permissions.test.ts +47 -0
  53. package/src/services/stream-processor/permissions.ts +53 -0
  54. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  55. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  56. package/src/services/stream-processor/wasm-types.ts +18 -2
  57. package/src/sp00ky.auth-order.test.ts +65 -0
  58. package/src/sp00ky.ts +648 -0
  59. package/src/types.ts +192 -15
  60. package/src/utils/index.ts +35 -13
  61. package/src/utils/parser.ts +3 -2
  62. package/src/utils/surql.ts +24 -15
  63. package/src/utils/withRetry.test.ts +1 -1
  64. package/tsdown.config.ts +55 -1
  65. package/src/spooky.ts +0 -392
package/src/sp00ky.ts ADDED
@@ -0,0 +1,648 @@
1
+ import { DataModule } from './modules/data/index';
2
+ import type {
3
+ Sp00kyConfig,
4
+ QueryTimeToLive,
5
+ QueryStatusCallback,
6
+ Sp00kyQueryResultPromise,
7
+ PersistenceClient,
8
+ UpdateOptions,
9
+ RunOptions,
10
+ SyncHealth} from './types';
11
+ import {
12
+ LocalDatabaseService,
13
+ LocalMigrator,
14
+ RemoteDatabaseService,
15
+ } from './services/database/index';
16
+ import type { UpEvent } from './modules/sync/index';
17
+ import { Sp00kySync } from './modules/sync/index';
18
+ import type {
19
+ GetTable,
20
+ InnerQuery,
21
+ QueryOptions,
22
+ SchemaStructure,
23
+ TableModel,
24
+ TableNames,
25
+ BucketNames,
26
+ BackendNames,
27
+ BackendRoutes,
28
+ RoutePayload} from '@spooky-sync/query-builder';
29
+ import {
30
+ QueryBuilder
31
+ } from '@spooky-sync/query-builder';
32
+
33
+ import { DevToolsService } from './modules/devtools/index';
34
+ import { createLogger } from './services/logger/index';
35
+ import { AuthService } from './modules/auth/index';
36
+ import { StreamProcessorService } from './services/stream-processor/index';
37
+ import { extractSelectPermissions } from './services/stream-processor/permissions';
38
+ import { EventSystem } from './events/index';
39
+ import { CacheModule } from './modules/cache/index';
40
+ import type { RecordWithId } from './modules/cache/index';
41
+ import { CrdtManager, CrdtField } from './modules/crdt/index';
42
+ import { FeatureFlagModule, FeatureFlagHandle } from './modules/feature-flag/index';
43
+ import type { FeatureFlagOptions } from './modules/feature-flag/index';
44
+ import { LocalStoragePersistenceClient } from './services/persistence/localstorage';
45
+ import { parseParams, encodeRecordId } from './utils/index';
46
+ import { SurrealDBPersistenceClient } from './services/persistence/surrealdb';
47
+ import { ResilientPersistenceClient } from './services/persistence/resilient';
48
+
49
+ export class BucketHandle {
50
+ constructor(private bucketName: string, private remote: RemoteDatabaseService) {}
51
+
52
+ async put(path: string, content: string | Uint8Array | Blob): Promise<void> {
53
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".put($content);`, { content });
54
+ }
55
+
56
+ async get(path: string): Promise<unknown> {
57
+ const [result] = await this.remote.query<[unknown]>(`RETURN f"${this.bucketName}:/${path}".get();`);
58
+ return result;
59
+ }
60
+
61
+ async delete(path: string): Promise<void> {
62
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".delete();`);
63
+ }
64
+
65
+ async exists(path: string): Promise<boolean> {
66
+ const [result] = await this.remote.query<[boolean]>(`RETURN f"${this.bucketName}:/${path}".exists();`);
67
+ return result;
68
+ }
69
+
70
+ async head(path: string): Promise<Record<string, unknown>> {
71
+ const [result] = await this.remote.query<[Record<string, unknown>]>(`RETURN f"${this.bucketName}:/${path}".head();`);
72
+ return result;
73
+ }
74
+
75
+ async copy(sourcePath: string, targetPath: string): Promise<void> {
76
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".copy($target);`, { target: targetPath });
77
+ }
78
+
79
+ async rename(sourcePath: string, targetPath: string): Promise<void> {
80
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".rename($target);`, { target: targetPath });
81
+ }
82
+
83
+ async list(prefix?: string): Promise<string[]> {
84
+ const p = prefix ?? '';
85
+ const [result] = await this.remote.query<[string[]]>(`RETURN f"${this.bucketName}:/${p}".list();`);
86
+ return result;
87
+ }
88
+ }
89
+
90
+ export class Sp00kyClient<S extends SchemaStructure> {
91
+ private local: LocalDatabaseService;
92
+ private remote: RemoteDatabaseService;
93
+ private persistenceClient: PersistenceClient;
94
+
95
+ private migrator: LocalMigrator;
96
+ private cache: CacheModule;
97
+ private dataModule: DataModule<S>;
98
+ private sync: Sp00kySync<S>;
99
+ private devTools: DevToolsService;
100
+ private crdtManager: CrdtManager;
101
+ private featureFlags!: FeatureFlagModule<S>;
102
+
103
+ private logger: ReturnType<typeof createLogger>;
104
+ public auth: AuthService<S>;
105
+ public streamProcessor: StreamProcessorService;
106
+
107
+ get remoteClient() {
108
+ return this.remote.getClient();
109
+ }
110
+
111
+ get localClient() {
112
+ return this.local.getClient();
113
+ }
114
+
115
+ get pendingMutationCount(): number {
116
+ return this.sync.pendingMutationCount;
117
+ }
118
+
119
+ /** Number of times the initial list_ref LIVE subscription retried on
120
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
121
+ * pre-emptive user-table creation got there first; >0 when LIVE
122
+ * registration hit a "table not found" race. Exposed so the e2e
123
+ * suite can guard the pre-emptive path against regression. */
124
+ get liveRetryCount(): number {
125
+ return this.sync.liveRetryCount;
126
+ }
127
+
128
+ subscribeToPendingMutations(cb: (count: number) => void): () => void {
129
+ return this.sync.subscribeToPendingMutations(cb);
130
+ }
131
+
132
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
133
+ get syncHealth(): SyncHealth {
134
+ return this.sync.syncHealth;
135
+ }
136
+
137
+ /**
138
+ * Observe sync health. Fires immediately with the current status and again
139
+ * on every healthy↔degraded transition. Returns an unsubscribe.
140
+ */
141
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
142
+ return this.sync.subscribeToSyncHealth(cb);
143
+ }
144
+
145
+ constructor(private config: Sp00kyConfig<S>) {
146
+ const logger = createLogger(config.logLevel ?? 'info', config.otelTransmit);
147
+ this.logger = logger.child({ service: 'Sp00kyClient' });
148
+
149
+ this.logger.info(
150
+ {
151
+ config: { ...config, schema: '[SchemaStructure]' },
152
+ Category: 'sp00ky-client::Sp00kyClient::constructor',
153
+ },
154
+ 'Sp00kyClient initialized'
155
+ );
156
+
157
+ this.local = new LocalDatabaseService(this.config.database, logger);
158
+ this.remote = new RemoteDatabaseService(this.config.database, logger);
159
+
160
+ if (config.persistenceClient === 'surrealdb') {
161
+ this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
162
+ } else if (config.persistenceClient === 'localstorage' || !config.persistenceClient) {
163
+ this.persistenceClient = new LocalStoragePersistenceClient(logger);
164
+ } else {
165
+ this.persistenceClient = config.persistenceClient;
166
+ }
167
+
168
+ this.persistenceClient = new ResilientPersistenceClient(this.persistenceClient, logger);
169
+
170
+ this.streamProcessor = new StreamProcessorService(
171
+ new EventSystem(['stream_update']),
172
+ this.local,
173
+ this.persistenceClient,
174
+ logger
175
+ );
176
+ this.migrator = new LocalMigrator(this.local, logger);
177
+
178
+ this.cache = new CacheModule(
179
+ this.local,
180
+ this.streamProcessor,
181
+ (update) => {
182
+ // Direct callback from cache to data module
183
+ this.dataModule.onStreamUpdate(update);
184
+ },
185
+ logger
186
+ );
187
+
188
+ // Initialize CRDT Manager. `local` is used to read the initial
189
+ // `_00_crdt` snapshot when a field opens AND to mirror every local
190
+ // edit (so reload/offline see the freshest state); `remote` is used
191
+ // for the debounced outgoing UPSERTs and the parent-table LIVE feed.
192
+ // The debounce window is configurable via `crdtDebounceMs`.
193
+ this.crdtManager = new CrdtManager(
194
+ this.config.schema,
195
+ this.local,
196
+ this.remote,
197
+ logger,
198
+ config.crdtDebounceMs ?? 500,
199
+ );
200
+
201
+ this.dataModule = new DataModule(
202
+ this.cache,
203
+ this.local,
204
+ this.config.schema,
205
+ logger,
206
+ this.config.streamDebounceTime
207
+ );
208
+
209
+ // Initialize Auth
210
+ this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
211
+
212
+ // Initialize Sync
213
+ this.sync = new Sp00kySync(
214
+ this.local,
215
+ this.remote,
216
+ this.cache,
217
+ this.dataModule,
218
+ this.config.schema,
219
+ this.logger,
220
+ {
221
+ refSyncIntervalMs: this.config.refSyncIntervalMs,
222
+ anonymousLiveQueries: this.config.enableAnonymousLiveQueries,
223
+ // `syncHealth: false` (or `{ degradeAfterConsecutiveFailures: 0 }`)
224
+ // disables degraded reporting; otherwise default to 3.
225
+ degradeAfterConsecutiveFailures:
226
+ this.config.syncHealth === false
227
+ ? 0
228
+ : this.config.syncHealth?.degradeAfterConsecutiveFailures ?? 3,
229
+ }
230
+ );
231
+
232
+ // Initialize feature flags. Reuses the down-queue to register SSP plans
233
+ // on `_00_user_feature` and the auth subscription to re-register handles
234
+ // when the signed-in user changes.
235
+ this.featureFlags = new FeatureFlagModule({
236
+ dataModule: this.dataModule,
237
+ sync: this.sync,
238
+ auth: this.auth,
239
+ logger,
240
+ });
241
+
242
+ // Initialize DevTools
243
+ this.devTools = new DevToolsService(
244
+ this.local,
245
+ this.remote,
246
+ logger,
247
+ this.config.schema,
248
+ this.auth,
249
+ this.dataModule
250
+ );
251
+
252
+ // Register DevTools as a receiver for stream updates
253
+ this.streamProcessor.addReceiver(this.devTools);
254
+
255
+ // Wire up callbacks instead of events
256
+ this.setupCallbacks();
257
+ }
258
+
259
+ /**
260
+ * Setup direct callbacks instead of event subscriptions
261
+ */
262
+ private setupCallbacks() {
263
+ // Surface query fetch-status changes (idle/fetching) in DevTools. Logs a
264
+ // discrete event and triggers a state push so the active-queries panel
265
+ // reflects the flip immediately.
266
+ this.dataModule.onQueryStatusChange = (queryHash, status) => {
267
+ this.devTools.logEvent('QUERY_STATUS_CHANGED', { queryHash, status });
268
+ };
269
+
270
+ // Keep an actively-watched query's remote `_00_query.lastActiveAt` fresh so
271
+ // the server TTL sweep doesn't expire it out from under live subscribers.
272
+ // DataModule fires this only while the query still has ≥1 subscriber.
273
+ this.dataModule.onHeartbeat = (queryHash) => {
274
+ void this.sync.heartbeatQuery(queryHash).catch((err) => {
275
+ this.logger.warn(
276
+ { err, queryHash, Category: 'sp00ky-client::Sp00kyClient::onHeartbeat' },
277
+ 'TTL heartbeat failed'
278
+ );
279
+ });
280
+ };
281
+
282
+ // Eager teardown of an opt-in deregistered query: enqueue a `cleanup`
283
+ // down-event so it's serialized after any in-flight register/sync for the
284
+ // same query (avoids out-of-order delete-before-create).
285
+ this.dataModule.onDeregister = (queryHash) => {
286
+ this.sync.enqueueDownEvent({ type: 'cleanup', payload: { hash: queryHash } });
287
+ };
288
+
289
+ // Mutation callback for sync
290
+ this.dataModule.onMutation((mutations: UpEvent[]) => {
291
+ // Notify DevTools
292
+ this.devTools.onMutation(mutations);
293
+
294
+ // Enqueue in Sync
295
+ if (mutations.length > 0) {
296
+ this.sync.enqueueMutation(mutations);
297
+ }
298
+ });
299
+
300
+ // Sync events for incoming updates
301
+ this.sync.events.subscribe('SYNC_QUERY_UPDATED', (event: any) => {
302
+ this.devTools.logEvent('SYNC_QUERY_UPDATED', event.payload);
303
+ });
304
+
305
+ // Hand list_ref-driven row ingests to the CrdtManager so CRDT body
306
+ // / cursor updates reach the receiver even when the cross-session
307
+ // LIVE on the parent table is filtered out by the SurrealDB
308
+ // permission-LIVE gap. Same-user clients receive these rows via
309
+ // CrdtManager's own `LIVE SELECT * FROM <table>`; this hook is the
310
+ // redundant path that fires when only the list_ref bumped.
311
+ this.sync.engineEvents.subscribe('SYNC_REMOTE_DATA_INGESTED', (event: any) => {
312
+ try {
313
+ const records: Array<Record<string, any>> = event.payload?.records ?? [];
314
+ for (const row of records) {
315
+ const id = row?.id;
316
+ const table =
317
+ id && typeof id === 'object' && id.table !== undefined
318
+ ? String(id.table)
319
+ : undefined;
320
+ if (!table) continue;
321
+ this.crdtManager.applyRow(table, row);
322
+ }
323
+ } catch (err) {
324
+ this.logger.debug(
325
+ { err, Category: 'sp00ky-client::engineEvents::ingested' },
326
+ 'applyRow forwarding from sync ingest failed'
327
+ );
328
+ }
329
+ });
330
+
331
+ // Database events for DevTools
332
+ this.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => {
333
+ this.devTools.logEvent('LOCAL_QUERY', event.payload);
334
+ });
335
+
336
+ this.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => {
337
+ this.devTools.logEvent('REMOTE_QUERY', event.payload);
338
+ });
339
+ }
340
+
341
+ async init() {
342
+ this.logger.info(
343
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
344
+ 'Sp00kyClient initialization started'
345
+ );
346
+ try {
347
+ await this.local.connect();
348
+ this.logger.debug(
349
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
350
+ 'Local database connected'
351
+ );
352
+
353
+ await this.migrator.provision(this.config.schemaSurql);
354
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Schema provisioned');
355
+
356
+ await this.remote.connect();
357
+ this.logger.debug(
358
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
359
+ 'Remote database connected'
360
+ );
361
+
362
+ await this.streamProcessor.init();
363
+ // Seed table `select` permissions from the schema before any query is
364
+ // registered — otherwise the SSP default-denies every non-`_00_` table.
365
+ this.streamProcessor.setPermissions(
366
+ extractSelectPermissions(this.config.schemaSurql)
367
+ );
368
+ this.logger.debug(
369
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
370
+ 'StreamProcessor initialized'
371
+ );
372
+
373
+ await this.auth.init();
374
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Auth initialized');
375
+
376
+ // Salt query-id hashing with the SurrealDB session id so two browsers
377
+ // for the same user don't collide on shared `_00_query` rows. The same
378
+ // session id is the `session_id` key in `_00_cursor` rows, so the
379
+ // CrdtManager needs it too.
380
+ const sessionId = await this.fetchSessionId();
381
+ await this.dataModule.init(sessionId);
382
+ this.crdtManager.setSessionId(sessionId);
383
+ this.logger.debug(
384
+ { sessionId, Category: 'sp00ky-client::Sp00kyClient::init' },
385
+ 'DataModule initialized'
386
+ );
387
+
388
+ // Refresh the salt whenever auth state flips (sign-in, sign-out).
389
+ // session::id() changes per WebSocket session, and a sign-in spawns
390
+ // a new authenticated session, so the salt must follow. Also
391
+ // forward the user id into `DataModule` and `Sp00kySync` so they
392
+ // can route to per-user `_00_query_user_<id>` /
393
+ // `_00_list_ref_user_<id>` tables in `RefMode.Dedicated` — the
394
+ // LIVE subscription on `_00_list_ref_user_<id>` is restarted
395
+ // under the new auth context inside `Sp00kySync.setCurrentUserId`
396
+ // since SurrealDB binds the LIVE permission at registration time.
397
+ //
398
+ // Sync prefix BEFORE the first `await`: setting `currentUserId`
399
+ // synchronously here is critical because the AuthProvider's own
400
+ // subscribe callback runs right after ours and immediately enables
401
+ // queries that depend on the user id. Any `await` before
402
+ // `setCurrentUserId` would let those queries register against the
403
+ // stale (null) user id and hit the wrong `_00_query[_user_*]`
404
+ // table.
405
+ this.auth.subscribe(async (userId) => {
406
+ this.dataModule.setCurrentUserId(userId);
407
+ // Mirror the server's `fn::query::register` auth injection for the
408
+ // in-browser SSP: feed the current user's full record id + access
409
+ // method so `$auth`-gated table permissions (e.g. `thread`) resolve
410
+ // locally instead of being rejected. Set synchronously BEFORE the
411
+ // first `await` (like `setCurrentUserId` above) so queries that
412
+ // re-register on this auth flip see the fresh context, not a stale one.
413
+ this.streamProcessor.setSessionAuth(
414
+ this.auth.currentUser?.id ? encodeRecordId(this.auth.currentUser.id) : null,
415
+ this.auth.access
416
+ );
417
+ const next = await this.fetchSessionId();
418
+ this.dataModule.setSessionId(next);
419
+ this.crdtManager.setSessionId(next);
420
+ try {
421
+ await this.sync.setCurrentUserId(userId);
422
+ } catch (e) {
423
+ this.logger.error(
424
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::authChange' },
425
+ 'sync.setCurrentUserId failed'
426
+ );
427
+ }
428
+ });
429
+
430
+ await this.sync.init();
431
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Sync initialized');
432
+
433
+ this.featureFlags.init();
434
+ this.logger.debug(
435
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
436
+ 'FeatureFlagModule initialized'
437
+ );
438
+
439
+ this.logger.info(
440
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
441
+ 'Sp00kyClient initialization completed successfully'
442
+ );
443
+ } catch (e) {
444
+ this.logger.error(
445
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::init' },
446
+ 'Sp00kyClient initialization failed'
447
+ );
448
+ throw e;
449
+ }
450
+ }
451
+
452
+ async close() {
453
+ await this.featureFlags.closeAll();
454
+ this.crdtManager.closeAll();
455
+ await this.local.close();
456
+ await this.remote.close();
457
+ }
458
+
459
+ /**
460
+ * Subscribe to a feature flag for the current user. Returns a
461
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
462
+ * accessors reflect the latest assignment from `_00_user_feature`,
463
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
464
+ *
465
+ * Permissions are enforced by SurrealDB: a client can only ever see
466
+ * its own row, and cannot create or modify assignments.
467
+ */
468
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle {
469
+ return this.featureFlags.feature(key, options);
470
+ }
471
+
472
+ authenticate(token: string) {
473
+ return this.remote.getClient().authenticate(token);
474
+ }
475
+
476
+ /**
477
+ * Open a CRDT field for collaborative editing.
478
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
479
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
480
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
481
+ */
482
+ async openCrdtField(
483
+ table: string,
484
+ recordId: string,
485
+ field: string,
486
+ fallbackText?: string,
487
+ ): Promise<CrdtField> {
488
+ return this.crdtManager.open(table, recordId, field, fallbackText);
489
+ }
490
+
491
+ /**
492
+ * Close a CRDT field when editing is done.
493
+ */
494
+ closeCrdtField(table: string, recordId: string, field: string): void {
495
+ this.crdtManager.close(table, recordId, field);
496
+ }
497
+
498
+ deauthenticate() {
499
+ return this.remote.getClient().invalidate();
500
+ }
501
+
502
+ query<Table extends TableNames<S>>(
503
+ table: Table,
504
+ options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
505
+ ttl: QueryTimeToLive = '10m'
506
+ ): QueryBuilder<S, Table, Sp00kyQueryResultPromise> {
507
+ return new QueryBuilder<S, Table, Sp00kyQueryResultPromise>(
508
+ this.config.schema,
509
+ table,
510
+ async (q) => ({
511
+ hash: await this.initQuery(table, q, ttl),
512
+ }),
513
+ options
514
+ );
515
+ }
516
+
517
+ private async initQuery<Table extends TableNames<S>>(
518
+ table: Table,
519
+ q: InnerQuery<any, any, any>,
520
+ ttl: QueryTimeToLive
521
+ ) {
522
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
523
+ if (!tableSchema) {
524
+ throw new Error(`Table ${table} not found`);
525
+ }
526
+
527
+ const params = parseParams(tableSchema.columns, q.selectQuery.vars ?? {});
528
+ const hash = await this.dataModule.query(table, q.selectQuery.query, params, ttl);
529
+
530
+ // Instant-hydrate: for a cold query, fetch its rows one-shot from the remote
531
+ // (its own surql, run directly like useRemote) and display them NOW; the full
532
+ // realtime registration proceeds below. Hydrated rows carry their `_00_rv`
533
+ // versions so the registration's syncRecords skips re-pulling unchanged bodies.
534
+ // Best-effort: any failure (e.g. offline) just falls through to registration.
535
+ if (this.config.instantHydrate !== false && this.dataModule.isCold(hash)) {
536
+ try {
537
+ const [rows] = await this.remote.query<[RecordWithId[]]>(q.selectQuery.query, params);
538
+ await this.dataModule.applyHydration(hash, rows ?? []);
539
+ } catch (err) {
540
+ this.logger.warn(
541
+ { err, hash, Category: 'sp00ky-client::Sp00kyClient::instantHydrate' },
542
+ 'Instant hydrate failed; proceeding with registration'
543
+ );
544
+ }
545
+ }
546
+
547
+ await this.sync.enqueueDownEvent({
548
+ type: 'register',
549
+ payload: {
550
+ hash,
551
+ },
552
+ });
553
+
554
+ return hash;
555
+ }
556
+
557
+ async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive) {
558
+ const tableName = sql.split('FROM ')[1].split(' ')[0];
559
+ return this.dataModule.query(tableName, sql, params, ttl);
560
+ }
561
+
562
+ async subscribe(
563
+ queryHash: string,
564
+ callback: (records: Record<string, any>[]) => void,
565
+ options?: { immediate?: boolean }
566
+ ): Promise<() => void> {
567
+ return this.dataModule.subscribe(queryHash, callback, options);
568
+ }
569
+
570
+ /**
571
+ * Opt-in eager teardown for a query whose last subscriber has gone away
572
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
573
+ * while any subscriber remains. Tears down the remote `_00_query` view +
574
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
575
+ * (no call here) keeps the view resident for cheap re-subscription.
576
+ */
577
+ deregisterQuery(queryHash: string): void {
578
+ this.dataModule.deregisterQuery(queryHash);
579
+ }
580
+
581
+ /**
582
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
583
+ * `{ immediate: true }` the callback fires synchronously with the current
584
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
585
+ */
586
+ subscribeQueryStatus(
587
+ queryHash: string,
588
+ callback: QueryStatusCallback,
589
+ options?: { immediate?: boolean }
590
+ ): () => void {
591
+ return this.dataModule.subscribeStatus(queryHash, callback, options);
592
+ }
593
+
594
+ /**
595
+ * Report the frontend processing time (ms) a client framework spent applying
596
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
597
+ * surface the "frontend" phase of the per-query timing breakdown.
598
+ */
599
+ reportFrontendTiming(queryHash: string, ms: number): void {
600
+ this.dataModule.recordFrontendTiming(queryHash, ms);
601
+ }
602
+
603
+ run<
604
+ B extends BackendNames<S>,
605
+ R extends BackendRoutes<S, B>,
606
+ >(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions) {
607
+ return this.dataModule.run(backend, path, payload, options);
608
+ }
609
+
610
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle {
611
+ return new BucketHandle(name, this.remote);
612
+ }
613
+
614
+ create(id: string, data: Record<string, unknown>) {
615
+ return this.dataModule.create(id, data);
616
+ }
617
+
618
+ update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) {
619
+ return this.dataModule.update(table, id, data, options);
620
+ }
621
+
622
+ delete(table: string, id: string) {
623
+ return this.dataModule.delete(table, id);
624
+ }
625
+
626
+ async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
627
+ return fn(this.remote.getClient());
628
+ }
629
+
630
+ /**
631
+ * Fetch SurrealDB's `session::id()` as a string. Used as a salt for
632
+ * query-id hashing so two sessions for the same user get distinct
633
+ * `_00_query` rows. Returns empty string if the query fails (we still
634
+ * boot, just without session scoping for IDs).
635
+ */
636
+ private async fetchSessionId(): Promise<string> {
637
+ try {
638
+ const [sid] = await this.remote.query<[string]>('RETURN <string>session::id()');
639
+ return typeof sid === 'string' ? sid : '';
640
+ } catch (e) {
641
+ this.logger.warn(
642
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::fetchSessionId' },
643
+ 'Failed to fetch session::id() — proceeding with empty salt'
644
+ );
645
+ return '';
646
+ }
647
+ }
648
+ }