@spooky-sync/core 0.0.1-canary.34 → 0.0.1-canary.341

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 (269) hide show
  1. package/AGENTS.md +90 -0
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2117 -142
  4. package/dist/index.js +16436 -2575
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +389 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +392 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +477 -0
  18. package/dist/types.d.ts +1917 -38
  19. package/dist/worker-edges.js +480 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +48 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +28 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +173 -0
  27. package/skills/sp00ky-core/SKILL.md +37 -7
  28. package/skills/sp00ky-core/references/config.md +7 -1
  29. package/src/boot/auth-flip.saga.test.ts +135 -0
  30. package/src/boot/auth-flip.saga.ts +77 -0
  31. package/src/boot/boot.saga.test.ts +203 -0
  32. package/src/boot/boot.saga.ts +146 -0
  33. package/src/boot/bucket-switch.saga.test.ts +189 -0
  34. package/src/boot/bucket-switch.saga.ts +136 -0
  35. package/src/boot/preload.saga.test.ts +96 -0
  36. package/src/boot/preload.saga.ts +45 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +352 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +235 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.test.ts +74 -0
  46. package/src/client/services.ts +436 -0
  47. package/src/client/sp00ky-client.test.ts +341 -0
  48. package/src/client/sp00ky-client.ts +625 -0
  49. package/src/events/events.test.ts +2 -1
  50. package/src/events/index.ts +3 -0
  51. package/src/index.ts +69 -1
  52. package/src/kernel/constants.test.ts +19 -0
  53. package/src/kernel/constants.ts +80 -0
  54. package/src/kernel/effects.test.ts +40 -0
  55. package/src/kernel/effects.ts +169 -0
  56. package/src/kernel/events.ts +57 -0
  57. package/src/kernel/interpreter.test.ts +116 -0
  58. package/src/kernel/interpreter.ts +148 -0
  59. package/src/kernel/saga.test.ts +89 -0
  60. package/src/kernel/saga.ts +73 -0
  61. package/src/live/index.test.ts +512 -0
  62. package/src/live/index.ts +1059 -0
  63. package/src/modules/app-release/index.test.ts +125 -0
  64. package/src/modules/app-release/index.ts +209 -0
  65. package/src/modules/auth/auth.local-first.test.ts +228 -0
  66. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  67. package/src/modules/auth/events/index.ts +9 -2
  68. package/src/modules/auth/impersonation-banner.ts +443 -0
  69. package/src/modules/auth/impersonation.integration.test.ts +205 -0
  70. package/src/modules/auth/impersonation.test.ts +377 -0
  71. package/src/modules/auth/impersonation.ts +179 -0
  72. package/src/modules/auth/index.ts +543 -22
  73. package/src/modules/crdt/acceptance.ts +75 -0
  74. package/src/modules/crdt/bytes.ts +50 -0
  75. package/src/modules/crdt/crdt-field.ts +125 -0
  76. package/src/modules/crdt/crdt.test.ts +515 -0
  77. package/src/modules/crdt/hash.ts +103 -0
  78. package/src/modules/crdt/index.ts +793 -0
  79. package/src/modules/crdt/loro-loader.ts +25 -0
  80. package/src/modules/crdt/mirror.ts +37 -0
  81. package/src/modules/devtools/flags.ts +349 -0
  82. package/src/modules/devtools/index.ts +748 -95
  83. package/src/modules/devtools/mutations.test.ts +92 -0
  84. package/src/modules/devtools/mutations.ts +160 -0
  85. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  86. package/src/modules/devtools/state-shape.test.ts +263 -0
  87. package/src/modules/devtools/storage-info.test.ts +79 -0
  88. package/src/modules/devtools/storage-info.ts +168 -0
  89. package/src/modules/devtools/versions.test.ts +74 -0
  90. package/src/modules/devtools/versions.ts +110 -0
  91. package/src/modules/feature-flag/index.test.ts +298 -0
  92. package/src/modules/feature-flag/index.ts +316 -0
  93. package/src/modules/ref-tables.test.ts +93 -0
  94. package/src/modules/ref-tables.ts +91 -0
  95. package/src/modules/web-push/index.test.ts +824 -0
  96. package/src/modules/web-push/index.ts +1027 -0
  97. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  98. package/src/mutation/jobs.test.ts +25 -0
  99. package/src/mutation/jobs.ts +41 -0
  100. package/src/mutation/mutation-id.test.ts +37 -0
  101. package/src/mutation/mutation-id.ts +35 -0
  102. package/src/mutation/pending-writes.integration.test.ts +175 -0
  103. package/src/mutation/push.saga.test.ts +361 -0
  104. package/src/mutation/push.saga.ts +245 -0
  105. package/src/mutation/rows.test.ts +278 -0
  106. package/src/mutation/rows.ts +499 -0
  107. package/src/mutation/tray.saga.test.ts +63 -0
  108. package/src/mutation/tray.saga.ts +48 -0
  109. package/src/mutation/write.saga.test.ts +316 -0
  110. package/src/mutation/write.saga.ts +268 -0
  111. package/src/otel/index.ts +10 -7
  112. package/src/pure.ts +66 -0
  113. package/src/push/types.ts +174 -0
  114. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  115. package/src/query/env.test.ts +23 -0
  116. package/src/query/env.ts +65 -0
  117. package/src/query/fetch.saga.test.ts +199 -0
  118. package/src/query/fetch.saga.ts +120 -0
  119. package/src/query/hash.test.ts +14 -0
  120. package/src/query/hash.ts +18 -0
  121. package/src/query/id-set-plan.test.ts +132 -0
  122. package/src/query/lifecycle.saga.test.ts +274 -0
  123. package/src/query/lifecycle.saga.ts +186 -0
  124. package/src/query/list-ref-live.integration.test.ts +203 -0
  125. package/src/query/materialize.saga.test.ts +188 -0
  126. package/src/query/materialize.saga.ts +96 -0
  127. package/src/query/materialize.test.ts +58 -0
  128. package/src/query/materialize.ts +57 -0
  129. package/src/query/membership.saga.test.ts +482 -0
  130. package/src/query/membership.saga.ts +315 -0
  131. package/src/query/membership.test.ts +151 -0
  132. package/src/query/membership.ts +234 -0
  133. package/src/query/register.saga.test.ts +312 -0
  134. package/src/query/register.saga.ts +235 -0
  135. package/src/query/render-set.test.ts +47 -0
  136. package/src/query/render-set.ts +71 -0
  137. package/src/query/session-guard.integration.test.ts +304 -0
  138. package/src/query/sql.test.ts +118 -0
  139. package/src/query/sql.ts +157 -0
  140. package/src/query/window-query.test.ts +70 -0
  141. package/src/query/window-query.ts +208 -0
  142. package/src/services/blobs/blob-cache.test.ts +359 -0
  143. package/src/services/blobs/blob-cache.ts +603 -0
  144. package/src/services/blobs/blob-manifest.ts +227 -0
  145. package/src/services/blobs/blob-store.test.ts +77 -0
  146. package/src/services/blobs/blob-store.ts +359 -0
  147. package/src/services/blobs/blob.fixture.ts +90 -0
  148. package/src/services/blobs/index.ts +70 -0
  149. package/src/services/database/cache-engine.ts +209 -0
  150. package/src/services/database/connection-supervisor.test.ts +318 -0
  151. package/src/services/database/connection-supervisor.ts +422 -0
  152. package/src/services/database/database.query-timeout.test.ts +140 -0
  153. package/src/services/database/database.responses.test.ts +43 -0
  154. package/src/services/database/database.ts +156 -61
  155. package/src/services/database/engine-factory.ts +33 -0
  156. package/src/services/database/errors.ts +34 -0
  157. package/src/services/database/events/index.ts +2 -1
  158. package/src/services/database/index.ts +7 -0
  159. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  160. package/src/services/database/local-migrator.integration.test.ts +110 -0
  161. package/src/services/database/local-migrator.ts +61 -16
  162. package/src/services/database/local.test.ts +150 -0
  163. package/src/services/database/local.ts +508 -63
  164. package/src/services/database/plan-render.test.ts +159 -0
  165. package/src/services/database/plan-render.ts +108 -0
  166. package/src/services/database/relation-resolver.test.ts +484 -0
  167. package/src/services/database/relation-resolver.ts +0 -0
  168. package/src/services/database/remote.ts +285 -6
  169. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  170. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  171. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  172. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  173. package/src/services/database/sqlite-column-reset.ts +91 -0
  174. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  175. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  176. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  177. package/src/services/database/sqlite-lock-verify.ts +45 -0
  178. package/src/services/database/sqlite-open.test.ts +150 -0
  179. package/src/services/database/sqlite-open.ts +164 -0
  180. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  181. package/src/services/database/sqlite-plan-sql.ts +196 -0
  182. package/src/services/database/sqlite-projection.test.ts +121 -0
  183. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  184. package/src/services/database/sqlite-select.test.ts +261 -0
  185. package/src/services/database/sqlite-select.ts +131 -0
  186. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  187. package/src/services/database/sqlite-transport.ts +224 -0
  188. package/src/services/database/sqlite-worker.ts +437 -0
  189. package/src/services/database/surql-translate.ts +417 -0
  190. package/src/services/database/surreal-cache-engine.ts +163 -0
  191. package/src/services/logger/index.test.ts +132 -0
  192. package/src/services/logger/index.ts +189 -7
  193. package/src/services/persistence/localstorage.ts +2 -2
  194. package/src/services/persistence/resilient.ts +10 -3
  195. package/src/services/persistence/surrealdb.ts +4 -4
  196. package/src/services/stream-processor/index.ts +806 -67
  197. package/src/services/stream-processor/permissions.test.ts +47 -0
  198. package/src/services/stream-processor/permissions.ts +53 -0
  199. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  200. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  201. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  202. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  203. package/src/services/stream-processor/wasm-types.ts +58 -2
  204. package/src/services/tabs/broker-client.ts +284 -0
  205. package/src/services/tabs/broker.test.ts +381 -0
  206. package/src/services/tabs/coordinator.test.ts +386 -0
  207. package/src/services/tabs/coordinator.ts +646 -0
  208. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  209. package/src/services/tabs/leader-locks.ts +75 -0
  210. package/src/services/tabs/protocol.ts +262 -0
  211. package/src/services/tabs/support.ts +36 -0
  212. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  213. package/src/sp00ky.ts +5 -395
  214. package/src/state/client-state.ts +216 -0
  215. package/src/state/lifecycle.test.ts +184 -0
  216. package/src/state/lifecycle.ts +127 -0
  217. package/src/state/reducers.test.ts +319 -0
  218. package/src/state/reducers.ts +550 -0
  219. package/src/state/selectors.test.ts +188 -0
  220. package/src/state/selectors.ts +259 -0
  221. package/src/sw/index.test.ts +582 -0
  222. package/src/sw/index.ts +607 -0
  223. package/src/sw/store.ts +96 -0
  224. package/src/sync/connection.saga.test.ts +97 -0
  225. package/src/sync/connection.saga.ts +89 -0
  226. package/src/sync/live.saga.test.ts +229 -0
  227. package/src/sync/live.saga.ts +116 -0
  228. package/src/sync/policy.health.test.ts +56 -0
  229. package/src/sync/policy.test.ts +663 -0
  230. package/src/sync/policy.ts +515 -0
  231. package/src/sync/poll.saga.test.ts +51 -0
  232. package/src/sync/poll.saga.ts +36 -0
  233. package/src/sync/tabs.saga.test.ts +78 -0
  234. package/src/sync/tabs.saga.ts +96 -0
  235. package/src/testing/adapters.ts +137 -0
  236. package/src/testing/build.ts +63 -0
  237. package/src/testing/fake-services.ts +63 -0
  238. package/src/testing/run-pure.test.ts +92 -0
  239. package/src/testing/run-pure.ts +128 -0
  240. package/src/testing/services.ts +17 -0
  241. package/src/types.ts +661 -10
  242. package/src/utils/blurhash.ts +90 -0
  243. package/src/utils/edges.ts +57 -0
  244. package/src/utils/error-classification.test.ts +105 -0
  245. package/src/utils/error-classification.ts +64 -0
  246. package/src/utils/index.ts +89 -12
  247. package/src/utils/parser.test.ts +67 -102
  248. package/src/utils/parser.ts +64 -2
  249. package/src/utils/semver.test.ts +32 -0
  250. package/src/utils/semver.ts +30 -0
  251. package/src/utils/sha256.ts +15 -0
  252. package/src/utils/surql.ts +29 -18
  253. package/src/utils/utils.test.ts +3 -2
  254. package/tsdown.config.ts +117 -3
  255. package/vitest.config.ts +48 -0
  256. package/src/modules/cache/index.ts +0 -241
  257. package/src/modules/cache/types.ts +0 -19
  258. package/src/modules/data/data.test.ts +0 -58
  259. package/src/modules/data/index.ts +0 -879
  260. package/src/modules/sync/engine.ts +0 -173
  261. package/src/modules/sync/events/index.ts +0 -77
  262. package/src/modules/sync/index.ts +0 -3
  263. package/src/modules/sync/queue/index.ts +0 -2
  264. package/src/modules/sync/queue/queue-down.ts +0 -89
  265. package/src/modules/sync/queue/queue-up.ts +0 -223
  266. package/src/modules/sync/scheduler.ts +0 -84
  267. package/src/modules/sync/sync.ts +0 -421
  268. package/src/modules/sync/utils.test.ts +0 -311
  269. package/src/modules/sync/utils.ts +0 -167
package/dist/types.d.ts CHANGED
@@ -1,7 +1,142 @@
1
- import { RecordId } from "surrealdb";
2
- import { RecordId as RecordId$1, SchemaStructure } from "@spooky-sync/query-builder";
1
+ import { AccessDefinition, ColumnSchema, QueryPlan, QueryPlan as QueryPlan$1, RecordId, SchemaStructure, TypeNameToTypeMap, WhereNode } from "@spooky-sync/query-builder";
2
+ import { RecordId as RecordId$1, Surreal, SurrealEvents, SurrealTransaction } from "surrealdb";
3
3
  import { Level, Level as Level$1, Logger, LoggerOptions } from "pino";
