@spooky-sync/core 0.0.1-canary.33 → 0.0.1-canary.331

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 (266) hide show
  1. package/AGENTS.md +84 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2080 -142
  4. package/dist/index.js +16009 -2480
  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 +373 -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 +1857 -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 +32 -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 +187 -0
  34. package/src/boot/bucket-switch.saga.ts +133 -0
  35. package/src/boot/preload.saga.test.ts +80 -0
  36. package/src/boot/preload.saga.ts +40 -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 +195 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.test.ts +74 -0
  46. package/src/client/services.ts +434 -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 +167 -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/events/index.ts +9 -2
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +205 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +476 -22
  72. package/src/modules/crdt/acceptance.ts +75 -0
  73. package/src/modules/crdt/bytes.ts +50 -0
  74. package/src/modules/crdt/crdt-field.ts +125 -0
  75. package/src/modules/crdt/crdt.test.ts +469 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +757 -0
  78. package/src/modules/crdt/loro-loader.ts +25 -0
  79. package/src/modules/crdt/mirror.ts +37 -0
  80. package/src/modules/devtools/flags.ts +349 -0
  81. package/src/modules/devtools/index.ts +746 -95
  82. package/src/modules/devtools/mutations.test.ts +92 -0
  83. package/src/modules/devtools/mutations.ts +160 -0
  84. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  85. package/src/modules/devtools/state-shape.test.ts +263 -0
  86. package/src/modules/devtools/storage-info.test.ts +79 -0
  87. package/src/modules/devtools/storage-info.ts +168 -0
  88. package/src/modules/devtools/versions.test.ts +74 -0
  89. package/src/modules/devtools/versions.ts +110 -0
  90. package/src/modules/feature-flag/index.test.ts +298 -0
  91. package/src/modules/feature-flag/index.ts +316 -0
  92. package/src/modules/ref-tables.test.ts +93 -0
  93. package/src/modules/ref-tables.ts +91 -0
  94. package/src/modules/web-push/index.test.ts +824 -0
  95. package/src/modules/web-push/index.ts +1027 -0
  96. package/src/mutation/jobs.test.ts +25 -0
  97. package/src/mutation/jobs.ts +41 -0
  98. package/src/mutation/mutation-id.test.ts +37 -0
  99. package/src/mutation/mutation-id.ts +35 -0
  100. package/src/mutation/pending-writes.integration.test.ts +175 -0
  101. package/src/mutation/push.saga.test.ts +301 -0
  102. package/src/mutation/push.saga.ts +225 -0
  103. package/src/mutation/rows.test.ts +231 -0
  104. package/src/mutation/rows.ts +427 -0
  105. package/src/mutation/tray.saga.test.ts +63 -0
  106. package/src/mutation/tray.saga.ts +48 -0
  107. package/src/mutation/write.saga.test.ts +316 -0
  108. package/src/mutation/write.saga.ts +268 -0
  109. package/src/otel/index.ts +10 -7
  110. package/src/pure.ts +66 -0
  111. package/src/push/types.ts +174 -0
  112. package/src/query/anon-query-isolation.integration.test.ts +527 -0
  113. package/src/query/env.test.ts +23 -0
  114. package/src/query/env.ts +65 -0
  115. package/src/query/fetch.saga.test.ts +199 -0
  116. package/src/query/fetch.saga.ts +120 -0
  117. package/src/query/hash.test.ts +14 -0
  118. package/src/query/hash.ts +18 -0
  119. package/src/query/id-set-plan.test.ts +132 -0
  120. package/src/query/lifecycle.saga.test.ts +274 -0
  121. package/src/query/lifecycle.saga.ts +186 -0
  122. package/src/query/list-ref-live.integration.test.ts +203 -0
  123. package/src/query/materialize.saga.test.ts +115 -0
  124. package/src/query/materialize.saga.ts +84 -0
  125. package/src/query/materialize.test.ts +58 -0
  126. package/src/query/materialize.ts +57 -0
  127. package/src/query/membership.saga.test.ts +407 -0
  128. package/src/query/membership.saga.ts +282 -0
  129. package/src/query/membership.test.ts +118 -0
  130. package/src/query/membership.ts +201 -0
  131. package/src/query/register.saga.test.ts +311 -0
  132. package/src/query/register.saga.ts +235 -0
  133. package/src/query/render-set.test.ts +47 -0
  134. package/src/query/render-set.ts +71 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +157 -0
  137. package/src/query/window-query.test.ts +70 -0
  138. package/src/query/window-query.ts +208 -0
  139. package/src/services/blobs/blob-cache.test.ts +359 -0
  140. package/src/services/blobs/blob-cache.ts +603 -0
  141. package/src/services/blobs/blob-manifest.ts +227 -0
  142. package/src/services/blobs/blob-store.test.ts +77 -0
  143. package/src/services/blobs/blob-store.ts +359 -0
  144. package/src/services/blobs/blob.fixture.ts +90 -0
  145. package/src/services/blobs/index.ts +70 -0
  146. package/src/services/database/cache-engine.ts +209 -0
  147. package/src/services/database/connection-supervisor.test.ts +318 -0
  148. package/src/services/database/connection-supervisor.ts +422 -0
  149. package/src/services/database/database.query-timeout.test.ts +140 -0
  150. package/src/services/database/database.responses.test.ts +43 -0
  151. package/src/services/database/database.ts +156 -61
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/events/index.ts +2 -1
  155. package/src/services/database/index.ts +7 -0
  156. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  157. package/src/services/database/local-migrator.integration.test.ts +110 -0
  158. package/src/services/database/local-migrator.ts +61 -16
  159. package/src/services/database/local.test.ts +150 -0
  160. package/src/services/database/local.ts +508 -63
  161. package/src/services/database/plan-render.test.ts +159 -0
  162. package/src/services/database/plan-render.ts +108 -0
  163. package/src/services/database/relation-resolver.test.ts +484 -0
  164. package/src/services/database/relation-resolver.ts +0 -0
  165. package/src/services/database/remote.ts +285 -6
  166. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  167. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  168. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  169. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  170. package/src/services/database/sqlite-column-reset.ts +91 -0
  171. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  172. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  173. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  174. package/src/services/database/sqlite-lock-verify.ts +45 -0
  175. package/src/services/database/sqlite-open.test.ts +150 -0
  176. package/src/services/database/sqlite-open.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  178. package/src/services/database/sqlite-plan-sql.ts +196 -0
  179. package/src/services/database/sqlite-projection.test.ts +121 -0
  180. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  181. package/src/services/database/sqlite-select.test.ts +261 -0
  182. package/src/services/database/sqlite-select.ts +131 -0
  183. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  184. package/src/services/database/sqlite-transport.ts +224 -0
  185. package/src/services/database/sqlite-worker.ts +437 -0
  186. package/src/services/database/surql-translate.ts +417 -0
  187. package/src/services/database/surreal-cache-engine.ts +163 -0
  188. package/src/services/logger/index.test.ts +132 -0
  189. package/src/services/logger/index.ts +189 -7
  190. package/src/services/persistence/localstorage.ts +2 -2
  191. package/src/services/persistence/resilient.ts +10 -3
  192. package/src/services/persistence/surrealdb.ts +4 -4
  193. package/src/services/stream-processor/index.ts +806 -67
  194. package/src/services/stream-processor/permissions.test.ts +47 -0
  195. package/src/services/stream-processor/permissions.ts +53 -0
  196. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  197. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  198. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  199. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  200. package/src/services/stream-processor/wasm-types.ts +58 -2
  201. package/src/services/tabs/broker-client.ts +284 -0
  202. package/src/services/tabs/broker.test.ts +381 -0
  203. package/src/services/tabs/coordinator.test.ts +386 -0
  204. package/src/services/tabs/coordinator.ts +646 -0
  205. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  206. package/src/services/tabs/leader-locks.ts +75 -0
  207. package/src/services/tabs/protocol.ts +262 -0
  208. package/src/services/tabs/support.ts +36 -0
  209. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  210. package/src/sp00ky.ts +5 -395
  211. package/src/state/client-state.ts +208 -0
  212. package/src/state/lifecycle.test.ts +141 -0
  213. package/src/state/lifecycle.ts +99 -0
  214. package/src/state/reducers.test.ts +306 -0
  215. package/src/state/reducers.ts +531 -0
  216. package/src/state/selectors.test.ts +188 -0
  217. package/src/state/selectors.ts +258 -0
  218. package/src/sw/index.test.ts +582 -0
  219. package/src/sw/index.ts +607 -0
  220. package/src/sw/store.ts +96 -0
  221. package/src/sync/connection.saga.test.ts +97 -0
  222. package/src/sync/connection.saga.ts +89 -0
  223. package/src/sync/live.saga.test.ts +178 -0
  224. package/src/sync/live.saga.ts +107 -0
  225. package/src/sync/policy.health.test.ts +56 -0
  226. package/src/sync/policy.test.ts +663 -0
  227. package/src/sync/policy.ts +515 -0
  228. package/src/sync/poll.saga.test.ts +51 -0
  229. package/src/sync/poll.saga.ts +36 -0
  230. package/src/sync/tabs.saga.test.ts +78 -0
  231. package/src/sync/tabs.saga.ts +96 -0
  232. package/src/testing/adapters.ts +137 -0
  233. package/src/testing/build.ts +63 -0
  234. package/src/testing/fake-services.ts +63 -0
  235. package/src/testing/run-pure.test.ts +92 -0
  236. package/src/testing/run-pure.ts +128 -0
  237. package/src/testing/services.ts +17 -0
  238. package/src/types.ts +633 -10
  239. package/src/utils/blurhash.ts +90 -0
  240. package/src/utils/edges.ts +39 -0
  241. package/src/utils/error-classification.test.ts +54 -0
  242. package/src/utils/error-classification.ts +25 -0
  243. package/src/utils/index.ts +89 -12
  244. package/src/utils/parser.test.ts +67 -102
  245. package/src/utils/parser.ts +64 -2
  246. package/src/utils/semver.test.ts +32 -0
  247. package/src/utils/semver.ts +30 -0
  248. package/src/utils/sha256.ts +15 -0
  249. package/src/utils/surql.ts +29 -18
  250. package/src/utils/utils.test.ts +3 -2
  251. package/tsdown.config.ts +117 -3
  252. package/vitest.config.ts +48 -0
  253. package/src/modules/cache/index.ts +0 -241
  254. package/src/modules/cache/types.ts +0 -19
  255. package/src/modules/data/data.test.ts +0 -58
  256. package/src/modules/data/index.ts +0 -879
  257. package/src/modules/sync/engine.ts +0 -173
  258. package/src/modules/sync/events/index.ts +0 -77
  259. package/src/modules/sync/index.ts +0 -3
  260. package/src/modules/sync/queue/index.ts +0 -2
  261. package/src/modules/sync/queue/queue-down.ts +0 -89
  262. package/src/modules/sync/queue/queue-up.ts +0 -223
  263. package/src/modules/sync/scheduler.ts +0 -84
  264. package/src/modules/sync/sync.ts +0 -421
  265. package/src/modules/sync/utils.test.ts +0 -311
  266. 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,1118 @@ 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
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
826
+ type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
827
+ 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;
828
+ declare class AuthService<S extends SchemaStructure> {
829
+ private schema;
830
+ private remote;
831
+ private persistenceClient;
832
+ private logger;
833
+ token: string | null;
834
+ currentUser: any | null;
835
+ isAuthenticated: boolean;
836
+ /**
837
+ * The record-access method name for the current session (e.g. `"account"`),
838
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
839
+ * permission injection so `$access`-gated table predicates resolve locally,
840
+ * mirroring the server's `$access`. Null when logged out.
841
+ */
842
+ access: string | null;
843
+ isLoading: boolean;
844
+ private events;
845
+ private signOutHooks;
846
+ /** The impersonation last announced, for change detection. */
847
+ private announcedImpersonation;
848
+ /** Target of an impersonation that just ended, until the client purges its
849
+ * local bucket (see `consumeEndedImpersonation`). */
850
+ private endedImpersonationTarget;
851
+ /** The way back to the admin in flight. The Stop button, the session poll,
852
+ * a refused renewal and a rejected check can all end an impersonation, and
853
+ * they share this one: a second stop running beside the first found the
854
+ * admin token already taken and signed the admin out. */
855
+ private stopping;
856
+ /** A token renewal in flight, which a stop waits out (see `renewImpersonation`). */
857
+ private renewing;
858
+ private impersonationTimers;
859
+ get eventSystem(): AuthEventSystem;
860
+ constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
861
+ init(): Promise<void>;
862
+ getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
863
+ /**
864
+ * Subscribe to auth state changes.
865
+ * callback is called immediately with current value and whenever validation status changes.
866
+ * `immediate: false` skips that first call: only changes are reported.
867
+ */
868
+ subscribe(cb: (userId: string | null) => void, opts?: {
869
+ immediate?: boolean;
870
+ }): () => void;
871
+ /**
872
+ * Run `hook` at the start of every sign-out, while the token and the socket
873
+ * still belong to the leaving user (Web Push removes this device's
874
+ * subscription here). Hooks are best-effort: they run in parallel, errors
875
+ * are swallowed, and the sign-out goes on after
876
+ * {@link SIGN_OUT_HOOK_TIMEOUT_MS} whatever they are doing. Returns a disposer.
877
+ */
878
+ onBeforeSignOut(hook: SignOutHook): () => void;
879
+ private runSignOutHooks;
880
+ /**
881
+ * The signed-in user as subscribers see it: the raw `table:id` string, the
882
+ * way the token's `ID` claim spells it. `currentUser.id` is that string while
883
+ * the session is restored from the token and the server's `RecordId` once
884
+ * `check()` has answered, and the two must announce as the same user: every
885
+ * subscriber that compares ids (feature flags, app release) took the switch
886
+ * for a new principal and reset, so flag-gated UI blinked off and back on a
887
+ * few seconds into every reload. A `RecordId`'s own `toString()` will not do
888
+ * either, as it escapes ids like `user:⟨5abc⟩` that the claim spells raw.
889
+ */
890
+ private announcedUserId;
891
+ private notifyListeners;
892
+ /**
893
+ * The impersonation the current session is, or null. Derived from the
894
+ * token in use, so it always describes the identity the server sees.
895
+ */
896
+ get impersonation(): ImpersonationInfo | null;
897
+ /** Subscribe to impersonation changes; called immediately with the current value. */
898
+ subscribeImpersonation(cb: (info: ImpersonationInfo | null) => void): () => void;
899
+ /**
900
+ * Act as `targetId` (a record id such as `user:abc`). Admins only, and only
901
+ * when the project enabled `impersonation` in sp00ky.yml: the server refuses
902
+ * everything else. `reason` is recorded in the audit log.
903
+ *
904
+ * The admin's session is kept aside and restored by
905
+ * {@link stopImpersonating}. Local data switches to the target's bucket
906
+ * exactly as on a sign-in, and that bucket is removed on stop.
907
+ */
908
+ impersonate(targetId: string, reason: string): Promise<ImpersonationInfo>;
909
+ /**
910
+ * Return to the admin session. Always leaves the impersonated identity,
911
+ * even when the server cannot be reached: the admin token is restored
912
+ * locally first and verified afterwards, and a rejected admin token ends in
913
+ * a full sign-out rather than staying on the target.
914
+ */
915
+ stopImpersonating(opts?: {
916
+ serverEnded?: boolean;
917
+ }): Promise<void>;
918
+ private leaveImpersonation;
919
+ /** Re-sign the impersonation token before it expires. */
920
+ renewImpersonation(): Promise<void>;
921
+ private applyRenewal;
922
+ /** Users an admin may pick from. Admin-only on the server. */
923
+ searchImpersonationTargets(search: string): Promise<ImpersonationCandidate[]>;
924
+ /** Open impersonation sessions. Admin-only on the server. */
925
+ listActiveImpersonations(): Promise<ActiveImpersonation[]>;
926
+ /**
927
+ * The target of an impersonation that ended, once. The bucket switch calls
928
+ * this after leaving a bucket so it can delete that user's local data.
929
+ */
930
+ consumeEndedImpersonation(): string | null;
931
+ /**
932
+ * Restore a session from the locally cached JWT, with NO network.
933
+ *
934
+ * This is what makes a warm boot paint instantly and what makes an offline
935
+ * boot possible at all: the token is in local storage, and it already carries
936
+ * both the access method and the `$auth.id` record id. Everything the client
937
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
938
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
939
+ * available before a socket exists.
940
+ *
941
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
942
+ * afterwards in the background and downgrades to a real sign-out if the
943
+ * server rejects it. Nothing is trusted that the server has not also seen -
944
+ * the local store only ever holds rows the server previously sent.
945
+ *
946
+ * Returns the restored user id, or null when there is no usable token.
947
+ */
948
+ restoreSessionFromToken(): Promise<string | null>;
949
+ /**
950
+ * Check for existing session and validate
951
+ */
952
+ check(accessToken?: string): Promise<void>;
953
+ /** Hold a session the server accepted without its user row: the id comes
954
+ * from the token, as on a warm boot. A token naming no user is refused. */
955
+ private keepAcceptedSession;
956
+ /**
957
+ * The server refused `token`. A refused impersonation token (stopped,
958
+ * expired, or revoked) returns to the admin session instead of signing the
959
+ * admin out; anything else signs out.
960
+ */
961
+ private rejectToken;
962
+ /**
963
+ * Sign out and clear session. While impersonating this ends the
964
+ * impersonation and signs the admin out too.
965
+ */
966
+ signOut(): Promise<void>;
967
+ private setSession;
968
+ /** Fallback when the token carries no `AC` claim: if the schema defines
969
+ * exactly one record-access method, assume the session used it. */
970
+ private defaultAccessName;
971
+ signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
972
+ signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
973
+ }
974
+ //#endregion
975
+ //#region src/push/types.d.ts
976
+ /**
977
+ * Web Push wire types shared by the page (`db.webPush`), the service worker
978
+ * bridge (`@spooky-sync/core/sw`) and the live feed. Pure: types plus a few
979
+ * dependency-free helpers, safe in any context.
980
+ *
981
+ * `PushPayload` mirrors `packages/push-core/src/config.rs` (`PushPayload`,
982
+ * `PayloadKind`, `Op`, `NotificationTemplate`). Keep the two in step.
983
+ */
984
+ /** Payload format version this build understands. */
985
+ declare const PUSH_PAYLOAD_VERSION = 1;
986
+ type PushPayloadKind = 'rule' | 'message';
987
+ type PushOp = 'create' | 'update' | 'delete';
988
+ type PushUrgency = 'very-low' | 'low' | 'normal' | 'high';
989
+ /** One button on a notification (`NotificationAction` plus a per-action `url`). */
990
+ interface PushNotificationAction {
991
+ action: string;
992
+ title: string;
993
+ icon?: string;
994
+ /** Opened instead of the notification's `url` when this action is clicked. */
995
+ url?: string;
996
+ [key: string]: unknown;
997
+ }
998
+ /**
999
+ * What a content push shows. Every key other than `title` and `url` is passed
1000
+ * to `showNotification` as is, unknown ones included (`vibrate`, `timestamp`,
1001
+ * whatever a browser adds later).
1002
+ */
1003
+ interface PushNotification {
1004
+ title?: string;
1005
+ body?: string;
1006
+ icon?: string;
1007
+ badge?: string;
1008
+ image?: string;
1009
+ lang?: string;
1010
+ dir?: string;
1011
+ /** Defaults to the push's `topic`. */
1012
+ tag?: string;
1013
+ /** Opened (or focused) on click. */
1014
+ url?: string;
1015
+ requireInteraction?: boolean;
1016
+ renotify?: boolean;
1017
+ silent?: boolean;
1018
+ actions?: PushNotificationAction[];
1019
+ /** Merged into the notification's `data` next to the bridge's own keys. */
1020
+ data?: Record<string, unknown>;
1021
+ [key: string]: unknown;
1022
+ }
1023
+ /**
1024
+ * The JSON every push carries (then RFC 8291 encrypted). `notification`
1025
+ * present: a content push the service worker shows as is. Absent: a
1026
+ * content-free nudge, the app renders from its own data.
1027
+ */
1028
+ interface PushPayload {
1029
+ v: number;
1030
+ kind: PushPayloadKind;
1031
+ /** Rule name (`kind: 'rule'`). */
1032
+ rule?: string;
1033
+ /** `_00_push_message` id (`kind: 'message'`). */
1034
+ message?: string;
1035
+ /** The row that fired the rule. */
1036
+ table?: string;
1037
+ id?: string;
1038
+ op?: PushOp;
1039
+ topic?: string;
1040
+ notification?: PushNotification;
1041
+ data?: Record<string, unknown>;
1042
+ /** Epoch ms when the engine built it. */
1043
+ ts: number;
1044
+ }
1045
+ /** Page -> service worker: the session to use for live rendering. */
1046
+ interface BridgeTokenMessage {
1047
+ type: 'sp00ky:token';
1048
+ token: string;
1049
+ userId: string;
1050
+ /** The SurrealDB endpoint (`wss://host/rpc`), not the push endpoint. */
1051
+ endpoint: string;
1052
+ namespace: string;
1053
+ database: string;
1054
+ /** VAPID public key (base64url) the page subscribed with, for `pushsubscriptionchange`. */
1055
+ publicKey?: string;
1056
+ /** This browser's push endpoint, when subscribed. */
1057
+ pushEndpoint?: string;
1058
+ }
1059
+ /** Page -> service worker: forget the session and close every notification. */
1060
+ interface BridgeSignOutMessage {
1061
+ type: 'sp00ky:signout';
1062
+ }
1063
+ /** Service worker -> page messages. */
1064
+ type WebPushClientMessage = /** A push arrived while this page was visible, so nothing was shown. */
1065
+ {
1066
+ type: 'sp00ky:push';
1067
+ payload: PushPayload;
1068
+ }
1069
+ /** A notification was clicked and the bridge was told to route in-app. */ | {
1070
+ type: 'sp00ky:navigate';
1071
+ url: string;
1072
+ payload?: PushPayload;
1073
+ action?: string;
1074
+ }
1075
+ /** The browser rotated the push subscription; the page should `sync()`. */ | {
1076
+ type: 'sp00ky:subscriptionchange';
1077
+ endpoint?: string;
153
1078
  };
