@spooky-sync/core 0.0.0-canary.1 → 0.0.1-alpha.1

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 (228) hide show
  1. package/AGENTS.md +74 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2178 -411
  4. package/dist/index.js +12503 -2475
  5. package/dist/otel/index.d.ts +21 -0
  6. package/dist/otel/index.js +86 -0
  7. package/dist/sqlite-open.js +322 -0
  8. package/dist/sqlite-worker.d.ts +1 -0
  9. package/dist/sqlite-worker.js +439 -0
  10. package/dist/tabs-broker-worker.d.ts +8 -0
  11. package/dist/tabs-broker-worker.js +472 -0
  12. package/dist/types.d.ts +1060 -0
  13. package/package.json +49 -12
  14. package/scripts/check-broker-bundle.mjs +33 -0
  15. package/skills/sp00ky-core/SKILL.md +276 -0
  16. package/skills/sp00ky-core/references/auth.md +98 -0
  17. package/skills/sp00ky-core/references/config.md +76 -0
  18. package/src/boot/auth-flip.saga.test.ts +82 -0
  19. package/src/boot/auth-flip.saga.ts +62 -0
  20. package/src/boot/boot.saga.test.ts +151 -0
  21. package/src/boot/boot.saga.ts +128 -0
  22. package/src/boot/bucket-switch.saga.test.ts +158 -0
  23. package/src/boot/bucket-switch.saga.ts +115 -0
  24. package/src/boot/preload.saga.test.ts +51 -0
  25. package/src/boot/preload.saga.ts +31 -0
  26. package/src/bucket-blurhash.test.ts +148 -0
  27. package/src/build-globals.d.ts +12 -0
  28. package/src/client/bucket-handle.test.ts +117 -0
  29. package/src/client/bucket-handle.ts +227 -0
  30. package/src/client/router.test.ts +56 -0
  31. package/src/client/router.ts +94 -0
  32. package/src/client/runtime.test.ts +178 -0
  33. package/src/client/runtime.ts +285 -0
  34. package/src/client/services.ts +349 -0
  35. package/src/client/sp00ky-client.test.ts +241 -0
  36. package/src/client/sp00ky-client.ts +482 -0
  37. package/src/events/events.test.ts +2 -1
  38. package/src/events/index.ts +3 -0
  39. package/src/index.ts +37 -1
  40. package/src/kernel/constants.test.ts +19 -0
  41. package/src/kernel/constants.ts +54 -0
  42. package/src/kernel/effects.test.ts +40 -0
  43. package/src/kernel/effects.ts +159 -0
  44. package/src/kernel/events.ts +55 -0
  45. package/src/kernel/interpreter.test.ts +116 -0
  46. package/src/kernel/interpreter.ts +143 -0
  47. package/src/kernel/saga.test.ts +89 -0
  48. package/src/kernel/saga.ts +73 -0
  49. package/src/modules/app-release/index.test.ts +125 -0
  50. package/src/modules/app-release/index.ts +209 -0
  51. package/src/modules/auth/auth.local-first.test.ts +141 -0
  52. package/src/modules/auth/events/index.ts +2 -1
  53. package/src/modules/auth/index.ts +138 -25
  54. package/src/modules/crdt/crdt-field.ts +294 -0
  55. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  56. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  57. package/src/modules/crdt/index.ts +463 -0
  58. package/src/modules/crdt/loro-loader.ts +25 -0
  59. package/src/modules/devtools/flags.ts +349 -0
  60. package/src/modules/devtools/index.ts +459 -47
  61. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  62. package/src/modules/devtools/state-shape.test.ts +149 -0
  63. package/src/modules/devtools/storage-info.test.ts +79 -0
  64. package/src/modules/devtools/storage-info.ts +168 -0
  65. package/src/modules/devtools/versions.test.ts +74 -0
  66. package/src/modules/devtools/versions.ts +110 -0
  67. package/src/modules/feature-flag/index.test.ts +251 -0
  68. package/src/modules/feature-flag/index.ts +316 -0
  69. package/src/modules/ref-tables.test.ts +91 -0
  70. package/src/modules/ref-tables.ts +88 -0
  71. package/src/mutation/jobs.test.ts +25 -0
  72. package/src/mutation/jobs.ts +41 -0
  73. package/src/mutation/mutation-id.test.ts +37 -0
  74. package/src/mutation/mutation-id.ts +35 -0
  75. package/src/mutation/push.saga.test.ts +285 -0
  76. package/src/mutation/push.saga.ts +215 -0
  77. package/src/mutation/rows.test.ts +201 -0
  78. package/src/mutation/rows.ts +377 -0
  79. package/src/mutation/tray.saga.test.ts +63 -0
  80. package/src/mutation/tray.saga.ts +48 -0
  81. package/src/mutation/write.saga.test.ts +163 -0
  82. package/src/mutation/write.saga.ts +166 -0
  83. package/src/otel/index.ts +127 -0
  84. package/src/query/env.test.ts +23 -0
  85. package/src/query/env.ts +56 -0
  86. package/src/query/fetch.saga.test.ts +156 -0
  87. package/src/query/fetch.saga.ts +109 -0
  88. package/src/query/hash.test.ts +14 -0
  89. package/src/query/hash.ts +18 -0
  90. package/src/query/id-set-plan.test.ts +132 -0
  91. package/src/query/lifecycle.saga.test.ts +122 -0
  92. package/src/query/lifecycle.saga.ts +101 -0
  93. package/src/query/materialize.saga.test.ts +82 -0
  94. package/src/query/materialize.saga.ts +75 -0
  95. package/src/query/materialize.test.ts +50 -0
  96. package/src/query/materialize.ts +44 -0
  97. package/src/query/membership.saga.test.ts +246 -0
  98. package/src/query/membership.saga.ts +208 -0
  99. package/src/query/membership.test.ts +118 -0
  100. package/src/query/membership.ts +158 -0
  101. package/src/query/register.saga.test.ts +251 -0
  102. package/src/query/register.saga.ts +190 -0
  103. package/src/query/render-set.test.ts +36 -0
  104. package/src/query/render-set.ts +60 -0
  105. package/src/query/sql.test.ts +62 -0
  106. package/src/query/sql.ts +79 -0
  107. package/src/query/window-query.test.ts +70 -0
  108. package/src/query/window-query.ts +195 -0
  109. package/src/services/blobs/blob-cache.test.ts +359 -0
  110. package/src/services/blobs/blob-cache.ts +603 -0
  111. package/src/services/blobs/blob-manifest.ts +227 -0
  112. package/src/services/blobs/blob-store.test.ts +77 -0
  113. package/src/services/blobs/blob-store.ts +359 -0
  114. package/src/services/blobs/blob.fixture.ts +90 -0
  115. package/src/services/blobs/index.ts +70 -0
  116. package/src/services/database/cache-engine.ts +193 -0
  117. package/src/services/database/connection-supervisor.test.ts +289 -0
  118. package/src/services/database/connection-supervisor.ts +415 -0
  119. package/src/services/database/database.query-timeout.test.ts +140 -0
  120. package/src/services/database/database.responses.test.ts +43 -0
  121. package/src/services/database/database.ts +145 -62
  122. package/src/services/database/engine-factory.ts +33 -0
  123. package/src/services/database/errors.ts +34 -0
  124. package/src/services/database/events/index.ts +2 -1
  125. package/src/services/database/index.ts +7 -0
  126. package/src/services/database/local-migrator.ts +30 -27
  127. package/src/services/database/local.test.ts +64 -0
  128. package/src/services/database/local.ts +484 -67
  129. package/src/services/database/plan-render.test.ts +159 -0
  130. package/src/services/database/plan-render.ts +108 -0
  131. package/src/services/database/relation-resolver.test.ts +467 -0
  132. package/src/services/database/relation-resolver.ts +0 -0
  133. package/src/services/database/remote.ts +222 -15
  134. package/src/services/database/sqlite-cache-engine.test.ts +617 -0
  135. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  136. package/src/services/database/sqlite-cache-engine.ts +1349 -0
  137. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  138. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  139. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  140. package/src/services/database/sqlite-lock-verify.ts +45 -0
  141. package/src/services/database/sqlite-open.test.ts +150 -0
  142. package/src/services/database/sqlite-open.ts +164 -0
  143. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  144. package/src/services/database/sqlite-plan-sql.ts +138 -0
  145. package/src/services/database/sqlite-projection.test.ts +99 -0
  146. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  147. package/src/services/database/sqlite-select.test.ts +246 -0
  148. package/src/services/database/sqlite-select.ts +131 -0
  149. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  150. package/src/services/database/sqlite-transport.ts +224 -0
  151. package/src/services/database/sqlite-worker.ts +437 -0
  152. package/src/services/database/surql-translate.ts +416 -0
  153. package/src/services/database/surreal-cache-engine.ts +161 -0
  154. package/src/services/logger/index.ts +6 -101
  155. package/src/services/persistence/localstorage.ts +2 -2
  156. package/src/services/persistence/resilient.ts +41 -0
  157. package/src/services/persistence/surrealdb.ts +10 -10
  158. package/src/services/stream-processor/index.ts +796 -84
  159. package/src/services/stream-processor/permissions.test.ts +47 -0
  160. package/src/services/stream-processor/permissions.ts +53 -0
  161. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  162. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  163. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  164. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  165. package/src/services/stream-processor/wasm-types.ts +59 -3
  166. package/src/services/tabs/broker-client.ts +283 -0
  167. package/src/services/tabs/broker.test.ts +327 -0
  168. package/src/services/tabs/coordinator.test.ts +365 -0
  169. package/src/services/tabs/coordinator.ts +633 -0
  170. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  171. package/src/services/tabs/leader-locks.ts +75 -0
  172. package/src/services/tabs/protocol.ts +262 -0
  173. package/src/services/tabs/support.ts +36 -0
  174. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  175. package/src/sp00ky.ts +5 -0
  176. package/src/state/client-state.ts +184 -0
  177. package/src/state/lifecycle.test.ts +118 -0
  178. package/src/state/lifecycle.ts +86 -0
  179. package/src/state/reducers.test.ts +280 -0
  180. package/src/state/reducers.ts +462 -0
  181. package/src/state/selectors.test.ts +149 -0
  182. package/src/state/selectors.ts +184 -0
  183. package/src/sync/connection.saga.test.ts +84 -0
  184. package/src/sync/connection.saga.ts +86 -0
  185. package/src/sync/live.saga.test.ts +69 -0
  186. package/src/sync/live.saga.ts +49 -0
  187. package/src/sync/policy.health.test.ts +56 -0
  188. package/src/sync/policy.test.ts +659 -0
  189. package/src/sync/policy.ts +507 -0
  190. package/src/sync/poll.saga.test.ts +51 -0
  191. package/src/sync/poll.saga.ts +36 -0
  192. package/src/sync/tabs.saga.test.ts +74 -0
  193. package/src/sync/tabs.saga.ts +92 -0
  194. package/src/testing/adapters.ts +133 -0
  195. package/src/testing/build.ts +61 -0
  196. package/src/testing/fake-services.ts +34 -0
  197. package/src/testing/run-pure.test.ts +92 -0
  198. package/src/testing/run-pure.ts +128 -0
  199. package/src/testing/services.ts +17 -0
  200. package/src/types.ts +557 -16
  201. package/src/utils/blurhash.ts +90 -0
  202. package/src/utils/error-classification.test.ts +54 -0
  203. package/src/utils/error-classification.ts +25 -0
  204. package/src/utils/index.ts +86 -13
  205. package/src/utils/parser.test.ts +49 -120
  206. package/src/utils/parser.ts +32 -2
  207. package/src/utils/semver.test.ts +32 -0
  208. package/src/utils/semver.ts +30 -0
  209. package/src/utils/surql.ts +30 -18
  210. package/src/utils/utils.test.ts +2 -1
  211. package/src/utils/withRetry.test.ts +1 -1
  212. package/tsdown.config.ts +86 -1
  213. package/vitest.config.ts +48 -0
  214. package/src/modules/cache/index.ts +0 -241
  215. package/src/modules/cache/types.ts +0 -19
  216. package/src/modules/data/data.test.ts +0 -58
  217. package/src/modules/data/index.ts +0 -777
  218. package/src/modules/sync/engine.ts +0 -163
  219. package/src/modules/sync/events/index.ts +0 -77
  220. package/src/modules/sync/index.ts +0 -3
  221. package/src/modules/sync/queue/index.ts +0 -2
  222. package/src/modules/sync/queue/queue-down.ts +0 -89
  223. package/src/modules/sync/queue/queue-up.ts +0 -223
  224. package/src/modules/sync/scheduler.ts +0 -84
  225. package/src/modules/sync/sync.ts +0 -407
  226. package/src/modules/sync/utils.test.ts +0 -311
  227. package/src/modules/sync/utils.ts +0 -171
  228. package/src/spooky.ts +0 -346