4
4
 
5
+ //#region src/modules/auth/impersonation.d.ts
6
+
7
+ /**
8
+ * Admin impersonation, client side.
9
+ *
10
+ * The server does the enforcing (see `impersonation_remote.surql` in the CLI):
11
+ * an admin calls `fn::_00_impersonate::start`, receives a token for the
12
+ * `_00_impersonate` access method, and authenticates with it, so `$auth.id` is
13
+ * the target user. Everything here is state and timers around that:
14
+ *
15
+ * - the admin's own token is kept under {@link ORIGIN_TOKEN_KEY} so Stop (and a
16
+ * reload in between) can return to it;
17
+ * - the impersonation state is derived from the token's claims, never stored
18
+ * separately, so it cannot disagree with the session actually in use;
19
+ * - the token is re-signed before it expires, and the session is polled so a
20
+ * stop or revocation made elsewhere reaches an open WebSocket quickly.
21
+ */
22
+ /** Access method impersonation tokens are issued for. */
23
+ declare const IMPERSONATION_ACCESS = "_00_impersonate";
24
+ /** Persistence key holding the admin's own token while impersonating. */
25
+ declare const ORIGIN_TOKEN_KEY = "sp00ky_auth_token_origin";
26
+ /** How often an active impersonation re-checks its session on the server. */
27
+ declare const SESSION_POLL_MS = 60000;
28
+ interface ImpersonationInfo {
29
+ /** `_00_impersonation:<id>` the session is bound to. */
30
+ session: string;
31
+ /** Record id being impersonated. */
32
+ target: string;
33
+ /** Record id of the admin. */
34
+ admin: string;
35
+ /** When the current token expires (it is renewed before then). */
36
+ tokenExpiresAt: Date | null;
37
+ }
38
+ interface TokenClaims {
39
+ access: string | null;
40
+ userId: string | null;
41
+ exp: number | null;
42
+ impersonation: {
43
+ session: string;
44
+ admin: string;
45
+ } | null;
46
+ }
47
+ /**
48
+ * Read the claims of a SurrealDB record-access JWT WITHOUT verifying it. The
49
+ * server still enforces the token on every request; this is only so the client
50
+ * can act on what it already holds before a round trip completes.
51
+ *
52
+ * Returns nulls on any malformed input.
53
+ */
54
+ declare function decodeTokenClaims(token: string): TokenClaims;
55
+ /** The impersonation a token represents, or null for a regular session. */
56
+ declare function impersonationFromToken(token: string | null): ImpersonationInfo | null;
57
+ /** Same impersonation, for change detection (renewals only move the expiry). */
58
+ declare function sameImpersonation(a: ImpersonationInfo | null, b: ImpersonationInfo | null): boolean;
59
+ /**
60
+ * When to renew a token expiring at `expSecs`: at 80% of its remaining life,
61
+ * never sooner than 5s from now, and immediately once it is inside that.
62
+ */
63
+ declare function renewDelayMs(expSecs: number, nowMs: number): number;
64
+ interface ImpersonationTimerHost {
65
+ /** Current impersonation, or null. */
66
+ current(): ImpersonationInfo | null;
67
+ /** Re-sign the token. Rejects when the session has ended. */
68
+ renew(): Promise<void>;
69
+ /** Whether the server still considers the session live. */
70
+ stillActive(): Promise<boolean>;
71
+ /** Leave the impersonation because the server ended it. */
72
+ endedRemotely(reason: string): Promise<void>;
73
+ /** Whether a failure was a reachability problem (retry) rather than an answer. */
74
+ isNetworkError(error: unknown): boolean;
75
+ }
76
+ /**
77
+ * The two timers an active impersonation needs. `sync()` is called whenever
78
+ * the auth state changes and arms or clears them to match.
79
+ */
80
+ declare class ImpersonationTimers {
81
+ private host;
82
+ private renewTimer;
83
+ private pollTimer;
84
+ private armedFor;
85
+ constructor(host: ImpersonationTimerHost);
86
+ sync(): void;
87
+ clear(): void;
88
+ private renew;
89
+ private poll;
90
+ }
91
+ //#endregion
92
+ //#region src/modules/auth/impersonation-banner.d.ts
93
+ /**
94
+ * Restyling of the built-in banner. Every field is optional; anything unset
95
+ * keeps the default. Colours are plain CSS values, so a project can pass its
96
+ * own tokens (`var(--brand-warning)`) as long as they resolve at the document
97
+ * level.
98
+ */
99
+ interface ImpersonationBannerTheme {
100
+ /** Height of the warning bar above the page. */
101
+ heightPx?: number;
102
+ /** Gutter left, right and below the page. `0` frames only from the top. */
103
+ insetPx?: number;
104
+ /** Radius of the framed page's corners. `0` squares them off. */
105
+ radiusPx?: number;
106
+ /** The backdrop behind the page. Any CSS `background` value. */
107
+ background?: string;
108
+ /** Colour of the warning text on the backdrop. */
109
+ text?: string;
110
+ /** Background of the Stop button. */
111
+ accent?: string;
112
+ /** Text colour of the Stop button. */
113
+ accentText?: string;
114
+ /** Label for the Stop button. Defaults to `Stop`. */
115
+ stopLabel?: string;
116
+ /** The warning sentence. Defaults to `Impersonating <target> as <admin>`.
117
+ * Wrap a run in `**` to emphasise it; the result is text, never markup. */
118
+ label?: (info: ImpersonationInfo) => string;
119
+ /** Keep the bar but leave the page's own layout completely alone. The CSS
120
+ * variable is still published, so the app can do its own offset. */
121
+ noPageShift?: boolean;
122
+ }
123
+ interface ImpersonationBannerConfig {
124
+ /**
125
+ * - `'default'` renders the built-in banner.
126
+ * - `'custom'` leaves the page alone so the app can render its own from
127
+ * `useImpersonation()` / `auth.subscribeImpersonation`. Acknowledge it
128
+ * with `client.acknowledgeImpersonationBanner()` while it is on screen;
129
+ * if nothing acknowledges within {@link CUSTOM_BANNER_GRACE_MS}, the
130
+ * built-in banner appears, on the assumption that the custom one failed
131
+ * to render rather than that nobody should be warned.
132
+ * - `'none'` renders nothing, ever. The app takes over responsibility for
133
+ * telling whoever is looking at the page that it is not their session.
134
+ */
135
+ mode?: 'default' | 'custom' | 'none';
136
+ /** Restyle the built-in banner (also used if `custom` falls back). */
137
+ theme?: ImpersonationBannerTheme;
138
+ }
139
+ //#endregion
5
140
  //#region src/events/index.d.ts
6
141
  /**
7
142
  * Utility type to define the payload structure of an event.
@@ -123,35 +258,1151 @@ declare class EventSystem<E extends EventTypeMap> {
123
258
  private broadcastEvent;
124
259
  }
125
260
  //#endregion
261
+ //#region src/utils/surql.d.ts
262
+ interface SealedQuery<T = void> {
263
+ readonly sql: string;
264
+ readonly extract: (results: unknown[]) => T;
265
+ }
266
+ //#endregion
267
+ //#region src/services/database/events/index.d.ts
268
+ declare const DatabaseEventTypes: {
269
+ readonly LocalQuery: "DATABASE_LOCAL_QUERY";
270
+ readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
271
+ };
272
+ interface DatabaseQueryEventPayload {
273
+ query: string;
274
+ vars?: Record<string, unknown>;
275
+ duration: number;
276
+ success: boolean;
277
+ error?: string;
278
+ timestamp: number;
279
+ }
280
+ type DatabaseEventTypeMap = {
281
+ [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
282
+ [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
283
+ };
284
+ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
285
+ //#endregion
286
+ //#region src/modules/devtools/storage-info.d.ts
287
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
288
+ interface EngineStorageDiagnostics {
289
+ engine: 'sqlite';
290
+ bucketId: string;
291
+ useOpfs: boolean;
292
+ workerSelectConfigured: boolean;
293
+ /** `false` while configured `true` means the runtime downgraded to the
294
+ * legacy multi-hop select (stale cached worker bundle). */
295
+ workerSelectEffective: boolean;
296
+ /** page_count * page_size. */
297
+ dbSizeBytes?: number;
298
+ /** freelist_count * page_size — reclaimable via VACUUM. */
299
+ freelistBytes?: number;
300
+ tableCounts?: {
301
+ table: string;
302
+ rows: number;
303
+ }[];
304
+ error?: string;
305
+ }
306
+ /**
307
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
308
+ * configured (apps that never asked for it get `null`, so the panel shows
309
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
310
+ * app asked to share one store and this tab is not, so it owns or contends for
311
+ * the OPFS pool alone.
312
+ */
313
+ //#endregion
314
+ //#region src/services/database/cache-engine.d.ts
315
+ /**
316
+ * A materialized row. Keys are field names; values are already decoded to the
317
+ * client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
318
+ * every backend hands `DataModule` the same shape SurrealDB does today.
319
+ */
320
+ type Row = Record<string, unknown>;
321
+ /** A record identifier — a `RecordId` or its stable string form (`table:id`). */
322
+ type Id = unknown;
323
+ /** How an order clause is expressed everywhere in the engine layer. */
324
+ type OrderBy = [field: string, direction: 'asc' | 'desc'][];
325
+ /**
326
+ * Batched relation fetch: "give me every row of `table` whose `matchField` is
327
+ * one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
328
+ * primitive relation decomposition (§3) leans on — implemented as
329
+ * `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
330
+ * `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
331
+ * here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
332
+ */
333
+ interface RelationFetch {
334
+ table: string;
335
+ matchField: string;
336
+ keys: Id[];
337
+ where?: WhereNode[];
338
+ orderBy?: OrderBy;
339
+ select?: string[];
340
+ }
341
+ /**
342
+ * The read side of an engine, minus relation resolution — the surface a
343
+ * {@link RelationResolver} needs. Kept separate so the resolver can be unit
344
+ * tested against an in-memory fake without a full engine.
345
+ */
346
+ interface RowFetcher {
347
+ /** Batched fan-out fetch. See {@link RelationFetch}. */
348
+ fetchRelation(req: RelationFetch): Promise<Row[]>;
349
+ }
350
+ /** A transaction handle — the same verbs as the engine, but atomic. */
351
+ interface EngineTx {
352
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
353
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
354
+ delete(table: string, id: Id): Promise<void>;
355
+ }
356
+ /**
357
+ * A pluggable local cache backend. SurrealDB (the default) and SQLite both
358
+ * implement this; the rest of the client talks verbs, never SurrealQL.
359
+ *
360
+ * Reactivity is NOT part of this contract: the local cache is passive. The SSP
361
+ * (remote) drives change; `DataModule` writes rows here and re-reads them. The
362
+ * `epoch` field preserves the existing bucket-switch fencing (see
363
+ * `LocalDatabaseService.epoch`): an async chain captures it at start and its
364
+ * write is dropped if the epoch moved (a bucket switch) in between.
365
+ */
366
+ interface LocalCacheEngine extends RowFetcher {
367
+ /** Monotonic store generation; bumped on every bucket switch. */
368
+ readonly epoch: number;
369
+ connect(bucketId: string): Promise<void>;
370
+ switchBucket(bucketId: string): Promise<void>;
371
+ close(): Promise<void>;
372
+ /** Run `fn` inside a single atomic transaction. */
373
+ transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
374
+ /**
375
+ * Materialize a query, including its `.related()` tree (via §3
376
+ * decomposition). Params bind `where` `paramRef`s and any windowing id-set.
377
+ */
378
+ select(plan: QueryPlan$1, params?: Record<string, unknown>): Promise<Row[]>;
379
+ /** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
380
+ selectByIds(table: string, ids: Id[], opts?: {
381
+ select?: string[];
382
+ orderBy?: OrderBy;
383
+ }): Promise<Row[]>;
384
+ /** Single-record read by primary id, or `null`. */
385
+ getById(table: string, id: Id): Promise<Row | null>;
386
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
387
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
388
+ delete(table: string, id: Id): Promise<void>;
389
+ }
390
+ /**
391
+ * The full surface the client's `this.local` field depends on: the
392
+ * engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
393
+ * SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
394
+ * `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
395
+ * `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
396
+ * either can back `this.local`.
397
+ *
398
+ * `getClient()` returns the underlying SurrealDB `Surreal` handle where one
399
+ * exists (SurrealDB backend); backends without one (SQLite) throw — it is only
400
+ * used by advanced/DevTools paths, never on the hot path.
401
+ */
402
+ interface LocalStore extends LocalCacheEngine {
403
+ /**
404
+ * Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
405
+ * `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
406
+ * schemaless engines (SQLite creates tables lazily) → false, so the client
407
+ * skips the `LocalMigrator` entirely for them.
408
+ */
409
+ readonly usesSurqlSchema: boolean;
410
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>, opts?: {
411
+ epoch?: number;
412
+ }): Promise<T>;
413
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: {
414
+ epoch?: number;
415
+ }): Promise<T>;
416
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
417
+ switchStore(bucketId: string): Promise<void>;
418
+ beginSwitch(): () => void;
419
+ getEvents(): DatabaseEventSystem;
420
+ getClient(): unknown;
421
+ getConfig(): Sp00kyConfig<any>['database'];
422
+ readonly currentBucketId: string;
423
+ /** Which built-in backend this is. OPTIONAL: absent (custom engines) is
424
+ * reported as `'custom'` by DevTools. More robust than `instanceof` for
425
+ * engines constructed outside this package. */
426
+ readonly engineKind?: 'surrealdb' | 'sqlite';
427
+ /** Engine-specific storage numbers for DevTools (DB file size, per-table
428
+ * row counts). OPTIONAL: only engines with something to report implement it. */
429
+ getStorageDiagnostics?(opts?: {
430
+ tableCounts?: boolean;
431
+ }): Promise<EngineStorageDiagnostics>;
432
+ /**
433
+ * Durability of this engine's local store. OPTIONAL: engines that don't
434
+ * report it (SurrealDB, custom engines) are treated as `'unknown'` by the
435
+ * client facade, so adding this needs no change on their side.
436
+ */
437
+ readonly storageHealth?: StorageHealth;
438
+ /**
439
+ * Delete a bucket's persisted store. Never the open one. OPTIONAL and
440
+ * best-effort: used to remove an impersonated user's data from the admin's
441
+ * device once the impersonation ends.
442
+ */
443
+ dropBucket?(bucketId: string): Promise<void>;
444
+ /** Fires immediately with the current snapshot, then on every change.
445
+ * Returns an unsubscribe function. */
446
+ subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
447
+ /**
448
+ * Every cached row's `(id, _00_rv)` per table, ids in stable `table:id`
449
+ * form. The in-browser circuit primes and reconciles itself from this on
450
+ * boot instead of re-downloading the working set. OPTIONAL: an engine
451
+ * without it boots the circuit empty, as before.
452
+ */
453
+ scanVersions?(tables: string[]): Promise<Record<string, [string, number][]>>;
454
+ /**
455
+ * Reset the cached `_00_rv` of every table whose column set (`fingerprints`,
456
+ * see `columnFingerprints`) changed since the store last recorded it, except
457
+ * the rows in `keep`, and record the new sets. Returns the tables reset.
458
+ * For engines that keep bodies across schema changes: a body landed under an
459
+ * older schema lacks the columns it did not know, at the server's version,
460
+ * and would never be fetched again. OPTIONAL: an engine that rebuilds its
461
+ * store on a schema change (SurrealDB) does not need it.
462
+ */
463
+ resetChangedTables?(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]>;
464
+ /**
465
+ * Circuit snapshot storage, keyed. Lives in the same durable store as the
466
+ * rows (OPFS SQLite), so it is per-bucket by construction, atomic, and
467
+ * readable by follower tabs over the port transport. OPTIONAL: an engine
468
+ * without it primes from `scanVersions` alone.
469
+ */
470
+ getSnapshot?(key: string): Promise<StoredSnapshot | null>;
471
+ putSnapshot?(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void>;
472
+ deleteSnapshot?(key: string): Promise<void>;
473
+ }
474
+ /** Describes a stored circuit snapshot; what decides whether it is usable. */
475
+ interface SnapshotMeta {
476
+ /** Bump when the wire shape the circuit reads changes. */
477
+ formatVersion: number;
478
+ /** Hash of the schema the rows were projected under. */
479
+ schemaHash: string;
480
+ savedAt: number;
481
+ /** Highest `_00_rv` per table at save time (diagnostics). */
482
+ maxRv?: Record<string, number>;
483
+ [key: string]: unknown;
484
+ }
485
+ interface StoredSnapshot {
486
+ bytes: Uint8Array;
487
+ meta: SnapshotMeta;
488
+ }
489
+ /** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
490
+ type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
491
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
492
+ * a guard against a cyclic schema producing unbounded fan-out. */
493
+ //#endregion
126
494
  //#region src/services/logger/index.d.ts