154
- type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
1079
+ /** `urlBase64ToUint8Array`: the VAPID key as `applicationServerKey` wants it. */
1080
+
1081
+ /** A payload this build can act on (`v` known, `kind` set). */
1082
+ declare function isPushPayload(value: unknown): value is PushPayload;
1083
+ //#endregion
1084
+ //#region src/modules/web-push/index.d.ts
1085
+ /**
1086
+ * `db.webPush`: this browser's Web Push subscription, on the page.
1087
+ *
1088
+ * Every server call is a `fn::push::*` function over the client's remote
1089
+ * connection (see `apps/cli/src/push_tables.surql`). Nothing here touches a
1090
+ * browser API at import time, and every method answers "unsupported" instead
1091
+ * of throwing where there is no window, service worker or push manager
1092
+ * (SSR, Node, workers, iOS Safari outside a home-screen app).
1093
+ */
1094
+ interface WebPushConfig {
1095
+ /**
1096
+ * Registered with `navigator.serviceWorker.register(url)` when the page has
1097
+ * no service worker yet. Leave unset when the app (or vite-plugin-pwa)
1098
+ * registers its own.
1099
+ */
1100
+ serviceWorkerUrl?: string;
1101
+ /**
1102
+ * Reconcile this browser's subscription after sign-in (see `sync()`): a
1103
+ * rotated key, a browser that dropped the subscription or a server row that
1104
+ * went away are repaired without a prompt. Default `true`.
1105
+ */
1106
+ autoSync?: boolean;
1107
+ /**
1108
+ * Let `sync()` subscribe a signed-in user whenever notification permission
1109
+ * is already granted, even if they never subscribed on this browser.
1110
+ * Default `false`: only a user who called `subscribe()` here is restored.
1111
+ */
1112
+ autoResubscribe?: boolean;
1113
+ /**
1114
+ * Remove this device's subscription for the user on `signOut()` (before the
1115
+ * token is dropped, bounded by a short timeout). Default `true`.
1116
+ */
1117
+ unsubscribeOnSignOut?: boolean;
1118
+ /**
1119
+ * Post the session token to the app's service worker whenever it changes,
1120
+ * while notifications are allowed, so `@spooky-sync/core/sw` can render from
1121
+ * live data. Never posts an impersonation token. Default `true`.
1122
+ */
1123
+ bridge?: boolean;
1124
+ }
1125
+ type WebPushUnsupportedReason = 'no-window' | 'insecure-context' | 'no-service-worker' | 'no-push-manager' | 'no-notification' | 'ios-not-installed';
1126
+ interface WebPushSupport {
1127
+ supported: boolean;
1128
+ permission: NotificationPermission | 'unsupported';
1129
+ reason?: WebPushUnsupportedReason;
1130
+ }
1131
+ interface WebPushInfo {
1132
+ /** A host with push on has published its key. */
1133
+ enabled: boolean;
1134
+ /** VAPID public key (base64url), the browser's `applicationServerKey`. */
1135
+ publicKey?: string;
1136
+ /** Id of that key. */
1137
+ kid?: string;
1138
+ /**
1139
+ * Every kind of device the project reaches: `web` once a VAPID key is
1140
+ * published, `apns` / `fcm` when `push.apns` / `push.fcm` are configured.
1141
+ */
1142
+ providers?: PushDeviceKind[];
1143
+ }
1144
+ /** How a device is reached: a browser (Web Push), APNs or FCM. */
1145
+ type PushDeviceKind = 'web' | 'apns' | 'fcm';
1146
+ interface WebPushDevice {
1147
+ /** `_00_push_subscription:<id>` */
1148
+ id: string;
1149
+ /** Web: the push service URL. Native: `<kind>:<token>`. */
1150
+ endpoint: string;
1151
+ /** Rows the Flutter / native side registered are `apns` or `fcm`. */
1152
+ kind: PushDeviceKind;
1153
+ /** `web`, `ios`, `android` or `macos`. */
1154
+ platform?: string;
1155
+ /** Native: bundle id / package name. */
1156
+ appId?: string;
1157
+ /** APNs: `sandbox` or `production`. */
1158
+ environment?: string;
1159
+ /** Key id a web device subscribed under (empty for native ones). */
1160
+ kid: string;
1161
+ label?: string;
1162
+ userAgent?: string;
1163
+ /** Rule names this device receives; undefined = every rule. */
1164
+ rules?: string[];
1165
+ meta?: Record<string, unknown>;
1166
+ createdAt?: Date;
1167
+ updatedAt?: Date;
1168
+ lastOkAt?: Date;
1169
+ lastError?: string;
1170
+ failures: number;
1171
+ disabledAt?: Date;
1172
+ disabledReason?: string;
1173
+ /** Subscribed under the current key (pushes reach it). Undefined when unknown. */
1174
+ current?: boolean;
1175
+ /** This browser. */
1176
+ thisDevice: boolean;
1177
+ }
1178
+ interface WebPushSubscribeOptions {
1179
+ /** Defaults to the page's service worker registration (`serviceWorker.ready`). */
1180
+ registration?: ServiceWorkerRegistration;
1181
+ /** Shown in the device list ("Work laptop"). */
1182
+ label?: string;
1183
+ /** Rule names this device wants. Omitted or empty: every rule. */
1184
+ rules?: string[];
1185
+ /** Free-form app data about the device. */
1186
+ meta?: Record<string, unknown>;
1187
+ /** Ask for notification permission when it is still `default`. Default `true`. Call from a user gesture. */
1188
+ requestPermission?: boolean;
1189
+ }
1190
+ interface WebPushUnsubscribeOptions {
1191
+ /** Remove every device of the user, not only this one. */
1192
+ all?: boolean;
1193
+ /** Keep the browser's PushSubscription (only the server row goes). */
1194
+ keepBrowserSubscription?: boolean;
1195
+ }
1196
+ interface WebPushSyncOptions {
1197
+ registration?: ServiceWorkerRegistration;
1198
+ /** Overrides `webPush.autoResubscribe` for this call. */
1199
+ autoResubscribe?: boolean;
1200
+ }
1201
+ /**
1202
+ * What `sync()` did. `ok`: nothing to repair. `resubscribed`: the browser
1203
+ * subscription was (re)created. `registered`: the server row was re-created.
1204
+ * The rest say why nothing happened.
1205
+ */
1206
+ type WebPushSyncStatus = 'ok' | 'resubscribed' | 'registered' | 'unsupported' | 'signed-out' | 'impersonating' | 'permission-default' | 'permission-denied' | 'not-subscribed' | 'disabled' | 'no-registration' | 'error';
1207
+ interface WebPushUpdateOptions {
1208
+ label?: string;
1209
+ /** Rule names; `null` or `[]` resets the device to every rule. */
1210
+ rules?: string[] | null;
1211
+ meta?: Record<string, unknown>;
1212
+ }
1213
+ /** A push to yourself (`fn::push::notify`). */
1214
+ interface WebPushMessageInput {
1215
+ /** Omit for a content-free nudge. */
1216
+ notification?: PushNotification;
1217
+ data?: Record<string, unknown>;
1218
+ topic?: string;
1219
+ urgency?: PushUrgency;
1220
+ /** Push-service TTL, seconds. */
1221
+ ttl?: number;
1222
+ /** In the future: scheduled. */
1223
+ sendAt?: Date | string | number;
1224
+ }
1225
+ interface WebPushMessage {
1226
+ /** `_00_push_message:<id>` */
1227
+ id: string;
1228
+ status: string;
1229
+ sendAt?: Date;
1230
+ createdAt?: Date;
1231
+ }
1232
+ type WebPushErrorCode = 'unsupported' | 'signed-out' | 'impersonating' | 'disabled' | 'permission-denied' | 'permission-default' | 'no-registration' | 'not-subscribed' | 'subscribe-failed' | 'server';
1233
+ declare class WebPushError extends Error {
1234
+ readonly code: WebPushErrorCode;
1235
+ readonly cause?: unknown | undefined;
1236
+ constructor(code: WebPushErrorCode, message: string, cause?: unknown | undefined);
1237
+ }
1238
+ interface WebPushAuthPort {
1239
+ readonly token: string | null;
1240
+ readonly currentUser: {
1241
+ id?: unknown;
1242
+ } | null;
1243
+ readonly isAuthenticated: boolean;
1244
+ readonly impersonation: unknown;
1245
+ subscribe(cb: (userId: unknown) => void): () => void;
1246
+ onBeforeSignOut(hook: (ctx: SignOutContext) => Promise<void> | void): () => void;
1247
+ }
1248
+ interface WebPushRemotePort {
1249
+ query<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
1250
+ }
1251
+ /** Browser globals, read at call time. Injectable for tests. */
1252
+ interface WebPushGlobals {
1253
+ window?: unknown;
1254
+ navigator?: Navigator & {
1255
+ standalone?: boolean;
1256
+ };
1257
+ Notification?: {
1258
+ permission: NotificationPermission;
1259
+ requestPermission(cb?: (p: NotificationPermission) => void): Promise<NotificationPermission> | void;
1260
+ };
1261
+ isSecureContext?: boolean;
1262
+ matchMedia?: (query: string) => {
1263
+ matches: boolean;
1264
+ };
1265
+ PushManager?: unknown;
1266
+ }
1267
+ interface WebPushModuleDeps {
1268
+ remote: WebPushRemotePort;
1269
+ auth: WebPushAuthPort;
1270
+ persistence: PersistenceClient;
1271
+ logger: Logger$1;
1272
+ database: {
1273
+ endpoint?: string;
1274
+ namespace: string;
1275
+ database: string;
1276
+ };
1277
+ /** Transport state; auto-sync waits for `connected`. */
1278
+ connection?: {
1279
+ subscribe(cb: (state: string) => void): () => void;
1280
+ };
1281
+ config?: WebPushConfig;
1282
+ globals?: () => WebPushGlobals;
1283
+ }
1284
+ declare const PUSH_ENDPOINT_KEY = "sp00ky_push_endpoint";
1285
+ /** `table:id` of a record id value, without the SDK's escaping. */
1286
+
1287
+ /** Where Web Push can work, from the given globals. */
1288
+ declare function detectWebPushSupport(g: WebPushGlobals): WebPushSupport;
1289
+ declare class WebPushModule {
1290
+ private readonly deps;
1291
+ private readonly logger;
1292
+ private readonly config;
1293
+ private readonly globals;
1294
+ private infoCache;
1295
+ private lastInfo;
1296
+ private readonly bridges;
1297
+ private readonly disposers;
1298
+ private syncedFor;
1299
+ private syncTimer;
1300
+ private attached;
1301
+ constructor(deps: WebPushModuleDeps);
1302
+ /**
1303
+ * Wire sign-out, auto-sync and the token bridge. Called by the client once;
1304
+ * a no-op beyond the sign-out hook where push is unsupported.
1305
+ */
1306
+ attach(): () => void;
1307
+ dispose(): void;
1308
+ support(): WebPushSupport;
1309
+ /** Is push on for this deployment, and with which key. Cached; `refresh` re-reads. */
1310
+ info(options?: {
1311
+ refresh?: boolean;
1312
+ }): Promise<WebPushInfo>;
1313
+ /** This browser holds a push subscription registered for the signed-in user. No server round trip. */
1314
+ isSubscribed(): Promise<boolean>;
1315
+ /** The user's devices, this one marked. */
1316
+ devices(): Promise<WebPushDevice[]>;
1317
+ /**
1318
+ * Ask for permission (when still `default`), subscribe this browser with the
1319
+ * deployment's key and register it for the signed-in user. Call it from a
1320
+ * click handler: permission prompts need a user gesture.
1321
+ */
1322
+ subscribe(options?: WebPushSubscribeOptions): Promise<WebPushDevice>;
1323
+ /** Remove this device (or every device, `all`) for the signed-in user. Returns how many rows went. */
1324
+ unsubscribe(options?: WebPushUnsubscribeOptions): Promise<number>;
1325
+ /**
1326
+ * Reconcile after sign-in (runs by itself with `autoSync`). Needs granted
1327
+ * permission and a user who subscribed on this browser (or
1328
+ * `autoResubscribe`). Repairs a missing browser subscription, one made with
1329
+ * a rotated key, and a missing, disabled or stale server row. Never throws.
1330
+ */
1331
+ sync(options?: WebPushSyncOptions): Promise<WebPushSyncStatus>;
1332
+ /** Change this device's label, rule filter or meta. */
1333
+ update(options: WebPushUpdateOptions): Promise<WebPushDevice | null>;
1334
+ /** Push to yourself, now or at `sendAt` (reminders). Omit `notification` for a nudge. */
1335
+ notify(message: WebPushMessageInput): Promise<WebPushMessage>;
1336
+ /** Cancel a scheduled message. `true` when it was still pending. */
1337
+ cancel(id: string | RecordId$1): Promise<boolean>;
1338
+ /** A visible test notification to every device of the user. */
1339
+ test(options?: {
1340
+ title?: string;
1341
+ body?: string;
1342
+ }): Promise<WebPushMessage>;
1343
+ /**
1344
+ * Post the session to the service worker now and whenever the token
1345
+ * changes (`{ type: 'sp00ky:token', token, userId, endpoint, namespace,
1346
+ * database }`). Never posts an impersonation token. Returns a disposer.
1347
+ * With `webPush.bridge` (the default) this already runs while notification
1348
+ * permission is granted.
1349
+ */
1350
+ bridge(registration?: ServiceWorkerRegistration): () => void;
1351
+ /** Messages from the push service worker (`sp00ky:push` while visible, `sp00ky:navigate`, ...). */
1352
+ onMessage(cb: (message: WebPushClientMessage) => void): () => void;
1353
+ private userId;
1354
+ private assertSignedIn;
1355
+ private assertNotImpersonating;
1356
+ private call;
1357
+ private listRaw;
1358
+ private register;
1359
+ private readStored;
1360
+ private writeStored;
1361
+ /** The page's registration: given, existing, registered from config, or `ready` within `waitMs`. */
1362
+ private registration;
1363
+ /** This browser's subscription, without waiting for a worker. */
1364
+ private currentSubscription;
1365
+ private thisEndpoint;
1366
+ private postToWorker;
1367
+ private startBridge;
1368
+ private refreshBridges;
1369
+ private tokenMessage;
1370
+ /** Sign-out hook: tell the worker, and drop this device's row for the user. Bounded. */
1371
+ private beforeSignOut;
1372
+ }
155
1373
  //#endregion
