@spooky-sync/core 0.0.1-canary.16 → 0.0.1-canary.161

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 (123) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +1406 -364
  3. package/dist/index.js +7773 -1391
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/sqlite-open.js +276 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +420 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +434 -0
  11. package/dist/types.d.ts +874 -0
  12. package/package.json +20 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/sp00ky-core/SKILL.md +258 -0
  15. package/skills/sp00ky-core/references/auth.md +98 -0
  16. package/skills/sp00ky-core/references/config.md +76 -0
  17. package/src/build-globals.d.ts +12 -0
  18. package/src/events/events.test.ts +2 -1
  19. package/src/events/index.ts +3 -0
  20. package/src/index.ts +16 -2
  21. package/src/modules/app-release/index.test.ts +125 -0
  22. package/src/modules/app-release/index.ts +201 -0
  23. package/src/modules/auth/events/index.ts +2 -1
  24. package/src/modules/auth/index.ts +59 -20
  25. package/src/modules/cache/index.ts +112 -32
  26. package/src/modules/cache/types.ts +2 -2
  27. package/src/modules/crdt/crdt-field.ts +294 -0
  28. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  29. package/src/modules/crdt/index.ts +361 -0
  30. package/src/modules/crdt/loro-loader.ts +25 -0
  31. package/src/modules/data/data.hydration.test.ts +142 -0
  32. package/src/modules/data/data.rebind.test.ts +147 -0
  33. package/src/modules/data/data.run.test.ts +113 -0
  34. package/src/modules/data/data.status.test.ts +249 -0
  35. package/src/modules/data/index.ts +1151 -129
  36. package/src/modules/data/mutation-id.test.ts +25 -0
  37. package/src/modules/data/mutation-id.ts +35 -0
  38. package/src/modules/data/window-query.test.ts +52 -0
  39. package/src/modules/data/window-query.ts +154 -0
  40. package/src/modules/devtools/index.ts +325 -37
  41. package/src/modules/devtools/notify-throttle.test.ts +149 -0
  42. package/src/modules/devtools/storage-info.test.ts +79 -0
  43. package/src/modules/devtools/storage-info.ts +143 -0
  44. package/src/modules/devtools/versions.test.ts +74 -0
  45. package/src/modules/devtools/versions.ts +81 -0
  46. package/src/modules/feature-flag/index.test.ts +120 -0
  47. package/src/modules/feature-flag/index.ts +209 -0
  48. package/src/modules/ref-tables.test.ts +91 -0
  49. package/src/modules/ref-tables.ts +88 -0
  50. package/src/modules/sync/engine.ts +101 -37
  51. package/src/modules/sync/events/index.ts +9 -2
  52. package/src/modules/sync/queue/queue-down.ts +12 -5
  53. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  54. package/src/modules/sync/queue/queue-up.ts +216 -56
  55. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  56. package/src/modules/sync/scheduler.ts +77 -9
  57. package/src/modules/sync/sync.health.test.ts +149 -0
  58. package/src/modules/sync/sync.subquery.test.ts +82 -0
  59. package/src/modules/sync/sync.ts +1333 -92
  60. package/src/modules/sync/utils.test.ts +269 -2
  61. package/src/modules/sync/utils.ts +182 -17
  62. package/src/otel/index.ts +127 -0
  63. package/src/services/database/cache-engine.ts +160 -0
  64. package/src/services/database/database.ts +11 -11
  65. package/src/services/database/engine-factory.ts +33 -0
  66. package/src/services/database/events/index.ts +2 -1
  67. package/src/services/database/index.ts +6 -0
  68. package/src/services/database/local-migrator.ts +28 -27
  69. package/src/services/database/local.test.ts +64 -0
  70. package/src/services/database/local.ts +478 -67
  71. package/src/services/database/plan-render.test.ts +159 -0
  72. package/src/services/database/plan-render.ts +108 -0
  73. package/src/services/database/relation-resolver.test.ts +413 -0
  74. package/src/services/database/relation-resolver.ts +0 -0
  75. package/src/services/database/remote.ts +13 -13
  76. package/src/services/database/sqlite-cache-engine.test.ts +464 -0
  77. package/src/services/database/sqlite-cache-engine.ts +1154 -0
  78. package/src/services/database/sqlite-open.test.ts +150 -0
  79. package/src/services/database/sqlite-open.ts +164 -0
  80. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  81. package/src/services/database/sqlite-plan-sql.ts +106 -0
  82. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  83. package/src/services/database/sqlite-select.test.ts +246 -0
  84. package/src/services/database/sqlite-select.ts +113 -0
  85. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  86. package/src/services/database/sqlite-transport.ts +219 -0
  87. package/src/services/database/sqlite-worker.ts +437 -0
  88. package/src/services/database/surql-translate.ts +291 -0
  89. package/src/services/database/surreal-cache-engine.ts +141 -0
  90. package/src/services/logger/index.ts +6 -109
  91. package/src/services/persistence/localstorage.ts +2 -2
  92. package/src/services/persistence/resilient.ts +11 -4
  93. package/src/services/persistence/surrealdb.ts +10 -10
  94. package/src/services/stream-processor/index.ts +444 -52
  95. package/src/services/stream-processor/permissions.test.ts +47 -0
  96. package/src/services/stream-processor/permissions.ts +53 -0
  97. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  98. package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
  99. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  100. package/src/services/stream-processor/wasm-types.ts +23 -2
  101. package/src/services/tabs/broker-client.ts +283 -0
  102. package/src/services/tabs/broker.test.ts +278 -0
  103. package/src/services/tabs/coordinator.test.ts +192 -0
  104. package/src/services/tabs/coordinator.ts +567 -0
  105. package/src/services/tabs/fake-ports.fixture.ts +70 -0
  106. package/src/services/tabs/leader-locks.ts +75 -0
  107. package/src/services/tabs/protocol.ts +239 -0
  108. package/src/services/tabs/support.ts +36 -0
  109. package/src/services/tabs/tabs-broker-worker.ts +581 -0
  110. package/src/sp00ky.auth-order.test.ts +92 -0
  111. package/src/sp00ky.init-query.test.ts +183 -0
  112. package/src/sp00ky.ts +1225 -0
  113. package/src/types.ts +342 -15
  114. package/src/utils/error-classification.test.ts +44 -0
  115. package/src/utils/error-classification.ts +7 -0
  116. package/src/utils/index.ts +35 -13
  117. package/src/utils/parser.ts +3 -2
  118. package/src/utils/semver.test.ts +32 -0
  119. package/src/utils/semver.ts +30 -0
  120. package/src/utils/surql.ts +30 -18
  121. package/src/utils/withRetry.test.ts +1 -1
  122. package/tsdown.config.ts +86 -1
  123. package/src/spooky.ts +0 -395
package/dist/index.d.ts CHANGED
@@ -1,166 +1,19 @@
1
+ import { A as StorageHealthStatus, B as DatabaseEventSystem, C as RecordVersionDiff, D as Sp00kyQueryResult, E as Sp00kyConfig, F as TimingPhase, G as EventSystem, H as Logger$1, I as UpdateOptions, L as UpEvent, M as SyncHealth, N as SyncHealthConfig, O as Sp00kyQueryResultPromise, P as SyncHealthStatus, R as LocalStore, S as RecordVersionArray, T as RunOptions, U as SyncEventSystem, V as DatabaseEventTypes, W as EventDefinition, _ as QueryStatus, a as MutationCallback, b as QueryTimings, c as PersistenceClient, d as PreloadOptions, f as PreloadRefresh, g as QueryState, h as QueryHash, i as MATERIALIZATION_SAMPLE_WINDOW, j as StoreType, k as StorageHealth, l as PhaseStat, m as QueryConfigRecord, n as EventSubscriptionOptions, o as MutationEvent, p as QueryConfig, r as Level, s as MutationEventType, t as DebounceOptions, u as PinoTransmit, v as QueryStatusCallback, w as RegistrationTimings, x as QueryUpdateCallback, y as QueryTimeToLive, z as SealedQuery } from "./types.js";
1
2
  import * as surrealdb0 from "surrealdb";
2
- import { Duration, RecordId, Surreal, SurrealTransaction } from "surrealdb";
3
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RecordId as RecordId$1, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
4
- import { Level, Level as Level$1, Logger } from "pino";
3
+ import { Duration, RecordId, Surreal as Surreal$1, SurrealTransaction } from "surrealdb";
4
+ import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
5
+ import { Logger } from "pino";
6
+ import { LoroDoc } from "loro-crdt";
5
7
 
