@spooky-sync/core 0.0.1-canary.38 → 0.0.1-canary.381

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