156
1374
  //#region src/types.d.ts
157
1375
  /**
@@ -192,6 +1410,24 @@ interface PersistenceClient {
192
1410
  * Format: number + unit (m=minutes, h=hours, d=days).
193
1411
  */
194
1412
  type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
1413
+ /**
1414
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
1415
+ * The FIRST load (cold) always fetches + blocks regardless.
1416
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
1417
+ * real `useQuery` mounts and registers its live view. No network on load.
1418
+ * - `background`: return instantly, but kick a one-time silent refetch.
1419
+ * - `stale`: like `background`, but only if the cached copy is older than
1420
+ * `staleTime`.
1421
+ */
1422
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
1423
+ interface PreloadOptions {
1424
+ /** Abort a cold preload that is still waiting for the server. */
1425
+ signal?: AbortSignal;
1426
+ /** @deprecated Preload is a registered query now; a warm preload never refetches by itself. Ignored. */
1427
+ refresh?: PreloadRefresh;
1428
+ /** @deprecated Ignored. */
1429
+ staleTime?: QueryTimeToLive;
1430
+ }
195
1431
  /**
196
1432
  * Result object returned when a query is registered or executed.
197
1433
  */
@@ -220,29 +1456,423 @@ interface Sp00kyConfig<S extends SchemaStructure> {
220
1456
  store?: StoreType;
221
1457
  /** Authentication token. */
222
1458
  token?: string;
1459
+ /**
1460
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
1461
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
1462
+ * table/relation level. Defaults to true; set false to force the legacy
1463
+ * multi-hop path (escape hatch while the worker-side path beds in).
1464
+ */
1465
+ workerSelect?: boolean;
1466
+ /**
1467
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
1468
+ * keep the connection alive indefinitely without configuration. See
1469
+ * {@link ReconnectConfig}.
1470
+ */
1471
+ reconnect?: ReconnectConfig;
1472
+ /**
1473
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
1474
+ * a single promise chain, so one call that never settles (half-open socket:
1475
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
1476
+ * otherwise wedge ALL later remote traffic behind it — including the sync
1477
+ * poll's own health probe, leaving health pinned at `healthy` with no
1478
+ * banner and no self-heal. The deadline turns that into an ordinary network
1479
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
1480
+ */
1481
+ queryTimeoutMs?: number;
1482
+ /**
1483
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
1484
+ * or a query on the in-process surrealdb engine). Local ops are serialized
1485
+ * too, and one that never answered - a worker starved behind a long select,
1486
+ * a lock verification with no clock - left every `db.create`/`db.update`
1487
+ * promise pending for the tab's lifetime. On expiry the call rejects with
1488
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
1489
+ * not retried). `0` disables. Defaults to `30_000`.
1490
+ */
1491
+ localOpTimeoutMs?: number;
223
1492
  };
