@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
@@ -0,0 +1,874 @@
1
+ import { RecordId } from "surrealdb";
2
+ import { QueryPlan, QueryPlan as QueryPlan$1, RecordId as RecordId$1, SchemaStructure, WhereNode } from "@spooky-sync/query-builder";
3
+ import { Level, Level as Level$1, Logger, LoggerOptions } from "pino";
4
+
5
+ //#region src/events/index.d.ts
6
+ /**
7
+ * Utility type to define the payload structure of an event.
8
+ * If the payload type P is never, it defines payload as undefined.
9
+ */
10
+ type EventPayloadDefinition<P> = [P] extends [never] ? {
11
+ payload: undefined;
12
+ } : {
13
+ payload: P;
14
+ };
15
+ /**
16
+ * Defines the structure of an event with a specific type and payload.
17
+ * @template T The string literal type of the event.
18
+ * @template P The type of the event payload.
19
+ */
20
+ type EventDefinition<T extends string, P> = {
21
+ type: T;
22
+ } & EventPayloadDefinition<P>;
23
+ /**
24
+ * A map of event types to their definitions.
25
+ * Keys are event names, values are EventDefinitions.
26
+ */
27
+ type EventTypeMap = Record<string, EventDefinition<any, unknown> | EventDefinition<any, never>>;
28
+ /**
29
+ * Options for pushing/emitting events.
30
+ */
31
+ interface PushEventOptions {
32
+ /** Configuration for debouncing the event. */
33
+ debounced?: {
34
+ key: string;
35
+ delay: number;
36
+ };
37
+ }
38
+ /**
39
+ * Extracts the full Event object type from the map for a given key.
40
+ */
41
+ type Event<E extends EventTypeMap, T extends EventType<E>> = E[T];
42
+ /**
43
+ * Extracts the payload type from the map for a given key.
44
+ */
45
+ type EventPayload<E extends EventTypeMap, T extends EventType<E>> = E[T]['payload'];
46
+ /**
47
+ * Array of available event type keys.
48
+ */
49
+ type EventTypes<E extends EventTypeMap> = (keyof E)[];
50
+ /**
51
+ * Represents a valid key (event name) from the EventTypeMap.
52
+ */
53
+ type EventType<E extends EventTypeMap> = keyof E;
54
+ /**
55
+ * Function signature for an event handler.
56
+ */
57
+ type EventHandler<E extends EventTypeMap, T extends EventType<E>> = (event: Event<E, T>) => void;
58
+ /**
59
+ * Options when subscribing to an event.
60
+ */
61
+ type EventSubscriptionOptions$1 = {
62
+ /** If true, the handler will be called immediately with the last emitted event of this type (if any). */
63
+ immediately?: boolean;
64
+ /** If true, the subscription will be automatically removed after the first event is handled. */
65
+ once?: boolean;
66
+ };
67
+ /**
68
+ * A type-safe event system that handles subscription, emission (including debouncing), and buffering of events.
69
+ * @template E The EventTypeMap defining all supported events.
70
+ */
71
+ declare class EventSystem<E extends EventTypeMap> {
72
+ private _eventTypes;
73
+ private subscriberId;
74
+ private isProcessing;
75
+ private buffer;
76
+ private subscribers;
77
+ private subscribersTypeMap;
78
+ private lastEvents;
79
+ private debouncedEvents;
80
+ constructor(_eventTypes: EventTypes<E>);
81
+ get eventTypes(): EventTypes<E>;
82
+ /**
83
+ * Subscribes a handler to a specific event type.
84
+ * @param type The event type to subscribe to.
85
+ * @param handler The function to call when the event occurs.
86
+ * @param options Subscription options (once, immediately).
87
+ * @returns A subscription ID that can be used to unsubscribe.
88
+ */
89
+ subscribe<T extends EventType<E>>(type: T, handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number;
90
+ /**
91
+ * Subscribes a handler to multiple event types.
92
+ * @param types An array of event types to subscribe to.
93
+ * @param handler The function to call when any of the events occur.
94
+ * @param options Subscription options.
95
+ * @returns An array of subscription IDs.
96
+ */
97
+ subscribeMany<T extends EventType<E>>(types: T[], handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number[];
98
+ /**
99
+ * Unsubscribes a specific subscription by ID.
100
+ * @param id The subscription ID returned by subscribe().
101
+ * @returns True if the subscription was found and removed, false otherwise.
102
+ */
103
+ unsubscribe(id: number): boolean;
104
+ /**
105
+ * Emits an event with the given type and payload.
106
+ * @param type The type of event to emit.
107
+ * @param payload The data associated with the event.
108
+ */
109
+ emit<T extends EventType<E>, P extends EventPayload<E, T>>(type: T, payload: P): void;
110
+ /**
111
+ * Adds a fully constructed event object to the system.
112
+ * Similar to emit, but takes the full event object directly.
113
+ * Supports debouncing if options are provided.
114
+ * @param event The event object.
115
+ * @param options Options for the event push (e.g., debouncing).
116
+ */
117
+ addEvent<T extends EventType<E>>(event: Event<E, T>, options?: PushEventOptions): void;
118
+ private handleDebouncedEvent;
119
+ private scheduleProcessing;
120
+ private processEvents;
121
+ private dequeue;
122
+ private setLastEvent;
123
+ private broadcastEvent;
124
+ }
125
+ //#endregion
126
+ //#region src/modules/sync/events/index.d.ts
127
+ declare const SyncEventTypes: {
128
+ readonly QueryUpdated: "SYNC_QUERY_UPDATED";
129
+ readonly RemoteDataIngested: "SYNC_REMOTE_DATA_INGESTED";
130
+ readonly MutationRolledBack: "SYNC_MUTATION_ROLLED_BACK";
131
+ readonly SyncHealthChanged: "SYNC_HEALTH_CHANGED";
132
+ };
133
+ type SyncEventTypeMap = {
134
+ [SyncEventTypes.QueryUpdated]: EventDefinition<typeof SyncEventTypes.QueryUpdated, {
135
+ queryId: any;
136
+ localHash?: string;
137
+ localArray?: RecordVersionArray;
138
+ remoteHash?: string;
139
+ remoteArray?: RecordVersionArray;
140
+ records: Record<string, any>[];
141
+ }>;
142
+ [SyncEventTypes.RemoteDataIngested]: EventDefinition<typeof SyncEventTypes.RemoteDataIngested, {
143
+ records: Record<string, any>[];
144
+ }>;
145
+ [SyncEventTypes.MutationRolledBack]: EventDefinition<typeof SyncEventTypes.MutationRolledBack, {
146
+ eventType: string;
147
+ recordId: string;
148
+ error: string;
149
+ }>;
150
+ [SyncEventTypes.SyncHealthChanged]: EventDefinition<typeof SyncEventTypes.SyncHealthChanged, SyncHealth>;
151
+ };
152
+ type SyncEventSystem = EventSystem<SyncEventTypeMap>;
153
+ //#endregion
154
+ //#region src/services/logger/index.d.ts
155
+ type Logger$1 = Logger;
156
+ //#endregion
157
+ //#region src/services/database/events/index.d.ts
158
+ declare const DatabaseEventTypes: {
159
+ readonly LocalQuery: "DATABASE_LOCAL_QUERY";
160
+ readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
161
+ };
162
+ interface DatabaseQueryEventPayload {
163
+ query: string;
164
+ vars?: Record<string, unknown>;
165
+ duration: number;
166
+ success: boolean;
167
+ error?: string;
168
+ timestamp: number;
169
+ }
170
+ type DatabaseEventTypeMap = {
171
+ [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
172
+ [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
173
+ };
174
+ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
175
+ //#endregion
176
+ //#region src/utils/surql.d.ts
177
+ interface SealedQuery<T = void> {
178
+ readonly sql: string;
179
+ readonly extract: (results: unknown[]) => T;
180
+ }
181
+ //#endregion
182
+ //#region src/modules/devtools/storage-info.d.ts
183
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
184
+ interface EngineStorageDiagnostics {
185
+ engine: 'sqlite';
186
+ bucketId: string;
187
+ useOpfs: boolean;
188
+ workerSelectConfigured: boolean;
189
+ /** `false` while configured `true` means the runtime downgraded to the
190
+ * legacy multi-hop select (stale cached worker bundle). */
191
+ workerSelectEffective: boolean;
192
+ /** page_count * page_size. */
193
+ dbSizeBytes?: number;
194
+ /** freelist_count * page_size — reclaimable via VACUUM. */
195
+ freelistBytes?: number;
196
+ tableCounts?: {
197
+ table: string;
198
+ rows: number;
199
+ }[];
200
+ error?: string;
201
+ }
202
+ /**
203
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
204
+ * configured (apps that never asked for it get `null`, so the panel shows
205
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
206
+ * app asked to share one store and this tab is not, so it owns or contends for
207
+ * the OPFS pool alone.
208
+ */
209
+ //#endregion
210
+ //#region src/services/database/cache-engine.d.ts
211
+ /**
212
+ * A materialized row. Keys are field names; values are already decoded to the
213
+ * client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
214
+ * every backend hands `DataModule` the same shape SurrealDB does today.
215
+ */
216
+ type Row = Record<string, unknown>;
217
+ /** A record identifier — a `RecordId` or its stable string form (`table:id`). */
218
+ type Id = unknown;
219
+ /** How an order clause is expressed everywhere in the engine layer. */
220
+ type OrderBy = [field: string, direction: 'asc' | 'desc'][];
221
+ /**
222
+ * Batched relation fetch: "give me every row of `table` whose `matchField` is
223
+ * one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
224
+ * primitive relation decomposition (§3) leans on — implemented as
225
+ * `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
226
+ * `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
227
+ * here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
228
+ */
229
+ interface RelationFetch {
230
+ table: string;
231
+ matchField: string;
232
+ keys: Id[];
233
+ where?: WhereNode[];
234
+ orderBy?: OrderBy;
235
+ select?: string[];
236
+ }
237
+ /**
238
+ * The read side of an engine, minus relation resolution — the surface a
239
+ * {@link RelationResolver} needs. Kept separate so the resolver can be unit
240
+ * tested against an in-memory fake without a full engine.
241
+ */
242
+ interface RowFetcher {
243
+ /** Batched fan-out fetch. See {@link RelationFetch}. */
244
+ fetchRelation(req: RelationFetch): Promise<Row[]>;
245
+ }
246
+ /** A transaction handle — the same verbs as the engine, but atomic. */
247
+ interface EngineTx {
248
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
249
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
250
+ delete(table: string, id: Id): Promise<void>;
251
+ }
252
+ /**
253
+ * A pluggable local cache backend. SurrealDB (the default) and SQLite both
254
+ * implement this; the rest of the client talks verbs, never SurrealQL.
255
+ *
256
+ * Reactivity is NOT part of this contract: the local cache is passive. The SSP
257
+ * (remote) drives change; `DataModule` writes rows here and re-reads them. The
258
+ * `epoch` field preserves the existing bucket-switch fencing (see
259
+ * `LocalDatabaseService.epoch`): an async chain captures it at start and its
260
+ * write is dropped if the epoch moved (a bucket switch) in between.
261
+ */
262
+ interface LocalCacheEngine extends RowFetcher {
263
+ /** Monotonic store generation; bumped on every bucket switch. */
264
+ readonly epoch: number;
265
+ connect(bucketId: string): Promise<void>;
266
+ switchBucket(bucketId: string): Promise<void>;
267
+ close(): Promise<void>;
268
+ /** Run `fn` inside a single atomic transaction. */
269
+ transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
270
+ /**
271
+ * Materialize a query, including its `.related()` tree (via §3
272
+ * decomposition). Params bind `where` `paramRef`s and any windowing id-set.
273
+ */
274
+ select(plan: QueryPlan$1, params?: Record<string, unknown>): Promise<Row[]>;
275
+ /** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
276
+ selectByIds(table: string, ids: Id[], opts?: {
277
+ select?: string[];
278
+ orderBy?: OrderBy;
279
+ }): Promise<Row[]>;
280
+ /** Single-record read by primary id, or `null`. */
281
+ getById(table: string, id: Id): Promise<Row | null>;
282
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
283
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
284
+ delete(table: string, id: Id): Promise<void>;
285
+ }
286
+ /**
287
+ * The full surface the client's `this.local` field depends on: the
288
+ * engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
289
+ * SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
290
+ * `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
291
+ * `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
292
+ * either can back `this.local`.
293
+ *
294
+ * `getClient()` returns the underlying SurrealDB `Surreal` handle where one
295
+ * exists (SurrealDB backend); backends without one (SQLite) throw — it is only
296
+ * used by advanced/DevTools paths, never on the hot path.
297
+ */
298
+ interface LocalStore extends LocalCacheEngine {
299
+ /**
300
+ * Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
301
+ * `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
302
+ * schemaless engines (SQLite creates tables lazily) → false, so the client
303
+ * skips the `LocalMigrator` entirely for them.
304
+ */
305
+ readonly usesSurqlSchema: boolean;
306
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>, opts?: {
307
+ epoch?: number;
308
+ }): Promise<T>;
309
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: {
310
+ epoch?: number;
311
+ }): Promise<T>;
312
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
313
+ switchStore(bucketId: string): Promise<void>;
314
+ beginSwitch(): () => void;
315
+ getEvents(): DatabaseEventSystem;
316
+ getClient(): unknown;
317
+ getConfig(): Sp00kyConfig<any>['database'];
318
+ readonly currentBucketId: string;
319
+ /** Which built-in backend this is. OPTIONAL: absent (custom engines) is
320
+ * reported as `'custom'` by DevTools. More robust than `instanceof` for
321
+ * engines constructed outside this package. */
322
+ readonly engineKind?: 'surrealdb' | 'sqlite';
323
+ /** Engine-specific storage numbers for DevTools (DB file size, per-table
324
+ * row counts). OPTIONAL: only engines with something to report implement it. */
325
+ getStorageDiagnostics?(opts?: {
326
+ tableCounts?: boolean;
327
+ }): Promise<EngineStorageDiagnostics>;
328
+ /**
329
+ * Durability of this engine's local store. OPTIONAL: engines that don't
330
+ * report it (SurrealDB, custom engines) are treated as `'unknown'` by the
331
+ * client facade, so adding this needs no change on their side.
332
+ */
333
+ readonly storageHealth?: StorageHealth;
334
+ /** Fires immediately with the current snapshot, then on every change.
335
+ * Returns an unsubscribe function. */
336
+ subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
337
+ }
338
+ /** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
339
+ type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
340
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
341
+ * a guard against a cyclic schema producing unbounded fan-out. */
342
+ //#endregion
343
+ //#region src/modules/sync/queue/queue-up.d.ts
344
+ type CreateEvent = {
345
+ type: 'create';
346
+ mutation_id: RecordId;
347
+ record_id: RecordId;
348
+ data: Record<string, unknown>;
349
+ record?: Record<string, unknown>;
350
+ tableName?: string;
351
+ options?: PushEventOptions;
352
+ };
353
+ type UpdateEvent = {
354
+ type: 'update';
355
+ mutation_id: RecordId;
356
+ record_id: RecordId;
357
+ data: Record<string, unknown>;
358
+ record?: Record<string, unknown>;
359
+ beforeRecord?: Record<string, unknown>;
360
+ options?: PushEventOptions;
361
+ };
362
+ type DeleteEvent = {
363
+ type: 'delete';
364
+ mutation_id: RecordId;
365
+ record_id: RecordId;
366
+ options?: PushEventOptions;
367
+ };
368
+ type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
369
+ //#endregion
370
+ //#region src/types.d.ts
371
+ /**
372
+ * A pino browser transmit object for forwarding logs to an external sink (e.g. OpenTelemetry).
373
+ */
374
+ type PinoTransmit = NonNullable<NonNullable<LoggerOptions['browser']>['transmit']>;
375
+ /**
376
+ * The type of storage backend to use for the local database.
377
+ * - 'memory': In-memory storage (transient).
378
+ * - 'indexeddb': IndexedDB storage (persistent).
379
+ */
380
+ type StoreType = 'memory' | 'indexeddb';
381
+ /**
382
+ * Interface for a custom persistence client.
383
+ * Allows providing a custom storage mechanism for the local database.
384
+ */
385
+ interface PersistenceClient {
386
+ /**
387
+ * Sets a value in the storage.
388
+ * @param key The key to set.
389
+ * @param value The value to store.
390
+ */
391
+ set<T>(key: string, value: T): Promise<void>;
392
+ /**
393
+ * Gets a value from the storage.
394
+ * @param key The key to retrieve.
395
+ * @returns The stored value or null if not found.
396
+ */
397
+ get<T>(key: string): Promise<T | null>;
398
+ /**
399
+ * Removes a value from the storage.
400
+ * @param key The key to remove.
401
+ */
402
+ remove(key: string): Promise<void>;
403
+ }
404
+ /**
405
+ * Supported Time-To-Live (TTL) values for cached queries.
406
+ * Format: number + unit (m=minutes, h=hours, d=days).
407
+ */
408
+ type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
409
+ /**
410
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
411
+ * The FIRST load (cold) always fetches + blocks regardless.
412
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
413
+ * real `useQuery` mounts and registers its live view. No network on load.
414
+ * - `background`: return instantly, but kick a one-time silent refetch.
415
+ * - `stale`: like `background`, but only if the cached copy is older than
416
+ * `staleTime`.
417
+ */
418
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
419
+ interface PreloadOptions {
420
+ /** How to refresh when the query is already cached locally. Default `onUse`. */
421
+ refresh?: PreloadRefresh;
422
+ /** For `refresh: 'stale'` — max age before a warm copy is refetched. Default `1h`. */
423
+ staleTime?: QueryTimeToLive;
424
+ }
425
+ /**
426
+ * Result object returned when a query is registered or executed.
427
+ */
428
+ interface Sp00kyQueryResult {
429
+ /** The unique hash identifier for the query. */
430
+ hash: string;
431
+ }
432
+ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
433
+ interface EventSubscriptionOptions {
434
+ priority?: number;
435
+ }
436
+ /**
437
+ * Configuration options for the Sp00ky client.
438
+ * @template S The schema structure type.
439
+ */
440
+ interface Sp00kyConfig<S extends SchemaStructure> {
441
+ /** Database connection configuration. */
442
+ database: {
443
+ /** The SurrealDB endpoint URL. */
444
+ endpoint?: string;
445
+ /** The namespace to use. */
446
+ namespace: string;
447
+ /** The database name. */
448
+ database: string;
449
+ /** The local store type implementation. */
450
+ store?: StoreType;
451
+ /** Authentication token. */
452
+ token?: string;
453
+ /**
454
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
455
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
456
+ * table/relation level. Defaults to true; set false to force the legacy
457
+ * multi-hop path (escape hatch while the worker-side path beds in).
458
+ */
459
+ workerSelect?: boolean;
460
+ };
461
+ /** The schema definition. */
462
+ schema: S;
463
+ /** The compiled SURQL schema string. */
464
+ schemaSurql: string;
465
+ /** Logging level. */
466
+ logLevel: Level$1;
467
+ /**
468
+ * Persistence client to use.
469
+ * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
470
+ */
471
+ persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
472
+ /**
473
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
474
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
475
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
476
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
477
+ * this engine. See `services/database/cache-engine.ts`.
478
+ */
479
+ localEngine?: LocalEngineChoice;
480
+ /**
481
+ * Share ONE durable local store across all tabs of this origin (default
482
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
483
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
484
+ * worker and the sync loop, and follower tabs read/write the same store over
485
+ * MessagePorts, so every tab is durable instead of only the first one.
486
+ *
487
+ * Falls back to solo mode (exactly the flag-off behavior, including the
488
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
489
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
490
+ * not sqlite, or the broker rejects the tab (mixed app versions).
491
+ *
492
+ * Failover: when the leader tab closes or freezes, a follower is promoted
493
+ * within seconds; queries briefly refetch and mutations are never lost once
494
+ * their local write resolved (the shared outbox survives in the store).
495
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
496
+ */
497
+ sharedTabs?: boolean;
498
+ /**
499
+ * Persist the in-browser SSP circuit (store + view caches) as a snapshot so a
500
+ * reload can restore it instead of re-materializing. Default `false`, and
501
+ * that default is deliberate.
502
+ *
503
+ * The circuit is DERIVED state: the durable local store (OPFS SQLite) is the
504
+ * source of truth, and every first paint already reads row bodies from it
505
+ * (`DataManager.createNewQuery` / `materializeRecords`) using the circuit only
506
+ * for row identity and ordering. A snapshot buys nothing on reload while
507
+ * costing a full deep clone of every row of every ingested table plus a JSON
508
+ * encode of the result, `Circuit::save` in the Rust core, mirroring the
509
+ * server's rule in `ssp-node`: *never per-ingest*.
510
+ *
511
+ * When enabled, snapshots are written on a checkpoint interval
512
+ * ({@link circuitCheckpointMs}) and on `pagehide`, never per ingest or per
513
+ * query registration. Enable only for a workload that has measured a win.
514
+ */
515
+ persistCircuit?: boolean;
516
+ /**
517
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
518
+ * 30000. Ignored when `persistCircuit` is off.
519
+ */
520
+ circuitCheckpointMs?: number;
521
+ /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
522
+ otelTransmit?: PinoTransmit;
523
+ /**
524
+ * Debounce time in milliseconds for stream updates (the client-side SSP
525
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
526
+ * per-record updates per query before notifying readers).
527
+ * Defaults to 50ms.
528
+ */
529
+ streamDebounceTime?: number;
530
+ /**
531
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
532
+ * changes to the remote database. Local writes happen immediately on
533
+ * every keystroke (so reload/offline works), but the remote UPSERT is
534
+ * coalesced over this window. Lower = snappier remote propagation +
535
+ * more network traffic; higher = less traffic + more lag for other
536
+ * collaborators. Defaults to 500ms.
537
+ */
538
+ crdtDebounceMs?: number;
539
+ /**
540
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
541
+ * preloaded at client startup (fetched as a separate chunk on page load) so
542
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
543
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
544
+ * out of apps that don't use collaboration. Defaults to `false`.
545
+ */
546
+ crdt?: boolean;
547
+ /**
548
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
549
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
550
+ * convergence + more query load; higher = the inverse. Non-positive
551
+ * values fall back to the default (500ms).
552
+ */
553
+ refSyncIntervalMs?: number;
554
+ /**
555
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
556
+ * registered with no server result yet, its surql also runs directly on the
557
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
558
+ * before the full register lifecycle completes. Hydrated rows carry their
559
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
560
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
561
+ * paints from the local cache immediately — however the rows got there
562
+ * (preload, prior sync). Default `false`: the register lifecycle
563
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
564
+ * freshness path and no duplicate one-shot fetches are made.
565
+ */
566
+ instantHydrate?: boolean;
567
+ /**
568
+ * Enable realtime sync while signed out. When `true`, the client starts its
569
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
570
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
571
+ * page gets live `useQuery` updates over world-readable tables. Requires the
572
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
573
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
574
+ * one-shot but never sync live.
575
+ */
576
+ enableAnonymousLiveQueries?: boolean;
577
+ /**
578
+ * Surface sustained sync failures as a "degraded" health status that the app
579
+ * can observe via `subscribeToSyncHealth` (or the client-solid
580
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
581
+ *
582
+ * Individual failures — a transient remote 500 on query registration, a
583
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
584
+ * throw at the app. This only controls when a *run* of consecutive failures
585
+ * is reported. Status flips back to `healthy` on the next successful sync
586
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
587
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
588
+ */
589
+ syncHealth?: SyncHealthConfig | false;
590
+ }
591
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
592
+ interface SyncHealthConfig {
593
+ /**
594
+ * Number of consecutive failed sync rounds (up or down) before the status
595
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
596
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
597
+ * disables degraded reporting entirely.
598
+ */
599
+ degradeAfterConsecutiveFailures?: number;
600
+ }
601
+ type SyncHealthStatus = 'healthy' | 'degraded';
602
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
603
+ interface SyncHealth {
604
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
605
+ status: SyncHealthStatus;
606
+ /** Consecutive failed sync rounds at the moment of this report. */
607
+ consecutiveFailures: number;
608
+ /** Classification of the most recent failure (only set while `degraded`). */
609
+ kind?: 'network' | 'application';
610
+ /** Message of the most recent failure (only set while `degraded`). */
611
+ error?: string;
612
+ /**
613
+ * `true` once at least one sync round has succeeded this session. Lets a UI
614
+ * distinguish a first-time "connecting" phase (never reached the server yet,
615
+ * so a cold-start failure run is expected) from a real lost connection after
616
+ * a working session. Never resets back to `false` once set.
617
+ */
618
+ everConnected: boolean;
619
+ }
620
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
621
+ /**
622
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
623
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
624
+ * server, this one is about whether the local store survives a reload.
625
+ *
626
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
627
+ * which only one client per bucket can hold open. When it can't be opened (a
628
+ * second tab of the app already has it, an insecure context, a full pool) the
629
+ * engine keeps working against an in-memory DB, which holds the whole dataset
630
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
631
+ * so a UI can warn about it.
632
+ */
633
+ interface StorageHealth {
634
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
635
+ status: StorageHealthStatus;
636
+ /**
637
+ * `true` only when durable storage was REQUESTED and could not be opened.
638
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
639
+ * is a choice rather than a failure, so a UI can key off this alone.
640
+ */
641
+ fallback: boolean;
642
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
643
+ error?: string;
644
+ /**
645
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
646
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
647
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
648
+ * single-tab behavior. Absent entirely when the feature is off.
649
+ */
650
+ role?: 'leader' | 'follower' | 'solo';
651
+ }
652
+ type QueryHash = string;
653
+ type RecordVersionArray = Array<[string, number]>;
654
+ /**
655
+ * Represents the difference between two record version sets.
656
+ * Used for synchronizing local and remote states.
657
+ */
658
+ interface RecordVersionDiff {
659
+ /** List of records added. */
660
+ added: Array<{
661
+ id: RecordId$1<string>;
662
+ version: number;
663
+ }>;
664
+ /** List of records updated. */
665
+ updated: Array<{
666
+ id: RecordId$1<string>;
667
+ version: number;
668
+ }>;
669
+ /** List of record IDs removed. */
670
+ removed: RecordId$1<string>[];
671
+ }
672
+ /**
673
+ * Configuration for a specific query instance.
674
+ * Stores metadata about the query's state, parameters, and versioning.
675
+ */
676
+ interface QueryConfig {
677
+ /** The unique ID of the query config record. */
678
+ id: RecordId$1<string>;
679
+ /** The SURQL query string. */
680
+ surql: string;
681
+ /**
682
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
683
+ * `_00_query`). Present when the query came from the query-builder. Non-
684
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
685
+ * instead of re-running `surql`, which they cannot parse.
686
+ */
687
+ plan?: QueryPlan;
688
+ /** Parameters used in the query. */
689
+ params: Record<string, any>;
690
+ /** The version array representing the local state of results. */
691
+ localArray: RecordVersionArray;
692
+ /** The version array representing the remote (server) state of results. */
693
+ remoteArray: RecordVersionArray;
694
+ /**
695
+ * In-memory only (never persisted to `_00_query`): version array of the
696
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
697
+ * child-body sync is idempotent across polls. Kept separate from
698
+ * `remoteArray` so related child rows never enter the primary window /
699
+ * `rowCount` / `localArray`.
700
+ */
701
+ subqueryRemoteArray?: RecordVersionArray;
702
+ /** Time-To-Live for this query. */
703
+ ttl: QueryTimeToLive;
704
+ /** Timestamp when the query was last accessed/active. */
705
+ lastActiveAt: Date;
706
+ /** The name of the table this query targets (if applicable). */
707
+ tableName: string;
708
+ }
709
+ type QueryConfigRecord = QueryConfig & {
710
+ id: string;
711
+ };
712
+ /**
713
+ * Runtime fetch status of a live query.
714
+ * - `idle`: registered, initial sync completed, and not currently fetching
715
+ * missing records — the materialized rows are authoritative (a windowed
716
+ * query's short result really is the end of the list).
717
+ * - `fetching`: the query is registering (a query is born `fetching` until its
718
+ * initial remote sync completes) or the sync engine is fetching/ingesting
719
+ * missing records for it. Any pending debounced result is flushed BEFORE the
720
+ * flip back to `idle`, so idle status never races ahead of the rows.
721
+ */
722
+ type QueryStatus = 'idle' | 'fetching';
723
+ /**
724
+ * Internal state of a live query.
725
+ */
726
+ interface QueryState {
727
+ /** The configuration for this query. */
728
+ config: QueryConfig;
729
+ /** The current cached records for this query. */
730
+ records: Record<string, any>[];
731
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
732
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
733
+ hydrated?: boolean;
734
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
735
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
736
+ * always emits at least once even when its records are unchanged — otherwise
737
+ * an empty re-registered window would never notify and stay "loading". */
738
+ syncNotified?: boolean;
739
+ /** Timer for TTL expiration. */
740
+ ttlTimer: NodeJS.Timeout | null;
741
+ /** TTL duration in milliseconds. */
742
+ ttlDurationMs: number;
743
+ /** Number of times the query has been updated. */
744
+ updateCount: number;
745
+ /** Timestamp (ms) of the last user-visible update, or null before the first
746
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
747
+ lastUpdatedAt: number | null;
748
+ /**
749
+ * Rolling window of the most recent materialization-step latencies (ms).
750
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
751
+ * before each persist to `_00_query`. Samples themselves are not persisted.
752
+ */
753
+ materializationSamples: number[];
754
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
755
+ lastIngestLatencyMs: number | null;
756
+ /** Cumulative count of ingest/materialization errors observed for this query. */
757
+ errorCount: number;
758
+ /**
759
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
760
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
761
+ * pulling missing records for this query, otherwise `idle`.
762
+ */
763
+ status: QueryStatus;
764
+ /**
765
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
766
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
767
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
768
+ */
769
+ phaseSamples: Record<string, number[]>;
770
+ /** Most recent sample (ms) per phase, or null. */
771
+ phaseLast: Record<string, number | null>;
772
+ /** One-shot SSP registration timings (ms). */
773
+ registrationTimings: RegistrationTimings;
774
+ }
775
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
776
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
777
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
778
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
779
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
780
+ /** One-shot registration timings (ms), captured once when a query registers. */
781
+ interface RegistrationTimings {
782
+ /** SSP surql→plan parse + permission injection. */
783
+ parseMs: number | null;
784
+ /** SSP operator-DAG build. */
785
+ planMs: number | null;
786
+ /** SSP initial snapshot evaluation. */
787
+ snapshotMs: number | null;
788
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
789
+ wallMs: number | null;
790
+ }
791
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
792
+ interface PhaseStat {
793
+ lastMs: number | null;
794
+ p50: number | null;
795
+ p90: number | null;
796
+ p99: number | null;
797
+ count: number;
798
+ }
799
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
800
+ interface QueryTimings {
801
+ ssp: PhaseStat;
802
+ sspStoreApply: PhaseStat;
803
+ sspCircuitStep: PhaseStat;
804
+ sspTransform: PhaseStat;
805
+ localFetch: PhaseStat;
806
+ remoteFetch: PhaseStat;
807
+ frontend: PhaseStat;
808
+ registration: RegistrationTimings;
809
+ updateCount: number;
810
+ errorCount: number;
811
+ }
812
+ type QueryUpdateCallback = (records: Record<string, any>[]) => void;
813
+ type QueryStatusCallback = (status: QueryStatus) => void;
814
+ type MutationCallback = (mutations: UpEvent[]) => void;
815
+ type MutationEventType = 'create' | 'update' | 'delete';
816
+ /**
817
+ * Represents a mutation event (create, update, delete) to be synchronized.
818
+ */
819
+ interface MutationEvent {
820
+ /** Example: 'create', 'update', or 'delete'. */
821
+ type: MutationEventType;
822
+ /** unique id of the mutation */
823
+ mutation_id: RecordId$1<string>;
824
+ /** The ID of the record being mutated. */
825
+ record_id: RecordId$1<string>;
826
+ /** The data payload for create/update operations. */
827
+ data?: any;
828
+ /** The full record data (optional context). */
829
+ record?: any;
830
+ /** Options for the mutation event (e.g., debounce settings). */
831
+ options?: PushEventOptions;
832
+ /** Timestamp when the event was created. */
833
+ createdAt: Date;
834
+ }
835
+ /**
836
+ * Options for run operations.
837
+ */
838
+ interface RunOptions {
839
+ assignedTo?: string;
840
+ max_retries?: number;
841
+ retry_strategy?: 'linear' | 'exponential';
842
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
843
+ timeout?: number;
844
+ /**
845
+ * Minimum delay in milliseconds before the job is eligible to run. While
846
+ * delayed the job stays pending (enqueued) and can still be killed.
847
+ */
848
+ delay?: number;
849
+ }
850
+ /**
851
+ * Options for update operations.
852
+ */
853
+ interface UpdateOptions {
854
+ /**
855
+ * Debounce configuration for the update.
856
+ * If boolean, enables default debounce behavior.
857
+ */
858
+ debounced?: boolean | DebounceOptions;
859
+ }
860
+ /**
861
+ * Configuration options for debouncing updates.
862
+ */
863
+ interface DebounceOptions {
864
+ /**
865
+ * The key to use for debouncing.
866
+ * - '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'.
867
+ * - 'recordId_x_fields': Debounce based on record ID and specific fields.
868
+ */
869
+ key?: 'recordId' | 'recordId_x_fields';
870
+ /** The debounce delay in milliseconds. */
871
+ delay?: number;
872
+ }
873
+ //#endregion
874
+ export { StorageHealthStatus as A, DatabaseEventSystem as B, RecordVersionDiff as C, Sp00kyQueryResult as D, Sp00kyConfig as E, TimingPhase as F, EventSystem as G, Logger$1 as H, UpdateOptions as I, UpEvent as L, SyncHealth as M, SyncHealthConfig as N, Sp00kyQueryResultPromise as O, SyncHealthStatus as P, LocalStore as R, RecordVersionArray as S, RunOptions as T, SyncEventSystem as U, DatabaseEventTypes as V, EventDefinition as W, QueryStatus as _, MutationCallback as a, QueryTimings as b, PersistenceClient as c, PreloadOptions as d, PreloadRefresh as f, QueryState as g, QueryHash as h, MATERIALIZATION_SAMPLE_WINDOW as i, StoreType as j, StorageHealth as k, PhaseStat as l, QueryConfigRecord as m, EventSubscriptionOptions as n, MutationEvent as o, QueryConfig as p, Level$1 as r, MutationEventType as s, DebounceOptions as t, PinoTransmit as u, QueryStatusCallback as v, RegistrationTimings as w, QueryUpdateCallback as x, QueryTimeToLive as y, SealedQuery as z };