@@ -0,0 +1,1060 @@
1
+ import { QueryPlan, QueryPlan as QueryPlan$1, RecordId, SchemaStructure, WhereNode } from "@spooky-sync/query-builder";
2
+ import { Level as Level$1, LoggerOptions } from "pino";
3
+
4
+ //#region src/events/index.d.ts
5
+ /**
6
+ * Utility type to define the payload structure of an event.
7
+ * If the payload type P is never, it defines payload as undefined.
8
+ */
9
+ type EventPayloadDefinition<P> = [P] extends [never] ? {
10
+ payload: undefined;
11
+ } : {
12
+ payload: P;
13
+ };
14
+ /**
15
+ * Defines the structure of an event with a specific type and payload.
16
+ * @template T The string literal type of the event.
17
+ * @template P The type of the event payload.
18
+ */
19
+ type EventDefinition<T extends string, P> = {
20
+ type: T;
21
+ } & EventPayloadDefinition<P>;
22
+ /**
23
+ * A map of event types to their definitions.
24
+ * Keys are event names, values are EventDefinitions.
25
+ */
26
+ type EventTypeMap = Record<string, EventDefinition<any, unknown> | EventDefinition<any, never>>;
27
+ /**
28
+ * Options for pushing/emitting events.
29
+ */
30
+ interface PushEventOptions {
31
+ /** Configuration for debouncing the event. */
32
+ debounced?: {
33
+ key: string;
34
+ delay: number;
35
+ };
36
+ }
37
+ /**
38
+ * Extracts the full Event object type from the map for a given key.
39
+ */
40
+ type Event<E extends EventTypeMap, T extends EventType<E>> = E[T];
41
+ /**
42
+ * Extracts the payload type from the map for a given key.
43
+ */
44
+ type EventPayload<E extends EventTypeMap, T extends EventType<E>> = E[T]['payload'];
45
+ /**
46
+ * Array of available event type keys.
47
+ */
48
+ type EventTypes<E extends EventTypeMap> = (keyof E)[];
49
+ /**
50
+ * Represents a valid key (event name) from the EventTypeMap.
51
+ */
52
+ type EventType<E extends EventTypeMap> = keyof E;
53
+ /**
54
+ * Function signature for an event handler.
55
+ */
56
+ type EventHandler<E extends EventTypeMap, T extends EventType<E>> = (event: Event<E, T>) => void;
57
+ /**
58
+ * Options when subscribing to an event.
59
+ */
60
+ type EventSubscriptionOptions$1 = {
61
+ /** If true, the handler will be called immediately with the last emitted event of this type (if any). */
62
+ immediately?: boolean;
63
+ /** If true, the subscription will be automatically removed after the first event is handled. */
64
+ once?: boolean;
65
+ };
66
+ /**
67
+ * A type-safe event system that handles subscription, emission (including debouncing), and buffering of events.
68
+ * @template E The EventTypeMap defining all supported events.
69
+ */
70
+ declare class EventSystem<E extends EventTypeMap> {
71
+ private _eventTypes;
72
+ private subscriberId;
73
+ private isProcessing;
74
+ private buffer;
75
+ private subscribers;
76
+ private subscribersTypeMap;
77
+ private lastEvents;
78
+ private debouncedEvents;
79
+ constructor(_eventTypes: EventTypes<E>);
80
+ get eventTypes(): EventTypes<E>;
81
+ /**
82
+ * Subscribes a handler to a specific event type.
83
+ * @param type The event type to subscribe to.
84
+ * @param handler The function to call when the event occurs.
85
+ * @param options Subscription options (once, immediately).
86
+ * @returns A subscription ID that can be used to unsubscribe.
87
+ */
88
+ subscribe<T extends EventType<E>>(type: T, handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number;
89
+ /**
90
+ * Subscribes a handler to multiple event types.
91
+ * @param types An array of event types to subscribe to.
92
+ * @param handler The function to call when any of the events occur.
93
+ * @param options Subscription options.
94
+ * @returns An array of subscription IDs.
95
+ */
96
+ subscribeMany<T extends EventType<E>>(types: T[], handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number[];
97
+ /**
98
+ * Unsubscribes a specific subscription by ID.
99
+ * @param id The subscription ID returned by subscribe().
100
+ * @returns True if the subscription was found and removed, false otherwise.
101
+ */
102
+ unsubscribe(id: number): boolean;
103
+ /**
104
+ * Emits an event with the given type and payload.
105
+ * @param type The type of event to emit.
106
+ * @param payload The data associated with the event.
107
+ */
108
+ emit<T extends EventType<E>, P extends EventPayload<E, T>>(type: T, payload: P): void;
109
+ /**
110
+ * Adds a fully constructed event object to the system.
111
+ * Similar to emit, but takes the full event object directly.
112
+ * Supports debouncing if options are provided.
113
+ * @param event The event object.
114
+ * @param options Options for the event push (e.g., debouncing).
115
+ */
116
+ addEvent<T extends EventType<E>>(event: Event<E, T>, options?: PushEventOptions): void;
117
+ private handleDebouncedEvent;
118
+ private scheduleProcessing;
119
+ private processEvents;
120
+ private dequeue;
121
+ private setLastEvent;
122
+ private broadcastEvent;
123
+ }
124
+ //#endregion
125
+ //#region src/utils/surql.d.ts
126
+ interface SealedQuery<T = void> {
127
+ readonly sql: string;
128
+ readonly extract: (results: unknown[]) => T;
129
+ }
130
+ //#endregion
131
+ //#region src/services/database/events/index.d.ts
132
+ declare const DatabaseEventTypes: {
133
+ readonly LocalQuery: "DATABASE_LOCAL_QUERY";
134
+ readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
135
+ };
136
+ interface DatabaseQueryEventPayload {
137
+ query: string;
138
+ vars?: Record<string, unknown>;
139
+ duration: number;
140
+ success: boolean;
141
+ error?: string;
142
+ timestamp: number;
143
+ }
144
+ type DatabaseEventTypeMap = {
145
+ [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
146
+ [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
147
+ };
148
+ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
149
+ //#endregion
150
+ //#region src/modules/devtools/storage-info.d.ts
151
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
152
+ interface EngineStorageDiagnostics {
153
+ engine: 'sqlite';
154
+ bucketId: string;
155
+ useOpfs: boolean;
156
+ workerSelectConfigured: boolean;
157
+ /** `false` while configured `true` means the runtime downgraded to the
158
+ * legacy multi-hop select (stale cached worker bundle). */
159
+ workerSelectEffective: boolean;
160
+ /** page_count * page_size. */
161
+ dbSizeBytes?: number;
162
+ /** freelist_count * page_size — reclaimable via VACUUM. */
163
+ freelistBytes?: number;
164
+ tableCounts?: {
165
+ table: string;
166
+ rows: number;
167
+ }[];
168
+ error?: string;
169
+ }
170
+ /**
171
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
172
+ * configured (apps that never asked for it get `null`, so the panel shows
173
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
174
+ * app asked to share one store and this tab is not, so it owns or contends for
175
+ * the OPFS pool alone.
176
+ */
177
+ //#endregion
178
+ //#region src/services/database/cache-engine.d.ts
179
+ /**
180
+ * A materialized row. Keys are field names; values are already decoded to the
181
+ * client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
182
+ * every backend hands `DataModule` the same shape SurrealDB does today.
183
+ */
184
+ type Row = Record<string, unknown>;
185
+ /** A record identifier — a `RecordId` or its stable string form (`table:id`). */
186
+ type Id = unknown;
187
+ /** How an order clause is expressed everywhere in the engine layer. */
188
+ type OrderBy = [field: string, direction: 'asc' | 'desc'][];
189
+ /**
190
+ * Batched relation fetch: "give me every row of `table` whose `matchField` is
191
+ * one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
192
+ * primitive relation decomposition (§3) leans on — implemented as
193
+ * `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
194
+ * `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
195
+ * here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
196
+ */
197
+ interface RelationFetch {
198
+ table: string;
199
+ matchField: string;
200
+ keys: Id[];
201
+ where?: WhereNode[];
202
+ orderBy?: OrderBy;
203
+ select?: string[];
204
+ }
205
+ /**
206
+ * The read side of an engine, minus relation resolution — the surface a
207
+ * {@link RelationResolver} needs. Kept separate so the resolver can be unit
208
+ * tested against an in-memory fake without a full engine.
209
+ */
210
+ interface RowFetcher {
211
+ /** Batched fan-out fetch. See {@link RelationFetch}. */
212
+ fetchRelation(req: RelationFetch): Promise<Row[]>;
213
+ }
214
+ /** A transaction handle — the same verbs as the engine, but atomic. */
215
+ interface EngineTx {
216
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
217
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
218
+ delete(table: string, id: Id): Promise<void>;
219
+ }
220
+ /**
221
+ * A pluggable local cache backend. SurrealDB (the default) and SQLite both
222
+ * implement this; the rest of the client talks verbs, never SurrealQL.
223
+ *
224
+ * Reactivity is NOT part of this contract: the local cache is passive. The SSP
225
+ * (remote) drives change; `DataModule` writes rows here and re-reads them. The
226
+ * `epoch` field preserves the existing bucket-switch fencing (see
227
+ * `LocalDatabaseService.epoch`): an async chain captures it at start and its
228
+ * write is dropped if the epoch moved (a bucket switch) in between.
229
+ */
230
+ interface LocalCacheEngine extends RowFetcher {
231
+ /** Monotonic store generation; bumped on every bucket switch. */
232
+ readonly epoch: number;
233
+ connect(bucketId: string): Promise<void>;
234
+ switchBucket(bucketId: string): Promise<void>;
235
+ close(): Promise<void>;
236
+ /** Run `fn` inside a single atomic transaction. */
237
+ transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
238
+ /**
239
+ * Materialize a query, including its `.related()` tree (via §3
240
+ * decomposition). Params bind `where` `paramRef`s and any windowing id-set.
241
+ */
242
+ select(plan: QueryPlan$1, params?: Record<string, unknown>): Promise<Row[]>;
243
+ /** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
244
+ selectByIds(table: string, ids: Id[], opts?: {
245
+ select?: string[];
246
+ orderBy?: OrderBy;
247
+ }): Promise<Row[]>;
248
+ /** Single-record read by primary id, or `null`. */
249
+ getById(table: string, id: Id): Promise<Row | null>;
250
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
251
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
252
+ delete(table: string, id: Id): Promise<void>;
253
+ }
254
+ /**
255
+ * The full surface the client's `this.local` field depends on: the
256
+ * engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
257
+ * SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
258
+ * `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
259
+ * `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
260
+ * either can back `this.local`.
261
+ *
262
+ * `getClient()` returns the underlying SurrealDB `Surreal` handle where one
263
+ * exists (SurrealDB backend); backends without one (SQLite) throw — it is only
264
+ * used by advanced/DevTools paths, never on the hot path.
265
+ */
266
+ interface LocalStore extends LocalCacheEngine {
267
+ /**
268
+ * Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
269
+ * `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
270
+ * schemaless engines (SQLite creates tables lazily) → false, so the client
271
+ * skips the `LocalMigrator` entirely for them.
272
+ */
273
+ readonly usesSurqlSchema: boolean;
274
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>, opts?: {
275
+ epoch?: number;
276
+ }): Promise<T>;
277
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: {
278
+ epoch?: number;
279
+ }): Promise<T>;
280
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
281
+ switchStore(bucketId: string): Promise<void>;
282
+ beginSwitch(): () => void;
283
+ getEvents(): DatabaseEventSystem;
284
+ getClient(): unknown;
285
+ getConfig(): Sp00kyConfig<any>['database'];
286
+ readonly currentBucketId: string;
287
+ /** Which built-in backend this is. OPTIONAL: absent (custom engines) is
288
+ * reported as `'custom'` by DevTools. More robust than `instanceof` for
289
+ * engines constructed outside this package. */
290
+ readonly engineKind?: 'surrealdb' | 'sqlite';
291
+ /** Engine-specific storage numbers for DevTools (DB file size, per-table
292
+ * row counts). OPTIONAL: only engines with something to report implement it. */
293
+ getStorageDiagnostics?(opts?: {
294
+ tableCounts?: boolean;
295
+ }): Promise<EngineStorageDiagnostics>;
296
+ /**
297
+ * Durability of this engine's local store. OPTIONAL: engines that don't
298
+ * report it (SurrealDB, custom engines) are treated as `'unknown'` by the
299
+ * client facade, so adding this needs no change on their side.
300
+ */
301
+ readonly storageHealth?: StorageHealth;
302
+ /** Fires immediately with the current snapshot, then on every change.
303
+ * Returns an unsubscribe function. */
304
+ subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
305
+ /**
306
+ * Every cached row's `(id, _00_rv)` per table, ids in stable `table:id`
307
+ * form. The in-browser circuit primes and reconciles itself from this on
308
+ * boot instead of re-downloading the working set. OPTIONAL: an engine
309
+ * without it boots the circuit empty, as before.
310
+ */
311
+ scanVersions?(tables: string[]): Promise<Record<string, [string, number][]>>;
312
+ /**
313
+ * Circuit snapshot storage, keyed. Lives in the same durable store as the
314
+ * rows (OPFS SQLite), so it is per-bucket by construction, atomic, and
315
+ * readable by follower tabs over the port transport. OPTIONAL: an engine
316
+ * without it primes from `scanVersions` alone.
317
+ */
318
+ getSnapshot?(key: string): Promise<StoredSnapshot | null>;
319
+ putSnapshot?(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void>;
320
+ deleteSnapshot?(key: string): Promise<void>;
321
+ }
322
+ /** Describes a stored circuit snapshot; what decides whether it is usable. */
323
+ interface SnapshotMeta {
324
+ /** Bump when the wire shape the circuit reads changes. */
325
+ formatVersion: number;
326
+ /** Hash of the schema the rows were projected under. */
327
+ schemaHash: string;
328
+ savedAt: number;
329
+ /** Highest `_00_rv` per table at save time (diagnostics). */
330
+ maxRv?: Record<string, number>;
331
+ [key: string]: unknown;
332
+ }
333
+ interface StoredSnapshot {
334
+ bytes: Uint8Array;
335
+ meta: SnapshotMeta;
336
+ }
337
+ /** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
338
+ type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
339
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
340
+ * a guard against a cyclic schema producing unbounded fan-out. */
341
+ //#endregion
342
+ //#region src/types.d.ts
343
+ /**
344
+ * A pino browser transmit object for forwarding logs to an external sink (e.g. OpenTelemetry).
345
+ */
346
+ type PinoTransmit = NonNullable<NonNullable<LoggerOptions['browser']>['transmit']>;
347
+ /**
348
+ * The type of storage backend to use for the local database.
349
+ * - 'memory': In-memory storage (transient).
350
+ * - 'indexeddb': IndexedDB storage (persistent).
351
+ */
352
+ type StoreType = 'memory' | 'indexeddb';
353
+ /**
354
+ * Interface for a custom persistence client.
355
+ * Allows providing a custom storage mechanism for the local database.
356
+ */
357
+ interface PersistenceClient {
358
+ /**
359
+ * Sets a value in the storage.
360
+ * @param key The key to set.
361
+ * @param value The value to store.
362
+ */
363
+ set<T>(key: string, value: T): Promise<void>;
364
+ /**
365
+ * Gets a value from the storage.
366
+ * @param key The key to retrieve.
367
+ * @returns The stored value or null if not found.
368
+ */
369
+ get<T>(key: string): Promise<T | null>;
370
+ /**
371
+ * Removes a value from the storage.
372
+ * @param key The key to remove.
373
+ */
374
+ remove(key: string): Promise<void>;
375
+ }
376
+ /**
377
+ * Supported Time-To-Live (TTL) values for cached queries.
378
+ * Format: number + unit (m=minutes, h=hours, d=days).
379
+ */
380
+ type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
381
+ /**
382
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
383
+ * The FIRST load (cold) always fetches + blocks regardless.
384
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
385
+ * real `useQuery` mounts and registers its live view. No network on load.
386
+ * - `background`: return instantly, but kick a one-time silent refetch.
387
+ * - `stale`: like `background`, but only if the cached copy is older than
388
+ * `staleTime`.
389
+ */
390
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
391
+ interface PreloadOptions {
392
+ /** Abort a cold preload that is still waiting for the server. */
393
+ signal?: AbortSignal;
394
+ /** @deprecated Preload is a registered query now; a warm preload never refetches by itself. Ignored. */
395
+ refresh?: PreloadRefresh;
396
+ /** @deprecated Ignored. */
397
+ staleTime?: QueryTimeToLive;
398
+ }
399
+ /**
400
+ * Result object returned when a query is registered or executed.
401
+ */
402
+ interface Sp00kyQueryResult {
403
+ /** The unique hash identifier for the query. */
404
+ hash: string;
405
+ }
406
+ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
407
+ interface EventSubscriptionOptions {
408
+ priority?: number;
409
+ }
410
+ /**
411
+ * Configuration options for the Sp00ky client.
412
+ * @template S The schema structure type.
413
+ */
414
+ interface Sp00kyConfig<S extends SchemaStructure> {
415
+ /** Database connection configuration. */
416
+ database: {
417
+ /** The SurrealDB endpoint URL. */
418
+ endpoint?: string;
419
+ /** The namespace to use. */
420
+ namespace: string;
421
+ /** The database name. */
422
+ database: string;
423
+ /** The local store type implementation. */
424
+ store?: StoreType;
425
+ /** Authentication token. */
426
+ token?: string;
427
+ /**
428
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
429
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
430
+ * table/relation level. Defaults to true; set false to force the legacy
431
+ * multi-hop path (escape hatch while the worker-side path beds in).
432
+ */
433
+ workerSelect?: boolean;
434
+ /**
435
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
436
+ * keep the connection alive indefinitely without configuration. See
437
+ * {@link ReconnectConfig}.
438
+ */
439
+ reconnect?: ReconnectConfig;
440
+ /**
441
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
442
+ * a single promise chain, so one call that never settles (half-open socket:
443
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
444
+ * otherwise wedge ALL later remote traffic behind it — including the sync
445
+ * poll's own health probe, leaving health pinned at `healthy` with no
446
+ * banner and no self-heal. The deadline turns that into an ordinary network
447
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
448
+ */
449
+ queryTimeoutMs?: number;
450
+ /**
451
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
452
+ * or a query on the in-process surrealdb engine). Local ops are serialized
453
+ * too, and one that never answered - a worker starved behind a long select,
454
+ * a lock verification with no clock - left every `db.create`/`db.update`
455
+ * promise pending for the tab's lifetime. On expiry the call rejects with
456
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
457
+ * not retried). `0` disables. Defaults to `30_000`.
458
+ */
459
+ localOpTimeoutMs?: number;
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
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
482
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
483
+ * how bucket reads behaved before it existed.
484
+ *
485
+ * Nothing in this cache expires on a timer — an image whose row is still in
486
+ * the local store has to stay available offline. Bytes are only dropped when
487
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
488
+ * reconcile finds no file behind a row, or when the cache is over budget, in
489
+ * which case the least-recently-used unpinned entries go first. See
490
+ * `services/blobs/blob-cache.ts`.
491
+ */
492
+ blobCache?: {
493
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
494
+ enabled?: boolean;
495
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
496
+ * `navigator.storage.estimate()`. */
497
+ maxBytes?: number;
498
+ /**
499
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
500
+ * `false`, matching the local store: cached files are namespaced per local
501
+ * bucket, so signing back in is warm and no user can read another's cache.
502
+ * Turn on for shared devices.
503
+ */
504
+ clearOnSignOut?: boolean;
505
+ };
506
+ /**
507
+ * Share ONE durable local store across all tabs of this origin (default
508
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
509
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
510
+ * worker and the sync loop, and follower tabs read/write the same store over
511
+ * MessagePorts, so every tab is durable instead of only the first one.
512
+ *
513
+ * Falls back to solo mode (exactly the flag-off behavior, including the
514
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
515
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
516
+ * not sqlite, or the broker rejects the tab (mixed app versions).
517
+ *
518
+ * Failover: when the leader tab closes or freezes, a follower is promoted
519
+ * within seconds; queries briefly refetch and mutations are never lost once
520
+ * their local write resolved (the shared outbox survives in the store).
521
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
522
+ */
523
+ sharedTabs?: boolean;
524
+ /**
525
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
526
+ * store, so a reload restores it and only steps in what changed since.
527
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
528
+ * can hold the bytes) and `false` otherwise.
529
+ *
530
+ * Without a snapshot the circuit is primed by reading every cached row back
531
+ * out of the local store; either way a reload never re-downloads the working
532
+ * set, which is what an empty circuit used to force: every id in the
533
+ * server's list_ref classified as missing.
534
+ *
535
+ * Snapshots are store-only (views are re-registered per session) and written
536
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
537
+ * goes hidden, never per ingest or per query registration.
538
+ */
539
+ persistCircuit?: boolean;
540
+ /**
541
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
542
+ * 30000. Ignored when `persistCircuit` is off.
543
+ */
544
+ circuitCheckpointMs?: number;
545
+ /**
546
+ * Keep only the fields registered queries evaluate (filter predicates, join
547
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
548
+ * Default `true`. The circuit only ever reads those fields; bodies are
549
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
550
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
551
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
552
+ * without has that field merged in from the local store on registration.
553
+ */
554
+ circuitProjection?: boolean;
555
+ /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
556
+ otelTransmit?: PinoTransmit;
557
+ /**
558
+ * Debounce time in milliseconds for stream updates (the client-side SSP
559
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
560
+ * per-record updates per query before notifying readers).
561
+ * Defaults to 50ms.
562
+ */
563
+ streamDebounceTime?: number;
564
+ /**
565
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
566
+ * changes to the remote database. Local writes happen immediately on
567
+ * every keystroke (so reload/offline works), but the remote UPSERT is
568
+ * coalesced over this window. Lower = snappier remote propagation +
569
+ * more network traffic; higher = less traffic + more lag for other
570
+ * collaborators. Defaults to 500ms.
571
+ */
572
+ crdtDebounceMs?: number;
573
+ /**
574
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
575
+ * preloaded at client startup (fetched as a separate chunk on page load) so
576
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
577
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
578
+ * out of apps that don't use collaboration. Defaults to `false`.
579
+ */
580
+ crdt?: boolean;
581
+ /**
582
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
583
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
584
+ * convergence + more query load; higher = the inverse. Non-positive
585
+ * values fall back to the default (500ms).
586
+ */
587
+ refSyncIntervalMs?: number;
588
+ /**
589
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
590
+ * registered with no server result yet, its surql also runs directly on the
591
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
592
+ * before the full register lifecycle completes. Hydrated rows carry their
593
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
594
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
595
+ * paints from the local cache immediately — however the rows got there
596
+ * (preload, prior sync). Default `false`: the register lifecycle
597
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
598
+ * freshness path and no duplicate one-shot fetches are made.
599
+ */
600
+ instantHydrate?: boolean;
601
+ /**
602
+ * Enable realtime sync while signed out. When `true`, the client starts its
603
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
604
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
605
+ * page gets live `useQuery` updates over world-readable tables. Requires the
606
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
607
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
608
+ * one-shot but never sync live.
609
+ */
610
+ enableAnonymousLiveQueries?: boolean;
611
+ /**
612
+ * Surface sustained sync failures as a "degraded" health status that the app
613
+ * can observe via `subscribeToSyncHealth` (or the client-solid
614
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
615
+ *
616
+ * Individual failures — a transient remote 500 on query registration, a
617
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
618
+ * throw at the app. This only controls when a *run* of consecutive failures
619
+ * is reported. Status flips back to `healthy` on the next successful sync
620
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
621
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
622
+ */
623
+ syncHealth?: SyncHealthConfig | false;
624
+ /**
625
+ * Automatic blurhash placeholders for bucket image uploads. On every
626
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
627
+ * the client computes a blurhash and stores it as a tiny sidecar object
628
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
629
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
630
+ * helpers) to paint a placeholder until the image is decoded.
631
+ *
632
+ * `true` (the default) enables with 4x3 components; pass
633
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
634
+ * A per-call `put(path, content, { blurhash })` option overrides this.
635
+ */
636
+ blurhash?: boolean | {
637
+ componentX?: number;
638
+ componentY?: number;
639
+ };
640
+ /**
641
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
642
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
643
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
644
+ * settles stops every later mutation for the session, with no retry and no
645
+ * error. On expiry the push is treated as a network failure and re-queued.
646
+ * `0` disables. Defaults to `30_000`.
647
+ */
648
+ pushTimeoutMs?: number;
649
+ /**
650
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
651
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
652
+ * Defaults to 30000; `0` disables the timeout.
653
+ */
654
+ downTimeoutMs?: number;
655
+ }
656
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
657
+ interface SyncHealthConfig {
658
+ /**
659
+ * Number of consecutive failed sync rounds (up or down) before the status
660
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
661
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
662
+ * disables degraded reporting entirely.
663
+ */
664
+ degradeAfterConsecutiveFailures?: number;
665
+ }
666
+ /**
667
+ * Tunables for WebSocket reconnect and liveness detection. See
668
+ * {@link Sp00kyConfig.database.reconnect}.
669
+ *
670
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
671
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
672
+ * supervisor above it re-opens the connection from scratch whenever the SDK
673
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
674
+ * engine permanently in that case, so a supervisor is required, not optional.
675
+ * The heartbeat covers the third case: a socket that never closes at all.
676
+ */
677
+ interface ReconnectConfig {
678
+ /**
679
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
680
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
681
+ * ~62s outage and then gives up for the life of the page).
682
+ */
683
+ attempts?: number;
684
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
685
+ retryDelayMax?: number;
686
+ /**
687
+ * Cadence of the application-level liveness probe (`RETURN true`) that
688
+ * detects a half-open socket the transport never reports as closed.
689
+ * `0` disables the heartbeat. Defaults to `20_000`.
690
+ */
691
+ heartbeatIntervalMs?: number;
692
+ /**
693
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
694
+ * regardless of what its `readyState` claims, so the connection is torn down
695
+ * and rebuilt. Defaults to `10_000`.
696
+ */
697
+ heartbeatTimeoutMs?: number;
698
+ /**
699
+ * Cap on the supervisor's own backoff between `connect()` retries once the
700
+ * SDK has given up. Defaults to `15_000`.
701
+ */
702
+ superviseRetryDelayMaxMs?: number;
703
+ }
704
+ /**
705
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
706
+ *
707
+ * These answer different questions: `connection` is about the socket,
708
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
709
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
710
+ * usually still `healthy` for the first few seconds.
711
+ */
712
+ type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
713
+ type SyncHealthStatus = 'healthy' | 'degraded';
714
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
715
+ interface SyncHealth {
716
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
717
+ status: SyncHealthStatus;
718
+ /** Consecutive failed sync rounds at the moment of this report. */
719
+ consecutiveFailures: number;
720
+ /** Classification of the most recent failure (only set while `degraded`). */
721
+ kind?: 'network' | 'application';
722
+ /** Message of the most recent failure (only set while `degraded`). */
723
+ error?: string;
724
+ /**
725
+ * `true` once at least one sync round has succeeded this session. Lets a UI
726
+ * distinguish a first-time "connecting" phase (never reached the server yet,
727
+ * so a cold-start failure run is expected) from a real lost connection after
728
+ * a working session. Never resets back to `false` once set.
729
+ */
730
+ everConnected: boolean;
731
+ /**
732
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
733
+ * one flips the instant the socket drops, whereas `status` only degrades
734
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
735
+ * immediately without waiting for the degrade threshold.
736
+ */
737
+ connection: ConnectionState;
738
+ }
739
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
740
+ /**
741
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
742
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
743
+ * server, this one is about whether the local store survives a reload.
744
+ *
745
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
746
+ * which only one client per bucket can hold open. When it can't be opened (a
747
+ * second tab of the app already has it, an insecure context, a full pool) the
748
+ * engine keeps working against an in-memory DB, which holds the whole dataset
749
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
750
+ * so a UI can warn about it.
751
+ */
752
+ interface StorageHealth {
753
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
754
+ status: StorageHealthStatus;
755
+ /**
756
+ * `true` only when durable storage was REQUESTED and could not be opened.
757
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
758
+ * is a choice rather than a failure, so a UI can key off this alone.
759
+ */
760
+ fallback: boolean;
761
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
762
+ error?: string;
763
+ /**
764
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
765
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
766
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
767
+ * single-tab behavior. Absent entirely when the feature is off.
768
+ */
769
+ role?: 'leader' | 'follower' | 'solo';
770
+ }
771
+ type QueryHash = string;
772
+ type RecordVersionArray = Array<[string, number]>;
773
+ /**
774
+ * Represents the difference between two record version sets.
775
+ * Used for synchronizing local and remote states.
776
+ */
777
+ interface RecordVersionDiff {
778
+ /** List of records added. */
779
+ added: Array<{
780
+ id: RecordId<string>;
781
+ version: number;
782
+ }>;
783
+ /** List of records updated. */
784
+ updated: Array<{
785
+ id: RecordId<string>;
786
+ version: number;
787
+ }>;
788
+ /** List of record IDs removed. */
789
+ removed: RecordId<string>[];
790
+ }
791
+ /**
792
+ * Configuration for a specific query instance.
793
+ * Stores metadata about the query's state, parameters, and versioning.
794
+ */
795
+ interface QueryConfig {
796
+ /** The unique ID of the query config record. */
797
+ id: RecordId<string>;
798
+ /** The SURQL query string. */
799
+ surql: string;
800
+ /**
801
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
802
+ * `_00_query`). Present when the query came from the query-builder. Non-
803
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
804
+ * instead of re-running `surql`, which they cannot parse.
805
+ */
806
+ plan?: QueryPlan;
807
+ /** Parameters used in the query. */
808
+ params: Record<string, any>;
809
+ /** The version array representing the local state of results. */
810
+ localArray: RecordVersionArray;
811
+ /** The version array representing the remote (server) state of results. */
812
+ remoteArray: RecordVersionArray;
813
+ /**
814
+ * In-memory only (never persisted to `_00_query`): version array of the
815
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
816
+ * child-body sync is idempotent across polls. Kept separate from
817
+ * `remoteArray` so related child rows never enter the primary window /
818
+ * `rowCount` / `localArray`.
819
+ */
820
+ subqueryRemoteArray?: RecordVersionArray;
821
+ /**
822
+ * Whether authoritative membership (`remoteArray`) has ever been established
823
+ * for this query — either fetched from `_00_list_ref` this session, or read
824
+ * back from the durable `_00_view` row on a cold start.
825
+ *
826
+ * Tri-state matters: "known and empty" must render an empty list, while
827
+ * "never established" has to fall back to a predicate scan of the local store
828
+ * so a query first run on this device still paints offline. A
829
+ * `remoteArray.length === 0` check cannot tell those apart.
830
+ *
831
+ * On a cold start it is seeded from the durable `_00_view` row when that
832
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
833
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
834
+ * by an old client that mirrored unflushed reads still self-heals.
835
+ */
836
+ membershipKnown?: boolean;
837
+ /**
838
+ * Key of this query's durable `_00_view` membership row: a hash of
839
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
840
+ * survives a reload (which mints a new session id) and a bucket switch.
841
+ * In-memory only.
842
+ */
843
+ membershipKey?: string;
844
+ /** Time-To-Live for this query. */
845
+ ttl: QueryTimeToLive;
846
+ /** Timestamp when the query was last accessed/active. */
847
+ lastActiveAt: Date;
848
+ /** The name of the table this query targets (if applicable). */
849
+ tableName: string;
850
+ }
851
+ type QueryConfigRecord = QueryConfig & {
852
+ id: string;
853
+ };
854
+ /**
855
+ * Runtime fetch status of a live query.
856
+ * - `idle`: registered, initial sync completed, and not currently fetching
857
+ * missing records — the materialized rows are authoritative (a windowed
858
+ * query's short result really is the end of the list).
859
+ * - `fetching`: the query is registering (a query is born `fetching` until its
860
+ * initial remote sync completes) or the sync engine is fetching/ingesting
861
+ * missing records for it. Any pending debounced result is flushed BEFORE the
862
+ * flip back to `idle`, so idle status never races ahead of the rows.
863
+ */
864
+ type QueryStatus = 'idle' | 'fetching';
865
+ /**
866
+ * What the server's `_00_query` row says about a view, read alongside its
867
+ * `_00_list_ref` edges (registration, the poll, a targeted re-read).
868
+ *
869
+ * - `present: false`: the row is not there (or not readable). The SSP no
870
+ * longer has this view: a TTL sweep, an SSP reset, a scheduler wipe. An
871
+ * empty edge set read at the same time is NOT "no rows", it is "no view".
872
+ * - `state: 'materializing'`: the SSP has (re)computed the set and its edges
873
+ * are in flight; an empty read is "not landed yet".
874
+ * - `state: 'ready'`: the edges are committed (flipped in the same
875
+ * transaction), so `rowCount === 0` with no edges is a real empty result.
876
+ * - `state: null`: a server that predates the marker; only `rowCount` can be
877
+ * used, with its `> 0` = flush window / `0` = empty ambiguity.
878
+ */
879
+ interface ServerViewMeta {
880
+ present: boolean;
881
+ /** `_00_query.rowCount`; `null` when unreadable. */
882
+ rowCount: number | null;
883
+ state: 'materializing' | 'ready' | null;
884
+ }
885
+ /** Outcome of handing a server id-set to `DataModule.updateQueryRemoteArray`. */
886
+ type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
887
+ /**
888
+ * Internal state of a live query.
889
+ */
890
+ interface QueryState {
891
+ /** The configuration for this query. */
892
+ config: QueryConfig;
893
+ /** The current cached records for this query. */
894
+ records: Record<string, any>[];
895
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
896
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
897
+ hydrated?: boolean;
898
+ /** Set once a server-side membership set has been accepted this session
899
+ * (`updateQueryRemoteArray`). The `register` down-event is enqueued before
900
+ * the instant-hydrate, so a hydrate that finishes later must not prime
901
+ * membership over the authoritative set. Ephemeral. */
902
+ serverMembership?: boolean;
903
+ /**
904
+ * Set when the server's `_00_query` row for this query went missing while
905
+ * we held membership (TTL sweep, SSP reset, scheduler wipe). The view is
906
+ * being re-registered; until a readable row comes back, empty reads are
907
+ * NOT the server's answer and nothing is dropped. Ephemeral.
908
+ */
909
+ viewLost?: boolean;
910
+ /** Last `_00_query.state` read from the server, for DevTools. Ephemeral. */
911
+ serverState?: 'materializing' | 'ready' | null;
912
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
913
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
914
+ * always emits at least once even when its records are unchanged — otherwise
915
+ * an empty re-registered window would never notify and stay "loading". */
916
+ syncNotified?: boolean;
917
+ /** Timer for TTL expiration. */
918
+ ttlTimer: NodeJS.Timeout | null;
919
+ /** TTL duration in milliseconds. */
920
+ ttlDurationMs: number;
921
+ /** When the last TTL heartbeat for this query was sent (ms epoch); `undefined` before the first. */
922
+ lastHeartbeatAt?: number;
923
+ /** Number of times the query has been updated. */
924
+ updateCount: number;
925
+ /** Timestamp (ms) of the last user-visible update, or null before the first
926
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
927
+ lastUpdatedAt: number | null;
928
+ /**
929
+ * Rolling window of the most recent materialization-step latencies (ms).
930
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
931
+ * before each persist to `_00_query`. Samples themselves are not persisted.
932
+ */
933
+ materializationSamples: number[];
934
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
935
+ lastIngestLatencyMs: number | null;
936
+ /** Cumulative count of ingest/materialization errors observed for this query. */
937
+ errorCount: number;
938
+ /**
939
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
940
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
941
+ * pulling missing records for this query, otherwise `idle`.
942
+ */
943
+ status: QueryStatus;
944
+ /**
945
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
946
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
947
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
948
+ */
949
+ phaseSamples: Record<string, number[]>;
950
+ /** Most recent sample (ms) per phase, or null. */
951
+ phaseLast: Record<string, number | null>;
952
+ /** One-shot SSP registration timings (ms). */
953
+ registrationTimings: RegistrationTimings;
954
+ }
955
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
956
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
957
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
958
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
959
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
960
+ /** One-shot registration timings (ms), captured once when a query registers. */
961
+ interface RegistrationTimings {
962
+ /** SSP surql→plan parse + permission injection. */
963
+ parseMs: number | null;
964
+ /** SSP operator-DAG build. */
965
+ planMs: number | null;
966
+ /** SSP initial snapshot evaluation. */
967
+ snapshotMs: number | null;
968
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
969
+ wallMs: number | null;
970
+ }
971
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
972
+ interface PhaseStat {
973
+ lastMs: number | null;
974
+ p50: number | null;
975
+ p90: number | null;
976
+ p99: number | null;
977
+ count: number;
978
+ }
979
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
980
+ interface QueryTimings {
981
+ ssp: PhaseStat;
982
+ sspStoreApply: PhaseStat;
983
+ sspCircuitStep: PhaseStat;
984
+ sspTransform: PhaseStat;
985
+ localFetch: PhaseStat;
986
+ remoteFetch: PhaseStat;
987
+ frontend: PhaseStat;
988
+ registration: RegistrationTimings;
989
+ updateCount: number;
990
+ errorCount: number;
991
+ }
992
+ type QueryUpdateCallback = (records: Record<string, any>[]) => void;
993
+ type QueryStatusCallback = (status: QueryStatus) => void;
994
+ /**
995
+ * Observer for a query's authority flips: `true` once server membership is
996
+ * known for it (registration, poll, durable seed), `false` when it is reset
997
+ * (bucket switch). What the bindings' `isAuthoritative()` mirrors.
998
+ */
999
+ type QueryAuthorityCallback = (known: boolean) => void;
1000
+ type MutationCallback = (mutations: MutationEvent[]) => void;
1001
+ type MutationEventType = 'create' | 'update' | 'delete';
1002
+ /**
1003
+ * Represents a mutation event (create, update, delete) to be synchronized.
1004
+ */
1005
+ interface MutationEvent {
1006
+ /** Example: 'create', 'update', or 'delete'. */
1007
+ type: MutationEventType;
1008
+ /** unique id of the mutation */
1009
+ mutation_id: RecordId<string>;
1010
+ /** The ID of the record being mutated. */
1011
+ record_id: RecordId<string>;
1012
+ /** The data payload for create/update operations. */
1013
+ data?: any;
1014
+ /** The full record data (optional context). */
1015
+ record?: any;
1016
+ /** Options for the mutation event (e.g., debounce settings). */
1017
+ options?: PushEventOptions;
1018
+ /** Timestamp when the event was created. */
1019
+ createdAt: Date;
1020
+ }
1021
+ /**
1022
+ * Options for run operations.
1023
+ */
1024
+ interface RunOptions {
1025
+ assignedTo?: string;
1026
+ max_retries?: number;
1027
+ retry_strategy?: 'linear' | 'exponential';
1028
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
1029
+ timeout?: number;
1030
+ /**
1031
+ * Minimum delay in milliseconds before the job is eligible to run. While
1032
+ * delayed the job stays pending (enqueued) and can still be killed.
1033
+ */
1034
+ delay?: number;
1035
+ }
1036
+ /**
1037
+ * Options for update operations.
1038
+ */
1039
+ interface UpdateOptions {
1040
+ /**
1041
+ * Debounce configuration for the update.
1042
+ * If boolean, enables default debounce behavior.
1043
+ */
1044
+ debounced?: boolean | DebounceOptions;
1045
+ }
1046
+ /**
1047
+ * Configuration options for debouncing updates.
1048
+ */
1049
+ interface DebounceOptions {
1050
+ /**
1051
+ * The key to use for debouncing.
1052
+ * - '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'.
1053
+ * - 'recordId_x_fields': Debounce based on record ID and specific fields.
1054
+ */
1055
+ key?: 'recordId' | 'recordId_x_fields';
1056
+ /** The debounce delay in milliseconds. */
1057
+ delay?: number;
1058
+ }
1059
+ //#endregion
1060
+ export { ServerViewMeta as A, TimingPhase as B, QueryTimings as C, RecordVersionDiff as D, RecordVersionArray as E, StorageHealthStatus as F, SealedQuery as G, LocalStore as H, StoreType as I, EventDefinition as K, SyncHealth as L, Sp00kyQueryResult as M, Sp00kyQueryResultPromise as N, RegistrationTimings as O, StorageHealth as P, SyncHealthConfig as R, QueryTimeToLive as S, ReconnectConfig as T, DatabaseEventSystem as U, UpdateOptions as V, DatabaseEventTypes as W, QueryConfigRecord as _, MATERIALIZATION_SAMPLE_WINDOW as a, QueryStatus as b, MutationEvent as c, PhaseStat as d, PinoTransmit as f, QueryConfig as g, QueryAuthorityCallback as h, Level$1 as i, Sp00kyConfig as j, RunOptions as k, MutationEventType as l, PreloadRefresh as m, DebounceOptions as n, MembershipOutcome as o, PreloadOptions as p, EventSystem as q, EventSubscriptionOptions as r, MutationCallback as s, ConnectionState as t, PersistenceClient as u, QueryHash as v, QueryUpdateCallback as w, QueryStatusCallback as x, QueryState as y, SyncHealthStatus as z };