224
- /** Unique client identifier. If not provided, one will be generated. */
225
- clientId?: string;
226
1493
  /** The schema definition. */
227
1494
  schema: S;
228
1495
  /** The compiled SURQL schema string. */
229
1496
  schemaSurql: string;
230
1497
  /** Logging level. */
231
- logLevel: Level;
1498
+ logLevel: Level$1;
232
1499
  /**
233
1500
  * Persistence client to use.
234
1501
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
235
1502
  */
236
1503
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
1504
+ /**
1505
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
1506
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
1507
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
1508
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
1509
+ * this engine. See `services/database/cache-engine.ts`.
1510
+ */
1511
+ localEngine?: LocalEngineChoice;
1512
+ /**
1513
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
1514
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
1515
+ * how bucket reads behaved before it existed.
1516
+ *
1517
+ * Nothing in this cache expires on a timer — an image whose row is still in
1518
+ * the local store has to stay available offline. Bytes are only dropped when
1519
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
1520
+ * reconcile finds no file behind a row, or when the cache is over budget, in
1521
+ * which case the least-recently-used unpinned entries go first. See
1522
+ * `services/blobs/blob-cache.ts`.
1523
+ */
1524
+ blobCache?: {
1525
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
1526
+ enabled?: boolean;
1527
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
1528
+ * `navigator.storage.estimate()`. */
1529
+ maxBytes?: number;
1530
+ /**
1531
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
1532
+ * `false`, matching the local store: cached files are namespaced per local
1533
+ * bucket, so signing back in is warm and no user can read another's cache.
1534
+ * Turn on for shared devices.
1535
+ */
1536
+ clearOnSignOut?: boolean;
1537
+ };
1538
+ /**
1539
+ * Share ONE durable local store across all tabs of this origin (default
1540
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
1541
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
1542
+ * worker and the sync loop, and follower tabs read/write the same store over
1543
+ * MessagePorts, so every tab is durable instead of only the first one.
1544
+ *
1545
+ * Falls back to solo mode (exactly the flag-off behavior, including the
1546
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
1547
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
1548
+ * not sqlite, or the broker rejects the tab (mixed app versions).
1549
+ *
1550
+ * Failover: when the leader tab closes or freezes, a follower is promoted
1551
+ * within seconds; queries briefly refetch and mutations are never lost once
1552
+ * their local write resolved (the shared outbox survives in the store).
1553
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
1554
+ */
1555
+ sharedTabs?: boolean;
1556
+ /**
1557
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
1558
+ * store, so a reload restores it and only steps in what changed since.
1559
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
1560
+ * can hold the bytes) and `false` otherwise.
1561
+ *
1562
+ * Without a snapshot the circuit is primed by reading every cached row back
1563
+ * out of the local store; either way a reload never re-downloads the working
1564
+ * set, which is what an empty circuit used to force: every id in the
1565
+ * server's list_ref classified as missing.
1566
+ *
1567
+ * Snapshots are store-only (views are re-registered per session) and written
1568
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
1569
+ * goes hidden, never per ingest or per query registration.
1570
+ */
1571
+ persistCircuit?: boolean;
1572
+ /**
1573
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
1574
+ * 30000. Ignored when `persistCircuit` is off.
1575
+ */
1576
+ circuitCheckpointMs?: number;
1577
+ /**
1578
+ * Keep only the fields registered queries evaluate (filter predicates, join
1579
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
1580
+ * Default `true`. The circuit only ever reads those fields; bodies are
1581
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
1582
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
1583
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
1584
+ * without has that field merged in from the local store on registration.
1585
+ */
1586
+ circuitProjection?: boolean;
237
1587
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
238
1588
  otelTransmit?: PinoTransmit;