6
- //#region src/events/index.d.ts
7
- /**
8
- * Utility type to define the payload structure of an event.
9
- * If the payload type P is never, it defines payload as undefined.
10
- */
11
- type EventPayloadDefinition<P> = [P] extends [never] ? {
12
- payload: undefined;
13
- } : {
14
- payload: P;
15
- };
16
- /**
17
- * Defines the structure of an event with a specific type and payload.
18
- * @template T The string literal type of the event.
19
- * @template P The type of the event payload.
20
- */
21
- type EventDefinition<T extends string, P> = {
22
- type: T;
23
- } & EventPayloadDefinition<P>;
24
- /**
25
- * A map of event types to their definitions.
26
- * Keys are event names, values are EventDefinitions.
27
- */
28
- type EventTypeMap = Record<string, EventDefinition<any, unknown> | EventDefinition<any, never>>;
29
- /**
30
- * Options for pushing/emitting events.
31
- */
32
- interface PushEventOptions {
33
- /** Configuration for debouncing the event. */
34
- debounced?: {
35
- key: string;
36
- delay: number;
37
- };
38
- }
39
- /**
40
- * Extracts the full Event object type from the map for a given key.
41
- */
42
- type Event<E extends EventTypeMap, T extends EventType<E>> = E[T];
43
- /**
44
- * Extracts the payload type from the map for a given key.
45
- */
46
- type EventPayload<E extends EventTypeMap, T extends EventType<E>> = E[T]['payload'];
47
- /**
48
- * Array of available event type keys.
49
- */
50
- type EventTypes<E extends EventTypeMap> = (keyof E)[];
51
- /**
52
- * Represents a valid key (event name) from the EventTypeMap.
53
- */
54
- type EventType<E extends EventTypeMap> = keyof E;
55
- /**
56
- * Function signature for an event handler.
57
- */
58
- type EventHandler<E extends EventTypeMap, T extends EventType<E>> = (event: Event<E, T>) => void;
59
- /**
60
- * Options when subscribing to an event.
61
- */
62
- type EventSubscriptionOptions$1 = {
63
- /** If true, the handler will be called immediately with the last emitted event of this type (if any). */
64
- immediately?: boolean;
65
- /** If true, the subscription will be automatically removed after the first event is handled. */
66
- once?: boolean;
67
- };
68
- /**
69
- * A type-safe event system that handles subscription, emission (including debouncing), and buffering of events.
70
- * @template E The EventTypeMap defining all supported events.
71
- */
72
- declare class EventSystem<E extends EventTypeMap> {
73
- private _eventTypes;
74
- private subscriberId;
75
- private isProcessing;
76
- private buffer;
77
- private subscribers;
78
- private subscribersTypeMap;
79
- private lastEvents;
80
- private debouncedEvents;
81
- constructor(_eventTypes: EventTypes<E>);
82
- get eventTypes(): EventTypes<E>;
83
- /**
84
- * Subscribes a handler to a specific event type.
85
- * @param type The event type to subscribe to.
86
- * @param handler The function to call when the event occurs.
87
- * @param options Subscription options (once, immediately).
88
- * @returns A subscription ID that can be used to unsubscribe.
89
- */
90
- subscribe<T extends EventType<E>>(type: T, handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number;
91
- /**
92
- * Subscribes a handler to multiple event types.
93
- * @param types An array of event types to subscribe to.
94
- * @param handler The function to call when any of the events occur.
95
- * @param options Subscription options.
96
- * @returns An array of subscription IDs.
97
- */
98
- subscribeMany<T extends EventType<E>>(types: T[], handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number[];
99
- /**
100
- * Unsubscribes a specific subscription by ID.
101
- * @param id The subscription ID returned by subscribe().
102
- * @returns True if the subscription was found and removed, false otherwise.
103
- */
104
- unsubscribe(id: number): boolean;
105
- /**
106
- * Emits an event with the given type and payload.
107
- * @param type The type of event to emit.
108
- * @param payload The data associated with the event.
109
- */
110
- emit<T extends EventType<E>, P extends EventPayload<E, T>>(type: T, payload: P): void;
111
- /**
112
- * Adds a fully constructed event object to the system.
113
- * Similar to emit, but takes the full event object directly.
114
- * Supports debouncing if options are provided.
115
- * @param event The event object.
116
- * @param options Options for the event push (e.g., debouncing).
117
- */
118
- addEvent<T extends EventType<E>>(event: Event<E, T>, options?: PushEventOptions): void;
119
- private handleDebouncedEvent;
120
- private scheduleProcessing;
121
- private processEvents;
122
- private dequeue;
123
- private setLastEvent;
124
- private broadcastEvent;
125
- }
126
- //#endregion
127
- //#region src/services/logger/index.d.ts
128
- type Logger$1 = Logger;
129
- //#endregion
130
- //#region src/services/database/events/index.d.ts
131
- declare const DatabaseEventTypes: {
132
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
133
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
134
- };
135
- interface DatabaseQueryEventPayload {
136
- query: string;
137
- vars?: Record<string, unknown>;
138
- duration: number;
139
- success: boolean;
140
- error?: string;
141
- timestamp: number;
142
- }
143
- type DatabaseEventTypeMap = {
144
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
145
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
146
- };
147
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
148
- //#endregion
149
- //#region src/utils/surql.d.ts
150
- interface SealedQuery<T = void> {
151
- readonly sql: string;
152
- readonly extract: (results: unknown[]) => T;
153
- }
154
- //#endregion
155
8
  //#region src/services/database/database.d.ts
156
9
  declare abstract class AbstractDatabaseService {
157
- protected client: Surreal;
10
+ protected client: Surreal$1;
158
11
  protected logger: Logger$1;
159
12
  protected events: DatabaseEventSystem;
160
13
  protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
161
- constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
14
+ constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
162
15
  abstract connect(): Promise<void>;
163
- getClient(): Surreal;
16
+ getClient(): Surreal$1;
164
17
  getEvents(): DatabaseEventSystem;
165
18
  tx(): Promise<SurrealTransaction>;
166
19
  private queryQueue;
@@ -172,21 +25,12 @@ declare abstract class AbstractDatabaseService {
172
25
  close(): Promise<void>;
173
26
  }
174
27
  //#endregion
175
- //#region src/services/database/local.d.ts
176
- declare class LocalDatabaseService extends AbstractDatabaseService {
177
- private config;
178
- protected eventType: "DATABASE_LOCAL_QUERY";
179
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
180
- getConfig(): SpookyConfig<any>['database'];
181
- connect(): Promise<void>;
182
- }
183
- //#endregion
184
28
  //#region src/services/database/remote.d.ts
185
29
  declare class RemoteDatabaseService extends AbstractDatabaseService {
186
30
  private config;
187
31
  protected eventType: "DATABASE_REMOTE_QUERY";
188
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
189
- getConfig(): SpookyConfig<any>['database'];
32
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
33
+ getConfig(): Sp00kyConfig<any>['database'];
190
34
  connect(): Promise<void>;
191
35
  signin(params: any): Promise<any>;
192
36
  signup(params: any): Promise<any>;
@@ -194,38 +38,44 @@ declare class RemoteDatabaseService extends AbstractDatabaseService {
194
38
  invalidate(): Promise<void>;
195
39
  }
196
40
  //#endregion
197
- //#region src/modules/sync/queue/queue-up.d.ts
198
- type CreateEvent = {
199
- type: 'create';
200
- mutation_id: RecordId;
201
- record_id: RecordId;
202
- data: Record<string, unknown>;
203
- record?: Record<string, unknown>;
204
- tableName?: string;
205
- options?: PushEventOptions;
41
+ //#region src/modules/sync/queue/queue-down.d.ts
42
+ type RegisterEvent = {
43
+ type: 'register';
44
+ payload: {
45
+ hash: string;
46
+ };
206
47
  };
207
- type UpdateEvent = {
208
- type: 'update';
209
- mutation_id: RecordId;
210
- record_id: RecordId;
211
- data: Record<string, unknown>;
212
- record?: Record<string, unknown>;
213
- beforeRecord?: Record<string, unknown>;
214
- options?: PushEventOptions;
48
+ type SyncEvent = {
49
+ type: 'sync';
50
+ payload: {
51
+ hash: string;
52
+ };
53
+ };
54
+ type HeartbeatEvent = {
55
+ type: 'heartbeat';
56
+ payload: {
57
+ hash: string;
58
+ };
215
59
  };
216
- type DeleteEvent = {
217
- type: 'delete';
218
- mutation_id: RecordId;
219
- record_id: RecordId;
220
- options?: PushEventOptions;
60
+ type CleanupEvent = {
61
+ type: 'cleanup';
62
+ payload: {
63
+ hash: string;
64
+ };
221
65
  };
222
- type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
66
+ type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
223
67
  //#endregion
224
68
  //#region src/services/stream-processor/wasm-types.d.ts
225
69
  interface WasmStreamUpdate {
226
70
  query_id: string;
227
71
  result_hash: string;
228
72
  result_data: RecordVersionArray;
73
+ timing_store_apply_ms?: number;
74
+ timing_circuit_step_ms?: number;
75
+ timing_transform_ms?: number;
76
+ timing_parse_ms?: number;
77
+ timing_plan_ms?: number;
78
+ timing_snapshot_ms?: number;
229
79
  }
230
80
  //#endregion
231
81
  //#region src/services/stream-processor/index.d.ts
@@ -246,6 +96,25 @@ interface StreamUpdate {
246
96
  queryHash: string;
247
97
  localArray: RecordVersionArray;
248
98
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
99
+ /**
100
+ * End-to-end ingest latency for the WASM call that produced this update,
101
+ * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
102
+ * for the initial register_view snapshot.
103
+ */
104
+ materializationTimeMs?: number;
105
+ /** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
106
+ storeApplyMs?: number;
107
+ circuitStepMs?: number;
108
+ transformMs?: number;
109
+ /**
110
+ * One-shot registration timings (ms). Only set on the StreamUpdate returned
111
+ * by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
112
+ */
113
+ registration?: {
114
+ parseMs: number;
115
+ planMs: number;
116
+ snapshotMs: number;
117
+ };
249
118
  }
250
119
  type StreamProcessorEvents = {
251
120
  stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
@@ -265,19 +134,123 @@ declare class StreamProcessorService {
265
134
  private processor;
266
135
  private isInitialized;
267
136
  private receivers;
268
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
137
+ private batching;
138
+ private batchBuffer;
139
+ private sessionAuth;
140
+ private stateKeySuffix;
141
+ private stateGeneration;
142
+ private persistState;
143
+ private persistCircuit;
144
+ private checkpointMs;
145
+ private checkpointTimer;
146
+ private snapshotDirty;
147
+ private pagehideHandler;
148
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, persistenceClient: PersistenceClient, logger: Logger);
269
149
  /**
270
150
  * Add a receiver for stream updates.
271
151
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
272
152
  */
273
153
  addReceiver(receiver: StreamUpdateReceiver): void;
274
154
  private notifyUpdates;
155
+ private dispatchUpdates;
156
+ /**
157
+ * Ingest a batch of record changes as a single bulk operation, firing only
158
+ * one coalesced `StreamUpdate` per affected query once every record has been
159
+ * ingested (instead of one update per record). Use this whenever multiple
160
+ * records land at once — e.g. sync fetching N missing rows — so a list query
161
+ * re-runs and the UI re-renders once for the whole batch rather than
162
+ * row-by-row.
163
+ *
164
+ * Internally opens a coalescing window, ingests each record, then flushes;
165
+ * processor state is persisted once for the whole batch. No-op for an empty
166
+ * batch.
167
+ */
168
+ ingestMany(records: Array<{
169
+ table: string;
170
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
171
+ id: string;
172
+ record: any;
173
+ }>): void;
174
+ /**
175
+ * Open a coalescing window. While open, the per-record stream updates
176
+ * emitted by `ingest` are buffered (one entry per queryHash) instead of
177
+ * dispatched. Always paired with `flushCoalescing()` in a try/finally by
178
+ * `ingestMany` so the window always closes — otherwise the processor stays
179
+ * stuck buffering forever.
180
+ *
181
+ * No-op if a window is already open (nested batches aren't expected here).
182
+ */
183
+ private beginCoalescing;
184
+ /**
185
+ * Close the coalescing window and flush: dispatch one coalesced
186
+ * `StreamUpdate` per buffered queryHash, then persist processor state once
187
+ * for the whole batch (instead of once per ingest).
188
+ */
189
+ private flushCoalescing;
275
190
  /**
276
191
  * Initialize the WASM module and processor.
277
192
  * This must be called before using other methods.
278
193
  */
279
194
  init(): Promise<void>;
195
+ /** Route the persisted circuit snapshot to a per-bucket key. */
196
+ setStateKeySuffix(bucketId: string): void;
197
+ private stateKey;
198
+ /**
199
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
200
+ * local-bucket switches: the old circuit holds the previous user's rows AND
201
+ * views registered with the previous `$auth` context, so neither may survive.
202
+ * Deliberately does NOT `loadState()` — a persisted snapshot references views
203
+ * under a dead sessionId salt; the DataModule rebind re-registers every live
204
+ * view against this fresh processor. Caller must re-seed `setPermissions`
205
+ * afterwards (a fresh circuit default-denies every table).
206
+ */
207
+ reset(): Promise<void>;
208
+ /**
209
+ * Release the wasm circuit and stop checkpointing. Call when the client is
210
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
211
+ * one full circuit per instance.
212
+ */
213
+ dispose(): void;
214
+ /**
215
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
216
+ * not expose `free`, and a double free must not take the app down.
217
+ */
218
+ private freeProcessor;
219
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
220
+ setPersistenceEnabled(enabled: boolean): void;
221
+ /**
222
+ * Opt into snapshot persistence (`persistCircuit`). Off by default: see the
223
+ * `persistCircuit` field comment for why per-ingest snapshots were removed.
224
+ * Must be called before `init()` for a snapshot to be restored at boot.
225
+ */
226
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
227
+ /**
228
+ * Record that the circuit changed. Cheap and O(1), the expensive snapshot is
229
+ * deferred to the checkpoint timer, and skipped entirely when
230
+ * `persistCircuit` is off (the default).
231
+ */
232
+ private markSnapshotDirty;
233
+ private startCheckpoints;
234
+ /** Stop checkpointing and drop the `pagehide` listener. */
235
+ stopCheckpoints(): void;
280
236
  loadState(): Promise<void>;
237
+ /**
238
+ * Seed per-table `select` permission predicates ({ [table]: whereText }).
239
+ * Must run after the processor exists and before any `register_view`, else
240
+ * non-`_00_` tables are default-denied and registration fails.
241
+ */
242
+ setPermissions(permissions: Record<string, string>): void;
243
+ /**
244
+ * Set the current session's auth identity for permission injection,
245
+ * mirroring the server's `fn::query::register`
246
+ * (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
247
+ * Stored as strings (empty when logged out) and applied to every
248
+ * `register_view` in {@link registerQueryPlan}. Must be set before a
249
+ * `$auth`-gated query registers (and re-set on auth state changes), or the
250
+ * in-browser SSP's `permission_inject` rejects it with
251
+ * "requires $auth but registration params lack it".
252
+ */
253
+ setSessionAuth(authId: string | null, access: string | null): void;
281
254
  saveState(): Promise<void>;
282
255
  /**
283
256
  * Ingest a record change into the processor.
@@ -297,203 +270,822 @@ declare class StreamProcessorService {
297
270
  private normalizeValue;
298
271
  }
299
272
  //#endregion
300
- //#region src/types.d.ts
301
- /**
302
- * The type of storage backend to use for the local database.
303
- * - 'memory': In-memory storage (transient).
304
- * - 'indexeddb': IndexedDB storage (persistent).
305
- */
306
- type StoreType = 'memory' | 'indexeddb';
273
+ //#region src/modules/cache/types.d.ts
274
+ type RecordWithId = Record<string, any> & {
275
+ id: RecordId<string>;
276
+ };
277
+ interface QueryConfig$1 {
278
+ queryHash: string;
279
+ surql: string;
280
+ params: Record<string, any>;
281
+ ttl: QueryTimeToLive | Duration;
282
+ lastActiveAt: Date;
283
+ }
284
+ interface CacheRecord {
285
+ table: string;
286
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
287
+ record: RecordWithId;
288
+ version: number;
289
+ }
290
+ //#endregion
291
+ //#region src/modules/cache/index.d.ts
307
292
  /**
308
- * Interface for a custom persistence client.
309
- * Allows providing a custom storage mechanism for the local database.
293
+ * CacheModule - Centralized storage and DBSP ingestion
294
+ *
295
+ * Single responsibility: Handle all local storage operations and DBSP ingestion.
296
+ * This module acts as the bridge between data operations and persistence.
310
297
  */
311
- interface PersistenceClient {
298
+ /** One ingested change, in exactly the shape `ingestMany` consumes. Shared
299
+ * with the tabs protocol so a leader can relay its ingests to followers. */
300
+ interface CacheIngestTuple {
301
+ table: string;
302
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
303
+ id: string;
304
+ record: Record<string, unknown>;
305
+ }
306
+ declare class CacheModule implements StreamUpdateReceiver {
307
+ private local;
308
+ private streamProcessor;
309
+ private logger;
310
+ private streamUpdateCallback;
311
+ private versionLookups;
312
+ /** Shared-tabs leader: fan every committed ingest out to follower circuits.
313
+ * Fired AFTER the local tx (the rows are already in the shared store, so a
314
+ * follower only needs the circuit feed). Never set on followers. */
315
+ private ingestRelay;
316
+ constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
312
317
  /**
313
- * Sets a value in the storage.
314
- * @param key The key to set.
315
- * @param value The value to store.
318
+ * Implements StreamUpdateReceiver interface
319
+ * Called directly by StreamProcessor when views change
316
320
  */
317
- set<T>(key: string, value: T): Promise<void>;
321
+ onStreamUpdate(update: StreamUpdate): void;
322
+ setIngestRelay(cb: ((tuples: CacheIngestTuple[]) => void) | null): void;
318
323
  /**
319
- * Gets a value from the storage.
320
- * @param key The key to retrieve.
321
- * @returns The stored value or null if not found.
324
+ * Shared-tabs follower: feed relayed tuples into THIS tab's circuit only.
325
+ * The rows are already in the shared store (the leader wrote them), so no
326
+ * local write happens here; the normal chain then runs: SSP -> stream update
327
+ * -> DataModule debounce -> materializeRecords (re-reads via the port
328
+ * transport) -> this tab's subscriptions fire with this tab's hashes.
322
329
  */
323
- get<T>(key: string): Promise<T | null>;
330
+ applyRelayedIngest(tuples: CacheIngestTuple[]): void;
331
+ lookup(recordId: string): number;
332
+ /** Drop the version cache on a bucket switch — a stale version would make
333
+ * the sync diff skip fetching a body the new bucket legitimately needs. */
334
+ clearVersionLookups(): void;
324
335
  /**
325
- * Removes a value from the storage.
326
- * @param key The key to remove.
336
+ * Save a single record to local DB and ingest into DBSP
337
+ * Used by mutations (create/update)
327
338
  */
328
- remove(key: string): Promise<void>;
329
- }
330
- /**
331
- * Supported Time-To-Live (TTL) values for cached queries.
332
- * Format: number + unit (m=minutes, h=hours, d=days).
333
- */
334
- type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
335
- /**
336
- * Result object returned when a query is registered or executed.
337
- */
338
- interface SpookyQueryResult {
339
- /** The unique hash identifier for the query. */
340
- hash: string;
341
- }
342
- type SpookyQueryResultPromise = Promise<SpookyQueryResult>;
343
- interface EventSubscriptionOptions {
344
- priority?: number;
339
+ save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
340
+ /**
341
+ * Save multiple records in a batch
342
+ * More efficient than calling save() multiple times
343
+ * Used by sync operations
344
+ */
345
+ saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
346
+ /**
347
+ * Delete a record from local DB and ingest deletion into DBSP
348
+ */
349
+ delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
350
+ /**
351
+ * Register a query with DBSP to create a materialized view
352
+ * Returns the initial result array
353
+ */
354
+ registerQuery(config: QueryConfig$1): {
355
+ localArray: RecordVersionArray;
356
+ registrationTimings?: {
357
+ parseMs: number;
358
+ planMs: number;
359
+ snapshotMs: number;
360
+ };
361
+ };
362
+ /**
363
+ * Unregister a query from DBSP
364
+ */
365
+ unregisterQuery(queryHash: string): void;
345
366
  }
367
+ //#endregion
368
+ //#region src/modules/data/index.d.ts
346
369
  /**
347
- * Configuration options for the Spooky client.
348
- * @template S The schema structure type.
370
+ * DataModule - Unified query and mutation management
371
+ *
372
+ * Merges the functionality of QueryManager and MutationManager.
373
+ * Uses CacheModule for all storage operations.
349
374
  */
350
- interface SpookyConfig<S extends SchemaStructure> {
351
- /** Database connection configuration. */
352
- database: {
353
- /** The SurrealDB endpoint URL. */
354
- endpoint?: string;
355
- /** The namespace to use. */
356
- namespace: string;
357
- /** The database name. */
358
- database: string;
359
- /** The local store type implementation. */
360
- store?: StoreType;
361
- /** Authentication token. */
362
- token?: string;
363
- };
364
- /** Unique client identifier. If not provided, one will be generated. */
365
- clientId?: string;
366
- /** The schema definition. */
367
- schema: S;
368
- /** The compiled SURQL schema string. */
369
- schemaSurql: string;
370
- /** Logging level. */
371
- logLevel: Level$1;
375
+ declare class DataModule<S extends SchemaStructure> {
376
+ private cache;
377
+ private local;
378
+ private schema;
379
+ private streamDebounceTime;
380
+ /** Tab identity baked into mutation ids (shared-tabs rollback routing);
381
+ * undefined in solo mode, where mutation-id falls back to a session id. */
382
+ private tabId;
383
+ private activeQueries;
384
+ private pendingQueries;
385
+ private subscriptions;
386
+ private statusSubscriptions;
387
+ private mutationCallbacks;
388
+ private debounceTimers;
389
+ private pendingStreamUpdates;
390
+ private fetchDepth;
391
+ private logger;
392
+ /**
393
+ * Optional observer notified whenever a query's fetch status changes.
394
+ * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
395
+ * settable field (rather than a constructor arg) because DevTools is
396
+ * constructed after DataModule.
397
+ */
398
+ onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
399
+ /**
400
+ * Optional observer invoked when a still-subscribed query's TTL heartbeat
401
+ * fires (~90% of the TTL). Wired by Sp00kyClient to
402
+ * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
403
+ * row's `lastActiveAt` so an actively-watched query never expires. Settable
404
+ * field (not a constructor arg) because the sync engine is wired after
405
+ * DataModule is constructed — mirrors `onQueryStatusChange`.
406
+ */
407
+ onHeartbeat?: (hash: QueryHash) => void;
408
+ /**
409
+ * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
410
+ * viewport-windowed list cancelling an off-screen window) loses its last
411
+ * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
412
+ * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
413
+ * instead of leaving it for the TTL sweep. The local view + state are freed in
414
+ * {@link finalizeDeregister} only after that remote delete, so a fast
415
+ * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
416
+ */
417
+ onDeregister?: (hash: QueryHash) => void;
418
+ private sessionId;
419
+ private currentUserId;
420
+ constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
421
+ init(sessionId: string): Promise<void>;
422
+ /**
423
+ * Update the session salt used in query-id hashing. Call this when the
424
+ * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
425
+ * registered queries will get fresh, session-scoped IDs.
426
+ */
427
+ setSessionId(sessionId: string): void;
428
+ /** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
429
+ * a follower's mutation routes back to the tab that made it. */
430
+ setTabId(tabId: string): void;
431
+ /**
432
+ * Update the authenticated user record id. Pass `null` on sign-out.
433
+ * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
434
+ * the poll route to the same per-user `_00_list_ref_user_<id>` the
435
+ * SSP writes to.
436
+ */
437
+ setCurrentUserId(userId: string | null): void;
438
+ /** Read-only view of the authenticated user id used for per-user
439
+ * `_00_list_ref` routing. Other modules consult this so they pick the
440
+ * same table name DataModule does. */
441
+ getCurrentUserId(): string | null;
442
+ /**
443
+ * Register a query and return its hash for subscriptions
444
+ */
445
+ query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
446
+ /**
447
+ * Subscribe to query updates
448
+ */
449
+ subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
450
+ immediate?: boolean;
451
+ }): () => void;
452
+ /**
453
+ * Subscribe to a query's fetch-status changes (idle/fetching).
454
+ * With `{ immediate: true }` the callback fires synchronously with the
455
+ * current status (defaults to `idle` if the query isn't registered yet).
456
+ */
457
+ subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
458
+ immediate?: boolean;
459
+ }): () => void;
460
+ /**
461
+ * Set a query's fetch status and notify status observers (DevTools +
462
+ * `subscribeStatus` listeners). No-op when the status is unchanged or the
463
+ * query is unknown.
464
+ */
465
+ setQueryStatus(queryHash: string, status: QueryStatus): void;
466
+ /**
467
+ * Enter a fetch cycle for a query. Refcounted: registration and concurrent
468
+ * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
469
+ * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
470
+ * emits `idle`. Always pair with `endFetching` in a `finally`.
471
+ */
472
+ beginFetching(queryHash: string): void;
473
+ /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
474
+ endFetching(queryHash: string): void;
475
+ /**
476
+ * Subscribe to mutations (for sync)
477
+ */
478
+ onMutation(callback: MutationCallback): () => void;
479
+ /**
480
+ * Handle stream updates from DBSP (via CacheModule)
481
+ */
482
+ onStreamUpdate(update: StreamUpdate): Promise<void>;
483
+ /**
484
+ * Process a query's pending (debounced) stream update NOW instead of on the
485
+ * trailing edge. Called by the sync engine before it flips a query back to
486
+ * `idle`, so the status change never races ahead of the rows it fetched.
487
+ * No-op when nothing is pending. The pending entry is removed before the
488
+ * await so a concurrently-firing timer can't process it twice.
489
+ */
490
+ flushPendingStreamUpdate(queryHash: string): Promise<void>;
491
+ private materializeRecords;
492
+ private processStreamUpdate;
493
+ /**
494
+ * Compute p55/p90/p99 from a rolling window of materialization samples.
495
+ * Returns nulls for any percentile that has no samples yet so SurrealDB
496
+ * `option<float>` columns stay NONE rather than 0 before the first ingest.
497
+ */
498
+ private computeMaterializationPercentiles;
499
+ /** Record a per-phase timing sample (ms) on a query's rolling window. */
500
+ private recordPhase;
501
+ /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
502
+ recordRemoteFetch(hash: string, ms: number): void;
503
+ /**
504
+ * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
505
+ * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
506
+ */
507
+ recordFrontendTiming(hash: string, ms: number): void;
508
+ /**
509
+ * Build the per-query processing-time breakdown surfaced to the DevTools panel
510
+ * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
511
+ * the rest come from the per-phase rolling windows + one-shot registration timings.
512
+ */
513
+ phaseTimings(q: QueryState): QueryTimings;
514
+ /**
515
+ * Get query state (for sync and devtools)
516
+ */
517
+ getQueryByHash(hash: string): QueryState | undefined;
518
+ /**
519
+ * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
520
+ * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
521
+ * We gate on `remoteArray`, not local `records`: a windowed query is often
522
+ * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
523
+ * but it still hasn't loaded its own full window from the server — so it should
524
+ * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
525
+ */
526
+ isCold(hash: string): boolean;
527
+ /**
528
+ * Walk a hydrated record's fields and append any EMBEDDED child records to
529
+ * `batch` (recursing for nested related fields). An embedded child is a
530
+ * value that is itself a record — a non-null object whose `id` is a
531
+ * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
532
+ * bare `RecordId` (a foreign-key reference) or any other value is skipped,
533
+ * so this never mistakes a FK column for an embedded body. Children are
534
+ * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
535
+ * to their table's real columns (which strips the alias/related fields).
536
+ * `seen` dedupes within the batch.
537
+ */
538
+ private collectEmbeddedChildren;
539
+ /**
540
+ * Prepare a subquery-bearing row (preload / hydration) for the schemafull
541
+ * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
542
+ * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
543
+ * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
544
+ * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
545
+ * with relations already RecordIds — passes through unchanged.
546
+ */
547
+ private flattenRelationsForStorage;
548
+ /**
549
+ * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
550
+ * surql run directly) so the query DISPLAYS immediately, while the full realtime
551
+ * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
552
+ * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
553
+ * `remoteArray` so windowed queries materialize the correct window (no sparse
554
+ * local-circuit issue). Runs at most once per query (the `hydrated` flag).
555
+ */
556
+ applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
557
+ /**
558
+ * Build the cache batch for a set of one-shot rows and persist it to the
559
+ * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
560
+ * and extracts EMBEDDED related children (any nesting depth) as their own
561
+ * records — a `.related()` query returns its children embedded, and a later
562
+ * correlated re-materialization needs them present as standalone rows.
563
+ * Shared by `applyHydration` (live registration) and `persistSnapshot`
564
+ * (preload).
565
+ */
566
+ private buildAndSaveCacheBatch;
567
+ /**
568
+ * Preload/prewarm: persist one-shot rows (and their embedded related children)
569
+ * into the local cache WITHOUT registering a query — no `activeQueries` entry,
570
+ * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
571
+ * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
572
+ * first paint from them instantly, then registers a live view to freshen.
573
+ */
574
+ persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
575
+ /**
576
+ * Read the durable preload freshness marker for a query hash, or null if this
577
+ * query was never preloaded in the current bucket. Co-located with the cached
578
+ * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
579
+ * data also clears the marker — a stale marker can't claim "warm" when the
580
+ * rows are gone. Any read error is treated as cold.
581
+ */
582
+ getPreloadMarker(hash: string): Promise<{
583
+ fetchedAt: number;
584
+ rowCount: number;
585
+ } | null>;
586
+ /** Stamp the preload freshness marker after a successful snapshot fetch. */
587
+ writePreloadMarker(hash: string, rowCount: number): Promise<void>;
588
+ /** True while ≥1 live subscriber is watching this query (refcount guard). */
589
+ hasSubscribers(hash: string): boolean;
590
+ /**
591
+ * Opt-in eager teardown for a query whose LAST subscriber just left — used by
592
+ * viewport-windowed lists to cancel off-screen windows instead of leaving
593
+ * their remote views to expire on the TTL sweep. No-op while any subscriber
594
+ * remains (refcount). Only enqueues the remote cleanup here; the local WASM
595
+ * view + in-memory state are freed in {@link finalizeDeregister} after the
596
+ * remote delete completes, so a re-subscribe in between aborts/heals it.
597
+ *
598
+ * NOTE: most queries should NOT use this — the default keep-alive on
599
+ * unsubscribe avoids re-registration churn on navigation.
600
+ */
601
+ deregisterQuery(hash: string): void;
602
+ /**
603
+ * Final local teardown after the remote `_00_query` row was deleted: free the
604
+ * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
605
+ * (`cleanupQuery`) guarantees no subscriber remains.
606
+ */
607
+ finalizeDeregister(hash: string): void;
608
+ /**
609
+ * Get query state by id (for sync and devtools)
610
+ */
611
+ getQueryById(id: RecordId<string>): QueryState | undefined;
612
+ /**
613
+ * Get all active queries (for devtools)
614
+ */
615
+ getActiveQueries(): QueryState[];
616
+ getActiveQueryHashes(): QueryHash[];
617
+ updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
618
+ updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void>;
619
+ /**
620
+ * Cancel every armed timer ahead of a local-bucket switch: stream-update
621
+ * debounce timers (their pending updates carry the OLD bucket's id-sets) and
622
+ * per-query TTL heartbeats (they'd refresh the previous user's remote
623
+ * `_00_query` rows under the new session). The rebind re-arms heartbeats.
624
+ */
625
+ quiesce(): void;
626
+ /**
627
+ * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
628
+ * `useQuery` subscriptions are keyed by hash and don't re-register on auth
629
+ * changes, so the hooks must stay attached. Per query:
630
+ * 1. reset the sync arrays + hydration flag and drop the previous user's
631
+ * records, notifying subscribers with the new-bucket materialization
632
+ * (usually empty) so their rows leave the UI immediately;
633
+ * 2. recreate the `_00_query` row in the new bucket;
634
+ * 3. re-register the SSP view on the (fresh, post-reset) processor — this
635
+ * also rebinds the view to the NEW `$auth` context;
636
+ * 4. restart the TTL heartbeat.
637
+ * Returns the hashes so the caller can enqueue remote re-registration, which
638
+ * refills records from the server via the normal register→sync→notify path.
639
+ */
640
+ rebindAfterBucketSwitch(): Promise<QueryHash[]>;
641
+ /**
642
+ * Called after a query's initial sync completes.
643
+ * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
644
+ */
645
+ notifyQuerySynced(queryHash: string): Promise<void>;
646
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
372
647
  /**
373
- * Persistence client to use.
374
- * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
648
+ * Build the outbox job record + resolve its table for a backend route.
649
+ *
650
+ * Every job is a single execution. Recurring work is declared server-side
651
+ * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
652
+ * so nothing here needs to know about schedules.
375
653
  */
376
- persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
377
- /** OpenTelemetry collector endpoint for telemetry data. */
378
- otelEndpoint?: string;
654
+ private buildJobRecord;
379
655
  /**
380
- * Debounce time in milliseconds for stream updates.
381
- * Defaults to 100ms.
656
+ * Create a new record
382
657
  */
383
- streamDebounceTime?: number;
658
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
659
+ /**
660
+ * Update an existing record
661
+ */
662
+ update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
663
+ /**
664
+ * Delete a record
665
+ */
666
+ delete(table: string, id: string): Promise<void>;
667
+ /**
668
+ * Rollback a failed optimistic create by deleting the record locally
669
+ */
670
+ rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
671
+ /**
672
+ * Rollback a failed optimistic update by restoring the previous record state
673
+ */
674
+ rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
675
+ /**
676
+ * Remove a record from all active query states and notify subscribers
677
+ */
678
+ private removeRecordFromQueries;
679
+ private createAndRegisterQuery;
680
+ private createNewQuery;
681
+ private calculateHash;
682
+ private startTTLHeartbeat;
683
+ private replaceRecordInQueries;
384
684
  }
385
- type QueryHash = string;
386
- type RecordVersionArray = Array<[string, number]>;
387
685
  /**
388
- * Represents the difference between two record version sets.
389
- * Used for synchronizing local and remote states.
686
+ * Parse update options to generate push event options
390
687
  */
391
- interface RecordVersionDiff {
392
- /** List of records added. */
393
- added: Array<{
394
- id: RecordId$1<string>;
395
- version: number;
396
- }>;
397
- /** List of records updated. */
398
- updated: Array<{
399
- id: RecordId$1<string>;
400
- version: number;
401
- }>;
402
- /** List of record IDs removed. */
403
- removed: RecordId$1<string>[];
688
+ //#endregion
689
+ //#region src/services/tabs/protocol.d.ts
690
+ type TabId = string;
691
+ type TabRole = 'solo' | 'leader' | 'follower';
692
+ /** Broker pings every tab at this cadence. */
693
+
694
+ /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
695
+ * consumes, so relayed batches feed follower circuits without reshaping. */
696
+ interface IngestTuple {
697
+ table: string;
698
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
699
+ id: string;
700
+ record: Record<string, unknown>;
404
701
  }
405
- /**
406
- * Configuration for a specific query instance.
407
- * Stores metadata about the query's state, parameters, and versioning.
408
- */
409
- interface QueryConfig {
410
- /** The unique ID of the query config record. */
411
- id: RecordId$1<string>;
412
- /** The SURQL query string. */
413
- surql: string;
414
- /** Parameters used in the query. */
415
- params: Record<string, any>;
416
- /** The version array representing the local state of results. */
417
- localArray: RecordVersionArray;
418
- /** The version array representing the remote (server) state of results. */
419
- remoteArray: RecordVersionArray;
420
- /** Time-To-Live for this query. */
421
- ttl: QueryTimeToLive;
422
- /** Timestamp when the query was last accessed/active. */
423
- lastActiveAt: Date;
424
- /** The name of the table this query targets (if applicable). */
425
- tableName: string;
702
+ type FollowerToLeaderMessage = {
703
+ type: 'sync-hello';
704
+ tabId: TabId;
426
705
  }
427
- type QueryConfigRecord = QueryConfig & {
428
- id: string;
706
+ /** The follower committed an outbox row (through the shared store) and the
707
+ * leader should drain it. Idempotent; a new leader's loadFromDatabase is
708
+ * the backstop for a notify lost in a failover window. */ | {
709
+ type: 'mutation-enqueued';
710
+ mutationId: string;
711
+ } | {
712
+ type: 'request-poll';
429
713
  };
430
- /**
431
- * Internal state of a live query.
432
- */
433
- interface QueryState {
434
- /** The configuration for this query. */
435
- config: QueryConfig;
436
- /** The current cached records for this query. */
437
- records: Record<string, any>[];
438
- /** Timer for TTL expiration. */
439
- ttlTimer: NodeJS.Timeout | null;
440
- /** TTL duration in milliseconds. */
441
- ttlDurationMs: number;
442
- /** Number of times the query has been updated. */
443
- updateCount: number;
444
- }
445
- type QueryUpdateCallback = (records: Record<string, any>[]) => void;
446
- type MutationCallback = (mutations: UpEvent[]) => void;
447
- type MutationEventType = 'create' | 'update' | 'delete';
448
- /**
449
- * Represents a mutation event (create, update, delete) to be synchronized.
450
- */
451
- interface MutationEvent {
452
- /** Example: 'create', 'update', or 'delete'. */
453
- type: MutationEventType;
454
- /** unique id of the mutation */
455
- mutation_id: RecordId$1<string>;
456
- /** The ID of the record being mutated. */
457
- record_id: RecordId$1<string>;
458
- /** The data payload for create/update operations. */
459
- data?: any;
460
- /** The full record data (optional context). */
461
- record?: any;
462
- /** Options for the mutation event (e.g., debounce settings). */
463
- options?: PushEventOptions;
464
- /** Timestamp when the event was created. */
465
- createdAt: Date;
714
+ type LeaderToFollowerMessage = {
715
+ type: 'db-ready';
716
+ leadershipId: number;
717
+ bucketId: string;
718
+ storageHealth: StorageHealth;
466
719
  }
467
- /**
468
- * Options for run operations.
469
- */
470
- interface RunOptions {
471
- assignedTo?: string;
472
- max_retries?: number;
473
- retry_strategy?: 'linear' | 'exponential';
720
+ /** Every ingest the leader's CacheModule committed, so follower circuits
721
+ * stay live without their own fetch. seq detects gaps. */ | {
722
+ type: 'ingest-relay';
723
+ tuples: IngestTuple[];
724
+ leadershipId: number;
725
+ seq: number;
726
+ }
727
+ /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
728
+ * queryId against its own DataModule and ignores foreign queries. */ | {
729
+ type: 'list-ref-change';
730
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
731
+ queryId: string;
732
+ recordId: string;
733
+ version: number;
734
+ parent: boolean;
735
+ }
736
+ /** The leader's drain rolled back a mutation owned by this tab. */ | {
737
+ type: 'mutation-rolled-back';
738
+ mutationId: string;
739
+ recordId: string;
740
+ eventType: 'create' | 'update' | 'delete';
741
+ error: string;
742
+ };
743
+ //#endregion
744
+ //#region src/services/tabs/coordinator.d.ts
745
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
746
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
747
+ declare class LeaderSyncHub {
748
+ readonly leadershipId: number;
749
+ private logger;
750
+ private followers;
751
+ private seq;
752
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
753
+ onFollowerDetached: ((tabId: TabId) => void) | null;
754
+ constructor(leadershipId: number, logger: Logger$1);
755
+ attach(tabId: TabId, port: MessagePort): void;
756
+ detach(tabId: TabId): void;
757
+ detachAll(): void;
758
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
759
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
760
+ /** Stamped ingest relay; seq lets followers detect gaps. */
761
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
762
+ get followerCount(): number;
763
+ get relayedBatches(): number;
764
+ }
765
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
766
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
767
+ * backstopped by the new leader reloading the shared outbox from the store. */
768
+ declare class SyncForwarder {
769
+ private tabId;
770
+ private port;
771
+ private queued;
772
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
773
+ constructor(tabId: TabId);
774
+ rebind(port: MessagePort): void;
775
+ unbind(): void;
776
+ private post;
777
+ mutationEnqueued(mutationId: string): void;
778
+ requestPoll(): void;
474
779
  }
780
+ //#endregion
781
+ //#region src/modules/sync/sync.d.ts
475
782
  /**
476
- * Options for update operations.
783
+ * Tunables for `Sp00kySync` construction.
477
784
  */
478
- interface UpdateOptions {
785
+ interface Sp00kySyncOptions {
786
+ /**
787
+ * Cadence (ms) for the `_00_list_ref` poll fallback that catches
788
+ * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
789
+ * values fall back to the default; see
790
+ * {@link resolveListRefPollInterval}.
791
+ */
792
+ refSyncIntervalMs?: number;
479
793
  /**
480
- * Debounce configuration for the update.
481
- * If boolean, enables default debounce behavior.
794
+ * Enable realtime sync for unauthenticated clients against the shared
795
+ * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
796
+ * Defaults to `false`.
482
797
  */
483
- debounced?: boolean | DebounceOptions;
798
+ anonymousLiveQueries?: boolean;
799
+ /**
800
+ * Consecutive failed sync rounds before sync health flips to `degraded`.
801
+ * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
802
+ * Defaults to `3`.
803
+ */
804
+ degradeAfterConsecutiveFailures?: number;
805
+ /**
806
+ * Max time a single mutation push may take before it is treated as a network
807
+ * failure and retried. Guards against an RPC that never settles wedging the
808
+ * up-queue for the session. Defaults to 30000; `0` disables the timeout.
809
+ */
810
+ pushTimeoutMs?: number;
484
811
  }
485
812
  /**
486
- * Configuration options for debouncing updates.
813
+ * The main synchronization engine for Sp00ky.
814
+ * Handles the bidirectional synchronization between the local database and the remote backend.
815
+ * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
816
+ * @template S The schema structure type.
487
817
  */
488
- interface DebounceOptions {
818
+ declare class Sp00kySync<S extends SchemaStructure> {
819
+ private local;
820
+ private remote;
821
+ private cache;
822
+ private dataModule;
823
+ private schema;
824
+ private upQueue;
825
+ private downQueue;
826
+ private isInit;
827
+ private logger;
828
+ private syncEngine;
829
+ /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
830
+ * from `this.events`, which carries Sp00kySync-level events like
831
+ * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
832
+ get engineEvents(): SyncEventSystem;
833
+ private scheduler;
834
+ private wasDisconnected;
835
+ events: SyncEventSystem;
836
+ private currentUserId;
837
+ private tabRole;
838
+ private tabId;
839
+ private hub;
840
+ private forwarder;
841
+ private refMode;
842
+ private readonly anonLiveEnabled;
843
+ private currentLiveQueryUuid;
844
+ private liveQueryUnsubscribe;
845
+ private listRefPollTimer;
846
+ private listRefPollRunning;
847
+ private listRefPollInFlight;
848
+ readonly refSyncIntervalMs: number;
849
+ private listRefIdleStreak;
850
+ private stillRemoteStreaks;
851
+ private lastLiveEventAt;
852
+ private _liveRetryCount;
853
+ get liveRetryCount(): number;
854
+ get isSyncing(): boolean;
855
+ get pendingMutationCount(): number;
856
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
857
+ private readonly degradeAfterFailures;
858
+ /** Per-push RPC deadline; see {@link withPushTimeout}. */
859
+ private readonly pushTimeoutMs;
860
+ private consecutiveSyncFailures;
861
+ private syncHealthStatus;
862
+ private lastSyncErrorKind;
863
+ private lastSyncErrorMessage;
864
+ private hasSyncedOnce;
865
+ private selfHealTimer;
866
+ private selfHealAttempts;
867
+ private static readonly SELF_HEAL_BASE_MS;
868
+ private static readonly SELF_HEAL_MAX_MS;
869
+ /** Current sync-health snapshot. */
870
+ get syncHealth(): SyncHealth;
871
+ /**
872
+ * Observe sync health. The callback fires immediately with the current
873
+ * status and again on every healthy↔degraded transition. Returns an
874
+ * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
875
+ */
876
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
877
+ private emitSyncHealth;
878
+ /**
879
+ * Fed by the scheduler once per drained sync round. Individual failures are
880
+ * absorbed by the queue's retry; only a run of `degradeAfterFailures`
881
+ * consecutive failures flips the status to `degraded`, and the next clean
882
+ * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
883
+ * is 0).
884
+ */
885
+ private recordSyncOutcome;
886
+ /**
887
+ * Begin self-heal retries (no-op if already running). Started on the
888
+ * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
889
+ */
890
+ private startSelfHeal;
891
+ private scheduleSelfHeal;
892
+ private stopSelfHeal;
893
+ constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
894
+ /**
895
+ * Initializes the synchronization system.
896
+ * Starts the scheduler and initiates the initial sync cycles.
897
+ * @throws Error if already initialized.
898
+ */
899
+ init(): Promise<void>;
900
+ /** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
901
+ * never starts LIVE; its own registration/poll paths stay untouched). */
902
+ setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void;
903
+ /** Leader duties: drain the shared outbox, own the single list_ref LIVE,
904
+ * relay LIVE events and rollbacks to followers via `hub`. Idempotent for a
905
+ * boot-time leader; a runtime promotion (failover) reloads the outbox,
906
+ * which now holds EVERY tab's rows, and restarts LIVE under this session. */
907
+ promoteToLeader(hub: LeaderSyncHub): Promise<void>;
908
+ /** Follower duties: no outbox drain, no LIVE. Mutations forward to the
909
+ * leader; everything else (registration, per-query sync, poll) runs
910
+ * against this tab's own remote session as usual. */
911
+ demoteToFollower(forwarder: SyncForwarder): void;
912
+ /**
913
+ * A pending mutation was discarded because it can never be sent.
914
+ *
915
+ * This is a lost write, so it must not stay invisible. Every failure in this
916
+ * chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
917
+ * shows, which is how an outbox could sit undrained for hours with the UI
918
+ * reporting nothing. Surfaces as a rollback event (the mutation will never
919
+ * apply, which is what a subscriber needs to know) and degrades sync health.
920
+ */
921
+ private onMutationDropped;
922
+ /** A forwarded outbox row from a follower: load + drain it. Idempotent. */
923
+ enqueueForwardedMutation(mutationId: string): Promise<void>;
924
+ /** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
925
+ * and run the exact same handling the LIVE subscription would have. */
926
+ private applyRelayedListRefChange;
927
+ /** One immediate poll cycle (failover convergence). */
928
+ forcePollRound(): Promise<void>;
929
+ /**
930
+ * Quiesce all sync activity ahead of a local-bucket switch. After this
931
+ * resolves, nothing in the sync module writes to the local store: the poll
932
+ * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
933
+ * timers are cancelled (their outbox rows are already persisted), and the
934
+ * scheduler has drained its in-flight queue item — including that item's
935
+ * outbox-row delete, which must land in the OLD bucket. Queued down-events
936
+ * are dropped (they reference old-bucket query rows; the post-switch rebind
937
+ * re-enqueues registrations). The old user's un-pushed outbox is deliberately
938
+ * NOT drained: the remote session already belongs to the next user.
939
+ */
940
+ prepareBucketSwitch(): Promise<void>;
941
+ /**
942
+ * Resume syncing against the freshly-opened bucket: reload the mutation
943
+ * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
944
+ * offline work) and restart the scheduler. LIVE + the list_ref poll restart
945
+ * via the `setCurrentUserId` call that follows in the auth listener.
946
+ */
947
+ completeBucketSwitch(): Promise<void>;
948
+ /**
949
+ * Push the authenticated user's record id from the parent client's
950
+ * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
951
+ * any) and re-registers it under the new user's dedicated table so
952
+ * SurrealDB binds the permission rule under the post-flip auth
953
+ * context. Pass `null` on sign-out.
954
+ *
955
+ * The dedicated `_00_list_ref_user_<id>` table is created lazily by
956
+ * the SSP when the first query registration arrives, which may be
957
+ * concurrent with this call. We retry the LIVE registration with a
958
+ * short backoff so a "table not found" race resolves without
959
+ * surfacing as a permanent auth-loading hang.
960
+ */
961
+ setCurrentUserId(userId: string | null): Promise<void>;
962
+ private startListRefPoll;
963
+ private stopListRefPoll;
964
+ /**
965
+ * One poll cycle: refetch `_00_list_ref` for every active query. Returns
966
+ * whether ANY query's remoteArray actually changed — the scheduler uses this
967
+ * to drive the adaptive idle backoff.
968
+ *
969
+ * Also the ONLY health signal that runs while the page is idle. Sync health is
970
+ * otherwise activity-driven (mutations/registrations via the scheduler,
971
+ * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
972
+ * would linger until the next mutation and a genuine idle drop would be
973
+ * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
974
+ * so idle health self-recovers (and self-degrades) with no user action. A clean
975
+ * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
976
+ * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
977
+ */
978
+ private pollListRefForActiveQueries;
979
+ /**
980
+ * Pull the upstream list_ref entries for `queryHash`, diff them
981
+ * against the local `remoteArray` cache, sync any added/updated rows
982
+ * through the SyncEngine, then persist the new remoteArray. This is
983
+ * the same shape `createRemoteQuery` does for its initial fetch and
984
+ * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
985
+ * it on a timer as a fallback for missed LIVE notifications.
986
+ */
987
+ private refetchListRefForQuery;
988
+ /**
989
+ * Resolve the current `_00_list_ref` table name for the active auth
990
+ * context. Public so the `createRemoteQuery` initial-fetch path can
991
+ * read from the right per-user table.
992
+ *
993
+ * Reads the user id from `DataModule` rather than the local mirror,
994
+ * because `DataModule.setCurrentUserId` runs synchronously from the
995
+ * auth callback (before any `await`), whereas `sync.setCurrentUserId`
996
+ * is async — the userQuery's initial fetch can fire between those
997
+ * two points and we need the correct table name immediately.
998
+ */
999
+ listRefTable(): string;
1000
+ private killRefLiveQuery;
1001
+ private restartRefLiveQuery;
1002
+ private subscribeToReconnect;
1003
+ private startRefLiveQueries;
1004
+ private handleRemoteListRefChange;
1005
+ /**
1006
+ * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
1007
+ * `parent` set) for a `.related()` query. Unlike primary rows, child rows
1008
+ * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
1009
+ * keep the child BODY fresh in the local cache so the in-browser SSP's
1010
+ * subquery-table dependency re-materializes the parent view.
1011
+ *
1012
+ * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
1013
+ * no-op: a child leaving this query's set must not delete a body another
1014
+ * query may still show (see `syncSubqueryChildren` deletion-safety note);
1015
+ * a genuine record delete propagates via the normal delete path.
1016
+ */
1017
+ private handleRemoteSubqueryChange;
1018
+ /**
1019
+ * Enqueues a 'down' event (from remote to local) for processing.
1020
+ * @param event The DownEvent to enqueue.
1021
+ */
1022
+ enqueueDownEvent(event: DownEvent): void;
1023
+ /**
1024
+ * Bound a mutation push so it always settles.
1025
+ *
1026
+ * `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
1027
+ * flag only clears in the `finally` of the drain loop. A push whose RPC never
1028
+ * settles (socket dropped mid-flight, response lost) therefore wedges the
1029
+ * up-queue for the rest of the session: no retry, no error, no further
1030
+ * mutation ever sent. A timeout turns that into an ordinary network failure,
1031
+ * which `UpQueue.next` re-queues for the next trigger. The message deliberately
1032
+ * contains "timed out" so `classifySyncError` treats it as `network` and
1033
+ * retries rather than rolling the mutation back.
1034
+ */
1035
+ private withPushTimeout;
1036
+ private processUpEvent;
1037
+ private handleRollback;
1038
+ private processDownEvent;
489
1039
  /**
490
- * The key to use for debouncing.
491
- * - 'recordId': Debounce based on the specific record ID. WARNING: IT WILL ONLY ACCEPT THE LATEST CHANGE AND DOES *NOT* MERGE THE PREVIOUS ONCES. IF YOU ARE UNSURE JUST USE 'recordId_x_fields'.
492
- * - 'recordId_x_fields': Debounce based on record ID and specific fields.
1040
+ * Synchronizes a specific query by hash.
1041
+ * Compares local and remote version arrays and fetches differences.
1042
+ * @param hash The hash of the query to sync.
493
1043
  */
494
- key?: 'recordId' | 'recordId_x_fields';
495
- /** The debounce delay in milliseconds. */
496
- delay?: number;
1044
+ syncQuery(hash: string): Promise<void>;
1045
+ /**
1046
+ * Run a sync for a single query while reflecting its fetch status. Marks the
1047
+ * query `fetching` for the duration when the diff actually pulls records
1048
+ * (added/updated), then resets to `idle` in a `finally` so a failed sync
1049
+ * never leaves a query stuck `fetching`. Part A's notification coalescing
1050
+ * means the single resulting UI update lands after this completes.
1051
+ */
1052
+ private runSyncForQuery;
1053
+ /**
1054
+ * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1055
+ * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1056
+ * server's `_00_list_ref` still lists them until it's processed, and the diff
1057
+ * would otherwise resurrect a just-deleted record.
1058
+ */
1059
+ private getPendingDeleteIds;
1060
+ /**
1061
+ * Enqueues a list of mutations (up events) to be sent to the remote.
1062
+ * @param mutations Array of UpEvents (create/update/delete) to enqueue.
1063
+ */
1064
+ enqueueMutation(mutations: UpEvent[]): Promise<void>;
1065
+ private registerQuery;
1066
+ private createRemoteQuery;
1067
+ /**
1068
+ * Sync the BODIES of a `.related()` query's subquery child rows into the
1069
+ * local cache, separately from the primary window array. The SSP writes
1070
+ * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
1071
+ * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
1072
+ * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
1073
+ * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
1074
+ * them into the local DB AND the in-browser SSP, whose subquery-table
1075
+ * dependency then re-materializes the parent view (no explicit notify).
1076
+ *
1077
+ * Deletion safety: we pass `removed: []` deliberately. A child body can be
1078
+ * shared by other queries; letting `handleRemovedRecords` delete one that
1079
+ * merely left THIS query's child set would clobber data another query still
1080
+ * shows. Genuine record deletes flow through the normal delete path; a
1081
+ * lingering orphan body is invisible (the correlated WHERE stops matching).
1082
+ *
1083
+ * Kept off `runSyncForQuery` on purpose so child fetches never flip the
1084
+ * query to `fetching` or skew its DevTools timings.
1085
+ */
1086
+ private syncSubqueryChildren;
1087
+ heartbeatQuery(queryHash: string): Promise<void>;
1088
+ private cleanupQuery;
497
1089
  }
498
1090
  //#endregion
499
1091
  //#region src/modules/auth/events/index.d.ts
@@ -518,6 +1110,13 @@ declare class AuthService<S extends SchemaStructure> {
518
1110
  token: string | null;
519
1111
  currentUser: any | null;
520
1112
  isAuthenticated: boolean;
1113
+ /**
1114
+ * The record-access method name for the current session (e.g. `"account"`),
1115
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
1116
+ * permission injection so `$access`-gated table predicates resolve locally,
1117
+ * mirroring the server's `$access`. Null when logged out.
1118
+ */
1119
+ access: string | null;
521
1120
  isLoading: boolean;
522
1121
  private events;
523
1122
  get eventSystem(): AuthEventSystem;
@@ -539,11 +1138,292 @@ declare class AuthService<S extends SchemaStructure> {
539
1138
  */
540
1139
  signOut(): Promise<void>;
541
1140
  private setSession;
1141
+ /** Fallback when the token carries no `AC` claim: if the schema defines
1142
+ * exactly one record-access method, assume the session used it. */
1143
+ private defaultAccessName;
542
1144
  signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
543
1145
  signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
544
1146
  }
545
1147
  //#endregion
546
- //#region src/spooky.d.ts
1148
+ //#region src/modules/crdt/crdt-field.d.ts
1149
+ declare const CURSOR_COLORS: string[];
1150
+ declare function cursorColorFromName(name: string): string;
1151
+ declare class CrdtField {
1152
+ private fieldName;
1153
+ private doc;
1154
+ private pushTimer;
1155
+ private local;
1156
+ private remote;
1157
+ private recordId;
1158
+ private sessionId;
1159
+ private unsubscribe;
1160
+ private lastPushTime;
1161
+ private lastCursorPushTime;
1162
+ private loadedFromCrdt;
1163
+ private pushRetryCount;
1164
+ private logger;
1165
+ private cursorsEnabled;
1166
+ /** Remote-push debounce. Local writes happen immediately on every Loro
1167
+ * update; the remote UPSERT is coalesced over this window. Configured
1168
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
1169
+ private remoteDebounceMs;
1170
+ private _onCursorUpdate;
1171
+ private pendingCursorUpdate;
1172
+ /** Callback set by the editor to receive remote cursor updates.
1173
+ * Any cursor data that arrived before this callback was set will be replayed. */
1174
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
1175
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
1176
+ /**
1177
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
1178
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
1179
+ * import graph so it only ships to apps that use CRDT fields.
1180
+ */
1181
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
1182
+ getDoc(): LoroDoc;
1183
+ /** Whether the LoroDoc was loaded from saved CRDT state */
1184
+ hasContent(): boolean;
1185
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
1186
+ /**
1187
+ * Stop syncing this field. Flushes one final remote push by default so the
1188
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
1189
+ * the remote session already belongs to the NEXT user, and pushing this
1190
+ * (previous user's) snapshot under it would clobber the record remotely.
1191
+ */
1192
+ stopSync(options?: {
1193
+ flush?: boolean;
1194
+ }): void;
1195
+ importRemote(state: Uint8Array): void;
1196
+ exportSnapshot(): Uint8Array;
1197
+ /** Push this session's cursor blob into the parent row at
1198
+ * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
1199
+ * field — the editor still calls this method optimistically, but
1200
+ * without `@cursor` on the schema there's nowhere to store the blob.
1201
+ * The UPDATE itself fires the parent table's LIVE feed, so other
1202
+ * browsers receive the cursor change without a separate `_00_rv` bump. */
1203
+ pushCursorState(encoded: Uint8Array): Promise<void>;
1204
+ /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
1205
+ importRemoteCursor(base64State: string): void;
1206
+ private scheduleRemotePush;
1207
+ /** SET path inside a parent row for the current snapshot. `@crdt`-only
1208
+ * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
1209
+ * fields hold a `{ state, cursors }` object so the snapshot lives at
1210
+ * `<field>.state` next to per-session cursor blobs. */
1211
+ private statePath;
1212
+ /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
1213
+ * every local update and every remote import so reloads (online or
1214
+ * offline) see the freshest content immediately. Failures are
1215
+ * swallowed — a stale local write must never block user input. */
1216
+ private persistLocal;
1217
+ private pushToRemote;
1218
+ }
1219
+ //#endregion
1220
+ //#region src/modules/crdt/index.d.ts
1221
+ /**
1222
+ * CrdtManager manages active CrdtField instances and their sync channels.
1223
+ *
1224
+ * Collaborative state lives in two dedicated tables (defined in
1225
+ * `apps/cli/src/meta_tables_remote.surql`):
1226
+ * - `_00_crdt` { record_id, field, state } — one row per (record, field)
1227
+ * - `_00_cursor` { record_id, session_id, field, state } — one row per
1228
+ * (record, session, field)
1229
+ *
1230
+ * Splitting them off the parent row is what makes offline edits mergeable:
1231
+ * each (record, field) gets its own row, so concurrent offline writes don't
1232
+ * collide on the parent's last-write-wins semantics.
1233
+ *
1234
+ * Cross-browser delivery still rides the parent table's existing LIVE feed
1235
+ * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
1236
+ * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
1237
+ * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
1238
+ * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
1239
+ * via subquery. Permission inheritance happens server-side via
1240
+ * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
1241
+ */
1242
+ declare class CrdtManager {
1243
+ private schema;
1244
+ private local;
1245
+ private remote;
1246
+ private debounceMs;
1247
+ private fields;
1248
+ private liveByTable;
1249
+ private pendingLive;
1250
+ private logger;
1251
+ private sessionId;
1252
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
1253
+ /** Set the session id that scopes this client's cursor entries. Must be
1254
+ * called before `open()` for cursors to be pushed under a stable key.
1255
+ * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
1256
+ * for the data-module salt). */
1257
+ setSessionId(sessionId: string): void;
1258
+ /**
1259
+ * Open a CRDT field for collaborative editing.
1260
+ *
1261
+ * @param table - Table name
1262
+ * @param recordId - Full record ID (e.g., "thread:abc")
1263
+ * @param field - Field name (e.g., "title", "content")
1264
+ * @param fallbackText - Current plain text from the record, used to seed the
1265
+ * LoroDoc if no CRDT state exists yet (migration path)
1266
+ */
1267
+ open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
1268
+ close(table: string, recordId: string, field: string): void;
1269
+ /**
1270
+ * Close every open field + table LIVE. Fields flush a final remote push by
1271
+ * default; pass `{ flush: false }` on a bucket switch, where that flush
1272
+ * would push the previous user's snapshot under the next user's session.
1273
+ */
1274
+ closeAll(options?: {
1275
+ flush?: boolean;
1276
+ }): void;
1277
+ /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
1278
+ * every open CrdtField on `table`. */
1279
+ private ensureTableSubscription;
1280
+ /** Apply a parent-row payload from a non-LIVE source (e.g. the
1281
+ * list_ref-driven sync engine, when the cross-user LIVE on the
1282
+ * parent table is filtered out by the SurrealDB cross-session
1283
+ * permission gap). Same semantics as the internal `dispatchRow`. */
1284
+ applyRow(table: string, row: Record<string, unknown>): void;
1285
+ /** Dispatch a parent-row LIVE event to every open CrdtField on that
1286
+ * record. Each open field reads its slice of the row directly — the
1287
+ * CRDT snapshot is a column on the parent now, so there is no
1288
+ * follow-up subquery. */
1289
+ private dispatchRow;
1290
+ /** One-shot remote fetch for a row whose CRDT field hasn't synced
1291
+ * locally yet (fresh device, memory-backed local DB after reload, …).
1292
+ * Used by `open()` when the local read came up empty. Subsequent
1293
+ * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
1294
+ private fetchAndDispatchRow;
1295
+ /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
1296
+ * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
1297
+ private fieldHasCursor;
1298
+ /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
1299
+ * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
1300
+ * `{ state, cursors }` where `state` carries the snapshot bytes. */
1301
+ private extractSnapshot;
1302
+ private killTableSubscription;
1303
+ private makeKey;
1304
+ /**
1305
+ * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
1306
+ * typos, removed annotations, and stale schema codegen at the call site instead
1307
+ * of silently producing a non-CRDT writer.
1308
+ */
1309
+ private assertCrdtField;
1310
+ }
1311
+ //#endregion
1312
+ //#region src/modules/feature-flag/index.d.ts
1313
+ interface FeatureFlagSnapshot {
1314
+ variant: string | undefined;
1315
+ payload: unknown | undefined;
1316
+ }
1317
+ interface FeatureFlagOptions {
1318
+ fallback?: string;
1319
+ ttl?: QueryTimeToLive;
1320
+ }
1321
+ declare class FeatureFlagHandle {
1322
+ readonly key: string;
1323
+ readonly fallback: string | undefined;
1324
+ private latest;
1325
+ private listeners;
1326
+ private unsubscribeFn;
1327
+ private onCloseFn;
1328
+ private closed;
1329
+ constructor(key: string, fallback: string | undefined);
1330
+ attach(unsubscribe: () => void): void;
1331
+ detach(): void;
1332
+ set(snapshot: FeatureFlagSnapshot): void;
1333
+ variant(): string | undefined;
1334
+ payload<T = unknown>(): T | undefined;
1335
+ enabled(): boolean;
1336
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
1337
+ onClose(cb: () => void): void;
1338
+ close(): void;
1339
+ }
1340
+ interface FeatureFlagModuleDeps<S extends SchemaStructure> {
1341
+ dataModule: DataModule<S>;
1342
+ sync: Sp00kySync<S>;
1343
+ auth: AuthService<S>;
1344
+ logger: Logger$1;
1345
+ }
1346
+ declare class FeatureFlagModule<S extends SchemaStructure> {
1347
+ private deps;
1348
+ private logger;
1349
+ private handles;
1350
+ private authUnsubscribe;
1351
+ private lastUserId;
1352
+ private querySubscription;
1353
+ private starting;
1354
+ private ttl;
1355
+ private snapshots;
1356
+ private loaded;
1357
+ constructor(deps: FeatureFlagModuleDeps<S>);
1358
+ init(): void;
1359
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
1360
+ closeAll(): Promise<void>;
1361
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
1362
+ private refresh;
1363
+ private teardownQuery;
1364
+ /** Start the single shared live query (idempotent; no-op with no handles). */
1365
+ private ensureStarted;
1366
+ /** Live query result → per-key snapshots → push to every active handle. */
1367
+ private applyRecords;
1368
+ }
1369
+ //#endregion
1370
+ //#region src/modules/app-release/index.d.ts
1371
+ interface AppReleaseSnapshot {
1372
+ /** Latest announced version for the app, or undefined when no row exists. */
1373
+ version: string | undefined;
1374
+ /** Clients should clear SW/caches when reloading onto this version. */
1375
+ cacheBust: boolean;
1376
+ /** Clients should reload/update immediately instead of asking. */
1377
+ mandatory: boolean;
1378
+ releasedAt: string | undefined;
1379
+ }
1380
+ interface AppReleaseOptions {
1381
+ ttl?: QueryTimeToLive;
1382
+ }
1383
+ declare class AppReleaseHandle {
1384
+ readonly app: string;
1385
+ private latest;
1386
+ private listeners;
1387
+ private onCloseFn;
1388
+ private closed;
1389
+ constructor(app: string);
1390
+ set(snapshot: AppReleaseSnapshot): void;
1391
+ snapshot(): AppReleaseSnapshot;
1392
+ version(): string | undefined;
1393
+ /** True when the announced version is semver-newer than `currentVersion`. */
1394
+ updateAvailable(currentVersion: string): boolean;
1395
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
1396
+ onClose(cb: () => void): void;
1397
+ close(): void;
1398
+ }
1399
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
1400
+ dataModule: DataModule<S>;
1401
+ sync: Sp00kySync<S>;
1402
+ auth: AuthService<S>;
1403
+ logger: Logger$1;
1404
+ }
1405
+ declare class AppReleaseModule<S extends SchemaStructure> {
1406
+ private deps;
1407
+ private logger;
1408
+ private handles;
1409
+ private authUnsubscribe;
1410
+ private lastUserId;
1411
+ private querySubscription;
1412
+ private starting;
1413
+ private ttl;
1414
+ private snapshots;
1415
+ private loaded;
1416
+ constructor(deps: AppReleaseModuleDeps<S>);
1417
+ init(): void;
1418
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
1419
+ closeAll(): Promise<void>;
1420
+ private refresh;
1421
+ private teardownQuery;
1422
+ private ensureStarted;
1423
+ private applyRecords;
1424
+ }
1425
+ //#endregion
1426
+ //#region src/sp00ky.d.ts
547
1427
  declare class BucketHandle {
548
1428
  private bucketName;
549
1429
  private remote;
@@ -557,7 +1437,7 @@ declare class BucketHandle {
557
1437
  rename(sourcePath: string, targetPath: string): Promise<void>;
558
1438
  list(prefix?: string): Promise<string[]>;
559
1439
  }
560
- declare class SpookyClient<S extends SchemaStructure> {
1440
+ declare class Sp00kyClient<S extends SchemaStructure> {
561
1441
  private config;
562
1442
  private local;
563
1443
  private remote;
@@ -567,28 +1447,176 @@ declare class SpookyClient<S extends SchemaStructure> {
567
1447
  private dataModule;
568
1448
  private sync;
569
1449
  private devTools;
1450
+ private crdtManager;
1451
+ private featureFlags;
1452
+ private appReleases;
1453
+ private preloadedHashes;
1454
+ private pendingQueryInits;
570
1455
  private logger;
571
1456
  auth: AuthService<S>;
572
1457
  streamProcessor: StreamProcessorService;
573
- get remoteClient(): Surreal;
574
- get localClient(): Surreal;
1458
+ private tabsCoordinator;
1459
+ private sharedActive;
1460
+ /** Current shared-tabs role, or null when the feature is off/fell back. */
1461
+ get tabRole(): TabRole | null;
1462
+ get remoteClient(): surrealdb0.Surreal;
1463
+ get localClient(): unknown;
575
1464
  get pendingMutationCount(): number;
1465
+ /** Number of times the initial list_ref LIVE subscription retried on
1466
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
1467
+ * pre-emptive user-table creation got there first; >0 when LIVE
1468
+ * registration hit a "table not found" race. Exposed so the e2e
1469
+ * suite can guard the pre-emptive path against regression. */
1470
+ get liveRetryCount(): number;
576
1471
  subscribeToPendingMutations(cb: (count: number) => void): () => void;
577
- constructor(config: SpookyConfig<S>);
1472
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
1473
+ get syncHealth(): SyncHealth;
1474
+ /**
1475
+ * Observe sync health. Fires immediately with the current status and again
1476
+ * on every healthy↔degraded transition. Returns an unsubscribe.
1477
+ */
1478
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1479
+ /** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
1480
+ * engines that don't report it. */
1481
+ get storageHealth(): StorageHealth;
1482
+ /**
1483
+ * Observe local-store durability. Fires immediately with the current snapshot
1484
+ * and again on every change (at most once per bucket open in practice).
1485
+ * Returns an unsubscribe.
1486
+ */
1487
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
1488
+ constructor(config: Sp00kyConfig<S>);
1489
+ /** The shared-tabs role machinery, wired to this client's modules. */
1490
+ private buildTabsCoordinator;
578
1491
  /**
579
1492
  * Setup direct callbacks instead of event subscriptions
580
1493
  */
581
1494
  private setupCallbacks;
582
1495
  init(): Promise<void>;
1496
+ private bucketSwitchChain;
1497
+ private pendingBucketTarget;
1498
+ /**
1499
+ * Ensure the local store is this user's bucket, switching if needed. Called
1500
+ * from the auth listener on every auth flip; concurrent calls are chained
1501
+ * and superseded intermediates are skipped (latest target wins).
1502
+ */
1503
+ private ensureLocalBucket;
1504
+ /**
1505
+ * The bucket-switch choreography: drain → swap → rebind.
1506
+ *
1507
+ * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
1508
+ * outbox delete lands in the OLD bucket, debounce timers cancelled),
1509
+ * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
1510
+ * (the remote session already belongs to the next user).
1511
+ *
1512
+ * Swap: gate closes so any local query issued mid-switch (sibling auth
1513
+ * subscribers, FeatureFlagModule) waits and then runs against the NEW
1514
+ * bucket; store swaps open-new-before-close-old; schema provisions
1515
+ * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
1516
+ * sessionId-salted hashes with stale arrays — record bodies stay warm);
1517
+ * SSP resets to a fresh circuit with re-seeded permissions.
1518
+ *
1519
+ * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
1520
+ * into the OLD bucket's `_00_kv` before this listener ran), active queries
1521
+ * re-homed keeping their hashes, sync resumed on the new bucket's own
1522
+ * outbox, and every query re-registered remotely to refill from the server.
1523
+ */
1524
+ private doSwitchBucket;
583
1525
  close(): Promise<void>;
1526
+ /**
1527
+ * Subscribe to a feature flag for the current user. Returns a
1528
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
1529
+ * accessors reflect the latest assignment from `_00_user_feature`,
1530
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
1531
+ *
1532
+ * Permissions are enforced by SurrealDB: a client can only ever see
1533
+ * its own row, and cannot create or modify assignments.
1534
+ */
1535
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
1536
+ /**
1537
+ * Observe the announced release of an app (`_00_app_release:<app>`, written
1538
+ * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
1539
+ * announced version plus the cache-bust/mandatory flags, and
1540
+ * `updateAvailable(currentVersion)` compares it semver-wise against the
1541
+ * running build. World-readable; writes are root-only.
1542
+ */
1543
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
584
1544
  authenticate(token: string): Promise<surrealdb0.Tokens>;
1545
+ /**
1546
+ * Open a CRDT field for collaborative editing.
1547
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
1548
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
1549
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
1550
+ */
1551
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
1552
+ /**
1553
+ * Close a CRDT field when editing is done.
1554
+ */
1555
+ closeCrdtField(table: string, recordId: string, field: string): void;
585
1556
  deauthenticate(): Promise<void>;
586
- query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, SpookyQueryResultPromise>;
1557
+ query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
587
1558
  private initQuery;
1559
+ /**
1560
+ * Background tail of {@link initQuery}: instant-hydrate (opt-in via
1561
+ * `config.instantHydrate`, and only when the query is cold) followed by
1562
+ * enqueuing the `register` down-event. Never rejects — both halves catch and
1563
+ * log, so `void`-ing the returned promise can't produce an unhandled
1564
+ * rejection. By default (hydrate off) the register lifecycle is the single
1565
+ * freshness path; the one-shot fetch is an optimization apps enable
1566
+ * explicitly, and it runs regardless of preload state — cache-first delivery
1567
+ * never depends on WHY rows are cached.
1568
+ */
1569
+ private finishQueryInit;
1570
+ /**
1571
+ * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
1572
+ * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
1573
+ *
1574
+ * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
1575
+ * - COLD (never preloaded in this bucket): fetch the query one-shot from the
1576
+ * remote, persist the rows (+ embedded `.related()` children), stamp the
1577
+ * marker — and AWAIT it. This is the "smart waiting" first load: callers can
1578
+ * `await db.preload(...)` to hold the UI until the data is ready.
1579
+ * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
1580
+ * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
1581
+ * Default `onUse` does nothing; the data freshens when the real `useQuery`
1582
+ * mounts and registers its live view.
1583
+ *
1584
+ * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
1585
+ * written, so it's retried next load). Deduped per session by query hash.
1586
+ */
1587
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
1588
+ /**
1589
+ * One-shot remote fetch + local persist for a preload query. Returns the row
1590
+ * count on success, or -1 on failure (best-effort: logged, never thrown) so
1591
+ * the caller skips stamping the freshness marker and retries next load.
1592
+ */
1593
+ private fetchAndPersist;
588
1594
  queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
589
1595
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
590
1596
  immediate?: boolean;
591
1597
  }): Promise<() => void>;
1598
+ /**
1599
+ * Opt-in eager teardown for a query whose last subscriber has gone away
1600
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
1601
+ * while any subscriber remains. Tears down the remote `_00_query` view +
1602
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
1603
+ * (no call here) keeps the view resident for cheap re-subscription.
1604
+ */
1605
+ deregisterQuery(queryHash: string): void;
1606
+ /**
1607
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
1608
+ * `{ immediate: true }` the callback fires synchronously with the current
1609
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
1610
+ */
1611
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
1612
+ immediate?: boolean;
1613
+ }): () => void;
1614
+ /**
1615
+ * Report the frontend processing time (ms) a client framework spent applying
1616
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
1617
+ * surface the "frontend" phase of the per-query timing breakdown.
1618
+ */
1619
+ reportFrontendTiming(queryHash: string, ms: number): void;
592
1620
  run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
593
1621
  bucket<B extends BucketNames<S>>(name: B): BucketHandle;
594
1622
  create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
@@ -597,15 +1625,29 @@ declare class SpookyClient<S extends SchemaStructure> {
597
1625
  }>;
598
1626
  delete(table: string, id: string): Promise<void>;
599
1627
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
600
- private persistClientId;
601
- private loadOrGenerateClientId;
1628
+ /**
1629
+ * Fetch SurrealDB's `session::id()` as a string. Used as a salt for
1630
+ * query-id hashing so two sessions for the same user get distinct
1631
+ * `_00_query` rows. Returns empty string if the query fails (we still
1632
+ * boot, just without session scoping for IDs).
1633
+ */
1634
+ private fetchSessionId;
602
1635
  }
603
1636
  //#endregion
1637
+ //#region src/utils/semver.d.ts
1638
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
1639
+ declare function semverGt(a: unknown, b: unknown): boolean;
1640
+ //#endregion
604
1641
  //#region src/utils/index.d.ts
605
1642
  declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
1643
+ /**
1644
+ * Convert plain text to simple HTML paragraphs.
1645
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
1646
+ */
1647
+ declare function textToHtml(text: string): string;
606
1648
  /**
607
1649
  * Helper for retrying DB operations with exponential backoff
608
1650
  */
609
1651
 
610
1652
  //#endregion
611
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, type Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions, SpookyClient, SpookyConfig, SpookyQueryResult, SpookyQueryResultPromise, StoreType, UpdateOptions, createAuthEventSystem, fileToUint8Array };
1653
+ export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagSnapshot, Level, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, createAuthEventSystem, cursorColorFromName, fileToUint8Array, semverGt, textToHtml };