127
495
  type Logger$1 = Logger;
496
+ /** One line the logger wrote, as the DevTools Logs tab and the MCP read it. */
497
+ interface CapturedLog {
498
+ /** Monotonic for the page's lifetime; a reader resumes after the last one it holds. */
499
+ seq: number;
500
+ time: number;
501
+ /** Pino's numeric level: 10 trace … 60 fatal. */
502
+ level: number;
503
+ msg: string;
504
+ /** The whole log object as JSON (what the console printed), capped at {@link LogTap.LINE_MAX}. */
505
+ line: string;
506
+ }
507
+ interface LogRead {
508
+ entries: CapturedLog[];
509
+ /** `seq` of the newest captured line; pass it back as `after` to resume. */
510
+ head: number;
511
+ /** Lines after `after` the ring overwrote before they were read (cleared ones excluded). */
512
+ dropped: number;
513
+ consoleLevel: Level;
514
+ captureLevel: Level;
515
+ }
516
+ /**
517
+ * JSON for a log object that can never throw into the call site: Errors keep
518
+ * their message and stack (plain `JSON.stringify` prints `{}`), bigints become
519
+ * strings, and a cycle prints `[Circular]` instead of throwing.
520
+ */
521
+
522
+ /**
523
+ * The page-side log buffer behind the DevTools Logs tab. Always on and
524
+ * bounded: a line costs the JSON the console write produces anyway, and a
525
+ * panel opened after boot still sees the boot.
526
+ *
527
+ * It also owns the logger's level. The console prints at the configured level
528
+ * only; `setCaptureLevel` changes what is RECORDED (debug without flooding the
529
+ * console), live on every child logger, and keeps it for this tab's session so
530
+ * a reload captures its boot at that level too.
531
+ */
532
+ declare class LogTap {
533
+ readonly consoleLevel: Level;
534
+ static readonly CAPACITY = 500;
535
+ static readonly LINE_MAX = 4000;
536
+ private readonly ring;
537
+ private seq;
538
+ /** `seq` at the last `clear()`: lines up to here are gone on purpose, not dropped. */
539
+ private clearedThrough;
540
+ private readonly listeners;
541
+ private readonly loggers;
542
+ private captureLevelValue;
543
+ constructor(consoleLevel: Level);
544
+ /** `seq` of the newest captured line. */
545
+ get head(): number;
546
+ get captureLevel(): Level;
547
+ /** What pino has to produce for both the console and the buffer. */
548
+ get effectiveLevel(): Level;
549
+ /** Whether the console prints a line at this numeric level. */
550
+ printsToConsole(level: number): boolean;
551
+ /** Remember a logger (the root and every child) so a level change reaches it. */
552
+ track(logger: Logger$1): void;
553
+ setCaptureLevel(level: Level): void;
554
+ record(o: Record<string, unknown>, line: string): void;
555
+ /** Lines after `after` (0 = everything still buffered), oldest first. */
556
+ read(after?: number, limit?: number): LogRead;
557
+ clear(): void;
558
+ /** Called synchronously inside the log call: keep it cheap, never log from it. */
559
+ subscribe(cb: () => void): () => void;
560
+ }
128
561
  //#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;