239
1589
  /**
240
- * Debounce time in milliseconds for stream updates.
241
- * Defaults to 100ms.
1590
+ * Debounce time in milliseconds for stream updates (the client-side SSP
1591
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
1592
+ * per-record updates per query before notifying readers).
1593
+ * Defaults to 50ms.
242
1594
  */
243
1595
  streamDebounceTime?: number;
1596
+ /**
1597
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
1598
+ * edits to the server. Local state is kept on every change (so reload and
1599
+ * offline work), but a field's own new ops go out as one edit-log row per
1600
+ * pause of this length (at most 2 s apart while typing continues).
1601
+ * Lower = snappier propagation and more rows; higher = fewer rows and more
1602
+ * lag for other collaborators. Defaults to 300ms.
1603
+ */
1604
+ crdtDebounceMs?: number;
1605
+ /**
1606
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
1607
+ * preloaded at client startup (fetched as a separate chunk on page load) so
1608
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
1609
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
1610
+ * out of apps that don't use collaboration. Defaults to `false`.
1611
+ */
1612
+ crdt?: boolean;
1613
+ /**
1614
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
1615
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
1616
+ * convergence + more query load; higher = the inverse. Non-positive
1617
+ * values fall back to the default (500ms).
1618
+ */
1619
+ refSyncIntervalMs?: number;
1620
+ /**
1621
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
1622
+ * registered with no server result yet, its surql also runs directly on the
1623
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
1624
+ * before the full register lifecycle completes. Hydrated rows carry their
1625
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
1626
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
1627
+ * paints from the local cache immediately — however the rows got there
1628
+ * (preload, prior sync). Default `false`: the register lifecycle
1629
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
1630
+ * freshness path and no duplicate one-shot fetches are made.
1631
+ */
1632
+ instantHydrate?: boolean;
1633
+ /**
1634
+ * Carry the changed row's body on the LIVE notification instead of going
1635
+ * back for it.
1636
+ *
1637
+ * The client holds exactly one live subscription, on its `_00_list_ref`
1638
+ * table, and today it is a doorbell: the notification is reduced to the
1639
+ * query hash and the row is then pulled with `SELECT * FROM $ids`. The edge
1640
+ * is a real graph edge, so `FETCH out` makes SurrealDB resolve the row into
1641
+ * the notification and the body fetch disappears.
1642
+ *
1643
+ * The push stays advisory: the body is landed exactly the way a fetched body
1644
+ * is (store write, circuit ingest, version recorded), so a notification the
1645
+ * server drops costs nothing but the old round trip. Membership is still
1646
+ * read back; only the body fetch is saved.
1647
+ *
1648
+ * Default `false`. The cost is wire bytes: one edit bumps the edge in every
1649
+ * view holding the row, and under `FETCH` each of those notifications
1650
+ * carries its own full copy of the body.
1651
+ */
1652
+ liveInlineBodies?: boolean;
1653
+ /**
1654
+ * Enable realtime sync while signed out. When `true`, the client starts its
1655
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
1656
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
1657
+ * page gets live `useQuery` updates over world-readable tables. Requires the
1658
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
1659
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
1660
+ * one-shot but never sync live, and a `preload` made while signed out returns
1661
+ * at once rather than wait for membership that never comes.
1662
+ */
1663
+ enableAnonymousLiveQueries?: boolean;
1664
+ /**
1665
+ * Opt in to the raw remote escape hatches (`useRemote`, `remoteQuery`,
1666
+ * `queryRaw`) when the generated schema's `policy.queryAllowlist` is `warn`
1667
+ * or `enforce`. With the allowlist on, the server only accepts query shapes
1668
+ * that `spky generate` collected from the query builder, so a hand-written
1669
+ * SurrealQL string cannot be allowlisted and these methods throw unless this
1670
+ * flag is `true`. Defaults to `false`.
1671
+ */
1672
+ allowRawRemote?: boolean;
1673
+ /**
1674
+ * How the "you are impersonating" warning is shown while an admin acts as
1675
+ * another user. The built-in one (hazard stripes at the top, the page
1676
+ * shifted down onto them) needs no configuration; this is for restyling it,
1677
+ * or replacing it with the app's own.
1678
+ *
1679
+ * See `ImpersonationBannerConfig`. Replacing it does not mean "no warning":
1680
+ * if the app has not acknowledged its own banner shortly after impersonation
1681
+ * starts, the built-in one appears anyway.
1682
+ */
1683
+ impersonationBanner?: ImpersonationBannerConfig;
1684
+ /**
1685
+ * Surface sustained sync failures as a "degraded" health status that the app
1686
+ * can observe via `subscribeToSyncHealth` (or the client-solid
1687
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
1688
+ *
1689
+ * Individual failures — a transient remote 500 on query registration, a
1690
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
1691
+ * throw at the app. This only controls when a *run* of consecutive failures
1692
+ * is reported. Status flips back to `healthy` on the next successful sync
1693
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
1694
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
1695
+ */
1696
+ syncHealth?: SyncHealthConfig | false;
1697
+ /**
1698
+ * Automatic blurhash placeholders for bucket image uploads. On every
1699
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
1700
+ * the client computes a blurhash and stores it as a tiny sidecar object
1701
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
1702
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
1703
+ * helpers) to paint a placeholder until the image is decoded.
1704
+ *
1705
+ * `true` (the default) enables with 4x3 components; pass
1706
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
1707
+ * A per-call `put(path, content, { blurhash })` option overrides this.
1708
+ */
1709
+ blurhash?: boolean | {
1710
+ componentX?: number;
1711
+ componentY?: number;
1712
+ };
1713
+ /**
1714
+ * Buckets declared `BACKEND "r2"` keep their files with the SSP (R2 on
1715
+ * Cloudflare, a directory under `spky dev`) instead of in SurrealDB, which
1716
+ * on Surreal Cloud can only hold memory buckets. `endpoint` is the SSP's
1717
+ * URL: `spky dev` and `spky deploy` hand it to Vite as
1718
+ * `VITE_SPKY_FILES_ENDPOINT`.
1719
+ */
1720
+ files?: {
1721
+ endpoint?: string;
1722
+ };
1723
+ /**
1724
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
1725
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
1726
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
1727
+ * settles stops every later mutation for the session, with no retry and no
1728
+ * error. On expiry the push is treated as a network failure and re-queued.
1729
+ * `0` disables. Defaults to `30_000`.
1730
+ */
1731
+ pushTimeoutMs?: number;
1732
+ /**
1733
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1734
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
1735
+ * Defaults to 30000; `0` disables the timeout.
1736
+ */
1737
+ downTimeoutMs?: number;
1738
+ /**
1739
+ * Web Push on this page (`client.webPush`, `db.webPush`). Everything is
1740
+ * optional and the defaults need no service worker configuration here:
1741
+ * `autoSync` (repair this browser's subscription after sign-in),
1742
+ * `unsubscribeOnSignOut` (drop this device's subscription on `signOut()`),
1743
+ * `bridge` (post the session to the service worker for live rendering) are
1744
+ * on; `serviceWorkerUrl` registers a worker when the app does not.
1745
+ * See the `push-notifications` docs page.
1746
+ */
1747
+ webPush?: WebPushConfig;
1748
+ }
1749
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
1750
+ interface SyncHealthConfig {
1751
+ /**
1752
+ * Number of consecutive failed sync rounds (up or down) before the status
1753
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
1754
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
1755
+ * disables degraded reporting entirely.
1756
+ */
1757
+ degradeAfterConsecutiveFailures?: number;
1758
+ }
1759
+ /**
1760
+ * Tunables for WebSocket reconnect and liveness detection. See
1761
+ * {@link Sp00kyConfig.database.reconnect}.
1762
+ *
1763
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
1764
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
1765
+ * supervisor above it re-opens the connection from scratch whenever the SDK
1766
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
1767
+ * engine permanently in that case, so a supervisor is required, not optional.
1768
+ * The heartbeat covers the third case: a socket that never closes at all.
1769
+ */
1770
+ interface ReconnectConfig {
1771
+ /**
1772
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
1773
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
1774
+ * ~62s outage and then gives up for the life of the page).
1775
+ */
1776
+ attempts?: number;
1777
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
1778
+ retryDelayMax?: number;
1779
+ /**
1780
+ * Cadence of the application-level liveness probe (`RETURN true`) that
1781
+ * detects a half-open socket the transport never reports as closed.
1782
+ * `0` disables the heartbeat. Defaults to `20_000`.
1783
+ */
1784
+ heartbeatIntervalMs?: number;
1785
+ /**
1786
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
1787
+ * regardless of what its `readyState` claims, so the connection is torn down
1788
+ * and rebuilt. Defaults to `10_000`.
1789
+ */
1790
+ heartbeatTimeoutMs?: number;
1791
+ /**
1792
+ * Cap on the supervisor's own backoff between `connect()` retries once the
1793
+ * SDK has given up. Defaults to `15_000`.
1794
+ */
1795
+ superviseRetryDelayMaxMs?: number;
1796
+ }
1797
+ /**
1798
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
1799
+ *
1800
+ * These answer different questions: `connection` is about the socket,
1801
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
1802
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
1803
+ * usually still `healthy` for the first few seconds.
1804
+ */
1805
+ type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
1806
+ type SyncHealthStatus = 'healthy' | 'degraded';
1807
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
1808
+ interface SyncHealth {
1809
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
1810
+ status: SyncHealthStatus;
1811
+ /** Consecutive failed sync rounds at the moment of this report. */
1812
+ consecutiveFailures: number;
1813
+ /** Classification of the most recent failure (only set while `degraded`). */
1814
+ kind?: 'network' | 'application';
1815
+ /** Message of the most recent failure (only set while `degraded`). */
1816
+ error?: string;
1817
+ /**
1818
+ * `true` once at least one sync round has succeeded this session. Lets a UI
1819
+ * distinguish a first-time "connecting" phase (never reached the server yet,
1820
+ * so a cold-start failure run is expected) from a real lost connection after
1821
+ * a working session. Never resets back to `false` once set.
1822
+ */
1823
+ everConnected: boolean;
1824
+ /**
1825
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
1826
+ * one flips the instant the socket drops, whereas `status` only degrades
1827
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
1828
+ * immediately without waiting for the degrade threshold.
1829
+ */
1830
+ connection: ConnectionState;
1831
+ }
1832
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
1833
+ /**
1834
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
1835
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
1836
+ * server, this one is about whether the local store survives a reload.
1837
+ *
1838
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
1839
+ * which only one client per bucket can hold open. When it can't be opened (a
1840
+ * second tab of the app already has it, an insecure context, a full pool) the
1841
+ * engine keeps working against an in-memory DB, which holds the whole dataset
1842
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
1843
+ * so a UI can warn about it.
1844
+ */
1845
+ interface StorageHealth {
1846
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
1847
+ status: StorageHealthStatus;
1848
+ /**
1849
+ * `true` only when durable storage was REQUESTED and could not be opened.
1850
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
1851
+ * is a choice rather than a failure, so a UI can key off this alone.
1852
+ */
1853
+ fallback: boolean;
1854
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
1855
+ error?: string;
1856
+ /**
1857
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
1858
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
1859
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
1860
+ * single-tab behavior. Absent entirely when the feature is off.
1861
+ */
1862
+ role?: 'leader' | 'follower' | 'solo';
244
1863
  }
