@spooky-sync/core 0.0.1-canary.27 → 0.0.1-canary.271

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