562
+ //#region src/services/database/database.d.ts
563
+ declare abstract class AbstractDatabaseService {
564
+ protected client: Surreal;
565
+ protected logger: Logger$1;
566
+ protected events: DatabaseEventSystem;
567
+ /**
568
+ * Per-query deadline in ms; `0` disables. The remote service sets it from
569
+ * `queryTimeoutMs` (see `RemoteDatabaseService`), the local one from
570
+ * `localOpTimeoutMs` (see `LocalDatabaseService`): a local query can be
571
+ * legitimately slow, but it must never be endless - every query waits on the
572
+ * previous link of {@link query}'s chain, and one that never settled wedged
573
+ * every later local op behind it.
574
+ */
575
+ protected queryTimeoutMs: number;
576
+ /** The error a deadline expiry rejects with; the local service substitutes
577
+ * its typed `LocalOpTimeoutError`. "timed out" in the message is
578
+ * load-bearing either way: `classifySyncError` keys off it. */
579
+ protected timeoutError(_query: string): Error;
580
+ protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
581
+ constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
582
+ abstract connect(): Promise<void>;
583
+ getClient(): Surreal;
584
+ getEvents(): DatabaseEventSystem;
585
+ tx(): Promise<SurrealTransaction>;
586
+ /**
587
+ * How many statements may be in flight at once.
588
+ *
589
+ * `1` serializes every statement behind the previous one. The local engines
590
+ * need that: overlapping ops trip the WASM / SQLite transaction layer. The
591
+ * remote service raises it (`RemoteDatabaseService`): a SurrealDB socket
592
+ * multiplexes requests by id, and serializing them capped the client at one
593
+ * statement per round trip (~5/s at 170ms RTT), so the `_00_list_ref` poll
594
+ * alone could hold every registration behind it and one slow one-shot read
595
+ * stalled the whole client. The scheduler's `MAX_CONCURRENT_DOWN` only means
596
+ * something when this is above 1.
597
+ */
598
+ protected maxConcurrentQueries: number;
599
+ private inFlightQueries;
600
+ private queryWaiters;
601
+ /** FIFO slot acquisition, so `maxConcurrentQueries = 1` keeps strict order. */
602
+ private acquireQuerySlot;
603
+ private releaseQuerySlot;
604
+ /**
605
+ * Resolve once every statement issued before this call has settled: take
606
+ * every slot (FIFO, so earlier statements go first), then hand them back.
607
+ * Bounded by {@link queryTimeoutMs}, like the statements it waits on.
608
+ */
609
+ protected drainStatements(): Promise<void>;
610
+ /**
611
+ * Hook run right before a statement is sent, inside its slot. The remote
612
+ * service uses it to hold statements while a connect is in flight, so a
613
+ * query never runs on a socket that is open but has not had its namespace
614
+ * and token applied yet. The default does nothing.
615
+ */
616
+ protected beforeQuery(): Promise<void>;
617
+ /**
618
+ * Execute a statement under {@link maxConcurrentQueries}.
619
+ *
620
+ * A statement that never settles would hold its slot forever, and with a
621
+ * limit of 1 that blocks every later statement behind it. {@link
622
+ * queryTimeoutMs} bounds each one: on expiry this promise rejects and the
623
+ * slot is released, even though the underlying RPC is still parked in the
624
+ * SDK's pending map.
625
+ */
626
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
627
+ /**
628
+ * Like {@link query} but never rejects on a statement error: every
629
+ * statement answers on its own as `{ status: 'OK', result }` or
630
+ * `{ status: 'ERR', error }`. This is what lets a batched outbox push judge
631
+ * each mutation separately.
632
+ */
633
+ queryResponses(query: string, vars?: Record<string, unknown>): Promise<Array<{
634
+ status: 'OK';
635
+ result: unknown;
636
+ } | {
637
+ status: 'ERR';
638
+ error: string;
639
+ }>>;
640
+ private runStatement;
641
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
642
+ close(): Promise<void>;
643
+ }
644
+ //#endregion
645
+ //#region src/services/database/remote.d.ts
646
+ /** Transport events the SDK publishes, mapped 1:1 to {@link ConnectionState}. */
647
+ type RemoteConnectionEvent = ConnectionState | 'error';
648
+ declare class RemoteDatabaseService extends AbstractDatabaseService {
649
+ private config;
650
+ protected eventType: "DATABASE_REMOTE_QUERY";
651
+ private readonly reconnectConfig;
652
+ /**
653
+ * In-flight `connect()`, so concurrent callers (boot + supervisor revive +
654
+ * an `online` event landing at the same moment) share one attempt instead of
655
+ * racing two sockets. Cleared on settle, so a later call always reconnects.
656
+ */
657
+ private connecting;
658
+ /**
659
+ * The token to re-authenticate a freshly opened socket with, kept current by
660
+ * {@link setAuthToken}.
661
+ *
662
+ * `config.token` is fixed at construction and most apps never set it: they
663
+ * sign in later, which authenticates the socket that happens to be open at
664
+ * the time. That is enough for the SDK's OWN reconnects (it replays
665
+ * `version`/`use`/`authenticate` itself), but not for the supervisor's revive
666
+ * loop, which builds a socket from scratch. Without this the revived socket
667
+ * came back UNAUTHENTICATED and stayed that way for the life of the page,
668
+ * while the client's `currentUserId` — restored from local storage — kept
669
+ * reporting the user as signed in.
670
+ *
671
+ * The visible damage is silent and total: `fn::query::register` sends
672
+ * `<string>($auth.id OR '')`, so every view registered afterwards is stamped
673
+ * with an empty identity, and every `$auth.id` predicate in it resolves
674
+ * false. Public tables keep returning rows while everything owned by the user
675
+ * returns nothing, on a page that still looks signed in.
676
+ */
677
+ private authToken;
678
+ /**
679
+ * Every `session::id()` this page's sockets have had, oldest first.
680
+ *
681
+ * The server stamps a view's `subscribers` entry with the session that
682
+ * registered or heartbeated it, and every socket (an SDK reconnect, a
683
+ * supervisor revive) is a new session. The pagehide release goes over HTTP,
684
+ * whose own session id matches none of them, so it names these instead. Kept
685
+ * for the page, not the socket: a view registered before a reconnect still
686
+ * carries the old id until its next heartbeat.
687
+ *
688
+ * The anonymous LIVE filters on the same ids (see `listRefLive`): its edges
689
+ * name the socket that registered their view, which may be an earlier one.
690
+ * A reload hands its ids to the next page with the salt.
691
+ */
692
+ private sessionIdsSeen;
693
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
694
+ /** See {@link sessionIdsSeen}. */
695
+ sessionIds(): readonly string[];
696
+ /**
697
+ * Take on the session ids of the page this one reloaded from. It kept that
698
+ * page's salt, so the views it re-registers still carry edges stamped by
699
+ * those sockets. Older than anything this page has seen, so they go first.
700
+ */
701
+ adoptSessionIds(ids: ReadonlyArray<string>): void;
702
+ /**
703
+ * Ask the socket that just connected for its session id. Straight to the
704
+ * SDK: it needs no namespace or identity, so it need not wait behind an
705
+ * in-flight connect or take a slot from the query queue.
706
+ */
707
+ private recordSessionId;
708
+ getConfig(): Sp00kyConfig<any>['database'];
709
+ /**
710
+ * Send one SurrealQL statement so that it survives the page going away.
711
+ *
712
+ * A WebSocket `send()` during `pagehide` is not guaranteed to flush — the
713
+ * browser may tear the socket down first, and the frame is simply lost.
714
+ * Measured: an unload-time release over the live socket reached the server
715
+ * zero times out of one. `fetch` with `keepalive` is the primitive the
716
+ * platform actually guarantees here, so this goes over SurrealDB's HTTP
717
+ * `/sql` endpoint instead of the RPC socket.
718
+ *
719
+ * Best-effort by design: no await, no retry, errors swallowed. Every caller
720
+ * must have a server-side fallback that makes a lost beacon a non-event.
721
+ *
722
+ * The statement runs in a fresh HTTP session: `session::id()` there is a new
723
+ * id, not this page's socket's, so anything keyed on it must be passed the
724
+ * ids from {@link sessionIds} instead.
725
+ */
726
+ beaconSql(sql: string): void;
727
+ /**
728
+ * Record the token every future connect should authenticate with, or `null`
729
+ * on sign-out. See {@link authToken}.
730
+ *
731
+ * Does not touch the CURRENT socket: callers authenticate that themselves
732
+ * (sign-in and session restore both already do). This only makes the next
733
+ * from-scratch connect reproduce that state.
734
+ */
735
+ setAuthToken(token: string | null): void;
736
+ /** The token the session is signed in with (or the configured one), for
737
+ * calls that leave the socket: `r2` bucket files go to the SSP over HTTP. */
738
+ getAuthToken(): string | null;
739
+ /** Resolved reconnect tunables; the supervisor reads its own knobs here. */
740
+ getReconnectConfig(): Required<ReconnectConfig>;
741
+ /** Current transport state as reported by the SDK. */
742
+ getStatus(): ConnectionState;
743
+ /**
744
+ * Observe transport events. Thin passthrough so callers (the supervisor,
745
+ * sync, CRDT) don't have to reach through `getClient()`.
746
+ */
747
+ subscribeConnection<K extends RemoteConnectionEvent>(event: K, cb: (...payload: SurrealEvents[K]) => void): () => void;
748
+ /**
749
+ * Tear the socket down on purpose. Used by the heartbeat watchdog when a
750
+ * socket stops answering but never closes: `close()` makes the SDK publish
751
+ * `disconnected`, which is what drives the supervisor's revive loop.
752
+ */
753
+ forceClose(): Promise<void>;
754
+ /** Resolve once no connect is in flight, for calls that go to the SDK
755
+ * client directly (sign-in, sign-up) and so skip `beforeQuery`. */
756
+ whenConnected(): Promise<void>;
757
+ /**
758
+ * Hold statements while a connect is in flight.
759
+ *
760
+ * `connect()` opens the socket, then selects the namespace/database, then
761
+ * authenticates - three round trips. The SDK considers the connection ready
762
+ * after the first, so a query queued during the other two ran on a socket
763
+ * with no namespace ("Specify a namespace to use") or, worse, no identity.
764
+ * Seen 2026-09-06 after the supervisor rebuilt a socket: a collection
765
+ * recount failed with exactly that error. Waiting on the in-flight connect
766
+ * costs nothing when no connect is running; a failed connect is not
767
+ * swallowed here - the query then fails on its own, as before.
768
+ */
769
+ protected beforeQuery(): Promise<void>;
770
+ /**
771
+ * Open (or re-open) the remote connection.
772
+ *
773
+ * Safe to call repeatedly: concurrent calls share the in-flight attempt, and
774
+ * a call after a `disconnected` builds a fresh socket. `use()` and
775
+ * `authenticate()` are re-applied here for the cold path; the SDK also
776
+ * replays them itself on its own internal reconnects.
777
+ */
778
+ connect(): Promise<void>;
779
+ private doConnect;
780
+ signin(params: any): Promise<any>;
781
+ signup(params: any): Promise<any>;
782
+ authenticate(token: string): Promise<any>;
783
+ invalidate(): Promise<void>;
784
+ }
785
+ //#endregion
786
+ //#region src/modules/auth/events/index.d.ts
787
+ declare const AuthEventTypes: {
788
+ readonly AuthStateChanged: "AUTH_STATE_CHANGED";
789
+ readonly ImpersonationChanged: "IMPERSONATION_CHANGED";
138
790
  };
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;
791
+ type AuthEventTypeMap = {
792
+ [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
793
+ [AuthEventTypes.ImpersonationChanged]: EventDefinition<typeof AuthEventTypes.ImpersonationChanged, ImpersonationInfo | null>;
147
794
  };
148
- type DeleteEvent = {
149
- type: 'delete';
150
- mutation_id: RecordId;
151
- record_id: RecordId;
152
- options?: PushEventOptions;
795
+ type AuthEventSystem = EventSystem<AuthEventTypeMap>;
796
+ declare function createAuthEventSystem(): AuthEventSystem;
797
+ //#endregion
798
+ //#region src/modules/auth/index.d.ts
799
+ /** What `fn::_00_impersonate::list_users` returns per row. */
800
+ interface ImpersonationCandidate {
801
+ id: string;
802
+ is_admin: boolean;
803
+ [field: string]: unknown;
804
+ }
805
+ /** An open session, as `fn::_00_impersonate::active` lists it. */
806
+ interface ActiveImpersonation {
807
+ session: string;
808
+ target: string;
809
+ admin: string;
810
+ reason: string;
811
+ started_at: unknown;
812
+ expires_at: unknown;
813
+ }
814
+ /** What a sign-out hook sees: the session that is about to end. */
815
+ interface SignOutContext {
816
+ /** `table:id` of the signed-in record, or null. */
817
+ userId: string | null;
818
+ token: string | null;
819
+ /** The session is an admin impersonation (its token is the target's). */
820
+ impersonating: boolean;
821
+ }
822
+ type SignOutHook = (ctx: SignOutContext) => Promise<void> | void;
823
+ /** Upper bound on the before-sign-out hooks, so a dead socket never holds a sign-out. */
824
+ declare const SIGN_OUT_HOOK_TIMEOUT_MS = 2000;
825
+ /**
826
+ * Floor between two session re-checks started by refused statements. A
827
+ * refused session fails every statement at once, and a check that keeps the
828
+ * session (the server was unreachable) must not be re-run by each of them.
829
+ */
830
+ declare const REFUSAL_RECHECK_MIN_MS = 30000;
831
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
832
+ type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
833
+ type ExtractAccessParams<S extends SchemaStructure, Name extends keyof S['access'], Method extends 'signIn' | 'signup'> = S['access'] extends undefined ? never : S['access'][Name] extends AccessDefinition ? Prettify<{ [K in keyof S['access'][Name][Method]['params']]: MapColumnType<S['access'][Name][Method]['params'][K]> }> : never;
834
+ declare class AuthService<S extends SchemaStructure> {
835
+ private schema;
836
+ private remote;
837
+ private persistenceClient;
838
+ private logger;
839
+ token: string | null;
840
+ currentUser: any | null;
841
+ isAuthenticated: boolean;
842
+ /**
843
+ * The record-access method name for the current session (e.g. `"account"`),
844
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
845
+ * permission injection so `$access`-gated table predicates resolve locally,
846
+ * mirroring the server's `$access`. Null when logged out.
847
+ */
848
+ access: string | null;
849
+ isLoading: boolean;
850
+ private events;
851
+ private signOutHooks;
852
+ /** The impersonation last announced, for change detection. */
853
+ private announcedImpersonation;
854
+ /** Target of an impersonation that just ended, until the client purges its
855
+ * local bucket (see `consumeEndedImpersonation`). */
856
+ private endedImpersonationTarget;
857
+ /** The way back to the admin in flight. The Stop button, the session poll,
858
+ * a refused renewal and a rejected check can all end an impersonation, and
859
+ * they share this one: a second stop running beside the first found the
860
+ * admin token already taken and signed the admin out. */
861
+ private stopping;
862
+ /** A token renewal in flight, which a stop waits out (see `renewImpersonation`). */
863
+ private renewing;
864
+ /** The session re-check in flight (see `watchSession`), shared by every trigger. */
865
+ private reverifying;
866
+ /** When a refused statement last started a re-check. */
867
+ private lastRefusalCheckAt;
868
+ private watchingSession;
869
+ private impersonationTimers;
870
+ get eventSystem(): AuthEventSystem;
871
+ constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
872
+ init(): Promise<void>;
873
+ /**
874
+ * Check the session again whenever the socket comes back, and whenever the
875
+ * server refuses a statement because of the session.
876
+ *
877
+ * The server judges a token only when a socket authenticates: the SDK
878
+ * replays `authenticate` on its own reconnects, `RemoteDatabaseService` on a
879
+ * socket it rebuilds. When the replay is refused (the app ended the session,
880
+ * say with a password reset) the SDK drops to an anonymous session, and the
881
+ * supervisor swallows the rebuild's error, so the socket reports `connected`
882
+ * while this service still announces the user. Every view registered from
883
+ * then on carried no identity: the page looked signed in and showed nothing
884
+ * of the user's. `check()` applies the token again and signs out when the
885
+ * server refuses it.
886
+ *
887
+ * A socket that never reconnects is ended by the app's session guard
888
+ * (`fn::sp00ky::session_live`) instead: its heartbeats stop finding rows,
889
+ * and the re-registration that follows is refused with "There was a problem
890
+ * with authentication", which starts a check here too.
891
+ */
892
+ private watchSession;
893
+ /** One `check()` for every trigger that lands while it runs. */
894
+ private reverify;
895
+ getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
896
+ /**
897
+ * Subscribe to auth state changes.
898
+ * callback is called immediately with current value and whenever validation status changes.
899
+ * `immediate: false` skips that first call: only changes are reported.
900
+ */
901
+ subscribe(cb: (userId: string | null) => void, opts?: {
902
+ immediate?: boolean;
903
+ }): () => void;
904
+ /**
905
+ * Run `hook` at the start of every sign-out, while the token and the socket
906
+ * still belong to the leaving user (Web Push removes this device's
907
+ * subscription here). Hooks are best-effort: they run in parallel, errors
908
+ * are swallowed, and the sign-out goes on after
909
+ * {@link SIGN_OUT_HOOK_TIMEOUT_MS} whatever they are doing. Returns a disposer.
910
+ */
911
+ onBeforeSignOut(hook: SignOutHook): () => void;
912
+ private runSignOutHooks;
913
+ /**
914
+ * The signed-in user as subscribers see it: the raw `table:id` string, the
915
+ * way the token's `ID` claim spells it. `currentUser.id` is that string while
916
+ * the session is restored from the token and the server's `RecordId` once
917
+ * `check()` has answered, and the two must announce as the same user: every
918
+ * subscriber that compares ids (feature flags, app release) took the switch
919
+ * for a new principal and reset, so flag-gated UI blinked off and back on a
920
+ * few seconds into every reload. A `RecordId`'s own `toString()` will not do
921
+ * either, as it escapes ids like `user:⟨5abc⟩` that the claim spells raw.
922
+ */
923
+ private announcedUserId;
924
+ private notifyListeners;
925
+ /**
926
+ * The impersonation the current session is, or null. Derived from the
927
+ * token in use, so it always describes the identity the server sees.
928
+ */
929
+ get impersonation(): ImpersonationInfo | null;
930
+ /** Subscribe to impersonation changes; called immediately with the current value. */
931
+ subscribeImpersonation(cb: (info: ImpersonationInfo | null) => void): () => void;
932
+ /**
933
+ * Act as `targetId` (a record id such as `user:abc`). Admins only, and only
934
+ * when the project enabled `impersonation` in sp00ky.yml: the server refuses
935
+ * everything else. `reason` is recorded in the audit log.
936
+ *
937
+ * The admin's session is kept aside and restored by
938
+ * {@link stopImpersonating}. Local data switches to the target's bucket
939
+ * exactly as on a sign-in, and that bucket is removed on stop.
940
+ */
941
+ impersonate(targetId: string, reason: string): Promise<ImpersonationInfo>;
942
+ /**
943
+ * Return to the admin session. Always leaves the impersonated identity,
944
+ * even when the server cannot be reached: the admin token is restored
945
+ * locally first and verified afterwards, and a rejected admin token ends in
946
+ * a full sign-out rather than staying on the target.
947
+ */
948
+ stopImpersonating(opts?: {
949
+ serverEnded?: boolean;
950
+ }): Promise<void>;
951
+ private leaveImpersonation;
952
+ /** Re-sign the impersonation token before it expires. */
953
+ renewImpersonation(): Promise<void>;
954
+ private applyRenewal;
955
+ /** Users an admin may pick from. Admin-only on the server. */
956
+ searchImpersonationTargets(search: string): Promise<ImpersonationCandidate[]>;
957
+ /** Open impersonation sessions. Admin-only on the server. */
958
+ listActiveImpersonations(): Promise<ActiveImpersonation[]>;
959
+ /**
960
+ * The target of an impersonation that ended, once. The bucket switch calls
961
+ * this after leaving a bucket so it can delete that user's local data.
962
+ */
963
+ consumeEndedImpersonation(): string | null;
964
+ /**
965
+ * Restore a session from the locally cached JWT, with NO network.
966
+ *
967
+ * This is what makes a warm boot paint instantly and what makes an offline
968
+ * boot possible at all: the token is in local storage, and it already carries
969
+ * both the access method and the `$auth.id` record id. Everything the client
970
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
971
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
972
+ * available before a socket exists.
973
+ *
974
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
975
+ * afterwards in the background and downgrades to a real sign-out if the
976
+ * server rejects it. Nothing is trusted that the server has not also seen -
977
+ * the local store only ever holds rows the server previously sent.
978
+ *
979
+ * Returns the restored user id, or null when there is no usable token.
980
+ */
981
+ restoreSessionFromToken(): Promise<string | null>;
982
+ /**
983
+ * Check for existing session and validate
984
+ */
985
+ check(accessToken?: string): Promise<void>;
986
+ /** Hold a session the server accepted without its user row: the id comes
987
+ * from the token, as on a warm boot. A token naming no user is refused. */
988
+ private keepAcceptedSession;
989
+ /**
990
+ * The server refused `token`. A refused impersonation token (stopped,
991
+ * expired, or revoked) returns to the admin session instead of signing the
992
+ * admin out; anything else signs out.
993
+ */
994
+ private rejectToken;
995
+ /**
996
+ * Sign out and clear session. While impersonating this ends the
997
+ * impersonation and signs the admin out too.
998
+ */
999
+ signOut(): Promise<void>;
1000
+ private setSession;
1001
+ /** Fallback when the token carries no `AC` claim: if the schema defines
1002
+ * exactly one record-access method, assume the session used it. */
1003
+ private defaultAccessName;
1004
+ signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
1005
+ signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
1006
+ }
1007
+ //#endregion
1008
+ //#region src/push/types.d.ts
1009
+ /**
1010
+ * Web Push wire types shared by the page (`db.webPush`), the service worker
1011
+ * bridge (`@spooky-sync/core/sw`) and the live feed. Pure: types plus a few
1012
+ * dependency-free helpers, safe in any context.
1013
+ *
1014
+ * `PushPayload` mirrors `packages/push-core/src/config.rs` (`PushPayload`,
1015
+ * `PayloadKind`, `Op`, `NotificationTemplate`). Keep the two in step.
1016
+ */
1017
+ /** Payload format version this build understands. */
1018
+ declare const PUSH_PAYLOAD_VERSION = 1;
1019
+ type PushPayloadKind = 'rule' | 'message';
1020
+ type PushOp = 'create' | 'update' | 'delete';
1021
+ type PushUrgency = 'very-low' | 'low' | 'normal' | 'high';
1022
+ /** One button on a notification (`NotificationAction` plus a per-action `url`). */
1023
+ interface PushNotificationAction {
1024
+ action: string;
1025
+ title: string;
1026
+ icon?: string;
1027
+ /** Opened instead of the notification's `url` when this action is clicked. */
1028
+ url?: string;
1029
+ [key: string]: unknown;
1030
+ }
1031
+ /**
1032
+ * What a content push shows. Every key other than `title` and `url` is passed
1033
+ * to `showNotification` as is, unknown ones included (`vibrate`, `timestamp`,
1034
+ * whatever a browser adds later).
1035
+ */
1036
+ interface PushNotification {
1037
+ title?: string;
1038
+ body?: string;
1039
+ icon?: string;
1040
+ badge?: string;
1041
+ image?: string;
1042
+ lang?: string;
1043
+ dir?: string;
1044
+ /** Defaults to the push's `topic`. */
1045
+ tag?: string;
1046
+ /** Opened (or focused) on click. */
1047
+ url?: string;
1048
+ requireInteraction?: boolean;
1049
+ renotify?: boolean;
1050
+ silent?: boolean;
1051
+ actions?: PushNotificationAction[];
1052
+ /** Merged into the notification's `data` next to the bridge's own keys. */
1053
+ data?: Record<string, unknown>;
1054
+ [key: string]: unknown;
1055
+ }
1056
+ /**
1057
+ * The JSON every push carries (then RFC 8291 encrypted). `notification`
1058
+ * present: a content push the service worker shows as is. Absent: a
1059
+ * content-free nudge, the app renders from its own data.
1060
+ */
1061
+ interface PushPayload {
1062
+ v: number;
1063
+ kind: PushPayloadKind;
1064
+ /** Rule name (`kind: 'rule'`). */
1065
+ rule?: string;
1066
+ /** `_00_push_message` id (`kind: 'message'`). */
1067
+ message?: string;
1068
+ /** The row that fired the rule. */
1069
+ table?: string;
1070
+ id?: string;
1071
+ op?: PushOp;
1072
+ topic?: string;
1073
+ notification?: PushNotification;
1074
+ data?: Record<string, unknown>;
1075
+ /** Epoch ms when the engine built it. */
1076
+ ts: number;
1077
+ }
1078
+ /** Page -> service worker: the session to use for live rendering. */
1079
+ interface BridgeTokenMessage {
1080
+ type: 'sp00ky:token';
1081
+ token: string;
1082
+ userId: string;
1083
+ /** The SurrealDB endpoint (`wss://host/rpc`), not the push endpoint. */
1084
+ endpoint: string;
1085
+ namespace: string;
1086
+ database: string;
1087
+ /** VAPID public key (base64url) the page subscribed with, for `pushsubscriptionchange`. */
1088
+ publicKey?: string;
1089
+ /** This browser's push endpoint, when subscribed. */
1090
+ pushEndpoint?: string;
1091
+ }
1092
+ /** Page -> service worker: forget the session and close every notification. */
1093
+ interface BridgeSignOutMessage {
1094
+ type: 'sp00ky:signout';
1095
+ }
1096
+ /** Service worker -> page messages. */
1097
+ type WebPushClientMessage = /** A push arrived while this page was visible, so nothing was shown. */
1098
+ {
1099
+ type: 'sp00ky:push';
1100
+ payload: PushPayload;
1101
+ }
1102
+ /** A notification was clicked and the bridge was told to route in-app. */ | {
1103
+ type: 'sp00ky:navigate';
1104
+ url: string;
1105
+ payload?: PushPayload;
1106
+ action?: string;
1107
+ }
1108
+ /** The browser rotated the push subscription; the page should `sync()`. */ | {
1109
+ type: 'sp00ky:subscriptionchange';
1110
+ endpoint?: string;
153
1111
  };
154
- type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
1112
+ /** `urlBase64ToUint8Array`: the VAPID key as `applicationServerKey` wants it. */
1113
+
1114
+ /** A payload this build can act on (`v` known, `kind` set). */
1115
+ declare function isPushPayload(value: unknown): value is PushPayload;
1116
+ //#endregion
1117
+ //#region src/modules/web-push/index.d.ts
1118
+ /**
1119
+ * `db.webPush`: this browser's Web Push subscription, on the page.
1120
+ *
1121
+ * Every server call is a `fn::push::*` function over the client's remote
1122
+ * connection (see `apps/cli/src/push_tables.surql`). Nothing here touches a
1123
+ * browser API at import time, and every method answers "unsupported" instead
1124
+ * of throwing where there is no window, service worker or push manager
1125
+ * (SSR, Node, workers, iOS Safari outside a home-screen app).
1126
+ */
1127
+ interface WebPushConfig {
1128
+ /**
1129
+ * Registered with `navigator.serviceWorker.register(url)` when the page has
1130
+ * no service worker yet. Leave unset when the app (or vite-plugin-pwa)
1131
+ * registers its own.
1132
+ */
1133
+ serviceWorkerUrl?: string;
1134
+ /**
1135
+ * Reconcile this browser's subscription after sign-in (see `sync()`): a
1136
+ * rotated key, a browser that dropped the subscription or a server row that
1137
+ * went away are repaired without a prompt. Default `true`.
1138
+ */
1139
+ autoSync?: boolean;
1140
+ /**
1141
+ * Let `sync()` subscribe a signed-in user whenever notification permission
1142
+ * is already granted, even if they never subscribed on this browser.
1143
+ * Default `false`: only a user who called `subscribe()` here is restored.
1144
+ */
1145
+ autoResubscribe?: boolean;
1146
+ /**
1147
+ * Remove this device's subscription for the user on `signOut()` (before the
1148
+ * token is dropped, bounded by a short timeout). Default `true`.
1149
+ */
1150
+ unsubscribeOnSignOut?: boolean;
1151
+ /**
1152
+ * Post the session token to the app's service worker whenever it changes,
1153
+ * while notifications are allowed, so `@spooky-sync/core/sw` can render from
1154
+ * live data. Never posts an impersonation token. Default `true`.
1155
+ */
1156
+ bridge?: boolean;
1157
+ }
1158
+ type WebPushUnsupportedReason = 'no-window' | 'insecure-context' | 'no-service-worker' | 'no-push-manager' | 'no-notification' | 'ios-not-installed';
1159
+ interface WebPushSupport {
1160
+ supported: boolean;
1161
+ permission: NotificationPermission | 'unsupported';
1162
+ reason?: WebPushUnsupportedReason;
1163
+ }
1164
+ interface WebPushInfo {
1165
+ /** A host with push on has published its key. */
1166
+ enabled: boolean;
1167
+ /** VAPID public key (base64url), the browser's `applicationServerKey`. */
1168
+ publicKey?: string;
1169
+ /** Id of that key. */
1170
+ kid?: string;
1171
+ /**
1172
+ * Every kind of device the project reaches: `web` once a VAPID key is
1173
+ * published, `apns` / `fcm` when `push.apns` / `push.fcm` are configured.
1174
+ */
1175
+ providers?: PushDeviceKind[];
1176
+ }
1177
+ /** How a device is reached: a browser (Web Push), APNs or FCM. */
1178
+ type PushDeviceKind = 'web' | 'apns' | 'fcm';
1179
+ interface WebPushDevice {
1180
+ /** `_00_push_subscription:<id>` */
1181
+ id: string;
1182
+ /** Web: the push service URL. Native: `<kind>:<token>`. */
1183
+ endpoint: string;
1184
+ /** Rows the Flutter / native side registered are `apns` or `fcm`. */
1185
+ kind: PushDeviceKind;
1186
+ /** `web`, `ios`, `android` or `macos`. */
1187
+ platform?: string;
1188
+ /** Native: bundle id / package name. */
1189
+ appId?: string;
1190
+ /** APNs: `sandbox` or `production`. */
1191
+ environment?: string;
1192
+ /** Key id a web device subscribed under (empty for native ones). */
1193
+ kid: string;
1194
+ label?: string;
1195
+ userAgent?: string;
1196
+ /** Rule names this device receives; undefined = every rule. */
1197
+ rules?: string[];
1198
+ meta?: Record<string, unknown>;
1199
+ createdAt?: Date;
1200
+ updatedAt?: Date;
1201
+ lastOkAt?: Date;
1202
+ lastError?: string;
1203
+ failures: number;
1204
+ disabledAt?: Date;
1205
+ disabledReason?: string;
1206
+ /** Subscribed under the current key (pushes reach it). Undefined when unknown. */
1207
+ current?: boolean;
1208
+ /** This browser. */
1209
+ thisDevice: boolean;
1210
+ }
1211
+ interface WebPushSubscribeOptions {
1212
+ /** Defaults to the page's service worker registration (`serviceWorker.ready`). */
1213
+ registration?: ServiceWorkerRegistration;
1214
+ /** Shown in the device list ("Work laptop"). */
1215
+ label?: string;
1216
+ /** Rule names this device wants. Omitted or empty: every rule. */
1217
+ rules?: string[];
1218
+ /** Free-form app data about the device. */
1219
+ meta?: Record<string, unknown>;
1220
+ /** Ask for notification permission when it is still `default`. Default `true`. Call from a user gesture. */
1221
+ requestPermission?: boolean;
1222
+ }
1223
+ interface WebPushUnsubscribeOptions {
1224
+ /** Remove every device of the user, not only this one. */
1225
+ all?: boolean;
1226
+ /** Keep the browser's PushSubscription (only the server row goes). */
1227
+ keepBrowserSubscription?: boolean;
1228
+ }
1229
+ interface WebPushSyncOptions {
1230
+ registration?: ServiceWorkerRegistration;
1231
+ /** Overrides `webPush.autoResubscribe` for this call. */
1232
+ autoResubscribe?: boolean;
1233
+ }
1234
+ /**
1235
+ * What `sync()` did. `ok`: nothing to repair. `resubscribed`: the browser
1236
+ * subscription was (re)created. `registered`: the server row was re-created.
1237
+ * The rest say why nothing happened.
1238
+ */
1239
+ type WebPushSyncStatus = 'ok' | 'resubscribed' | 'registered' | 'unsupported' | 'signed-out' | 'impersonating' | 'permission-default' | 'permission-denied' | 'not-subscribed' | 'disabled' | 'no-registration' | 'error';
1240
+ interface WebPushUpdateOptions {
1241
+ label?: string;
1242
+ /** Rule names; `null` or `[]` resets the device to every rule. */
1243
+ rules?: string[] | null;
1244
+ meta?: Record<string, unknown>;
1245
+ }
1246
+ /** A push to yourself (`fn::push::notify`). */
1247
+ interface WebPushMessageInput {
1248
+ /** Omit for a content-free nudge. */
1249
+ notification?: PushNotification;
1250
+ data?: Record<string, unknown>;
1251
+ topic?: string;
1252
+ urgency?: PushUrgency;
1253
+ /** Push-service TTL, seconds. */
1254
+ ttl?: number;
1255
+ /** In the future: scheduled. */
1256
+ sendAt?: Date | string | number;
1257
+ }
1258
+ interface WebPushMessage {
1259
+ /** `_00_push_message:<id>` */
1260
+ id: string;
1261
+ status: string;
1262
+ sendAt?: Date;
1263
+ createdAt?: Date;
1264
+ }
1265
+ type WebPushErrorCode = 'unsupported' | 'signed-out' | 'impersonating' | 'disabled' | 'permission-denied' | 'permission-default' | 'no-registration' | 'not-subscribed' | 'subscribe-failed' | 'server';
1266
+ declare class WebPushError extends Error {
1267
+ readonly code: WebPushErrorCode;
1268
+ readonly cause?: unknown | undefined;
1269
+ constructor(code: WebPushErrorCode, message: string, cause?: unknown | undefined);
1270
+ }
1271
+ interface WebPushAuthPort {
1272
+ readonly token: string | null;
1273
+ readonly currentUser: {
1274
+ id?: unknown;
1275
+ } | null;
1276
+ readonly isAuthenticated: boolean;
1277
+ readonly impersonation: unknown;
1278
+ subscribe(cb: (userId: unknown) => void): () => void;
1279
+ onBeforeSignOut(hook: (ctx: SignOutContext) => Promise<void> | void): () => void;
1280
+ }
1281
+ interface WebPushRemotePort {
1282
+ query<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
1283
+ }
1284
+ /** Browser globals, read at call time. Injectable for tests. */
1285
+ interface WebPushGlobals {
1286
+ window?: unknown;
1287
+ navigator?: Navigator & {
1288
+ standalone?: boolean;
1289
+ };
1290
+ Notification?: {
1291
+ permission: NotificationPermission;
1292
+ requestPermission(cb?: (p: NotificationPermission) => void): Promise<NotificationPermission> | void;
1293
+ };
1294
+ isSecureContext?: boolean;
1295
+ matchMedia?: (query: string) => {
1296
+ matches: boolean;
1297
+ };
1298
+ PushManager?: unknown;
1299
+ }
1300
+ interface WebPushModuleDeps {
1301
+ remote: WebPushRemotePort;
1302
+ auth: WebPushAuthPort;
1303
+ persistence: PersistenceClient;
1304
+ logger: Logger$1;
1305
+ database: {
1306
+ endpoint?: string;
1307
+ namespace: string;
1308
+ database: string;
1309
+ };
1310
+ /** Transport state; auto-sync waits for `connected`. */
1311
+ connection?: {
1312
+ subscribe(cb: (state: string) => void): () => void;
1313
+ };
1314
+ config?: WebPushConfig;
1315
+ globals?: () => WebPushGlobals;
1316
+ }
1317
+ declare const PUSH_ENDPOINT_KEY = "sp00ky_push_endpoint";
1318
+ /** `table:id` of a record id value, without the SDK's escaping. */
1319
+
1320
+ /** Where Web Push can work, from the given globals. */
1321
+ declare function detectWebPushSupport(g: WebPushGlobals): WebPushSupport;
1322
+ declare class WebPushModule {
1323
+ private readonly deps;
1324
+ private readonly logger;
1325
+ private readonly config;
1326
+ private readonly globals;
1327
+ private infoCache;
1328
+ private lastInfo;
1329
+ private readonly bridges;
1330
+ private readonly disposers;
1331
+ private syncedFor;
1332
+ private syncTimer;
1333
+ private attached;
1334
+ constructor(deps: WebPushModuleDeps);
1335
+ /**
1336
+ * Wire sign-out, auto-sync and the token bridge. Called by the client once;
1337
+ * a no-op beyond the sign-out hook where push is unsupported.
1338
+ */
1339
+ attach(): () => void;
1340
+ dispose(): void;
1341
+ support(): WebPushSupport;
1342
+ /** Is push on for this deployment, and with which key. Cached; `refresh` re-reads. */
1343
+ info(options?: {
1344
+ refresh?: boolean;
1345
+ }): Promise<WebPushInfo>;
1346
+ /** This browser holds a push subscription registered for the signed-in user. No server round trip. */
1347
+ isSubscribed(): Promise<boolean>;
1348
+ /** The user's devices, this one marked. */
1349
+ devices(): Promise<WebPushDevice[]>;
1350
+ /**
1351
+ * Ask for permission (when still `default`), subscribe this browser with the
1352
+ * deployment's key and register it for the signed-in user. Call it from a
1353
+ * click handler: permission prompts need a user gesture.
1354
+ */
1355
+ subscribe(options?: WebPushSubscribeOptions): Promise<WebPushDevice>;
1356
+ /** Remove this device (or every device, `all`) for the signed-in user. Returns how many rows went. */
1357
+ unsubscribe(options?: WebPushUnsubscribeOptions): Promise<number>;
1358
+ /**
1359
+ * Reconcile after sign-in (runs by itself with `autoSync`). Needs granted
1360
+ * permission and a user who subscribed on this browser (or
1361
+ * `autoResubscribe`). Repairs a missing browser subscription, one made with
1362
+ * a rotated key, and a missing, disabled or stale server row. Never throws.
1363
+ */
1364
+ sync(options?: WebPushSyncOptions): Promise<WebPushSyncStatus>;
1365
+ /** Change this device's label, rule filter or meta. */
1366
+ update(options: WebPushUpdateOptions): Promise<WebPushDevice | null>;
1367
+ /** Push to yourself, now or at `sendAt` (reminders). Omit `notification` for a nudge. */
1368
+ notify(message: WebPushMessageInput): Promise<WebPushMessage>;
1369
+ /** Cancel a scheduled message. `true` when it was still pending. */
1370
+ cancel(id: string | RecordId$1): Promise<boolean>;
1371
+ /** A visible test notification to every device of the user. */
1372
+ test(options?: {
1373
+ title?: string;
1374
+ body?: string;
1375
+ }): Promise<WebPushMessage>;
1376
+ /**
1377
+ * Post the session to the service worker now and whenever the token
1378
+ * changes (`{ type: 'sp00ky:token', token, userId, endpoint, namespace,
1379
+ * database }`). Never posts an impersonation token. Returns a disposer.
1380
+ * With `webPush.bridge` (the default) this already runs while notification
1381
+ * permission is granted.
1382
+ */
1383
+ bridge(registration?: ServiceWorkerRegistration): () => void;
1384
+ /** Messages from the push service worker (`sp00ky:push` while visible, `sp00ky:navigate`, ...). */
1385
+ onMessage(cb: (message: WebPushClientMessage) => void): () => void;
1386
+ private userId;
1387
+ private assertSignedIn;
1388
+ private assertNotImpersonating;
1389
+ private call;
1390
+ private listRaw;
1391
+ private register;
1392
+ private readStored;
1393
+ private writeStored;
1394
+ /** The page's registration: given, existing, registered from config, or `ready` within `waitMs`. */
1395
+ private registration;
1396
+ /** This browser's subscription, without waiting for a worker. */
1397
+ private currentSubscription;
1398
+ private thisEndpoint;
1399
+ private postToWorker;
1400
+ private startBridge;
1401
+ private refreshBridges;
1402
+ private tokenMessage;
1403
+ /** Sign-out hook: tell the worker, and drop this device's row for the user. Bounded. */
1404
+ private beforeSignOut;
1405
+ }
155
1406
  //#endregion
156
1407
  //#region src/types.d.ts
157
1408
  /**
@@ -192,6 +1443,24 @@ interface PersistenceClient {
192
1443
  * Format: number + unit (m=minutes, h=hours, d=days).
193
1444
  */
194
1445
  type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
1446
+ /**
1447
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
1448
+ * The FIRST load (cold) always fetches + blocks regardless.
1449
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
1450
+ * real `useQuery` mounts and registers its live view. No network on load.
1451
+ * - `background`: return instantly, but kick a one-time silent refetch.
1452
+ * - `stale`: like `background`, but only if the cached copy is older than
1453
+ * `staleTime`.
1454
+ */
1455
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
1456
+ interface PreloadOptions {
1457
+ /** Abort a cold preload that is still waiting for the server. */
1458
+ signal?: AbortSignal;
1459
+ /** @deprecated Preload is a registered query now; a warm preload never refetches by itself. Ignored. */
1460
+ refresh?: PreloadRefresh;
1461
+ /** @deprecated Ignored. */
1462
+ staleTime?: QueryTimeToLive;
1463
+ }
195
1464
  /**
196
1465
  * Result object returned when a query is registered or executed.
197
1466
  */
@@ -220,29 +1489,441 @@ interface Sp00kyConfig<S extends SchemaStructure> {
220
1489
  store?: StoreType;
221
1490
  /** Authentication token. */
222
1491
  token?: string;
1492
+ /**
1493
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
1494
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
1495
+ * table/relation level. Defaults to true; set false to force the legacy
1496
+ * multi-hop path (escape hatch while the worker-side path beds in).
1497
+ */
1498
+ workerSelect?: boolean;
1499
+ /**
1500
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
1501
+ * keep the connection alive indefinitely without configuration. See
1502
+ * {@link ReconnectConfig}.
1503
+ */
1504
+ reconnect?: ReconnectConfig;
1505
+ /**
1506
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
1507
+ * a single promise chain, so one call that never settles (half-open socket:
1508
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
1509
+ * otherwise wedge ALL later remote traffic behind it — including the sync
1510
+ * poll's own health probe, leaving health pinned at `healthy` with no
1511
+ * banner and no self-heal. The deadline turns that into an ordinary network
1512
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
1513
+ */
1514
+ queryTimeoutMs?: number;
1515
+ /**
1516
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
1517
+ * or a query on the in-process surrealdb engine). Local ops are serialized
1518
+ * too, and one that never answered - a worker starved behind a long select,
1519
+ * a lock verification with no clock - left every `db.create`/`db.update`
1520
+ * promise pending for the tab's lifetime. On expiry the call rejects with
1521
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
1522
+ * not retried). `0` disables. Defaults to `30_000`.
1523
+ */
1524
+ localOpTimeoutMs?: number;
223
1525
  };
224
- /** Unique client identifier. If not provided, one will be generated. */
225
- clientId?: string;
226
1526
  /** The schema definition. */
227
1527
  schema: S;
228
1528
  /** The compiled SURQL schema string. */
229
1529
  schemaSurql: string;
230
1530
  /** Logging level. */
231
- logLevel: Level;
1531
+ logLevel: Level$1;
232
1532
  /**
233
1533
  * Persistence client to use.
234
1534
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
235
1535
  */
236
1536
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
1537
+ /**
1538
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
1539
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
1540
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
1541
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
1542
+ * this engine. See `services/database/cache-engine.ts`.
1543
+ */
1544
+ localEngine?: LocalEngineChoice;
1545
+ /**
1546
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
1547
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
1548
+ * how bucket reads behaved before it existed.
1549
+ *
1550
+ * Nothing in this cache expires on a timer — an image whose row is still in
1551
+ * the local store has to stay available offline. Bytes are only dropped when
1552
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
1553
+ * reconcile finds no file behind a row, or when the cache is over budget, in
1554
+ * which case the least-recently-used unpinned entries go first. See
1555
+ * `services/blobs/blob-cache.ts`.
1556
+ */
1557
+ blobCache?: {
1558
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
1559
+ enabled?: boolean;
1560
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
1561
+ * `navigator.storage.estimate()`. */
1562
+ maxBytes?: number;
1563
+ /**
1564
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
1565
+ * `false`, matching the local store: cached files are namespaced per local
1566
+ * bucket, so signing back in is warm and no user can read another's cache.
1567
+ * Turn on for shared devices.
1568
+ */
1569
+ clearOnSignOut?: boolean;
1570
+ };
1571
+ /**
1572
+ * Share ONE durable local store across all tabs of this origin (default
1573
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
1574
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
1575
+ * worker and the sync loop, and follower tabs read/write the same store over
1576
+ * MessagePorts, so every tab is durable instead of only the first one.
1577
+ *
1578
+ * Falls back to solo mode (exactly the flag-off behavior, including the
1579
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
1580
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
1581
+ * not sqlite, or the broker rejects the tab (mixed app versions).
1582
+ *
1583
+ * Failover: when the leader tab closes or freezes, a follower is promoted
1584
+ * within seconds; queries briefly refetch and mutations are never lost once
1585
+ * their local write resolved (the shared outbox survives in the store).
1586
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
1587
+ */
1588
+ sharedTabs?: boolean;
1589
+ /**
1590
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
1591
+ * store, so a reload restores it and only steps in what changed since.
1592
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
1593
+ * can hold the bytes) and `false` otherwise.
1594
+ *
1595
+ * Without a snapshot the circuit is primed by reading every cached row back
1596
+ * out of the local store; either way a reload never re-downloads the working
1597
+ * set, which is what an empty circuit used to force: every id in the
1598
+ * server's list_ref classified as missing.
1599
+ *
1600
+ * Snapshots are store-only (views are re-registered per session) and written
1601
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
1602
+ * goes hidden, never per ingest or per query registration.
1603
+ */
1604
+ persistCircuit?: boolean;
1605
+ /**
1606
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
1607
+ * 30000. Ignored when `persistCircuit` is off.
1608
+ */
1609
+ circuitCheckpointMs?: number;
1610
+ /**
1611
+ * Keep only the fields registered queries evaluate (filter predicates, join
1612
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
1613
+ * Default `true`. The circuit only ever reads those fields; bodies are
1614
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
1615
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
1616
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
1617
+ * without has that field merged in from the local store on registration.
1618
+ */
1619
+ circuitProjection?: boolean;
237
1620
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
238
1621
  otelTransmit?: PinoTransmit;
239
1622
  /**
240
- * Debounce time in milliseconds for stream updates.
241
- * Defaults to 100ms.
1623
+ * Debounce time in milliseconds for stream updates (the client-side SSP
1624
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
1625
+ * per-record updates per query before notifying readers).
1626
+ * Defaults to 50ms.
242
1627
  */
243
1628
  streamDebounceTime?: number;
1629
+ /**
1630
+ * How long in milliseconds the first edit to a collaborative (CRDT) field
1631
+ * after a quiet spell waits before it goes out, so a burst of keystrokes
1632
+ * travels as one edit-log row. Local state is kept on every change (so
1633
+ * reload and offline work). Defaults to 50ms.
1634
+ */
1635
+ crdtDebounceMs?: number;
1636
+ /**
1637
+ * The shortest gap in milliseconds between two edit-log rows of one CRDT
1638
+ * field: while someone keeps typing, their edits go out on this cadence
1639
+ * instead of waiting for a pause. Lower = other collaborators see the text
1640
+ * sooner and more rows are written; higher = fewer rows and more lag.
1641
+ * Defaults to 200ms.
1642
+ */
1643
+ crdtSendIntervalMs?: number;
1644
+ /**
1645
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
1646
+ * preloaded at client startup (fetched as a separate chunk on page load) so
1647
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
1648
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
1649
+ * out of apps that don't use collaboration. Defaults to `false`.
1650
+ */
1651
+ crdt?: boolean;
1652
+ /**
1653
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
1654
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
1655
+ * convergence + more query load; higher = the inverse. Non-positive
1656
+ * values fall back to the default (500ms).
1657
+ */
1658
+ refSyncIntervalMs?: number;
1659
+ /**
1660
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
1661
+ * registered with no server result yet, its surql also runs directly on the
1662
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
1663
+ * before the full register lifecycle completes. Hydrated rows carry their
1664
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
1665
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
1666
+ * paints from the local cache immediately — however the rows got there
1667
+ * (preload, prior sync). Default `false`: the register lifecycle
1668
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
1669
+ * freshness path and no duplicate one-shot fetches are made.
1670
+ */
1671
+ instantHydrate?: boolean;
1672
+ /**
1673
+ * Carry the changed row's body on the LIVE notification instead of going
1674
+ * back for it.
1675
+ *
1676
+ * The client holds exactly one live subscription, on its `_00_list_ref`
1677
+ * table. Without this, the notification names the row and the client then
1678
+ * pulls it with `SELECT * FROM $ids`. The edge
1679
+ * is a real graph edge, so `FETCH out` makes SurrealDB resolve the row into
1680
+ * the notification and the body fetch disappears.
1681
+ *
1682
+ * The push stays advisory: the body is landed exactly the way a fetched body
1683
+ * is (store write, circuit ingest, version recorded), so a notification the
1684
+ * server drops costs nothing but the old round trip. A row joining a live
1685
+ * view is committed to membership from the notification either way (no
1686
+ * re-read); with this on, the body fetch is saved as well.
1687
+ *
1688
+ * Default `false`. The cost is wire bytes: one edit bumps the edge in every
1689
+ * view holding the row, and under `FETCH` each of those notifications
1690
+ * carries its own full copy of the body.
1691
+ */
1692
+ liveInlineBodies?: boolean;
1693
+ /**
1694
+ * Enable realtime sync while signed out. When `true`, the client starts its
1695
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
1696
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
1697
+ * page gets live `useQuery` updates over world-readable tables. Requires the
1698
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
1699
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
1700
+ * one-shot but never sync live, and a `preload` made while signed out returns
1701
+ * at once rather than wait for membership that never comes.
1702
+ */
1703
+ enableAnonymousLiveQueries?: boolean;
1704
+ /**
1705
+ * Opt in to the raw remote escape hatches (`useRemote`, `remoteQuery`,
1706
+ * `queryRaw`) when the generated schema's `policy.queryAllowlist` is `warn`
1707
+ * or `enforce`. With the allowlist on, the server only accepts query shapes
1708
+ * that `spky generate` collected from the query builder, so a hand-written
1709
+ * SurrealQL string cannot be allowlisted and these methods throw unless this
1710
+ * flag is `true`. Defaults to `false`.
1711
+ */
1712
+ allowRawRemote?: boolean;
1713
+ /**
1714
+ * How the "you are impersonating" warning is shown while an admin acts as
1715
+ * another user. The built-in one (hazard stripes at the top, the page
1716
+ * shifted down onto them) needs no configuration; this is for restyling it,
1717
+ * or replacing it with the app's own.
1718
+ *
1719
+ * See `ImpersonationBannerConfig`. Replacing it does not mean "no warning":
1720
+ * if the app has not acknowledged its own banner shortly after impersonation
1721
+ * starts, the built-in one appears anyway.
1722
+ */
1723
+ impersonationBanner?: ImpersonationBannerConfig;
1724
+ /**
1725
+ * Surface sustained sync failures as a "degraded" health status that the app
1726
+ * can observe via `subscribeToSyncHealth` (or the client-solid
1727
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
1728
+ *
1729
+ * Individual failures — a transient remote 500 on query registration, a
1730
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
1731
+ * throw at the app. This only controls when a *run* of consecutive failures
1732
+ * is reported. Status flips back to `healthy` on the next successful sync
1733
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
1734
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
1735
+ */
1736
+ syncHealth?: SyncHealthConfig | false;
1737
+ /**
1738
+ * Automatic blurhash placeholders for bucket image uploads. On every
1739
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
1740
+ * the client computes a blurhash and stores it as a tiny sidecar object
1741
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
1742
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
1743
+ * helpers) to paint a placeholder until the image is decoded.
1744
+ *
1745
+ * `true` (the default) enables with 4x3 components; pass
1746
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
1747
+ * A per-call `put(path, content, { blurhash })` option overrides this.
1748
+ */
1749
+ blurhash?: boolean | {
1750
+ componentX?: number;
1751
+ componentY?: number;
1752
+ };
1753
+ /**
1754
+ * Buckets declared `BACKEND "r2"` keep their files with the SSP (R2 on
1755
+ * Cloudflare, a directory under `spky dev`) instead of in SurrealDB, which
1756
+ * on Surreal Cloud can only hold memory buckets. `endpoint` is the SSP's
1757
+ * URL: `spky dev` and `spky deploy` hand it to Vite as
1758
+ * `VITE_SPKY_FILES_ENDPOINT`.
1759
+ */
1760
+ files?: {
1761
+ endpoint?: string;
1762
+ };
1763
+ /**
1764
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
1765
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
1766
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
1767
+ * settles stops every later mutation for the session, with no retry and no
1768
+ * error. On expiry the push is treated as a network failure and re-queued.
1769
+ * `0` disables. Defaults to `30_000`.
1770
+ */
1771
+ pushTimeoutMs?: number;
1772
+ /**
1773
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1774
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
1775
+ * Defaults to 30000; `0` disables the timeout.
1776
+ */
1777
+ downTimeoutMs?: number;
1778
+ /**
1779
+ * Web Push on this page (`client.webPush`, `db.webPush`). Everything is
1780
+ * optional and the defaults need no service worker configuration here:
1781
+ * `autoSync` (repair this browser's subscription after sign-in),
1782
+ * `unsubscribeOnSignOut` (drop this device's subscription on `signOut()`),
1783
+ * `bridge` (post the session to the service worker for live rendering) are
1784
+ * on; `serviceWorkerUrl` registers a worker when the app does not.
1785
+ * See the `push-notifications` docs page.
1786
+ */
1787
+ webPush?: WebPushConfig;
1788
+ }
1789
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
1790
+ interface SyncHealthConfig {
1791
+ /**
1792
+ * Number of consecutive failed sync rounds (up or down) before the status
1793
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
1794
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
1795
+ * disables degraded reporting entirely.
1796
+ */
1797
+ degradeAfterConsecutiveFailures?: number;
1798
+ }
1799
+ /**
1800
+ * Tunables for WebSocket reconnect and liveness detection. See
1801
+ * {@link Sp00kyConfig.database.reconnect}.
1802
+ *
1803
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
1804
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
1805
+ * supervisor above it re-opens the connection from scratch whenever the SDK
1806
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
1807
+ * engine permanently in that case, so a supervisor is required, not optional.
1808
+ * The heartbeat covers the third case: a socket that never closes at all.
1809
+ */
1810
+ interface ReconnectConfig {
1811
+ /**
1812
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
1813
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
1814
+ * ~62s outage and then gives up for the life of the page).
1815
+ */
1816
+ attempts?: number;
1817
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
1818
+ retryDelayMax?: number;
1819
+ /**
1820
+ * Cadence of the application-level liveness probe (`RETURN true`) that
1821
+ * detects a half-open socket the transport never reports as closed.
1822
+ * `0` disables the heartbeat. Defaults to `20_000`.
1823
+ */
1824
+ heartbeatIntervalMs?: number;
1825
+ /**
1826
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
1827
+ * regardless of what its `readyState` claims, so the connection is torn down
1828
+ * and rebuilt. Defaults to `10_000`.
1829
+ */
1830
+ heartbeatTimeoutMs?: number;
1831
+ /**
1832
+ * Cap on the supervisor's own backoff between `connect()` retries once the
1833
+ * SDK has given up. Defaults to `15_000`.
1834
+ */
1835
+ superviseRetryDelayMaxMs?: number;
1836
+ }
1837
+ /**
1838
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
1839
+ *
1840
+ * These answer different questions: `connection` is about the socket,
1841
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
1842
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
1843
+ * usually still `healthy` for the first few seconds.
1844
+ */
1845
+ type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
1846
+ type SyncHealthStatus = 'healthy' | 'degraded';
1847
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
1848
+ interface SyncHealth {
1849
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
1850
+ status: SyncHealthStatus;
1851
+ /** Consecutive failed sync rounds at the moment of this report. */
1852
+ consecutiveFailures: number;
1853
+ /** Classification of the most recent failure (only set while `degraded`). */
1854
+ kind?: 'network' | 'application';
1855
+ /** Message of the most recent failure (only set while `degraded`). */
1856
+ error?: string;
1857
+ /**
1858
+ * `true` once at least one sync round has succeeded this session. Lets a UI
1859
+ * distinguish a first-time "connecting" phase (never reached the server yet,
1860
+ * so a cold-start failure run is expected) from a real lost connection after
1861
+ * a working session. Never resets back to `false` once set.
1862
+ */
1863
+ everConnected: boolean;
1864
+ /**
1865
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
1866
+ * one flips the instant the socket drops, whereas `status` only degrades
1867
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
1868
+ * immediately without waiting for the degrade threshold.
1869
+ */
1870
+ connection: ConnectionState;
1871
+ }
1872
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
1873
+ /**
1874
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
1875
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
1876
+ * server, this one is about whether the local store survives a reload.
1877
+ *
1878
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
1879
+ * which only one client per bucket can hold open. When it can't be opened (a
1880
+ * second tab of the app already has it, an insecure context, a full pool) the
1881
+ * engine keeps working against an in-memory DB, which holds the whole dataset
1882
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
1883
+ * so a UI can warn about it.
1884
+ */
1885
+ interface StorageHealth {
1886
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
1887
+ status: StorageHealthStatus;
1888
+ /**
1889
+ * `true` only when durable storage was REQUESTED and could not be opened.
1890
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
1891
+ * is a choice rather than a failure, so a UI can key off this alone.
1892
+ */
1893
+ fallback: boolean;
1894
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
1895
+ error?: string;
1896
+ /**
1897
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
1898
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
1899
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
1900
+ * single-tab behavior. Absent entirely when the feature is off.
1901
+ */
1902
+ role?: 'leader' | 'follower' | 'solo';
244
1903
  }
245
1904
  type QueryHash = string;
1905
+ /**
1906
+ * One changed row delivered inline on a LIVE notification, when the
1907
+ * subscription was opened with the body joined on (see
1908
+ * {@link Sp00kyConfig.liveInlineBodies}). `version` is the edge's `version`,
1909
+ * i.e. the same number the membership read would have reported for this row.
1910
+ */
1911
+ interface InlineRow {
1912
+ id: string;
1913
+ version: number;
1914
+ record: Record<string, unknown>;
1915
+ }
1916
+ /**
1917
+ * A row that joined a query's view, or moved to a newer version, as one LIVE
1918
+ * notification on `_00_list_ref` reports it: the edge's `out` and `version`.
1919
+ * The client commits it to the query's membership straight away instead of
1920
+ * re-reading the edges (see `sync/live.saga.ts`).
1921
+ */
1922
+ interface EdgeDelta {
1923
+ hash: QueryHash;
1924
+ id: string;
1925
+ version: number;
1926
+ }
246
1927
  type RecordVersionArray = Array<[string, number]>;
247
1928
  /**
248
1929
  * Represents the difference between two record version sets.
@@ -251,16 +1932,16 @@ type RecordVersionArray = Array<[string, number]>;
251
1932
  interface RecordVersionDiff {
252
1933
  /** List of records added. */
253
1934
  added: Array<{
254
- id: RecordId$1<string>;
1935
+ id: RecordId<string>;
255
1936
  version: number;
256
1937
  }>;
257
1938
  /** List of records updated. */
258
1939
  updated: Array<{
259
- id: RecordId$1<string>;
1940
+ id: RecordId<string>;
260
1941
  version: number;
261
1942
  }>;
262
1943
  /** List of record IDs removed. */
263
- removed: RecordId$1<string>[];
1944
+ removed: RecordId<string>[];
264
1945
  }