245
1864
  type QueryHash = string;
1865
+ /**
1866
+ * One changed row delivered inline on a LIVE notification, when the
1867
+ * subscription was opened with the body joined on (see
1868
+ * {@link Sp00kyConfig.liveInlineBodies}). `version` is the edge's `version`,
1869
+ * i.e. the same number the membership read would have reported for this row.
1870
+ */
1871
+ interface InlineRow {
1872
+ id: string;
1873
+ version: number;
1874
+ record: Record<string, unknown>;
1875
+ }
246
1876
  type RecordVersionArray = Array<[string, number]>;
247
1877
  /**
248
1878
  * Represents the difference between two record version sets.
@@ -251,16 +1881,16 @@ type RecordVersionArray = Array<[string, number]>;
251
1881
  interface RecordVersionDiff {
252
1882
  /** List of records added. */
253
1883
  added: Array<{
254
- id: RecordId$1<string>;
1884
+ id: RecordId<string>;
255
1885
  version: number;
256
1886
  }>;
257
1887
  /** List of records updated. */
258
1888
  updated: Array<{
259
- id: RecordId$1<string>;
1889
+ id: RecordId<string>;
260
1890
  version: number;
261
1891
  }>;
262
1892
  /** List of record IDs removed. */
263
- removed: RecordId$1<string>[];
1893
+ removed: RecordId<string>[];
264
1894
  }
265
1895
  /**
266
1896
  * Configuration for a specific query instance.
@@ -268,15 +1898,53 @@ interface RecordVersionDiff {
268
1898
  */
269
1899
  interface QueryConfig {
270
1900
  /** The unique ID of the query config record. */
271
- id: RecordId$1<string>;
1901
+ id: RecordId<string>;
272
1902
  /** The SURQL query string. */
273
1903
  surql: string;
1904
+ /**
1905
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
1906
+ * `_00_query`). Present when the query came from the query-builder. Non-
1907
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
1908
+ * instead of re-running `surql`, which they cannot parse.
1909
+ */
1910
+ plan?: QueryPlan;
274
1911
  /** Parameters used in the query. */
275
1912
  params: Record<string, any>;
276
1913
  /** The version array representing the local state of results. */
277
1914
  localArray: RecordVersionArray;
278
1915
  /** The version array representing the remote (server) state of results. */
279
1916
  remoteArray: RecordVersionArray;
1917
+ /**
1918
+ * In-memory only (never persisted to `_00_query`): version array of the
1919
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
1920
+ * child-body sync is idempotent across polls. Kept separate from
1921
+ * `remoteArray` so related child rows never enter the primary window /
1922
+ * `rowCount` / `localArray`.
1923
+ */
1924
+ subqueryRemoteArray?: RecordVersionArray;
1925
+ /**
1926
+ * Whether authoritative membership (`remoteArray`) has ever been established
1927
+ * for this query — either fetched from `_00_list_ref` this session, or read
1928
+ * back from the durable `_00_view` row on a cold start.
1929
+ *
1930
+ * Tri-state matters: "known and empty" must render an empty list, while
1931
+ * "never established" has to fall back to a predicate scan of the local store
1932
+ * so a query first run on this device still paints offline. A
1933
+ * `remoteArray.length === 0` check cannot tell those apart.
1934
+ *
1935
+ * On a cold start it is seeded from the durable `_00_view` row when that
1936
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
1937
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
1938
+ * by an old client that mirrored unflushed reads still self-heals.
1939
+ */
1940
+ membershipKnown?: boolean;
1941
+ /**
1942
+ * Key of this query's durable `_00_view` membership row: a hash of
1943
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
1944
+ * survives a reload (which mints a new session id) and a bucket switch.
1945
+ * In-memory only.
1946
+ */
1947
+ membershipKey?: string;
280
1948
  /** Time-To-Live for this query. */
281
1949
  ttl: QueryTimeToLive;
282
1950
  /** Timestamp when the query was last accessed/active. */
@@ -287,6 +1955,39 @@ interface QueryConfig {
287
1955
  type QueryConfigRecord = QueryConfig & {
288
1956
  id: string;
289
1957
  };
1958
+ /**
1959
+ * Runtime fetch status of a live query.
1960
+ * - `idle`: registered, initial sync completed, and not currently fetching
1961
+ * missing records — the materialized rows are authoritative (a windowed
1962
+ * query's short result really is the end of the list).
1963
+ * - `fetching`: the query is registering (a query is born `fetching` until its
1964
+ * initial remote sync completes) or the sync engine is fetching/ingesting
1965
+ * missing records for it. Any pending debounced result is flushed BEFORE the
1966
+ * flip back to `idle`, so idle status never races ahead of the rows.
1967
+ */
1968
+ type QueryStatus = 'idle' | 'fetching';
1969
+ /**
1970
+ * What the server's `_00_query` row says about a view, read alongside its
1971
+ * `_00_list_ref` edges (registration, the poll, a targeted re-read).
1972
+ *
1973
+ * - `present: false`: the row is not there (or not readable). The SSP no
1974
+ * longer has this view: a TTL sweep, an SSP reset, a scheduler wipe. An
1975
+ * empty edge set read at the same time is NOT "no rows", it is "no view".
1976
+ * - `state: 'materializing'`: the SSP has (re)computed the set and its edges
1977
+ * are in flight; an empty read is "not landed yet".
1978
+ * - `state: 'ready'`: the edges are committed (flipped in the same
1979
+ * transaction), so `rowCount === 0` with no edges is a real empty result.
1980
+ * - `state: null`: a server that predates the marker; only `rowCount` can be
1981
+ * used, with its `> 0` = flush window / `0` = empty ambiguity.
1982
+ */
1983
+ interface ServerViewMeta {
1984
+ present: boolean;
1985
+ /** `_00_query.rowCount`; `null` when unreadable. */
1986
+ rowCount: number | null;
1987
+ state: 'materializing' | 'ready' | null;
1988
+ }
1989
+ /** Outcome of handing a server id-set to `DataModule.updateQueryRemoteArray`. */
1990
+ type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
290
1991
  /**
291
1992
  * Internal state of a live query.
292
1993
  */
@@ -295,15 +1996,112 @@ interface QueryState {
295
1996
  config: QueryConfig;
296
1997
  /** The current cached records for this query. */
297
1998
  records: Record<string, any>[];
1999
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
2000
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
2001
+ hydrated?: boolean;
2002
+ /** Set once a server-side membership set has been accepted this session
2003
+ * (`updateQueryRemoteArray`). The `register` down-event is enqueued before
2004
+ * the instant-hydrate, so a hydrate that finishes later must not prime
2005
+ * membership over the authoritative set. Ephemeral. */
2006
+ serverMembership?: boolean;
2007
+ /**
2008
+ * Set when the server's `_00_query` row for this query went missing while
2009
+ * we held membership (TTL sweep, SSP reset, scheduler wipe). The view is
2010
+ * being re-registered; until a readable row comes back, empty reads are
2011
+ * NOT the server's answer and nothing is dropped. Ephemeral.
2012
+ */
2013
+ viewLost?: boolean;
2014
+ /** Last `_00_query.state` read from the server, for DevTools. Ephemeral. */
2015
+ serverState?: 'materializing' | 'ready' | null;
2016
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
2017
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
2018
+ * always emits at least once even when its records are unchanged — otherwise
2019
+ * an empty re-registered window would never notify and stay "loading". */
2020
+ syncNotified?: boolean;
298
2021
  /** Timer for TTL expiration. */
299
2022
  ttlTimer: NodeJS.Timeout | null;
300
2023
  /** TTL duration in milliseconds. */
301
2024
  ttlDurationMs: number;
2025
+ /** When the last TTL heartbeat for this query was sent (ms epoch); `undefined` before the first. */
2026
+ lastHeartbeatAt?: number;
302
2027
  /** Number of times the query has been updated. */
303
2028
  updateCount: number;
2029
+ /** Timestamp (ms) of the last user-visible update, or null before the first
2030
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
2031
+ lastUpdatedAt: number | null;
2032
+ /**
2033
+ * Rolling window of the most recent materialization-step latencies (ms).
2034
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
2035
+ * before each persist to `_00_query`. Samples themselves are not persisted.
2036
+ */
2037
+ materializationSamples: number[];
2038
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
2039
+ lastIngestLatencyMs: number | null;
2040
+ /** Cumulative count of ingest/materialization errors observed for this query. */
2041
+ errorCount: number;
2042
+ /**
2043
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
2044
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
2045
+ * pulling missing records for this query, otherwise `idle`.
2046
+ */
2047
+ status: QueryStatus;
2048
+ /**
2049
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
2050
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
2051
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
2052
+ */
2053
+ phaseSamples: Record<string, number[]>;
2054
+ /** Most recent sample (ms) per phase, or null. */
2055
+ phaseLast: Record<string, number | null>;
2056
+ /** One-shot SSP registration timings (ms). */
2057
+ registrationTimings: RegistrationTimings;
2058
+ }
2059
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
2060
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
2061
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
2062
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
2063
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
2064
+ /** One-shot registration timings (ms), captured once when a query registers. */
2065
+ interface RegistrationTimings {
2066
+ /** SSP surql→plan parse + permission injection. */
2067
+ parseMs: number | null;
2068
+ /** SSP operator-DAG build. */
2069
+ planMs: number | null;
2070
+ /** SSP initial snapshot evaluation. */
2071
+ snapshotMs: number | null;
2072
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
2073
+ wallMs: number | null;
2074
+ }
2075
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
2076
+ interface PhaseStat {
2077
+ lastMs: number | null;
2078
+ p50: number | null;
2079
+ p90: number | null;
2080
+ p99: number | null;
2081
+ count: number;
2082
+ }
2083
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
2084
+ interface QueryTimings {
2085
+ ssp: PhaseStat;
2086
+ sspStoreApply: PhaseStat;
2087
+ sspCircuitStep: PhaseStat;
2088
+ sspTransform: PhaseStat;
2089
+ localFetch: PhaseStat;
2090
+ remoteFetch: PhaseStat;
2091
+ frontend: PhaseStat;
2092
+ registration: RegistrationTimings;
2093
+ updateCount: number;
2094
+ errorCount: number;
304
2095
  }
305
2096
  type QueryUpdateCallback = (records: Record<string, any>[]) => void;
306
- type MutationCallback = (mutations: UpEvent[]) => void;
2097
+ type QueryStatusCallback = (status: QueryStatus) => void;
2098
+ /**
2099
+ * Observer for a query's authority flips: `true` once server membership is
2100
+ * known for it (registration, poll, durable seed), `false` when it is reset
2101
+ * (bucket switch). What the bindings' `isAuthoritative()` mirrors.
2102
+ */
2103
+ type QueryAuthorityCallback = (known: boolean) => void;
2104
+ type MutationCallback = (mutations: MutationEvent[]) => void;
307
2105
  type MutationEventType = 'create' | 'update' | 'delete';
308
2106
  /**
309
2107
  * Represents a mutation event (create, update, delete) to be synchronized.
@@ -312,9 +2110,9 @@ interface MutationEvent {
312
2110
  /** Example: 'create', 'update', or 'delete'. */
313
2111
  type: MutationEventType;
314
2112
  /** unique id of the mutation */
315
- mutation_id: RecordId$1<string>;
2113
+ mutation_id: RecordId<string>;
316
2114
  /** The ID of the record being mutated. */
317
- record_id: RecordId$1<string>;
2115
+ record_id: RecordId<string>;
318
2116
  /** The data payload for create/update operations. */
319
2117
  data?: any;
320
2118
  /** The full record data (optional context). */
@@ -331,6 +2129,13 @@ interface RunOptions {
331
2129
  assignedTo?: string;
332
2130
  max_retries?: number;
333
2131
  retry_strategy?: 'linear' | 'exponential';
2132
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
2133
+ timeout?: number;
2134
+ /**
2135
+ * Minimum delay in milliseconds before the job is eligible to run. While
2136
+ * delayed the job stays pending (enqueued) and can still be killed.
2137
+ */
2138
+ delay?: number;
334
2139
  }
335
2140
  /**
336
2141
  * Options for update operations.
@@ -354,6 +2159,20 @@ interface DebounceOptions {
354
2159
  key?: 'recordId' | 'recordId_x_fields';
355
2160
  /** The debounce delay in milliseconds. */
356
2161
  delay?: number;
2162
+ /**
2163
+ * Keep the pending patch across a reload or a closed tab. Default `true`.
2164
+ *
2165
+ * Every call also writes the merged patch to `_00_pending_writes`, in the
2166
+ * same local transaction as the row itself. When the page is hidden (tab
2167
+ * switch, reload, close, app sent to the background) every pending patch is
2168
+ * moved into the outbox and pushed at once instead of waiting out `delay`.
2169
+ * A page that dies before that finishes leaves the patch in the store, and
2170
+ * the next boot moves it into the outbox.
2171
+ *
2172
+ * `false` keeps the patch in memory only, so whatever is still inside its
2173
+ * delay is lost on reload. Meant for throwaway state like a cursor position.
2174
+ */
2175
+ flushOnHide?: boolean;
357
2176
  }
358
2177
  //#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 };
2178
+ export { WebPushSubscribeOptions as $, RunOptions as A, Logger$1 as At, SyncHealthStatus as B, SESSION_POLL_MS as Bt, QueryTimeToLive as C, SignOutHook as Ct, RecordVersionArray as D, createAuthEventSystem as Dt, ReconnectConfig as E, AuthEventTypes as Et, StorageHealth as F, IMPERSONATION_ACCESS as Ft, WebPushConfig as G, sameImpersonation as Gt, UpdateOptions as H, decodeTokenClaims as Ht, StorageHealthStatus as I, ImpersonationInfo as It, WebPushErrorCode as J, WebPushDevice as K, StoreType as L, ImpersonationTimerHost as Lt, Sp00kyConfig as M, SealedQuery as Mt, Sp00kyQueryResult as N, EventDefinition as Nt, RecordVersionDiff as O, RemoteDatabaseService as Ot, Sp00kyQueryResultPromise as P, EventSystem as Pt, WebPushModule as Q, SyncHealth as R, ImpersonationTimers as Rt, QueryStatusCallback as S, SignOutContext as St, QueryUpdateCallback as T, AuthEventTypeMap as Tt, PUSH_ENDPOINT_KEY as U, impersonationFromToken as Ut, TimingPhase as V, TokenClaims as Vt, PushDeviceKind as W, renewDelayMs as Wt, WebPushMessage as X, WebPushInfo as Y, WebPushMessageInput as Z, QueryConfig as _, isPushPayload as _t, Level$1 as a, WebPushUpdateOptions as at, QueryState as b, ImpersonationCandidate as bt, MutationCallback as c, BridgeTokenMessage as ct, PersistenceClient as d, PushNotificationAction as dt, WebPushSupport as et, PhaseStat as f, PushOp as ft, QueryAuthorityCallback as g, WebPushClientMessage as gt, PreloadRefresh as h, PushUrgency as ht, InlineRow as i, WebPushUnsupportedReason as it, ServerViewMeta as j, LocalStore as jt, RegistrationTimings as k, LogTap as kt, MutationEvent as l, PUSH_PAYLOAD_VERSION as lt, PreloadOptions as m, PushPayloadKind as mt, DebounceOptions as n, WebPushSyncStatus as nt, MATERIALIZATION_SAMPLE_WINDOW as o, detectWebPushSupport as ot, PinoTransmit as p, PushPayload as pt, WebPushError as q, EventSubscriptionOptions as r, WebPushUnsubscribeOptions as rt, MembershipOutcome as s, BridgeSignOutMessage as st, ConnectionState as t, WebPushSyncOptions as tt, MutationEventType as u, PushNotification as ut, QueryConfigRecord as v, ActiveImpersonation as vt, QueryTimings as w, AuthEventSystem as wt, QueryStatus as x, SIGN_OUT_HOOK_TIMEOUT_MS as xt, QueryHash as y, AuthService as yt, SyncHealthConfig as z, ORIGIN_TOKEN_KEY as zt };