265
1946
  /**
266
1947
  * Configuration for a specific query instance.
@@ -268,15 +1949,53 @@ interface RecordVersionDiff {
268
1949
  */
269
1950
  interface QueryConfig {
270
1951
  /** The unique ID of the query config record. */
271
- id: RecordId$1<string>;
1952
+ id: RecordId<string>;
272
1953
  /** The SURQL query string. */
273
1954
  surql: string;
1955
+ /**
1956
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
1957
+ * `_00_query`). Present when the query came from the query-builder. Non-
1958
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
1959
+ * instead of re-running `surql`, which they cannot parse.
1960
+ */
1961
+ plan?: QueryPlan;
274
1962
  /** Parameters used in the query. */
275
1963
  params: Record<string, any>;
276
1964
  /** The version array representing the local state of results. */
277
1965
  localArray: RecordVersionArray;
278
1966
  /** The version array representing the remote (server) state of results. */
279
1967
  remoteArray: RecordVersionArray;
1968
+ /**
1969
+ * In-memory only (never persisted to `_00_query`): version array of the
1970
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
1971
+ * child-body sync is idempotent across polls. Kept separate from
1972
+ * `remoteArray` so related child rows never enter the primary window /
1973
+ * `rowCount` / `localArray`.
1974
+ */
1975
+ subqueryRemoteArray?: RecordVersionArray;
1976
+ /**
1977
+ * Whether authoritative membership (`remoteArray`) has ever been established
1978
+ * for this query — either fetched from `_00_list_ref` this session, or read
1979
+ * back from the durable `_00_view` row on a cold start.
1980
+ *
1981
+ * Tri-state matters: "known and empty" must render an empty list, while
1982
+ * "never established" has to fall back to a predicate scan of the local store
1983
+ * so a query first run on this device still paints offline. A
1984
+ * `remoteArray.length === 0` check cannot tell those apart.
1985
+ *
1986
+ * On a cold start it is seeded from the durable `_00_view` row when that
1987
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
1988
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
1989
+ * by an old client that mirrored unflushed reads still self-heals.
1990
+ */
1991
+ membershipKnown?: boolean;
1992
+ /**
1993
+ * Key of this query's durable `_00_view` membership row: a hash of
1994
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
1995
+ * survives a reload (which mints a new session id) and a bucket switch.
1996
+ * In-memory only.
1997
+ */
1998
+ membershipKey?: string;
280
1999
  /** Time-To-Live for this query. */
281
2000
  ttl: QueryTimeToLive;
282
2001
  /** Timestamp when the query was last accessed/active. */
@@ -287,6 +2006,39 @@ interface QueryConfig {
287
2006
  type QueryConfigRecord = QueryConfig & {
288
2007
  id: string;
289
2008
  };
2009
+ /**
2010
+ * Runtime fetch status of a live query.
2011
+ * - `idle`: registered, initial sync completed, and not currently fetching
2012
+ * missing records — the materialized rows are authoritative (a windowed
2013
+ * query's short result really is the end of the list).
2014
+ * - `fetching`: the query is registering (a query is born `fetching` until its
2015
+ * initial remote sync completes) or the sync engine is fetching/ingesting
2016
+ * missing records for it. Any pending debounced result is flushed BEFORE the
2017
+ * flip back to `idle`, so idle status never races ahead of the rows.
2018
+ */
2019
+ type QueryStatus = 'idle' | 'fetching';
2020
+ /**
2021
+ * What the server's `_00_query` row says about a view, read alongside its
2022
+ * `_00_list_ref` edges (registration, the poll, a targeted re-read).
2023
+ *
2024
+ * - `present: false`: the row is not there (or not readable). The SSP no
2025
+ * longer has this view: a TTL sweep, an SSP reset, a scheduler wipe. An
2026
+ * empty edge set read at the same time is NOT "no rows", it is "no view".
2027
+ * - `state: 'materializing'`: the SSP has (re)computed the set and its edges
2028
+ * are in flight; an empty read is "not landed yet".
2029
+ * - `state: 'ready'`: the edges are committed (flipped in the same
2030
+ * transaction), so `rowCount === 0` with no edges is a real empty result.
2031
+ * - `state: null`: a server that predates the marker; only `rowCount` can be
2032
+ * used, with its `> 0` = flush window / `0` = empty ambiguity.
2033
+ */
2034
+ interface ServerViewMeta {
2035
+ present: boolean;
2036
+ /** `_00_query.rowCount`; `null` when unreadable. */
2037
+ rowCount: number | null;
2038
+ state: 'materializing' | 'ready' | null;
2039
+ }
2040
+ /** Outcome of handing a server id-set to `DataModule.updateQueryRemoteArray`. */
2041
+ type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
290
2042
  /**
291
2043
  * Internal state of a live query.
292
2044
  */
@@ -295,15 +2047,121 @@ interface QueryState {
295
2047
  config: QueryConfig;
296
2048
  /** The current cached records for this query. */
297
2049
  records: Record<string, any>[];
2050
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
2051
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
2052
+ hydrated?: boolean;
2053
+ /** Set once a server-side membership set has been accepted this session
2054
+ * (`updateQueryRemoteArray`). The `register` down-event is enqueued before
2055
+ * the instant-hydrate, so a hydrate that finishes later must not prime
2056
+ * membership over the authoritative set. Ephemeral. */
2057
+ serverMembership?: boolean;
2058
+ /**
2059
+ * Set when the server's `_00_query` row for this query went missing while
2060
+ * we held membership (TTL sweep, SSP reset, scheduler wipe). The view is
2061
+ * being re-registered; until a readable row comes back, empty reads are
2062
+ * NOT the server's answer and nothing is dropped. Ephemeral.
2063
+ */
2064
+ viewLost?: boolean;
2065
+ /** Last `_00_query.state` read from the server, for DevTools. Ephemeral. */
2066
+ serverState?: 'materializing' | 'ready' | null;
2067
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
2068
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
2069
+ * always emits at least once even when its records are unchanged — otherwise
2070
+ * an empty re-registered window would never notify and stay "loading". */
2071
+ syncNotified?: boolean;
2072
+ /**
2073
+ * Subscribers hold the rows of a known membership (see `QueryLifecycle`'s
2074
+ * `answered`): what the authority channel and the bindings'
2075
+ * `isAuthoritative()` report. Ephemeral.
2076
+ */
2077
+ answered?: boolean;
298
2078
  /** Timer for TTL expiration. */
299
2079
  ttlTimer: NodeJS.Timeout | null;
300
2080
  /** TTL duration in milliseconds. */
301
2081
  ttlDurationMs: number;
2082
+ /** When the last TTL heartbeat for this query was sent (ms epoch); `undefined` before the first. */
2083
+ lastHeartbeatAt?: number;
302
2084
  /** Number of times the query has been updated. */
303
2085
  updateCount: number;
2086
+ /** Timestamp (ms) of the last user-visible update, or null before the first
2087
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
2088
+ lastUpdatedAt: number | null;
2089
+ /**
2090
+ * Rolling window of the most recent materialization-step latencies (ms).
2091
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
2092
+ * before each persist to `_00_query`. Samples themselves are not persisted.
2093
+ */
2094
+ materializationSamples: number[];
2095
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
2096
+ lastIngestLatencyMs: number | null;
2097
+ /** Cumulative count of ingest/materialization errors observed for this query. */
2098
+ errorCount: number;
2099
+ /**
2100
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
2101
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
2102
+ * pulling missing records for this query, otherwise `idle`.
2103
+ */
2104
+ status: QueryStatus;
2105
+ /**
2106
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
2107
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
2108
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
2109
+ */
2110
+ phaseSamples: Record<string, number[]>;
2111
+ /** Most recent sample (ms) per phase, or null. */
2112
+ phaseLast: Record<string, number | null>;
2113
+ /** One-shot SSP registration timings (ms). */
2114
+ registrationTimings: RegistrationTimings;
2115
+ }
2116
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
2117
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
2118
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
2119
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
2120
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
2121
+ /** One-shot registration timings (ms), captured once when a query registers. */
2122
+ interface RegistrationTimings {
2123
+ /** SSP surql→plan parse + permission injection. */
2124
+ parseMs: number | null;
2125
+ /** SSP operator-DAG build. */
2126
+ planMs: number | null;
2127
+ /** SSP initial snapshot evaluation. */
2128
+ snapshotMs: number | null;
2129
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
2130
+ wallMs: number | null;
2131
+ }
2132
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
2133
+ interface PhaseStat {
2134
+ lastMs: number | null;
2135
+ p50: number | null;
2136
+ p90: number | null;
2137
+ p99: number | null;
2138
+ count: number;
2139
+ }
2140
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
2141
+ interface QueryTimings {
2142
+ ssp: PhaseStat;
2143
+ sspStoreApply: PhaseStat;
2144
+ sspCircuitStep: PhaseStat;
2145
+ sspTransform: PhaseStat;
2146
+ localFetch: PhaseStat;
2147
+ remoteFetch: PhaseStat;
2148
+ frontend: PhaseStat;
2149
+ registration: RegistrationTimings;
2150
+ updateCount: number;
2151
+ errorCount: number;
304
2152
  }
305
2153
  type QueryUpdateCallback = (records: Record<string, any>[]) => void;
306
- type MutationCallback = (mutations: UpEvent[]) => void;
2154
+ type QueryStatusCallback = (status: QueryStatus) => void;
2155
+ /**
2156
+ * Observer for a query's authority flips: `true` once subscribers hold the
2157
+ * rendered rows of a known membership (a server answer whose bodies are
2158
+ * local, or the durable membership of an earlier session), delivered after
2159
+ * the rows that vouch for it; `false` when it is reset (bucket switch). Knowing the set is
2160
+ * not enough: a `cached` re-seed or a just-applied server set has no rows
2161
+ * painted yet. What the bindings' `isAuthoritative()` mirrors.
2162
+ */
2163
+ type QueryAuthorityCallback = (known: boolean) => void;
2164
+ type MutationCallback = (mutations: MutationEvent[]) => void;
307
2165
  type MutationEventType = 'create' | 'update' | 'delete';
308
2166
  /**
309
2167
  * Represents a mutation event (create, update, delete) to be synchronized.
@@ -312,9 +2170,9 @@ interface MutationEvent {
312
2170
  /** Example: 'create', 'update', or 'delete'. */
313
2171
  type: MutationEventType;
314
2172
  /** unique id of the mutation */
315
- mutation_id: RecordId$1<string>;
2173
+ mutation_id: RecordId<string>;
316
2174
  /** The ID of the record being mutated. */
317
- record_id: RecordId$1<string>;
2175
+ record_id: RecordId<string>;
318
2176
  /** The data payload for create/update operations. */
319
2177
  data?: any;
320
2178
  /** The full record data (optional context). */
@@ -331,6 +2189,13 @@ interface RunOptions {
331
2189
  assignedTo?: string;
332
2190
  max_retries?: number;
333
2191
  retry_strategy?: 'linear' | 'exponential';
2192
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
2193
+ timeout?: number;
2194
+ /**
2195
+ * Minimum delay in milliseconds before the job is eligible to run. While
2196
+ * delayed the job stays pending (enqueued) and can still be killed.
2197
+ */
2198
+ delay?: number;
334
2199
  }
335
2200
  /**
336
2201
  * Options for update operations.
@@ -354,6 +2219,20 @@ interface DebounceOptions {
354
2219
  key?: 'recordId' | 'recordId_x_fields';
355
2220
  /** The debounce delay in milliseconds. */
356
2221
  delay?: number;
2222
+ /**
2223
+ * Keep the pending patch across a reload or a closed tab. Default `true`.
2224
+ *
2225
+ * Every call also writes the merged patch to `_00_pending_writes`, in the
2226
+ * same local transaction as the row itself. When the page is hidden (tab
2227
+ * switch, reload, close, app sent to the background) every pending patch is
2228
+ * moved into the outbox and pushed at once instead of waiting out `delay`.
2229
+ * A page that dies before that finishes leaves the patch in the store, and
2230
+ * the next boot moves it into the outbox.
2231
+ *
2232
+ * `false` keeps the patch in memory only, so whatever is still inside its
2233
+ * delay is lost on reload. Meant for throwaway state like a cursor position.
2234
+ */
2235
+ flushOnHide?: boolean;
357
2236
  }
358
2237
  //#endregion
359
- export { Logger$1 as C, UpdateOptions as S, EventSystem as T, RunOptions as _, MutationEvent as a, Sp00kyQueryResultPromise 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, Sp00kyConfig as v, EventDefinition as w, StoreType as x, Sp00kyQueryResult as y };
2238
+ export { WebPushModule as $, RegistrationTimings as A, RemoteDatabaseService as At, SyncHealthConfig as B, ImpersonationTimers as Bt, QueryStatusCallback as C, SIGN_OUT_HOOK_TIMEOUT_MS as Ct, ReconnectConfig as D, AuthEventTypeMap as Dt, QueryUpdateCallback as E, AuthEventSystem as Et, Sp00kyQueryResultPromise as F, EventDefinition as Ft, PushDeviceKind as G, impersonationFromToken as Gt, TimingPhase as H, SESSION_POLL_MS as Ht, StorageHealth as I, EventSystem as It, WebPushError as J, WebPushConfig as K, renewDelayMs as Kt, StorageHealthStatus as L, IMPERSONATION_ACCESS as Lt, ServerViewMeta as M, Logger$1 as Mt, Sp00kyConfig as N, LocalStore as Nt, RecordVersionArray as O, AuthEventTypes as Ot, Sp00kyQueryResult as P, SealedQuery as Pt, WebPushMessageInput as Q, StoreType as R, ImpersonationInfo as Rt, QueryStatus as S, REFUSAL_RECHECK_MIN_MS as St, QueryTimings as T, SignOutHook as Tt, UpdateOptions as U, TokenClaims as Ut, SyncHealthStatus as V, ORIGIN_TOKEN_KEY as Vt, PUSH_ENDPOINT_KEY as W, decodeTokenClaims as Wt, WebPushInfo as X, WebPushErrorCode as Y, WebPushMessage as Z, QueryAuthorityCallback as _, WebPushClientMessage as _t, InlineRow as a, WebPushUnsupportedReason as at, QueryHash as b, AuthService as bt, MembershipOutcome as c, BridgeSignOutMessage as ct, MutationEventType as d, PushNotification as dt, WebPushSubscribeOptions as et, PersistenceClient as f, PushNotificationAction as ft, PreloadRefresh as g, PushUrgency as gt, PreloadOptions as h, PushPayloadKind as ht, EventSubscriptionOptions as i, WebPushUnsubscribeOptions as it, RunOptions as j, LogTap as jt, RecordVersionDiff as k, createAuthEventSystem as kt, MutationCallback as l, BridgeTokenMessage as lt, PinoTransmit as m, PushPayload as mt, DebounceOptions as n, WebPushSyncOptions as nt, Level$1 as o, WebPushUpdateOptions as ot, PhaseStat as p, PushOp as pt, WebPushDevice as q, sameImpersonation as qt, EdgeDelta as r, WebPushSyncStatus as rt, MATERIALIZATION_SAMPLE_WINDOW as s, detectWebPushSupport as st, ConnectionState as t, WebPushSupport as tt, MutationEvent as u, PUSH_PAYLOAD_VERSION as ut, QueryConfig as v, isPushPayload as vt, QueryTimeToLive as w, SignOutContext as wt, QueryState as x, ImpersonationCandidate as xt, QueryConfigRecord as y, ActiveImpersonation as yt, SyncHealth as z, ImpersonationTimerHost as zt };