@spooky-sync/core 0.0.1-canary.240 → 0.0.1-canary.241

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 (289) hide show
  1. package/AGENTS.md +34 -15
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +1136 -1846
  4. package/dist/index.js +10168 -11267
  5. package/dist/types.d.ts +22 -79
  6. package/package.json +8 -4
  7. package/skills/sp00ky-core/SKILL.md +18 -0
  8. package/src/boot/auth-flip.saga.test.ts +82 -0
  9. package/src/boot/auth-flip.saga.ts +62 -0
  10. package/src/boot/boot.saga.test.ts +151 -0
  11. package/src/boot/boot.saga.ts +128 -0
  12. package/src/boot/bucket-switch.saga.test.ts +158 -0
  13. package/src/boot/bucket-switch.saga.ts +115 -0
  14. package/src/boot/preload.saga.test.ts +51 -0
  15. package/src/boot/preload.saga.ts +31 -0
  16. package/src/client/bucket-handle.test.ts +117 -0
  17. package/src/client/bucket-handle.ts +227 -0
  18. package/src/client/router.test.ts +56 -0
  19. package/src/client/router.ts +94 -0
  20. package/src/client/runtime.test.ts +192 -0
  21. package/src/client/runtime.ts +296 -0
  22. package/src/client/services.ts +349 -0
  23. package/src/client/sp00ky-client.test.ts +241 -0
  24. package/src/client/sp00ky-client.ts +482 -0
  25. package/src/index.ts +1 -0
  26. package/src/kernel/constants.test.ts +19 -0
  27. package/src/kernel/constants.ts +54 -0
  28. package/src/kernel/effects.test.ts +40 -0
  29. package/src/kernel/effects.ts +159 -0
  30. package/src/kernel/events.ts +55 -0
  31. package/src/kernel/interpreter.test.ts +116 -0
  32. package/src/kernel/interpreter.ts +143 -0
  33. package/src/kernel/saga.test.ts +89 -0
  34. package/src/kernel/saga.ts +73 -0
  35. package/src/modules/app-release/index.ts +13 -5
  36. package/src/modules/devtools/index.ts +10 -3
  37. package/src/modules/devtools/state-shape.test.ts +4 -1
  38. package/src/modules/feature-flag/index.ts +13 -5
  39. package/src/mutation/jobs.test.ts +25 -0
  40. package/src/mutation/jobs.ts +41 -0
  41. package/src/{modules/data → mutation}/mutation-id.test.ts +12 -0
  42. package/src/mutation/push.saga.test.ts +285 -0
  43. package/src/mutation/push.saga.ts +215 -0
  44. package/src/mutation/rows.test.ts +201 -0
  45. package/src/mutation/rows.ts +377 -0
  46. package/src/mutation/tray.saga.test.ts +63 -0
  47. package/src/mutation/tray.saga.ts +48 -0
  48. package/src/mutation/write.saga.test.ts +163 -0
  49. package/src/mutation/write.saga.ts +166 -0
  50. package/src/query/env.test.ts +23 -0
  51. package/src/query/env.ts +56 -0
  52. package/src/query/fetch.saga.test.ts +156 -0
  53. package/src/query/fetch.saga.ts +109 -0
  54. package/src/query/hash.test.ts +14 -0
  55. package/src/query/hash.ts +18 -0
  56. package/src/{modules/data → query}/id-set-plan.test.ts +12 -2
  57. package/src/query/lifecycle.saga.test.ts +122 -0
  58. package/src/query/lifecycle.saga.ts +101 -0
  59. package/src/query/materialize.saga.test.ts +82 -0
  60. package/src/query/materialize.saga.ts +75 -0
  61. package/src/query/materialize.test.ts +50 -0
  62. package/src/query/materialize.ts +44 -0
  63. package/src/query/membership.saga.test.ts +246 -0
  64. package/src/query/membership.saga.ts +208 -0
  65. package/src/query/membership.test.ts +118 -0
  66. package/src/query/membership.ts +158 -0
  67. package/src/query/register.saga.test.ts +251 -0
  68. package/src/query/register.saga.ts +190 -0
  69. package/src/query/render-set.test.ts +36 -0
  70. package/src/query/render-set.ts +60 -0
  71. package/src/query/sql.test.ts +62 -0
  72. package/src/query/sql.ts +79 -0
  73. package/src/{modules/data → query}/window-query.test.ts +18 -0
  74. package/src/{modules/data → query}/window-query.ts +2 -1
  75. package/src/services/database/connection-supervisor.test.ts +29 -0
  76. package/src/services/database/connection-supervisor.ts +7 -0
  77. package/src/services/database/database.responses.test.ts +43 -0
  78. package/src/services/database/database.ts +25 -10
  79. package/src/services/database/local-migrator.ts +2 -2
  80. package/src/services/database/plan-render.test.ts +1 -1
  81. package/src/services/database/sqlite-cache-engine.test.ts +4 -3
  82. package/src/services/database/sqlite-cache-engine.ts +2 -11
  83. package/src/services/database/sqlite-devtools-queries.integration.test.ts +1 -1
  84. package/src/services/tabs/protocol.ts +7 -3
  85. package/src/sp00ky.ts +5 -1854
  86. package/src/state/client-state.ts +184 -0
  87. package/src/state/lifecycle.test.ts +118 -0
  88. package/src/state/lifecycle.ts +86 -0
  89. package/src/state/reducers.test.ts +280 -0
  90. package/src/state/reducers.ts +476 -0
  91. package/src/state/selectors.test.ts +149 -0
  92. package/src/state/selectors.ts +184 -0
  93. package/src/sync/connection.saga.test.ts +86 -0
  94. package/src/sync/connection.saga.ts +85 -0
  95. package/src/sync/live.saga.test.ts +69 -0
  96. package/src/sync/live.saga.ts +49 -0
  97. package/src/sync/policy.health.test.ts +56 -0
  98. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +31 -3
  99. package/src/{modules/sync/utils.ts → sync/policy.ts} +67 -5
  100. package/src/sync/poll.saga.test.ts +51 -0
  101. package/src/sync/poll.saga.ts +36 -0
  102. package/src/sync/tabs.saga.test.ts +74 -0
  103. package/src/sync/tabs.saga.ts +92 -0
  104. package/src/testing/adapters.ts +133 -0
  105. package/src/testing/build.ts +61 -0
  106. package/src/testing/fake-services.ts +34 -0
  107. package/src/testing/run-pure.test.ts +92 -0
  108. package/src/testing/run-pure.ts +128 -0
  109. package/src/testing/services.ts +17 -0
  110. package/src/types.ts +8 -7
  111. package/src/utils/utils.test.ts +2 -1
  112. package/vitest.config.ts +48 -0
  113. package/coverage/lcov-report/base.css +0 -224
  114. package/coverage/lcov-report/block-navigation.js +0 -87
  115. package/coverage/lcov-report/favicon.png +0 -0
  116. package/coverage/lcov-report/index.html +0 -476
  117. package/coverage/lcov-report/prettify.css +0 -1
  118. package/coverage/lcov-report/prettify.js +0 -2
  119. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  120. package/coverage/lcov-report/sorter.js +0 -210
  121. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +0 -271
  122. package/coverage/lcov-report/src/boot/boot.saga.ts.html +0 -469
  123. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +0 -430
  124. package/coverage/lcov-report/src/boot/index.html +0 -161
  125. package/coverage/lcov-report/src/boot/preload.saga.ts.html +0 -178
  126. package/coverage/lcov-report/src/client/bucket-handle.ts.html +0 -766
  127. package/coverage/lcov-report/src/client/index.html +0 -161
  128. package/coverage/lcov-report/src/client/router.ts.html +0 -367
  129. package/coverage/lcov-report/src/client/runtime.ts.html +0 -940
  130. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +0 -1531
  131. package/coverage/lcov-report/src/events/index.html +0 -116
  132. package/coverage/lcov-report/src/events/index.ts.html +0 -877
  133. package/coverage/lcov-report/src/index.html +0 -146
  134. package/coverage/lcov-report/src/index.ts.html +0 -202
  135. package/coverage/lcov-report/src/kernel/constants.ts.html +0 -247
  136. package/coverage/lcov-report/src/kernel/effects.ts.html +0 -562
  137. package/coverage/lcov-report/src/kernel/events.ts.html +0 -250
  138. package/coverage/lcov-report/src/kernel/index.html +0 -176
  139. package/coverage/lcov-report/src/kernel/interpreter.ts.html +0 -514
  140. package/coverage/lcov-report/src/kernel/saga.ts.html +0 -304
  141. package/coverage/lcov-report/src/modules/app-release/index.html +0 -116
  142. package/coverage/lcov-report/src/modules/app-release/index.ts.html +0 -712
  143. package/coverage/lcov-report/src/modules/auth/events/index.html +0 -116
  144. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +0 -142
  145. package/coverage/lcov-report/src/modules/auth/index.html +0 -116
  146. package/coverage/lcov-report/src/modules/auth/index.ts.html +0 -1225
  147. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +0 -967
  148. package/coverage/lcov-report/src/modules/crdt/index.html +0 -146
  149. package/coverage/lcov-report/src/modules/crdt/index.ts.html +0 -1474
  150. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +0 -160
  151. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +0 -1132
  152. package/coverage/lcov-report/src/modules/devtools/index.html +0 -161
  153. package/coverage/lcov-report/src/modules/devtools/index.ts.html +0 -2413
  154. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +0 -589
  155. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +0 -415
  156. package/coverage/lcov-report/src/modules/feature-flag/index.html +0 -116
  157. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +0 -1033
  158. package/coverage/lcov-report/src/modules/index.html +0 -116
  159. package/coverage/lcov-report/src/modules/ref-tables.ts.html +0 -349
  160. package/coverage/lcov-report/src/mutation/index.html +0 -191
  161. package/coverage/lcov-report/src/mutation/jobs.ts.html +0 -208
  162. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +0 -190
  163. package/coverage/lcov-report/src/mutation/push.saga.ts.html +0 -730
  164. package/coverage/lcov-report/src/mutation/rows.ts.html +0 -1216
  165. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +0 -229
  166. package/coverage/lcov-report/src/mutation/write.saga.ts.html +0 -583
  167. package/coverage/lcov-report/src/otel/index.html +0 -116
  168. package/coverage/lcov-report/src/otel/index.ts.html +0 -466
  169. package/coverage/lcov-report/src/query/env.ts.html +0 -253
  170. package/coverage/lcov-report/src/query/fetch.saga.ts.html +0 -412
  171. package/coverage/lcov-report/src/query/hash.ts.html +0 -139
  172. package/coverage/lcov-report/src/query/index.html +0 -281
  173. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +0 -388
  174. package/coverage/lcov-report/src/query/materialize.saga.ts.html +0 -310
  175. package/coverage/lcov-report/src/query/materialize.ts.html +0 -217
  176. package/coverage/lcov-report/src/query/membership.saga.ts.html +0 -709
  177. package/coverage/lcov-report/src/query/membership.ts.html +0 -559
  178. package/coverage/lcov-report/src/query/register.saga.ts.html +0 -655
  179. package/coverage/lcov-report/src/query/render-set.ts.html +0 -265
  180. package/coverage/lcov-report/src/query/sql.ts.html +0 -322
  181. package/coverage/lcov-report/src/query/window-query.ts.html +0 -670
  182. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +0 -1894
  183. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +0 -766
  184. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +0 -1162
  185. package/coverage/lcov-report/src/services/blobs/index.html +0 -161
  186. package/coverage/lcov-report/src/services/blobs/index.ts.html +0 -295
  187. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +0 -664
  188. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +0 -1330
  189. package/coverage/lcov-report/src/services/database/database.ts.html +0 -658
  190. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +0 -184
  191. package/coverage/lcov-report/src/services/database/errors.ts.html +0 -187
  192. package/coverage/lcov-report/src/services/database/events/index.html +0 -116
  193. package/coverage/lcov-report/src/services/database/events/index.ts.html +0 -184
  194. package/coverage/lcov-report/src/services/database/index.html +0 -386
  195. package/coverage/lcov-report/src/services/database/index.ts.html +0 -121
  196. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +0 -703
  197. package/coverage/lcov-report/src/services/database/local.ts.html +0 -1633
  198. package/coverage/lcov-report/src/services/database/plan-render.ts.html +0 -409
  199. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +0 -682
  200. package/coverage/lcov-report/src/services/database/remote.ts.html +0 -1036
  201. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +0 -4132
  202. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +0 -220
  203. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +0 -577
  204. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +0 -499
  205. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +0 -478
  206. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +0 -757
  207. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +0 -1333
  208. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +0 -568
  209. package/coverage/lcov-report/src/services/logger/index.html +0 -116
  210. package/coverage/lcov-report/src/services/logger/index.ts.html +0 -154
  211. package/coverage/lcov-report/src/services/persistence/index.html +0 -146
  212. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +0 -163
  213. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +0 -208
  214. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +0 -271
  215. package/coverage/lcov-report/src/services/stream-processor/index.html +0 -146
  216. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +0 -3313
  217. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +0 -244
  218. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +0 -346
  219. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +0 -934
  220. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +0 -1984
  221. package/coverage/lcov-report/src/services/tabs/index.html +0 -191
  222. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +0 -310
  223. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +0 -871
  224. package/coverage/lcov-report/src/services/tabs/support.ts.html +0 -193
  225. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +0 -2005
  226. package/coverage/lcov-report/src/sp00ky.ts.html +0 -100
  227. package/coverage/lcov-report/src/state/client-state.ts.html +0 -637
  228. package/coverage/lcov-report/src/state/index.html +0 -161
  229. package/coverage/lcov-report/src/state/lifecycle.ts.html +0 -343
  230. package/coverage/lcov-report/src/state/reducers.ts.html +0 -1471
  231. package/coverage/lcov-report/src/state/selectors.ts.html +0 -637
  232. package/coverage/lcov-report/src/sync/connection.saga.ts.html +0 -343
  233. package/coverage/lcov-report/src/sync/index.html +0 -176
  234. package/coverage/lcov-report/src/sync/live.saga.ts.html +0 -232
  235. package/coverage/lcov-report/src/sync/policy.ts.html +0 -1606
  236. package/coverage/lcov-report/src/sync/poll.saga.ts.html +0 -193
  237. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +0 -361
  238. package/coverage/lcov-report/src/types.ts.html +0 -2419
  239. package/coverage/lcov-report/src/utils/blurhash.ts.html +0 -355
  240. package/coverage/lcov-report/src/utils/error-classification.ts.html +0 -244
  241. package/coverage/lcov-report/src/utils/index.html +0 -191
  242. package/coverage/lcov-report/src/utils/index.ts.html +0 -820
  243. package/coverage/lcov-report/src/utils/parser.ts.html +0 -313
  244. package/coverage/lcov-report/src/utils/semver.ts.html +0 -175
  245. package/coverage/lcov-report/src/utils/surql.ts.html +0 -667
  246. package/coverage/lcov.info +0 -19079
  247. package/src/modules/cache/cache.relay.test.ts +0 -95
  248. package/src/modules/cache/index.ts +0 -361
  249. package/src/modules/cache/types.ts +0 -19
  250. package/src/modules/data/data.activity.test.ts +0 -109
  251. package/src/modules/data/data.authority.test.ts +0 -122
  252. package/src/modules/data/data.heartbeat-wake.test.ts +0 -115
  253. package/src/modules/data/data.hydration.test.ts +0 -142
  254. package/src/modules/data/data.membership.test.ts +0 -623
  255. package/src/modules/data/data.notify-table.test.ts +0 -41
  256. package/src/modules/data/data.pending-ids.test.ts +0 -199
  257. package/src/modules/data/data.rebind.test.ts +0 -170
  258. package/src/modules/data/data.rematerialize.test.ts +0 -114
  259. package/src/modules/data/data.run.test.ts +0 -113
  260. package/src/modules/data/data.settled-writes.test.ts +0 -235
  261. package/src/modules/data/data.status.test.ts +0 -249
  262. package/src/modules/data/data.test.ts +0 -58
  263. package/src/modules/data/index.ts +0 -2745
  264. package/src/modules/sync/engine.ts +0 -250
  265. package/src/modules/sync/events/index.ts +0 -84
  266. package/src/modules/sync/index.ts +0 -3
  267. package/src/modules/sync/queue/index.ts +0 -2
  268. package/src/modules/sync/queue/queue-down.test.ts +0 -228
  269. package/src/modules/sync/queue/queue-down.ts +0 -184
  270. package/src/modules/sync/queue/queue-up.forwarded.test.ts +0 -164
  271. package/src/modules/sync/queue/queue-up.ts +0 -407
  272. package/src/modules/sync/scheduler.pause.test.ts +0 -109
  273. package/src/modules/sync/scheduler.retry.test.ts +0 -237
  274. package/src/modules/sync/scheduler.ts +0 -286
  275. package/src/modules/sync/sync.cleanup.test.ts +0 -116
  276. package/src/modules/sync/sync.health.test.ts +0 -167
  277. package/src/modules/sync/sync.heartbeat.test.ts +0 -80
  278. package/src/modules/sync/sync.list-ref-meta.test.ts +0 -193
  279. package/src/modules/sync/sync.live-removal.test.ts +0 -289
  280. package/src/modules/sync/sync.reconnect.test.ts +0 -145
  281. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +0 -93
  282. package/src/modules/sync/sync.settled-poll.test.ts +0 -58
  283. package/src/modules/sync/sync.subquery.test.ts +0 -82
  284. package/src/modules/sync/sync.tabs.test.ts +0 -249
  285. package/src/modules/sync/sync.ts +0 -2626
  286. package/src/sp00ky.auth-order.test.ts +0 -112
  287. package/src/sp00ky.init-query.test.ts +0 -183
  288. package/src/sp00ky.local-first.test.ts +0 -60
  289. /package/src/{modules/data → mutation}/mutation-id.ts +0 -0
package/dist/index.d.ts CHANGED
@@ -1,14 +1,98 @@
1
- import { A as ServerViewMeta, B as TimingPhase, C as QueryTimings, D as RecordVersionDiff, E as RecordVersionArray, F as StorageHealthStatus, G as DatabaseEventSystem, H as UpEvent, I as StoreType, J as SyncEventSystem, K as DatabaseEventTypes, L as SyncHealth, M as Sp00kyQueryResult, N as Sp00kyQueryResultPromise, O as RegistrationTimings, P as StorageHealth, R as SyncHealthConfig, S as QueryTimeToLive, T as ReconnectConfig, U as LocalStore, V as UpdateOptions, W as SealedQuery, X as EventSystem, Y as EventDefinition, _ as QueryConfigRecord, a as MATERIALIZATION_SAMPLE_WINDOW, b as QueryStatus, c as MutationEvent, d as PhaseStat, f as PinoTransmit, g as QueryConfig, h as QueryAuthorityCallback, i as Level, j as Sp00kyConfig, k as RunOptions, l as MutationEventType, m as PreloadRefresh, n as DebounceOptions, o as MembershipOutcome, p as PreloadOptions, q as Logger$1, r as EventSubscriptionOptions, s as MutationCallback, t as ConnectionState, u as PersistenceClient, v as QueryHash, w as QueryUpdateCallback, x as QueryStatusCallback, y as QueryState, z as SyncHealthStatus } from "./types.js";
1
+ import { A as ServerViewMeta, B as TimingPhase, C as QueryTimings, D as RecordVersionDiff, E as RecordVersionArray, F as StorageHealthStatus, G as SealedQuery, H as LocalStore, I as StoreType, K as EventDefinition, L as SyncHealth, M as Sp00kyQueryResult, N as Sp00kyQueryResultPromise, O as RegistrationTimings, P as StorageHealth, R as SyncHealthConfig, S as QueryTimeToLive, T as ReconnectConfig, U as DatabaseEventSystem, V as UpdateOptions, W as DatabaseEventTypes, _ as QueryConfigRecord, a as MATERIALIZATION_SAMPLE_WINDOW, b as QueryStatus, c as MutationEvent, d as PhaseStat, f as PinoTransmit, g as QueryConfig, h as QueryAuthorityCallback, i as Level, j as Sp00kyConfig, k as RunOptions, l as MutationEventType, m as PreloadRefresh, n as DebounceOptions, o as MembershipOutcome, p as PreloadOptions, q as EventSystem, r as EventSubscriptionOptions, s as MutationCallback, t as ConnectionState, u as PersistenceClient, v as QueryHash, w as QueryUpdateCallback, x as QueryStatusCallback, y as QueryState, z as SyncHealthStatus } from "./types.js";
2
+ import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RecordId, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
2
3
  import * as surrealdb0 from "surrealdb";
3
- import { Duration, RecordId, Surreal as Surreal$1, SurrealEvents, SurrealTransaction } from "surrealdb";
4
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
5
- import { Logger } from "pino";
4
+ import { Duration, RecordId as RecordId$1, Surreal, SurrealEvents, SurrealTransaction } from "surrealdb";
5
+ import { Level as Level$1, Logger } from "pino";
6
6
  import { decode, encode, isBlurhashValid } from "blurhash";
7
7
  import { LoroDoc } from "loro-crdt";
8
8
 
9
+ //#region src/services/tabs/protocol.d.ts
10
+
11
+ type TabId = string;
12
+ type TabRole$1 = 'solo' | 'leader' | 'follower';
13
+ /** Broker pings every tab at this cadence. */
14
+
15
+ /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
16
+ * consumes, so relayed batches feed follower circuits without reshaping. */
17
+ interface IngestTuple {
18
+ table: string;
19
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
20
+ id: string;
21
+ record: Record<string, unknown>;
22
+ }
23
+ type FollowerToLeaderMessage = {
24
+ type: 'sync-hello';
25
+ tabId: TabId;
26
+ }
27
+ /** The follower committed an outbox row (through the shared store) and the
28
+ * leader should drain it. Idempotent; a new leader's loadFromDatabase is
29
+ * the backstop for a notify lost in a failover window. */ | {
30
+ type: 'mutation-enqueued';
31
+ mutationId: string;
32
+ } | {
33
+ type: 'request-poll';
34
+ }
35
+ /** An optimistic write this follower committed to the SHARED store and
36
+ * ingested into its own circuit. The leader ingests it (no DB write, the
37
+ * row is already there) and fans it out to every OTHER follower as
38
+ * `ingest-relay`, so a follower's write lands in every tab in one hop
39
+ * instead of after the server round-trip. */ | {
40
+ type: 'ingest';
41
+ tuples: IngestTuple[];
42
+ };
43
+ type LeaderToFollowerMessage = {
44
+ type: 'db-ready';
45
+ leadershipId: number;
46
+ bucketId: string;
47
+ storageHealth: StorageHealth;
48
+ }
49
+ /** Every ingest the leader's CacheModule committed, so follower circuits
50
+ * stay live without their own fetch. seq detects gaps. */ | {
51
+ type: 'ingest-relay';
52
+ tuples: IngestTuple[];
53
+ leadershipId: number;
54
+ seq: number;
55
+ }
56
+ /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
57
+ * queryId against its own DataModule and ignores foreign queries. */ | {
58
+ type: 'list-ref-change';
59
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
60
+ queryId: string;
61
+ recordId: string;
62
+ version: number;
63
+ parent: boolean;
64
+ }
65
+ /** The leader's drain rolled back a mutation owned by this tab. */ | {
66
+ type: 'mutation-rolled-back';
67
+ mutationId: string;
68
+ recordId: string;
69
+ eventType: 'create' | 'update' | 'delete';
70
+ error: string;
71
+ }
72
+ /** The leader's drain pushed a mutation and deleted its outbox row from the
73
+ * SHARED store. Every follower keeps the row in its overlay until its
74
+ * `_00_list_ref` membership arrives. */ | {
75
+ type: 'mutation-settled';
76
+ mutationId: string;
77
+ recordId: string;
78
+ eventType: 'create' | 'update' | 'delete';
79
+ }
80
+ /** The leader's LIVE saw edges of these queries change; followers re-read
81
+ * membership for the ones they hold. */ | {
82
+ type: 'membership-dirty';
83
+ hashes: string[];
84
+ }
85
+ /** The failed-writes tray changed size on the shared store. */ | {
86
+ type: 'failed-mutations-changed';
87
+ count: number;
88
+ };
89
+ //#endregion
90
+ //#region src/services/logger/index.d.ts
91
+ type Logger$1 = Logger;
92
+ //#endregion
9
93
  //#region src/services/database/database.d.ts
10
94
  declare abstract class AbstractDatabaseService {
11
- protected client: Surreal$1;
95
+ protected client: Surreal;
12
96
  protected logger: Logger$1;
13
97
  protected events: DatabaseEventSystem;
14
98
  /**
@@ -25,9 +109,9 @@ declare abstract class AbstractDatabaseService {
25
109
  * load-bearing either way: `classifySyncError` keys off it. */
26
110
  protected timeoutError(_query: string): Error;
27
111
  protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
28
- constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
112
+ constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
29
113
  abstract connect(): Promise<void>;
30
- getClient(): Surreal$1;
114
+ getClient(): Surreal;
31
115
  getEvents(): DatabaseEventSystem;
32
116
  tx(): Promise<SurrealTransaction>;
33
117
  /**
@@ -65,6 +149,20 @@ declare abstract class AbstractDatabaseService {
65
149
  * SDK's pending map.
66
150
  */
67
151
  query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
152
+ /**
153
+ * Like {@link query} but never rejects on a statement error: every
154
+ * statement answers on its own as `{ status: 'OK', result }` or
155
+ * `{ status: 'ERR', error }`. This is what lets a batched outbox push judge
156
+ * each mutation separately.
157
+ */
158
+ queryResponses(query: string, vars?: Record<string, unknown>): Promise<Array<{
159
+ status: 'OK';
160
+ result: unknown;
161
+ } | {
162
+ status: 'ERR';
163
+ error: string;
164
+ }>>;
165
+ private runStatement;
68
166
  execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
69
167
  close(): Promise<void>;
70
168
  }
@@ -285,32 +383,17 @@ declare class ConnectionSupervisor {
285
383
  private wake;
286
384
  }
287
385
  //#endregion
288
- //#region src/modules/sync/queue/queue-down.d.ts
289
- type RegisterEvent = {
290
- type: 'register';
291
- payload: {
292
- hash: string;
293
- };
294
- };
295
- type SyncEvent = {
296
- type: 'sync';
297
- payload: {
298
- hash: string;
299
- };
300
- };
301
- type HeartbeatEvent = {
302
- type: 'heartbeat';
303
- payload: {
304
- hash: string;
305
- };
306
- };
307
- type CleanupEvent = {
308
- type: 'cleanup';
309
- payload: {
310
- hash: string;
311
- };
312
- };
313
- type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
386
+ //#region src/services/database/local-migrator.d.ts
387
+ declare class LocalMigrator {
388
+ private localDb;
389
+ private logger;
390
+ constructor(localDb: LocalStore, logger: Logger$1);
391
+ provision(schemaSurql: string): Promise<void>;
392
+ private isSchemaUpToDate;
393
+ private recreateDatabase;
394
+ private splitStatements;
395
+ private createHashRecord;
396
+ }
314
397
  //#endregion
315
398
  //#region src/services/stream-processor/wasm-types.d.ts
316
399
  interface WasmStreamUpdate {
@@ -591,1482 +674,124 @@ declare class StreamProcessorService {
591
674
  private normalizeValue;
592
675
  }
593
676
  //#endregion
594
- //#region src/modules/cache/types.d.ts
595
- type RecordWithId = Record<string, any> & {
596
- id: RecordId<string>;
677
+ //#region src/modules/auth/events/index.d.ts
678
+ declare const AuthEventTypes: {
679
+ readonly AuthStateChanged: "AUTH_STATE_CHANGED";
597
680
  };
598
- interface QueryConfig$1 {
599
- queryHash: string;
600
- surql: string;
601
- params: Record<string, any>;
602
- ttl: QueryTimeToLive | Duration;
603
- lastActiveAt: Date;
604
- }
605
- interface CacheRecord {
606
- table: string;
607
- op: 'CREATE' | 'UPDATE' | 'DELETE';
608
- record: RecordWithId;
609
- version: number;
610
- }
681
+ type AuthEventTypeMap = {
682
+ [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
683
+ };
684
+ type AuthEventSystem = EventSystem<AuthEventTypeMap>;
685
+ declare function createAuthEventSystem(): AuthEventSystem;
611
686
  //#endregion
612
- //#region src/modules/cache/index.d.ts
613
- /**
614
- * CacheModule - Centralized storage and DBSP ingestion
615
- *
616
- * Single responsibility: Handle all local storage operations and DBSP ingestion.
617
- * This module acts as the bridge between data operations and persistence.
618
- */
619
- /** One ingested change, in exactly the shape `ingestMany` consumes. Shared
620
- * with the tabs protocol so a leader can relay its ingests to followers. */
621
- interface CacheIngestTuple {
622
- table: string;
623
- op: 'CREATE' | 'UPDATE' | 'DELETE';
624
- id: string;
625
- record: Record<string, unknown>;
626
- }
627
- declare class CacheModule implements StreamUpdateReceiver {
628
- private local;
629
- private streamProcessor;
687
+ //#region src/modules/auth/index.d.ts
688
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
689
+ type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
690
+ 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;
691
+ declare class AuthService<S extends SchemaStructure> {
692
+ private schema;
693
+ private remote;
694
+ private persistenceClient;
630
695
  private logger;
631
- private streamUpdateCallback;
632
- private versionLookups;
633
- /** Shared-tabs leader: fan every committed ingest out to follower circuits.
634
- * Fired AFTER the local tx (the rows are already in the shared store, so a
635
- * follower only needs the circuit feed). A follower relays its own
636
- * mutations to the leader the same way, see {@link setIngestRelay}. */
637
- private ingestRelay;
638
- /** See {@link setIngestRelay}. */
639
- private relayLocalWritesOnly;
640
- constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
641
- /**
642
- * Implements StreamUpdateReceiver interface
643
- * Called directly by StreamProcessor when views change
644
- */
645
- onStreamUpdate(update: StreamUpdate): void;
646
- /**
647
- * Fan every committed ingest out to the other tabs. The leader relays
648
- * everything (its sync fetches are the only copy the followers get). A
649
- * follower relays with `localWritesOnly`: just the mutation path, which is
650
- * the only thing it knows that the leader does not. Its sync-fetched
651
- * batches are the leader's data coming back and must not be re-broadcast,
652
- * or every follower registration would fan its whole working set to
653
- * every tab.
654
- */
655
- setIngestRelay(cb: ((tuples: CacheIngestTuple[]) => void) | null, opts?: {
656
- localWritesOnly?: boolean;
657
- }): void;
658
- /**
659
- * Shared-tabs follower: feed relayed tuples into THIS tab's circuit only.
660
- * The rows are already in the shared store (the leader wrote them), so no
661
- * local write happens here; the normal chain then runs: SSP -> stream update
662
- * -> DataModule debounce -> materializeRecords (re-reads via the port
663
- * transport) -> this tab's subscriptions fire with this tab's hashes.
664
- */
665
- applyRelayedIngest(tuples: CacheIngestTuple[]): void;
666
- lookup(recordId: string): number;
667
- /**
668
- * Seed the version memo from rows the circuit was primed with out of the
669
- * local store, so the first post-reload sync diff does not re-download
670
- * bodies the browser already has. Only rows the prime actually put into the
671
- * circuit belong here: a memo entry with no circuit row would make the diff
672
- * flag the id forever while nothing ever fetches it.
673
- */
674
- primeVersions(entries: [string, number][]): void;
675
- /** Drop the version cache on a bucket switch — a stale version would make
676
- * the sync diff skip fetching a body the new bucket legitimately needs. */
677
- clearVersionLookups(): void;
696
+ token: string | null;
697
+ currentUser: any | null;
698
+ isAuthenticated: boolean;
678
699
  /**
679
- * Save a single record to local DB and ingest into DBSP
680
- * Used by mutations (create/update)
700
+ * The record-access method name for the current session (e.g. `"account"`),
701
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
702
+ * permission injection so `$access`-gated table predicates resolve locally,
703
+ * mirroring the server's `$access`. Null when logged out.
681
704
  */
682
- save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
705
+ access: string | null;
706
+ isLoading: boolean;
707
+ private events;
708
+ get eventSystem(): AuthEventSystem;
709
+ constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
710
+ init(): Promise<void>;
711
+ getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
683
712
  /**
684
- * Save multiple records in a batch
685
- * More efficient than calling save() multiple times
686
- * Used by sync operations
713
+ * Subscribe to auth state changes.
714
+ * callback is called immediately with current value and whenever validation status changes.
687
715
  */
688
- saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
716
+ subscribe(cb: (userId: string | null) => void): () => void;
717
+ private notifyListeners;
689
718
  /**
690
- * Delete a record from local DB and ingest deletion into DBSP
719
+ * Restore a session from the locally cached JWT, with NO network.
720
+ *
721
+ * This is what makes a warm boot paint instantly and what makes an offline
722
+ * boot possible at all: the token is in local storage, and it already carries
723
+ * both the access method and the `$auth.id` record id. Everything the client
724
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
725
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
726
+ * available before a socket exists.
727
+ *
728
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
729
+ * afterwards in the background and downgrades to a real sign-out if the
730
+ * server rejects it. Nothing is trusted that the server has not also seen -
731
+ * the local store only ever holds rows the server previously sent.
732
+ *
733
+ * Returns the restored user id, or null when there is no usable token.
691
734
  */
692
- delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
735
+ restoreSessionFromToken(): Promise<string | null>;
693
736
  /**
694
- * Register a query with DBSP to create a materialized view
695
- * Returns the initial result array
737
+ * Check for existing session and validate
696
738
  */
697
- registerQuery(config: QueryConfig$1): {
698
- localArray: RecordVersionArray;
699
- registrationTimings?: {
700
- parseMs: number;
701
- planMs: number;
702
- snapshotMs: number;
703
- };
704
- };
739
+ check(accessToken?: string): Promise<void>;
705
740
  /**
706
- * Unregister a query from DBSP
741
+ * Sign out and clear session
707
742
  */
708
- unregisterQuery(queryHash: string): void;
743
+ signOut(): Promise<void>;
744
+ private setSession;
745
+ /** Fallback when the token carries no `AC` claim: if the schema defines
746
+ * exactly one record-access method, assume the session used it. */
747
+ private defaultAccessName;
748
+ signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
749
+ signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
709
750
  }
710
751
  //#endregion
711
- //#region src/modules/data/index.d.ts
712
- /**
713
- * DataModule - Unified query and mutation management
714
- *
715
- * Merges the functionality of QueryManager and MutationManager.
716
- * Uses CacheModule for all storage operations.
717
- */
718
- /** A `_00_window` row as read back: the id-set and whether the server vouched
719
- * for it (which is what allows an empty set to count as known membership). */
720
- interface DurableMembership {
721
- ids: RecordVersionArray;
722
- confirmed: boolean;
723
- }
724
- declare class DataModule<S extends SchemaStructure> {
725
- private cache;
752
+ //#region src/modules/crdt/crdt-field.d.ts
753
+ declare const CURSOR_COLORS: string[];
754
+ declare function cursorColorFromName(name: string): string;
755
+ declare class CrdtField {
756
+ private fieldName;
757
+ private doc;
758
+ private pushTimer;
726
759
  private local;
727
- private schema;
728
- private streamDebounceTime;
729
- /** Tab identity baked into mutation ids (shared-tabs rollback routing);
730
- * undefined in solo mode, where mutation-id falls back to a session id. */
731
- private tabId;
732
- private activeQueries;
733
- private pendingQueries;
734
- private subscriptions;
735
- private statusSubscriptions;
736
- /** Observers of a query's authority (`membershipKnown`) flips, keyed like `statusSubscriptions`. */
737
- private authoritySubscriptions;
738
- private mutationCallbacks;
739
- private debounceTimers;
740
- private pendingStreamUpdates;
741
- private fetchDepth;
742
- /**
743
- * Observers of the AGGREGATE fetch activity: how many queries are mid-fetch
744
- * right now. What a "downloading" indicator in the app chrome hangs off,
745
- * instead of subscribing to every query's status one by one.
746
- */
747
- private activitySubscriptions;
748
- private logger;
749
- /**
750
- * Optional observer notified whenever a query's fetch status changes.
751
- * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
752
- * settable field (rather than a constructor arg) because DevTools is
753
- * constructed after DataModule.
754
- */
755
- onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
756
- /**
757
- * Optional observer invoked when a still-subscribed query's TTL heartbeat
758
- * fires (~90% of the TTL). Wired by Sp00kyClient to
759
- * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
760
- * row's `lastActiveAt` so an actively-watched query never expires. Settable
761
- * field (not a constructor arg) because the sync engine is wired after
762
- * DataModule is constructed — mirrors `onQueryStatusChange`.
763
- */
764
- onHeartbeat?: (hash: QueryHash) => void;
765
- /**
766
- * Fired once per episode when the server's `_00_query` row for a query we
767
- * hold membership for is found missing (see `updateQueryRemoteArray`). Wired
768
- * by Sp00kyClient to enqueue a `register` down-event so the SSP rebuilds the
769
- * view; the client keeps rendering what it has meanwhile.
770
- */
771
- onViewLost?: (hash: QueryHash) => void;
772
- /** DevTools observer for authority flips; mirrors `onQueryStatusChange`. */
773
- onQueryAuthorityChange?: (hash: QueryHash, known: boolean) => void;
774
- /**
775
- * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
776
- * viewport-windowed list cancelling an off-screen window) loses its last
777
- * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
778
- * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
779
- * instead of leaving it for the TTL sweep. The local view + state are freed in
780
- * {@link finalizeDeregister} only after that remote delete, so a fast
781
- * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
782
- */
783
- onDeregister?: (hash: QueryHash) => void;
760
+ private remote;
761
+ private recordId;
784
762
  private sessionId;
785
- private currentUserId;
786
- constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
787
- init(sessionId: string): Promise<void>;
788
- /**
789
- * Update the session salt used in query-id hashing. Call this when the
790
- * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
791
- * registered queries will get fresh, session-scoped IDs.
792
- */
793
- setSessionId(sessionId: string): void;
794
- /** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
795
- * a follower's mutation routes back to the tab that made it. */
796
- setTabId(tabId: string): void;
797
- /**
798
- * Update the authenticated user record id. Pass `null` on sign-out.
799
- * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
800
- * the poll route to the same per-user `_00_list_ref_user_<id>` the
801
- * SSP writes to.
802
- */
803
- setCurrentUserId(userId: string | null): void;
804
- /** Read-only view of the authenticated user id used for per-user
805
- * `_00_list_ref` routing. Other modules consult this so they pick the
806
- * same table name DataModule does. */
807
- getCurrentUserId(): string | null;
808
- /**
809
- * Register a query and return its hash for subscriptions
810
- */
811
- query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
812
- /**
813
- * Subscribe to query updates
814
- */
815
- subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
816
- immediate?: boolean;
817
- }): () => void;
818
- /**
819
- * Subscribe to a query's fetch-status changes (idle/fetching).
820
- * With `{ immediate: true }` the callback fires synchronously with the
821
- * current status (defaults to `idle` if the query isn't registered yet).
822
- */
823
- subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
824
- immediate?: boolean;
825
- }): () => void;
826
- /**
827
- * Subscribe to a query's authority flips: whether server membership is known
828
- * for it. With `{ immediate: true }` the callback fires synchronously with
829
- * the current value (`false` for an unknown query).
830
- */
831
- subscribeAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
832
- immediate?: boolean;
833
- }): () => void;
834
- /** Whether server membership is known for `queryHash` (see `QueryConfig.membershipKnown`). */
835
- isAuthoritative(queryHash: string): boolean;
836
- /**
837
- * The single writer of `config.membershipKnown` for a live query. Fans out
838
- * to `subscribeAuthority` listeners and DevTools on a change; no-op when
839
- * unchanged or the query is unknown.
840
- */
841
- private setMembershipKnown;
842
- /**
843
- * Set a query's fetch status and notify status observers (DevTools +
844
- * `subscribeStatus` listeners). No-op when the status is unchanged or the
845
- * query is unknown.
846
- */
847
- setQueryStatus(queryHash: string, status: QueryStatus): void;
848
- /**
849
- * Enter a fetch cycle for a query. Refcounted: registration and concurrent
850
- * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
851
- * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
852
- * emits `idle`. Always pair with `endFetching` in a `finally`.
853
- */
854
- beginFetching(queryHash: string): void;
855
- /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
856
- endFetching(queryHash: string): void;
857
- /** How many queries are mid-fetch right now (see {@link subscribeActivity}). */
858
- get fetchingQueryCount(): number;
859
- /**
860
- * Observe the number of queries currently fetching. Fires on every change of
861
- * that number (a query entering or leaving its outermost fetch cycle), and
862
- * synchronously with the current value when `immediate` is set. One
863
- * subscription per indicator, however many queries the page holds.
864
- */
865
- subscribeActivity(callback: (fetching: number) => void, options?: {
866
- immediate?: boolean;
867
- }): () => void;
868
- private notifyActivity;
763
+ private unsubscribe;
764
+ private lastPushTime;
765
+ private lastCursorPushTime;
766
+ private loadedFromCrdt;
767
+ private pushRetryCount;
768
+ private logger;
769
+ private cursorsEnabled;
770
+ /** Remote-push debounce. Local writes happen immediately on every Loro
771
+ * update; the remote UPSERT is coalesced over this window. Configured
772
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
773
+ private remoteDebounceMs;
774
+ private _onCursorUpdate;
775
+ private pendingCursorUpdate;
776
+ /** Callback set by the editor to receive remote cursor updates.
777
+ * Any cursor data that arrived before this callback was set will be replayed. */
778
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
779
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
869
780
  /**
870
- * Subscribe to mutations (for sync)
781
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
782
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
783
+ * import graph so it only ships to apps that use CRDT fields.
871
784
  */
872
- onMutation(callback: MutationCallback): () => void;
785
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
786
+ getDoc(): LoroDoc;
787
+ /** Whether the LoroDoc was loaded from saved CRDT state */
788
+ hasContent(): boolean;
789
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
873
790
  /**
874
- * Handle stream updates from DBSP (via CacheModule)
875
- */
876
- onStreamUpdate(update: StreamUpdate): Promise<void>;
877
- /** Coalesce `update` onto the query's trailing timer (see onStreamUpdate). */
878
- private queueStreamUpdate;
879
- /**
880
- * Re-materialize + notify a query whose MEMBERSHIP changed without any row
881
- * needing to be fetched, i.e. without the SSP stream update that normally
882
- * carries the notify. That is every row this client wrote itself: the local
883
- * CREATE memoized it at `_00_rv = 1`, the server publishes it at 1, so the
884
- * sync engine rightly fetches nothing - and then nobody told the subscribers
885
- * that `remoteArray` now holds the id. The row appeared on reload only.
886
- *
887
- * Routed through the same per-query debounce as a real stream update, so it
888
- * cannot race one: a pending real update already materializes against the
889
- * current `remoteArray` and wins. The synthetic update re-uses the circuit's
890
- * last `localArray` and skips the persist/metrics that describe an ingest.
891
- */
892
- scheduleRematerialize(queryHash: string): void;
893
- /**
894
- * Process a query's pending (debounced) stream update NOW instead of on the
895
- * trailing edge. Called by the sync engine before it flips a query back to
896
- * `idle`, so the status change never races ahead of the rows it fetched.
897
- * No-op when nothing is pending. The pending entry is removed before the
898
- * await so a concurrently-firing timer can't process it twice.
899
- */
900
- flushPendingStreamUpdate(queryHash: string): Promise<boolean>;
901
- /**
902
- * Materialize a query's result rows from the local store.
903
- *
904
- * A query's rows are its MEMBERSHIP — the id-set the server put in
905
- * `_00_list_ref` (`remoteArray`) — not "every local body that matches the
906
- * WHERE". Those two disagree, and the disagreement was the bug: when a row
907
- * leaves a query's window but still exists upstream, `handleRemovedRecords`
908
- * keeps its local body and never re-fetches it, so a predicate re-scan finds
909
- * that stale body still matching and keeps rendering the row. Selecting the
910
- * id-set directly is also the only correct thing for a windowed query, where
911
- * re-applying `START m` against the shared local store skips the window's own
912
- * rows entirely (sparse windowing) and returns nothing.
913
- *
914
- * The rendered set is:
915
- *
916
- * (membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes
917
- *
918
- * The middle term keeps optimistic writes visible without re-admitting stale
919
- * rows. Every local write is fed to the SSP (`cache.saveBatch` →
920
- * `ingestMany`), so `localArray` answers "does this row match the predicate
921
- * per LOCAL truth". A pending write that moves a row into the window is in
922
- * `localArray` and shows; one that moves a row out is absent and does not; a
923
- * stale body the server dropped has no pending write at all, so it stays out.
924
- * `pendingDeletes` covers the reverse lag — the server still lists a row whose
925
- * DELETE is sitting in our outbox.
926
- *
927
- * Falls back to the predicate scan only when membership has never been
928
- * established (a query first run on this device), so an offline first paint
929
- * still shows something.
930
- */
931
- private materializeRecords;
932
- /**
933
- * The materialization itself, without the DevTools timing wrapper. Split out so
934
- * cold-start seeding can use it before a `QueryState` exists.
935
- */
936
- private materializeFromConfig;
937
- /**
938
- * The authoritative membership list to render from, or `null` when membership
939
- * has never been established and the caller must fall back to a scan.
940
- *
941
- * A windowed query has no usable fallback — re-running its `START m` locally
942
- * returns the wrong rows — so it renders from whatever id-set is on hand
943
- * (SSP's included) rather than degrading to a scan. That is the pre-existing
944
- * behavior for windows and is preserved.
945
- */
946
- private resolveMembership;
947
- private readonly settledWrites;
948
- private readonly settledDeletes;
949
- private pendingIds;
950
- private pendingIdsAt;
951
- private pendingIdsInflight;
952
- private static readonly PENDING_IDS_TTL_MS;
953
- private pendingIdsGen;
954
- private static readonly PENDING_IDS_MAX_REREADS;
955
- /** Drop the cached outbox ids. Cheap; call it on anything that could change
956
- * `_00_pending_mutations`. */
957
- private invalidatePendingIds;
958
- /**
959
- * Grace period for a settled write. Long enough to cover an SSP round trip
960
- * that is running slowly (seconds, not milliseconds, when the edge path is
961
- * backed up), short enough that a write the server silently dropped cannot
962
- * linger misleadingly.
963
- *
964
- * The rejection case does NOT rely on this expiring: an application error
965
- * rolls the mutation back and never reports it settled, so it vanishes at
966
- * once. This deadline only bounds the case where the write succeeded and its
967
- * membership never arrived at all.
968
- *
969
- * 30 s, up from 10 s. At 10 s every server hiccup longer than a scheduler
970
- * drain plus one slow database commit showed up as the user's own chat
971
- * message vanishing and coming back a minute later. 30 s covers a drain and
972
- * a stalled commit end to end; a membership that takes longer than that is
973
- * a server fault the admin heartbeat reports, not something to paper over.
974
- */
975
- private static readonly SETTLED_WRITE_GRACE_MS;
976
- /**
977
- * Whether any settled write or delete is still waiting for membership to
978
- * catch up. The sync poll keeps its fast cadence while this is true, so a
979
- * missed LIVE notification for the edge is picked up on the next poll tick
980
- * rather than after the idle backoff.
981
- */
982
- hasSettledWritesPending(): boolean;
983
- /**
984
- * Report that a mutation was accepted by the server and its outbox row
985
- * removed. Called only on the SUCCESS path — a rolled-back mutation must
986
- * disappear immediately, which is what makes this safe.
987
- */
988
- noteWriteSettled(recordId: string, mutationType: string): void;
989
- /** Drop entries past their deadline. */
990
- private pruneSettled;
991
- /** Apply the pending-write union and pending-delete subtraction, and map to
992
- * RecordIds for the engines' id-set path. */
993
- private buildRenderIds;
994
- private processStreamUpdate;
995
- /**
996
- * Compute p55/p90/p99 from a rolling window of materialization samples.
997
- * Returns nulls for any percentile that has no samples yet so SurrealDB
998
- * `option<float>` columns stay NONE rather than 0 before the first ingest.
999
- */
1000
- private computeMaterializationPercentiles;
1001
- /** Record a per-phase timing sample (ms) on a query's rolling window. */
1002
- private recordPhase;
1003
- /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
1004
- recordRemoteFetch(hash: string, ms: number): void;
1005
- /**
1006
- * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
1007
- * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
1008
- */
1009
- recordFrontendTiming(hash: string, ms: number): void;
1010
- /**
1011
- * Build the per-query processing-time breakdown surfaced to the DevTools panel
1012
- * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
1013
- * the rest come from the per-phase rolling windows + one-shot registration timings.
1014
- */
1015
- phaseTimings(q: QueryState): QueryTimings;
1016
- /**
1017
- * Get query state (for sync and devtools)
1018
- */
1019
- getQueryByHash(hash: string): QueryState | undefined;
1020
- /**
1021
- * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
1022
- * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
1023
- * We gate on `remoteArray`, not local `records`: a windowed query is often
1024
- * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
1025
- * but it still hasn't loaded its own full window from the server — so it should
1026
- * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
1027
- */
1028
- isCold(hash: string): boolean;
1029
- /**
1030
- * Walk a hydrated record's fields and append any EMBEDDED child records to
1031
- * `batch` (recursing for nested related fields). An embedded child is a
1032
- * value that is itself a record — a non-null object whose `id` is a
1033
- * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
1034
- * bare `RecordId` (a foreign-key reference) or any other value is skipped,
1035
- * so this never mistakes a FK column for an embedded body. Children are
1036
- * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
1037
- * to their table's real columns (which strips the alias/related fields).
1038
- * `seen` dedupes within the batch.
1039
- */
1040
- private collectEmbeddedChildren;
1041
- /**
1042
- * Prepare a subquery-bearing row (preload / hydration) for the schemafull
1043
- * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
1044
- * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
1045
- * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
1046
- * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
1047
- * with relations already RecordIds — passes through unchanged.
1048
- */
1049
- private flattenRelationsForStorage;
1050
- /**
1051
- * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
1052
- * surql run directly) so the query DISPLAYS immediately, while the full realtime
1053
- * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
1054
- * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
1055
- * `remoteArray` so windowed queries materialize the correct window (no sparse
1056
- * local-circuit issue). Runs at most once per query (the `hydrated` flag).
1057
- */
1058
- applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
1059
- /**
1060
- * Build the cache batch for a set of one-shot rows and persist it to the
1061
- * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
1062
- * and extracts EMBEDDED related children (any nesting depth) as their own
1063
- * records — a `.related()` query returns its children embedded, and a later
1064
- * correlated re-materialization needs them present as standalone rows.
1065
- * Shared by `applyHydration` (live registration) and `persistSnapshot`
1066
- * (preload).
1067
- */
1068
- private buildAndSaveCacheBatch;
1069
- /**
1070
- * Preload/prewarm: persist one-shot rows (and their embedded related children)
1071
- * into the local cache WITHOUT registering a query — no `activeQueries` entry,
1072
- * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
1073
- * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
1074
- * first paint from them instantly, then registers a live view to freshen.
1075
- */
1076
- persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
1077
- /**
1078
- * Read the durable preload freshness marker for a query hash, or null if this
1079
- * query was never preloaded in the current bucket. Co-located with the cached
1080
- * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
1081
- * data also clears the marker — a stale marker can't claim "warm" when the
1082
- * rows are gone. Any read error is treated as cold.
1083
- */
1084
- getPreloadMarker(hash: string): Promise<{
1085
- fetchedAt: number;
1086
- rowCount: number;
1087
- } | null>;
1088
- /** Stamp the preload freshness marker after a successful snapshot fetch. */
1089
- writePreloadMarker(hash: string, rowCount: number): Promise<void>;
1090
- /**
1091
- * Read the durable membership row, or `null` if this query has never had
1092
- * authoritative membership on this device. Any read error is treated as
1093
- * "unknown" so a broken row degrades to the predicate scan rather than
1094
- * rendering an empty list.
1095
- *
1096
- * `confirmed` is true only for rows written after the server itself vouched
1097
- * for the set (a non-empty id-set, or an empty one it reported a row count of
1098
- * zero for, or an empty one that followed a non-empty one in the same
1099
- * session). Rows written before the marker existed, including the `[]` rows a
1100
- * pre-`ea56f50e` client mirrored from an unflushed read, read as unconfirmed.
1101
- */
1102
- getWindowMembership(key: string): Promise<DurableMembership | null>;
1103
- /**
1104
- * Persist the durable membership row. Best-effort: callers must not fail a
1105
- * sync round because the mirror write failed.
1106
- *
1107
- * `confirmed` says whether a cold start may trust this row even when it is
1108
- * empty. A confirmed empty is a real answer ("the server says this query has
1109
- * no rows") and stays empty across a reload; an unconfirmed empty is the
1110
- * retry budget's guess and falls back to the predicate scan on the next boot,
1111
- * exactly as every empty row did before the marker existed.
1112
- */
1113
- writeWindowMembership(key: string, ids: RecordVersionArray, confirmed: boolean): Promise<void>;
1114
- /**
1115
- * Record ids with a mutation still in the outbox, split by direction.
1116
- *
1117
- * Both halves feed {@link materializeRecords}: `writes` keeps optimistic
1118
- * creates/updates visible before the server has acknowledged them, and
1119
- * `deletes` suppresses rows the server still lists because our DELETE hasn't
1120
- * been processed yet. Reading `_00_pending_mutations` (rather than tracking
1121
- * ids in memory) is what makes both survive a reload.
1122
- *
1123
- * On failure returns empty sets: membership alone then decides, which can
1124
- * briefly hide an optimistic write but never resurrects a deleted row.
1125
- */
1126
- getPendingRecordIds(): Promise<{
1127
- writes: Set<string>;
1128
- deletes: Set<string>;
1129
- }>;
1130
- /** The uncached read. Also the reload path after an invalidation, so the ids
1131
- * still survive a reload exactly as before. `gen` is the generation the read
1132
- * was issued under; the result is cached only if it is still current. */
1133
- private readPendingRecordIds;
1134
- /** True while ≥1 live subscriber is watching this query (refcount guard). */
1135
- hasSubscribers(hash: string): boolean;
1136
- /**
1137
- * Opt-in eager teardown for a query whose LAST subscriber just left — used by
1138
- * viewport-windowed lists to cancel off-screen windows instead of leaving
1139
- * their remote views to expire on the TTL sweep. No-op while any subscriber
1140
- * remains (refcount). Only enqueues the remote cleanup here; the local WASM
1141
- * view + in-memory state are freed in {@link finalizeDeregister} after the
1142
- * remote delete completes, so a re-subscribe in between aborts/heals it.
1143
- *
1144
- * NOTE: most queries should NOT use this — the default keep-alive on
1145
- * unsubscribe avoids re-registration churn on navigation.
1146
- */
1147
- deregisterQuery(hash: string): void;
1148
- /**
1149
- * Final local teardown after the remote `_00_query` row was deleted: free the
1150
- * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
1151
- * (`cleanupQuery`) guarantees no subscriber remains.
1152
- */
1153
- finalizeDeregister(hash: string): void;
1154
- /**
1155
- * Get query state by id (for sync and devtools)
1156
- */
1157
- getQueryById(id: RecordId<string>): QueryState | undefined;
1158
- /**
1159
- * Get all active queries (for devtools)
1160
- */
1161
- getActiveQueries(): QueryState[];
1162
- getActiveQueryHashes(): QueryHash[];
1163
- updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
1164
- updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray, opts?: {
1165
- /** The `_00_query` row as read in the same round trip as the edges. */
1166
- meta?: ServerViewMeta;
1167
- /**
1168
- * The caller verified upstream that the ids missing from `remoteArray`
1169
- * no longer exist (see `Sp00kySync` LIVE removal handling); an empty set
1170
- * is then a real answer even without a readable row.
1171
- */
1172
- verifiedRemoval?: boolean;
1173
- }): Promise<MembershipOutcome>;
1174
- /**
1175
- * Cancel every armed timer ahead of a local-bucket switch: stream-update
1176
- * debounce timers (their pending updates carry the OLD bucket's id-sets) and
1177
- * per-query TTL heartbeats (they'd refresh the previous user's remote
1178
- * `_00_query` rows under the new session). The rebind re-arms heartbeats.
1179
- */
1180
- quiesce(): void;
1181
- /**
1182
- * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
1183
- * `useQuery` subscriptions are keyed by hash and don't re-register on auth
1184
- * changes, so the hooks must stay attached. Per query:
1185
- * 1. reset the sync arrays + hydration flag and drop the previous user's
1186
- * records, notifying subscribers with the new-bucket materialization
1187
- * (usually empty) so their rows leave the UI immediately;
1188
- * 2. recreate the `_00_query` row in the new bucket;
1189
- * 3. re-register the SSP view on the (fresh, post-reset) processor — this
1190
- * also rebinds the view to the NEW `$auth` context;
1191
- * 4. restart the TTL heartbeat.
1192
- * Returns the hashes so the caller can enqueue remote re-registration, which
1193
- * refills records from the server via the normal register→sync→notify path.
1194
- */
1195
- rebindAfterBucketSwitch(): Promise<QueryHash[]>;
1196
- /**
1197
- * Called after a query's initial sync completes.
1198
- * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
1199
- */
1200
- notifyQuerySynced(queryHash: string): Promise<void>;
1201
- run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
1202
- /**
1203
- * Build the outbox job record + resolve its table for a backend route.
1204
- *
1205
- * Every job is a single execution. Recurring work is declared server-side
1206
- * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
1207
- * so nothing here needs to know about schedules.
1208
- */
1209
- private buildJobRecord;
1210
- /**
1211
- * Create a new record
1212
- */
1213
- create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
1214
- /**
1215
- * Update an existing record
1216
- */
1217
- update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
1218
- /**
1219
- * Delete a record
1220
- */
1221
- delete(table: string, id: string): Promise<void>;
1222
- /**
1223
- * Rollback a failed optimistic create by deleting the record locally
1224
- */
1225
- rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
1226
- /**
1227
- * Rollback a failed optimistic update by restoring the previous record state
1228
- */
1229
- rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
1230
- /**
1231
- * Force a re-materialize + notify of every active query on `tableName`.
1232
- * Used after a DELETE landed in the local store (this tab's own, or one
1233
- * relayed from another tab): the SSP may not emit a view update for a
1234
- * DELETE ingest, and the re-materialize reads the store, which already
1235
- * excludes the row. Each query is isolated so one failing re-materialize
1236
- * can't stop the others.
1237
- */
1238
- notifyTableQueries(tableName: string): Promise<void>;
1239
- /**
1240
- * Remove a record from all active query states and notify subscribers
1241
- */
1242
- private removeRecordFromQueries;
1243
- private createAndRegisterQuery;
1244
- private createNewQuery;
1245
- private calculateHash;
1246
- /**
1247
- * Session-independent counterpart of {@link calculateHash}: the key for a
1248
- * query's durable `_00_window` membership row.
1249
- *
1250
- * Deliberately the SAME inputs minus the `session::id()` salt, so the two keys
1251
- * can never drift apart. The salt is right for `_00_query` (two tabs must not
1252
- * fight over one row) and wrong for membership, which has to be recognizable
1253
- * after a reload — a reload mints a new session id, and offline the salt is
1254
- * `''`, so a salted key can never match what the previous session wrote.
1255
- */
1256
- private calculateMembershipKey;
1257
- private sha256;
1258
- private startTTLHeartbeat;
1259
- /**
1260
- * Heartbeat every watched query NOW and re-anchor its timer.
1261
- *
1262
- * The TTL timer is the only thing keeping a view alive on the server, and
1263
- * browsers throttle timers in hidden tabs (Chrome aligns them to one-minute
1264
- * ticks after five minutes hidden, and suspends them outright on some
1265
- * mobile platforms). A tab that comes back after a long stretch may have
1266
- * missed its beat by more than the server's slack, and the sweep will have
1267
- * taken the row and its edges. The client does not blank on that any more
1268
- * (`updateQueryRemoteArray` treats a missing row as "view lost"), but the
1269
- * sooner it finds out, the sooner the view is rebuilt: `heartbeatQuery`
1270
- * re-registers a query whose row is gone. Called on `visibilitychange` (to
1271
- * visible) and `online`.
1272
- *
1273
- * Queries beaten within the last `minGapMs` are skipped, so a flurry of
1274
- * wake events costs one beat per query. There is deliberately no local
1275
- * expiry anywhere in this module: the TTL is the server's, and the client's
1276
- * only duty is to keep asserting liveness while something is watching.
1277
- */
1278
- heartbeatOnWake(minGapMs?: number): number;
1279
- private replaceRecordInQueries;
1280
- }
1281
- /**
1282
- * Parse update options to generate push event options
1283
- */
1284
- //#endregion
1285
- //#region src/services/tabs/protocol.d.ts
1286
- type TabId = string;
1287
- type TabRole = 'solo' | 'leader' | 'follower';
1288
- /** Broker pings every tab at this cadence. */
1289
-
1290
- /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
1291
- * consumes, so relayed batches feed follower circuits without reshaping. */
1292
- interface IngestTuple {
1293
- table: string;
1294
- op: 'CREATE' | 'UPDATE' | 'DELETE';
1295
- id: string;
1296
- record: Record<string, unknown>;
1297
- }
1298
- type FollowerToLeaderMessage = {
1299
- type: 'sync-hello';
1300
- tabId: TabId;
1301
- }
1302
- /** The follower committed an outbox row (through the shared store) and the
1303
- * leader should drain it. Idempotent; a new leader's loadFromDatabase is
1304
- * the backstop for a notify lost in a failover window. */ | {
1305
- type: 'mutation-enqueued';
1306
- mutationId: string;
1307
- } | {
1308
- type: 'request-poll';
1309
- }
1310
- /** An optimistic write this follower committed to the SHARED store and
1311
- * ingested into its own circuit. The leader ingests it (no DB write, the
1312
- * row is already there) and fans it out to every OTHER follower as
1313
- * `ingest-relay`, so a follower's write lands in every tab in one hop
1314
- * instead of after the server round-trip. */ | {
1315
- type: 'ingest';
1316
- tuples: IngestTuple[];
1317
- };
1318
- type LeaderToFollowerMessage = {
1319
- type: 'db-ready';
1320
- leadershipId: number;
1321
- bucketId: string;
1322
- storageHealth: StorageHealth;
1323
- }
1324
- /** Every ingest the leader's CacheModule committed, so follower circuits
1325
- * stay live without their own fetch. seq detects gaps. */ | {
1326
- type: 'ingest-relay';
1327
- tuples: IngestTuple[];
1328
- leadershipId: number;
1329
- seq: number;
1330
- }
1331
- /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
1332
- * queryId against its own DataModule and ignores foreign queries. */ | {
1333
- type: 'list-ref-change';
1334
- action: 'CREATE' | 'UPDATE' | 'DELETE';
1335
- queryId: string;
1336
- recordId: string;
1337
- version: number;
1338
- parent: boolean;
1339
- }
1340
- /** The leader's drain rolled back a mutation owned by this tab. */ | {
1341
- type: 'mutation-rolled-back';
1342
- mutationId: string;
1343
- recordId: string;
1344
- eventType: 'create' | 'update' | 'delete';
1345
- error: string;
1346
- }
1347
- /** The leader's drain pushed a mutation and deleted its outbox row from the
1348
- * SHARED store. Every follower starts its settled-write grace so a row it
1349
- * was rendering as a pending write does not blink out before its
1350
- * `_00_list_ref` membership arrives. */ | {
1351
- type: 'mutation-settled';
1352
- mutationId: string;
1353
- recordId: string;
1354
- eventType: 'create' | 'update' | 'delete';
1355
- };
1356
- //#endregion
1357
- //#region src/services/tabs/coordinator.d.ts
1358
- /** Leader-side fan-out surface handed to the sync layer. The sync router
1359
- * (modules/sync/tab-router.ts) registers itself as the message handler. */
1360
- declare class LeaderSyncHub {
1361
- readonly leadershipId: number;
1362
- private logger;
1363
- private followers;
1364
- private seq;
1365
- onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1366
- onFollowerDetached: ((tabId: TabId) => void) | null;
1367
- constructor(leadershipId: number, logger: Logger$1);
1368
- attach(tabId: TabId, port: MessagePort): void;
1369
- detach(tabId: TabId): void;
1370
- detachAll(): void;
1371
- sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1372
- broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1373
- /** Stamped ingest relay; seq lets followers detect gaps. */
1374
- relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1375
- get followerCount(): number;
1376
- get relayedBatches(): number;
1377
- }
1378
- /** Follower half of the syncPort. Queues while detached (leaderless window)
1379
- * and flushes on rebind; a lost-in-flight mutation notify is additionally
1380
- * backstopped by the new leader reloading the shared outbox from the store. */
1381
- declare class SyncForwarder {
1382
- private tabId;
1383
- private port;
1384
- private queued;
1385
- onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1386
- constructor(tabId: TabId);
1387
- rebind(port: MessagePort): void;
1388
- unbind(): void;
1389
- private post;
1390
- mutationEnqueued(mutationId: string): void;
1391
- /** An optimistic write this tab just ingested. Deliberately NOT queued while
1392
- * detached: a new leader primes its circuit from the shared store, which
1393
- * already holds the row, and replaying a stale tuple at it later would put
1394
- * an older `_00_rv` in its version memo. */
1395
- ingest(tuples: IngestTuple[]): void;
1396
- requestPoll(): void;
1397
- }
1398
- //#endregion
1399
- //#region src/modules/sync/sync.d.ts
1400
- /**
1401
- * Tunables for `Sp00kySync` construction.
1402
- */
1403
- interface Sp00kySyncOptions {
1404
- /**
1405
- * Cadence (ms) for the `_00_list_ref` poll fallback that catches
1406
- * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
1407
- * values fall back to the default; see
1408
- * {@link resolveListRefPollInterval}.
1409
- */
1410
- refSyncIntervalMs?: number;
1411
- /**
1412
- * Enable realtime sync for unauthenticated clients against the shared
1413
- * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
1414
- * Defaults to `false`.
1415
- */
1416
- anonymousLiveQueries?: boolean;
1417
- /**
1418
- * Consecutive failed sync rounds before sync health flips to `degraded`.
1419
- * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
1420
- * Defaults to `3`.
1421
- */
1422
- degradeAfterConsecutiveFailures?: number;
1423
- /**
1424
- * Max time a single mutation push may take before it is treated as a network
1425
- * failure and retried. Guards against an RPC that never settles wedging the
1426
- * up-queue for the session. Defaults to 30000; `0` disables the timeout.
1427
- */
1428
- pushTimeoutMs?: number;
1429
- /**
1430
- * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1431
- * it is treated as a network failure and retried. The mirror of
1432
- * {@link pushTimeoutMs} for the read side, which had no such guard: a
1433
- * `fn::query::register` that never settled held its slot in the down drain,
1434
- * and every later registration behind it, for the rest of the session.
1435
- * Defaults to 30000; `0` disables the timeout.
1436
- */
1437
- downTimeoutMs?: number;
1438
- /**
1439
- * Transport supervisor. Sync reads its state to report `connection` in
1440
- * {@link SyncHealth} so a UI can show "reconnecting…" the instant the socket
1441
- * drops, without waiting for the degrade threshold. Optional: omitted in
1442
- * tests, where `connection` then reports `connected`.
1443
- */
1444
- connectionSupervisor?: ConnectionSupervisor;
1445
- }
1446
- /**
1447
- * The main synchronization engine for Sp00ky.
1448
- * Handles the bidirectional synchronization between the local database and the remote backend.
1449
- * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
1450
- * @template S The schema structure type.
1451
- */
1452
- declare class Sp00kySync<S extends SchemaStructure> {
1453
- private local;
1454
- private remote;
1455
- private cache;
1456
- private dataModule;
1457
- private schema;
1458
- private upQueue;
1459
- private downQueue;
1460
- private isInit;
1461
- private logger;
1462
- private syncEngine;
1463
- /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
1464
- * from `this.events`, which carries Sp00kySync-level events like
1465
- * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
1466
- get engineEvents(): SyncEventSystem;
1467
- private scheduler;
1468
- /**
1469
- * Set by any event that means the socket we registered on is gone, so the
1470
- * next `connected` knows it must re-subscribe rather than treat itself as the
1471
- * initial connect. See {@link subscribeToReconnect}.
1472
- */
1473
- private needsResubscribe;
1474
- /** When the last reconnect-driven full refetch ran, for burst coalescing. */
1475
- private lastReconnectRefetchAt;
1476
- /**
1477
- * Minimum gap between reconnect-driven full refetches. Long enough to absorb
1478
- * a flapping socket (the SDK reconnect ladder starts at 1s), short enough
1479
- * that a genuine drop minutes later still refetches.
1480
- */
1481
- private static readonly RECONNECT_REFETCH_COOLDOWN_MS;
1482
- /** Poll interval while waiting for a reconnected session to re-authenticate. */
1483
- private static readonly AUTH_READY_RETRY_MS;
1484
- /** Attempts before giving up on re-auth and skipping the refetch entirely. */
1485
- private static readonly AUTH_READY_MAX_ATTEMPTS;
1486
- events: SyncEventSystem;
1487
- private currentUserId;
1488
- private tabRole;
1489
- private tabId;
1490
- private hub;
1491
- private forwarder;
1492
- private refMode;
1493
- private readonly anonLiveEnabled;
1494
- private currentLiveQueryUuid;
1495
- private liveQueryUnsubscribe;
1496
- private listRefPollTimer;
1497
- private listRefPollRunning;
1498
- private listRefPollInFlight;
1499
- readonly refSyncIntervalMs: number;
1500
- private listRefIdleStreak;
1501
- private listRefPolledAt;
1502
- private stillRemoteStreaks;
1503
- private lastLiveEventAt;
1504
- private _liveRetryCount;
1505
- get liveRetryCount(): number;
1506
- get isSyncing(): boolean;
1507
- get pendingMutationCount(): number;
1508
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
1509
- private readonly degradeAfterFailures;
1510
- /** Per-push RPC deadline; see {@link withPushTimeout}. */
1511
- private readonly pushTimeoutMs;
1512
- private readonly downTimeoutMs;
1513
- private consecutiveSyncFailures;
1514
- private syncHealthStatus;
1515
- private lastSyncErrorKind;
1516
- private lastSyncErrorMessage;
1517
- private hasSyncedOnce;
1518
- private selfHealTimer;
1519
- private selfHealAttempts;
1520
- private static readonly SELF_HEAL_BASE_MS;
1521
- private static readonly SELF_HEAL_MAX_MS;
1522
- /**
1523
- * Transport supervisor, when one was supplied. Sync only reads state from it;
1524
- * it never drives reconnects itself.
1525
- */
1526
- private readonly connectionSupervisor?;
1527
- /**
1528
- * Mirror of the supervisor's state. Defaults to `connected` so a client
1529
- * constructed without a supervisor (tests, embedders) reports the same health
1530
- * shape it always has rather than a permanent false "disconnected".
1531
- */
1532
- private connectionState;
1533
- /** Current sync-health snapshot. */
1534
- get syncHealth(): SyncHealth;
1535
- /**
1536
- * Observe sync health. The callback fires immediately with the current
1537
- * status and again on every healthy↔degraded transition. Returns an
1538
- * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
1539
- */
1540
- subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1541
- private emitSyncHealth;
1542
- /**
1543
- * Mirror the supervisor's transport state into {@link SyncHealth} and emit on
1544
- * every change, so a UI can react to a dropped socket immediately instead of
1545
- * waiting for `degradeAfterFailures` failed rounds. `status` is untouched:
1546
- * a brief reconnect is not a degradation.
1547
- *
1548
- * No explicit unsubscribe: the supervisor is owned by the same client and
1549
- * drops all subscribers in its own `dispose()`, which `Sp00kyClient.close()`
1550
- * calls first.
1551
- */
1552
- private subscribeToConnectionState;
1553
- /**
1554
- * Fed by the scheduler once per drained sync round. Individual failures are
1555
- * absorbed by the queue's retry; only a run of `degradeAfterFailures`
1556
- * consecutive failures flips the status to `degraded`, and the next clean
1557
- * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
1558
- * is 0).
1559
- */
1560
- private recordSyncOutcome;
1561
- /**
1562
- * Begin self-heal retries (no-op if already running). Started on the
1563
- * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
1564
- */
1565
- private startSelfHeal;
1566
- private scheduleSelfHeal;
1567
- private stopSelfHeal;
1568
- /**
1569
- * Release a deregistered query's remote view immediately instead of leaving
1570
- * it to the TTL sweep. Off by default; see the reasoning in
1571
- * {@link cleanupQuery}. Kept as a field rather than deleted so the eager path
1572
- * can be re-enabled in a test once the subquery-body repair path exists.
1573
- */
1574
- private readonly releaseQueriesEagerly;
1575
- constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
1576
- /**
1577
- * Initializes the synchronization system.
1578
- * Starts the scheduler and initiates the initial sync cycles.
1579
- * @throws Error if already initialized.
1580
- */
1581
- init(): Promise<void>;
1582
- /** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
1583
- * never starts LIVE; its own registration/poll paths stay untouched). */
1584
- setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void;
1585
- /** In-flight {@link resumeLeaderDuties}, so a second call joins the first
1586
- * instead of double-draining the outbox. */
1587
- private leaderDutiesInFlight;
1588
- /** Resolves once the in-browser circuit has been primed from the local
1589
- * store. Every sync diff waits on it: diffing against an empty circuit
1590
- * classifies the whole working set as missing and re-downloads it. */
1591
- private primeGate;
1592
- /** The prime we last waited on. `whenPrimed` hands out one promise per
1593
- * prime, so a new identity means a new prime (boot, bucket switch) ran. */
1594
- private settledPrime;
1595
- setPrimeGate(gate: () => Promise<void>): void;
1596
- /**
1597
- * Leader WIRING only, and deliberately synchronous.
1598
- *
1599
- * The coordinator publishes the leader role and tells the broker
1600
- * `leader-ready` the moment the store is adopted, and the broker can mint a
1601
- * follower's ports on the very next tick. So the follower-message handler
1602
- * has to be live before this returns, or a mutation forwarded in that window
1603
- * is dropped. Everything that can block (outbox reload, LIVE restart) moved
1604
- * to {@link resumeLeaderDuties}: a promotion that waits on the network holds
1605
- * `leader-ready` back, and a broker whose leader never reports ready serves
1606
- * no follower ports and re-elects no one, which wedges the whole namespace.
1607
- */
1608
- promoteToLeader(hub: LeaderSyncHub): void;
1609
- /** Leader duties: drain the shared outbox, own the single list_ref LIVE,
1610
- * relay LIVE events and rollbacks to followers. Idempotent for a boot-time
1611
- * leader; a runtime promotion (failover) reloads the outbox, which now
1612
- * holds EVERY tab's rows, and restarts LIVE under this session. Runs in the
1613
- * background off the promotion path, so however long it takes (or if it
1614
- * never finishes) the tab is already a working leader. */
1615
- resumeLeaderDuties(): Promise<void>;
1616
- /** Follower duties: no outbox drain, no LIVE. Mutations forward to the
1617
- * leader; everything else (registration, per-query sync, poll) runs
1618
- * against this tab's own remote session as usual. */
1619
- demoteToFollower(forwarder: SyncForwarder): void;
1620
- /**
1621
- * A pending mutation was discarded because it can never be sent.
1622
- *
1623
- * This is a lost write, so it must not stay invisible. Every failure in this
1624
- * chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
1625
- * shows, which is how an outbox could sit undrained for hours with the UI
1626
- * reporting nothing. Surfaces as a rollback event (the mutation will never
1627
- * apply, which is what a subscriber needs to know) and degrades sync health.
1628
- */
1629
- private onMutationDropped;
1630
- /** A forwarded outbox row from a follower: load + drain it. Idempotent. */
1631
- enqueueForwardedMutation(mutationId: string): Promise<void>;
1632
- /**
1633
- * Tuples another tab already committed to the shared store: feed them to
1634
- * THIS tab's circuit (no local write). A DELETE additionally forces a
1635
- * re-materialize of the table's queries, exactly as the writing tab does
1636
- * for itself, because the SSP may not emit a view update for it.
1637
- */
1638
- private applyRelayedIngest;
1639
- /** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
1640
- * and run the exact same handling the LIVE subscription would have. */
1641
- private applyRelayedListRefChange;
1642
- /** One immediate poll cycle (failover convergence). */
1643
- forcePollRound(): Promise<void>;
1644
- /**
1645
- * Quiesce all sync activity ahead of a local-bucket switch. After this
1646
- * resolves, nothing in the sync module writes to the local store: the poll
1647
- * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
1648
- * timers are cancelled (their outbox rows are already persisted), and the
1649
- * scheduler has drained its in-flight queue item — including that item's
1650
- * outbox-row delete, which must land in the OLD bucket. Queued down-events
1651
- * are dropped (they reference old-bucket query rows; the post-switch rebind
1652
- * re-enqueues registrations). The old user's un-pushed outbox is deliberately
1653
- * NOT drained: the remote session already belongs to the next user.
1654
- */
1655
- prepareBucketSwitch(): Promise<void>;
1656
- /**
1657
- * Resume syncing against the freshly-opened bucket: reload the mutation
1658
- * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
1659
- * offline work) and restart the scheduler. LIVE + the list_ref poll restart
1660
- * via the `setCurrentUserId` call that follows in the auth listener.
1661
- */
1662
- completeBucketSwitch(): Promise<void>;
1663
- /**
1664
- * Push the authenticated user's record id from the parent client's
1665
- * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
1666
- * any) and re-registers it under the new user's dedicated table so
1667
- * SurrealDB binds the permission rule under the post-flip auth
1668
- * context. Pass `null` on sign-out.
1669
- *
1670
- * The dedicated `_00_list_ref_user_<id>` table is created lazily by
1671
- * the SSP when the first query registration arrives, which may be
1672
- * concurrent with this call. We retry the LIVE registration with a
1673
- * short backoff so a "table not found" race resolves without
1674
- * surfacing as a permanent auth-loading hang.
1675
- */
1676
- setCurrentUserId(userId: string | null): Promise<void>;
1677
- private startListRefPoll;
1678
- private stopListRefPoll;
1679
- /**
1680
- * One poll cycle: refetch `_00_list_ref` for the active queries that are due,
1681
- * one round trip per chunk (see `planListRefPollChunks`). Returns whether ANY
1682
- * query's remoteArray actually changed — the scheduler uses this to drive the
1683
- * adaptive idle backoff.
1684
- *
1685
- * Also the ONLY health signal that runs while the page is idle. Sync health is
1686
- * otherwise activity-driven (mutations/registrations via the scheduler,
1687
- * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
1688
- * would linger until the next mutation and a genuine idle drop would be
1689
- * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
1690
- * so idle health self-recovers (and self-degrades) with no user action. A clean
1691
- * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
1692
- * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
1693
- */
1694
- private pollListRefForActiveQueries;
1695
- /**
1696
- * The server's current `_00_list_ref` state for a chunk of queries in ONE
1697
- * round trip: primary edges, subquery-child edges and `_00_query.rowCount`.
1698
- * Every hash whose query still exists gets an entry (empty arrays and
1699
- * `rowCount: null` when nothing was readable), so a caller can tell "no
1700
- * edges" from "not asked". A hash is left out only when the select did not
1701
- * come back as an array at all — the old per-query code skipped the apply in
1702
- * that case too, since a non-array is not a membership set.
1703
- *
1704
- * Guarded against a batch that silently matches nothing: if the select
1705
- * returned no edge at all while the client holds edges for a query the
1706
- * server still reports rows for, the batch is not trusted and the chunk is
1707
- * re-read one query at a time with the single-query select. An empty set
1708
- * taken at face value would be recorded as the removal of every row.
1709
- */
1710
- private fetchListRefSnapshots;
1711
- /**
1712
- * Single-query form of {@link fetchListRefSnapshots}: the selects the
1713
- * registration path has always used, in one statement batch. `null` when
1714
- * the primary select did not come back as an array.
1715
- */
1716
- private fetchListRefSnapshot;
1717
- /**
1718
- * Land one poll snapshot for `queryHash`: diff the server's edges against the
1719
- * cached `remoteArray`, sync any added/updated rows through the SyncEngine,
1720
- * persist the new remoteArray and converge the subquery children. This is
1721
- * the same shape `createRemoteQuery` does for its initial fetch and what
1722
- * `handleRemoteListRefChange` does per-LIVE-event — we reuse it on a timer
1723
- * as a fallback for missed LIVE notifications. Returns whether membership
1724
- * changed.
1725
- */
1726
- private applyListRefSnapshot;
1727
- /**
1728
- * Re-read ONE query's server state now (edges + `_00_query` row) and land
1729
- * it through {@link applyListRefSnapshot}. The targeted form of the poll,
1730
- * for the moments that cannot wait for the next tick: a registration that
1731
- * answered `materializing`, and a LIVE removal that has to be checked
1732
- * against the row before it may empty a painted list.
1733
- */
1734
- private refetchListRefForQuery;
1735
- /** Per-query pending targeted re-reads: one timer and the ladder still to walk. */
1736
- private listRefRefetches;
1737
- /**
1738
- * Schedule a targeted re-read of `queryHash` after `delays[0]` ms. If the
1739
- * read still says the server is publishing (`materializing`), the next rung
1740
- * of the ladder is armed; any other outcome ends it. Re-scheduling a hash
1741
- * that already has a timer replaces it (latest wins), so bursts coalesce.
1742
- */
1743
- private scheduleListRefRefetch;
1744
- private clearListRefRefetch;
1745
- private clearListRefRefetches;
1746
- /**
1747
- * Resolve the current `_00_list_ref` table name for the active auth
1748
- * context. Public so the `createRemoteQuery` initial-fetch path can
1749
- * read from the right per-user table.
1750
- *
1751
- * Reads the user id from `DataModule` rather than the local mirror,
1752
- * because `DataModule.setCurrentUserId` runs synchronously from the
1753
- * auth callback (before any `await`), whereas `sync.setCurrentUserId`
1754
- * is async — the userQuery's initial fetch can fire between those
1755
- * two points and we need the correct table name immediately.
1756
- */
1757
- listRefTable(): string;
1758
- private killRefLiveQuery;
1759
- private restartRefLiveQuery;
1760
- /**
1761
- * Drop local LIVE bookkeeping without issuing a `KILL`.
1762
- *
1763
- * Called when the socket dies. The server-side subscription is scoped to that
1764
- * WebSocket session and died with it, so there is nothing left to kill — and
1765
- * by the time the reconnect handler runs, the client reports `connected`
1766
- * again, which would otherwise send a `KILL` for a stale uuid on the *new*
1767
- * session and hold up the restart queued behind it.
1768
- */
1769
- private invalidateRefLiveQuery;
1770
- private subscribeToReconnect;
1771
- /**
1772
- * Whether the REMOTE SESSION currently carries `$auth.id`.
1773
- *
1774
- * Not the same question as `currentUserId`, and that gap is the whole point:
1775
- * `currentUserId` is this client's own record of who signed in and survives a
1776
- * socket drop untouched, while `$auth` lives on the WebSocket session and has
1777
- * to be re-applied after every reconnect. Registering in the window between
1778
- * the two is silently destructive, because `fn::query::register` sends
1779
- * `<string>($auth.id OR '')` and the SSP stores that value write-once: the
1780
- * view's edges then route to the global `_00_list_ref` stamped `auth_id = ''`,
1781
- * which that table's own permission rule (`auth_id = $auth.id`) makes
1782
- * unreadable to the very user who registered it.
1783
- *
1784
- * Signed-out clients answer `true`: `''` is the honest identity there, not a
1785
- * race.
1786
- */
1787
- private remoteAuthEstablished;
1788
- /**
1789
- * Wait for the reconnected session to carry an identity again, then
1790
- * re-register every active query and re-bind LIVE.
1791
- *
1792
- * Giving up without registering is deliberately better than registering
1793
- * anyway: a registration made with no `$auth.id` produces a view its own
1794
- * owner cannot read, and it is write-once, so it stays that way. Skipping
1795
- * leaves the query unregistered and visibly loading, which the next
1796
- * reconnect or heartbeat retries.
1797
- */
1798
- private refetchAfterReconnect;
1799
- private startRefLiveQueries;
1800
- private handleRemoteListRefChange;
1801
- /** LIVE removals awaiting verification, per query, with their coalescing timer. */
1802
- private pendingLiveRemovals;
1803
- /**
1804
- * Hold a LIVE `_00_list_ref` DELETE for {@link LIVE_REMOVAL_COALESCE_MS},
1805
- * then verify the batch (see {@link flushLiveRemovals}). A sweep or a
1806
- * republish delivers a view's whole set as one burst, so one verification
1807
- * round covers it.
1808
- */
1809
- private queueLiveRemoval;
1810
- /**
1811
- * Verify a coalesced batch of LIVE removals against the upstream records.
1812
- * Ids that no longer exist upstream are dropped from membership (the body
1813
- * delete already happened inside `syncRecords`) and the query re-renders.
1814
- * Anything still present upstream - or a verification that could not run -
1815
- * is settled by a targeted re-read of the server's set for this query,
1816
- * where the `_00_query` row decides: gone = view lost (keep rows,
1817
- * re-register), `materializing` = wait, `ready` = adopt the smaller set.
1818
- */
1819
- private flushLiveRemovals;
1820
- private clearLiveRemovals;
1821
- /**
1822
- * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
1823
- * `parent` set) for a `.related()` query. Unlike primary rows, child rows
1824
- * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
1825
- * keep the child BODY fresh in the local cache so the in-browser SSP's
1826
- * subquery-table dependency re-materializes the parent view.
1827
- *
1828
- * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
1829
- * no-op: a child leaving this query's set must not delete a body another
1830
- * query may still show (see `syncSubqueryChildren` deletion-safety note);
1831
- * a genuine record delete propagates via the normal delete path.
1832
- */
1833
- private handleRemoteSubqueryChange;
1834
- /**
1835
- * Enqueues a 'down' event (from remote to local) for processing.
1836
- * @param event The DownEvent to enqueue.
1837
- */
1838
- enqueueDownEvent(event: DownEvent): void;
1839
- /**
1840
- * Bound a mutation push so it always settles.
1841
- *
1842
- * `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
1843
- * flag only clears in the `finally` of the drain loop. A push whose RPC never
1844
- * settles (socket dropped mid-flight, response lost) therefore wedges the
1845
- * up-queue for the rest of the session: no retry, no error, no further
1846
- * mutation ever sent. A timeout turns that into an ordinary network failure,
1847
- * which `UpQueue.next` re-queues for the next trigger. The message deliberately
1848
- * contains "timed out" so `classifySyncError` treats it as `network` and
1849
- * retries rather than rolling the mutation back.
1850
- */
1851
- private withPushTimeout;
1852
- private processUpEvent;
1853
- /**
1854
- * A mutation the server accepted, reported once its outbox row is gone.
1855
- *
1856
- * Keeps the written row in the render set until its membership arrives.
1857
- * Without this the row is briefly in neither term of
1858
- * `(membership ∪ pendingWrites) − pendingDeletes` — the outbox delete is
1859
- * tied to the push, while membership waits on the SSP ingesting the row,
1860
- * materializing the view, writing the `_00_list_ref` edge and this client
1861
- * reading it back. The writer therefore watched its own comment appear,
1862
- * vanish, and return, while every other client showed it throughout.
1863
- */
1864
- private handleMutationSettled;
1865
- private handleRollback;
1866
- private processDownEvent;
1867
- private withDownTimeout;
1868
- private runDownEvent;
1869
- /**
1870
- * Synchronizes a specific query by hash.
1871
- * Compares local and remote version arrays and fetches differences.
1872
- * @param hash The hash of the query to sync.
1873
- */
1874
- syncQuery(hash: string): Promise<void>;
1875
- /**
1876
- * Run a sync for a single query while reflecting its fetch status. Marks the
1877
- * query `fetching` for the duration when the diff actually pulls records
1878
- * (added/updated), then resets to `idle` in a `finally` so a failed sync
1879
- * never leaves a query stuck `fetching`. Part A's notification coalescing
1880
- * means the single resulting UI update lands after this completes.
1881
- */
1882
- private runSyncForQuery;
1883
- /**
1884
- * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1885
- * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1886
- * server's `_00_list_ref` still lists them until it's processed, and the diff
1887
- * would otherwise resurrect a just-deleted record.
1888
- */
1889
- private getPendingDeleteIds;
1890
- /**
1891
- * Enqueues a list of mutations (up events) to be sent to the remote.
1892
- * @param mutations Array of UpEvents (create/update/delete) to enqueue.
1893
- */
1894
- enqueueMutation(mutations: UpEvent[]): Promise<void>;
1895
- /**
1896
- * Best-effort release of THIS tab's views as the page goes away.
1897
- *
1898
- * Without it a closed tab's views stay materialized on the SSP for a full
1899
- * TTL (10 minutes by default), because nothing else tears them down:
1900
- * `releaseQueriesEagerly` is off, so the TTL sweep is the only reclaim path.
1901
- * On a busy tenant that is a generation of live views per reload, each still
1902
- * being stepped by every ingest, for ten minutes after the last human left.
1903
- *
1904
- * This is NOT `releaseQueriesEagerly` re-enabled. That released views
1905
- * mid-session on a viewport change and tore the window out from under a live
1906
- * page (see `cleanupQuery`); this runs only when the page itself is going
1907
- * away and nothing is left to render.
1908
- *
1909
- * Safe against other tabs by construction: `fn::query::unsubscribe` drops
1910
- * only this session from `subscribers` and deletes the row solely when it
1911
- * was the last one, so a second tab of the same user keeps its view.
1912
- *
1913
- * One statement, not one per id: an unload handler gets a few milliseconds,
1914
- * and N round trips would not survive it. Fire-and-forget — if the frame
1915
- * does not make it out, the TTL sweep still reclaims exactly as before, so
1916
- * the worst case is today's behaviour.
1917
- */
1918
- releaseViewsOnUnload(): void;
1919
- private registerQuery;
1920
- private createRemoteQuery;
1921
- /**
1922
- * Sync the BODIES of a `.related()` query's subquery child rows into the
1923
- * local cache, separately from the primary window array. The SSP writes
1924
- * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
1925
- * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
1926
- * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
1927
- * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
1928
- * them into the local DB AND the in-browser SSP, whose subquery-table
1929
- * dependency then re-materializes the parent view (no explicit notify).
1930
- *
1931
- * Deletion safety: we pass `removed: []` deliberately. A child body can be
1932
- * shared by other queries; letting `handleRemovedRecords` delete one that
1933
- * merely left THIS query's child set would clobber data another query still
1934
- * shows. Genuine record deletes flow through the normal delete path; a
1935
- * lingering orphan body is invisible (the correlated WHERE stops matching).
1936
- *
1937
- * Kept off `runSyncForQuery` on purpose so child fetches never flip the
1938
- * query to `fetching` or skew its DevTools timings.
1939
- */
1940
- private syncSubqueryChildren;
1941
- /**
1942
- * Converge a `.related()` query's child bodies onto `fresh` (the server's
1943
- * current child edges). Shared by the registration path above and the poll,
1944
- * which reads the child edges in its batched round trip. See
1945
- * {@link syncSubqueryChildren} for the deletion-safety rules.
1946
- */
1947
- private applySubqueryChildren;
1948
- heartbeatQuery(queryHash: string): Promise<void>;
1949
- private cleanupQuery;
1950
- }
1951
- //#endregion
1952
- //#region src/modules/auth/events/index.d.ts
1953
- declare const AuthEventTypes: {
1954
- readonly AuthStateChanged: "AUTH_STATE_CHANGED";
1955
- };
1956
- type AuthEventTypeMap = {
1957
- [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
1958
- };
1959
- type AuthEventSystem = EventSystem<AuthEventTypeMap>;
1960
- declare function createAuthEventSystem(): AuthEventSystem;
1961
- //#endregion
1962
- //#region src/modules/auth/index.d.ts
1963
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
1964
- type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
1965
- 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;
1966
- declare class AuthService<S extends SchemaStructure> {
1967
- private schema;
1968
- private remote;
1969
- private persistenceClient;
1970
- private logger;
1971
- token: string | null;
1972
- currentUser: any | null;
1973
- isAuthenticated: boolean;
1974
- /**
1975
- * The record-access method name for the current session (e.g. `"account"`),
1976
- * derived from the token's `AC` claim. Consumed by the in-browser SSP's
1977
- * permission injection so `$access`-gated table predicates resolve locally,
1978
- * mirroring the server's `$access`. Null when logged out.
1979
- */
1980
- access: string | null;
1981
- isLoading: boolean;
1982
- private events;
1983
- get eventSystem(): AuthEventSystem;
1984
- constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
1985
- init(): Promise<void>;
1986
- getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
1987
- /**
1988
- * Subscribe to auth state changes.
1989
- * callback is called immediately with current value and whenever validation status changes.
1990
- */
1991
- subscribe(cb: (userId: string | null) => void): () => void;
1992
- private notifyListeners;
1993
- /**
1994
- * Restore a session from the locally cached JWT, with NO network.
1995
- *
1996
- * This is what makes a warm boot paint instantly and what makes an offline
1997
- * boot possible at all: the token is in local storage, and it already carries
1998
- * both the access method and the `$auth.id` record id. Everything the client
1999
- * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
2000
- * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
2001
- * available before a socket exists.
2002
- *
2003
- * The session is OPTIMISTIC: the token is unverified here. `check()` runs
2004
- * afterwards in the background and downgrades to a real sign-out if the
2005
- * server rejects it. Nothing is trusted that the server has not also seen -
2006
- * the local store only ever holds rows the server previously sent.
2007
- *
2008
- * Returns the restored user id, or null when there is no usable token.
2009
- */
2010
- restoreSessionFromToken(): Promise<string | null>;
2011
- /**
2012
- * Check for existing session and validate
2013
- */
2014
- check(accessToken?: string): Promise<void>;
2015
- /**
2016
- * Sign out and clear session
2017
- */
2018
- signOut(): Promise<void>;
2019
- private setSession;
2020
- /** Fallback when the token carries no `AC` claim: if the schema defines
2021
- * exactly one record-access method, assume the session used it. */
2022
- private defaultAccessName;
2023
- signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
2024
- signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
2025
- }
2026
- //#endregion
2027
- //#region src/modules/crdt/crdt-field.d.ts
2028
- declare const CURSOR_COLORS: string[];
2029
- declare function cursorColorFromName(name: string): string;
2030
- declare class CrdtField {
2031
- private fieldName;
2032
- private doc;
2033
- private pushTimer;
2034
- private local;
2035
- private remote;
2036
- private recordId;
2037
- private sessionId;
2038
- private unsubscribe;
2039
- private lastPushTime;
2040
- private lastCursorPushTime;
2041
- private loadedFromCrdt;
2042
- private pushRetryCount;
2043
- private logger;
2044
- private cursorsEnabled;
2045
- /** Remote-push debounce. Local writes happen immediately on every Loro
2046
- * update; the remote UPSERT is coalesced over this window. Configured
2047
- * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
2048
- private remoteDebounceMs;
2049
- private _onCursorUpdate;
2050
- private pendingCursorUpdate;
2051
- /** Callback set by the editor to receive remote cursor updates.
2052
- * Any cursor data that arrived before this callback was set will be replayed. */
2053
- set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
2054
- get onCursorUpdate(): ((data: Uint8Array) => void) | null;
2055
- /**
2056
- * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
2057
- * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
2058
- * import graph so it only ships to apps that use CRDT fields.
2059
- */
2060
- constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
2061
- getDoc(): LoroDoc;
2062
- /** Whether the LoroDoc was loaded from saved CRDT state */
2063
- hasContent(): boolean;
2064
- startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
2065
- /**
2066
- * Stop syncing this field. Flushes one final remote push by default so the
2067
- * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
2068
- * the remote session already belongs to the NEXT user, and pushing this
2069
- * (previous user's) snapshot under it would clobber the record remotely.
791
+ * Stop syncing this field. Flushes one final remote push by default so the
792
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
793
+ * the remote session already belongs to the NEXT user, and pushing this
794
+ * (previous user's) snapshot under it would clobber the record remotely.
2070
795
  */
2071
796
  stopSync(options?: {
2072
797
  flush?: boolean;
@@ -2246,10 +971,26 @@ declare class FeatureFlagHandle {
2246
971
  onClose(cb: () => void): void;
2247
972
  close(): void;
2248
973
  }
974
+ /** The slice of the query engine this module drives: register a live query
975
+ * locally, ask for its remote registration, subscribe to its rows. */
976
+ interface LiveQueryPort$1 {
977
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
978
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
979
+ immediate?: boolean;
980
+ }): () => void;
981
+ }
982
+ interface RemoteRegisterPort$1 {
983
+ enqueueDownEvent(event: {
984
+ type: 'register';
985
+ payload: {
986
+ hash: string;
987
+ };
988
+ }): void;
989
+ }
2249
990
  interface FeatureFlagModuleDeps<S extends SchemaStructure> {
2250
- dataModule: DataModule<S>;
2251
- sync: Sp00kySync<S>;
2252
- auth: AuthService<S>;
991
+ dataModule: LiveQueryPort$1;
992
+ sync: RemoteRegisterPort$1;
993
+ auth: Pick<AuthService<S>, 'subscribe'>;
2253
994
  logger: Logger$1;
2254
995
  }
2255
996
  declare class FeatureFlagModule<S extends SchemaStructure> {
@@ -2292,60 +1033,824 @@ declare class FeatureFlagModule<S extends SchemaStructure> {
2292
1033
  private persistOverrides;
2293
1034
  }
2294
1035
  //#endregion
2295
- //#region src/modules/app-release/index.d.ts
2296
- interface AppReleaseSnapshot {
2297
- /** Latest announced version for the app, or undefined when no row exists. */
2298
- version: string | undefined;
2299
- /** Clients should clear SW/caches when reloading onto this version. */
2300
- cacheBust: boolean;
2301
- /** Clients should reload/update immediately instead of asking. */
2302
- mandatory: boolean;
2303
- releasedAt: string | undefined;
1036
+ //#region src/modules/app-release/index.d.ts
1037
+ interface AppReleaseSnapshot {
1038
+ /** Latest announced version for the app, or undefined when no row exists. */
1039
+ version: string | undefined;
1040
+ /** Clients should clear SW/caches when reloading onto this version. */
1041
+ cacheBust: boolean;
1042
+ /** Clients should reload/update immediately instead of asking. */
1043
+ mandatory: boolean;
1044
+ releasedAt: string | undefined;
1045
+ }
1046
+ interface AppReleaseOptions {
1047
+ ttl?: QueryTimeToLive;
1048
+ }
1049
+ declare class AppReleaseHandle {
1050
+ readonly app: string;
1051
+ private latest;
1052
+ private listeners;
1053
+ private onCloseFn;
1054
+ private closed;
1055
+ constructor(app: string);
1056
+ set(snapshot: AppReleaseSnapshot): void;
1057
+ snapshot(): AppReleaseSnapshot;
1058
+ version(): string | undefined;
1059
+ /** True when the announced version is semver-newer than `currentVersion`. */
1060
+ updateAvailable(currentVersion: string): boolean;
1061
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
1062
+ onClose(cb: () => void): void;
1063
+ close(): void;
1064
+ }
1065
+ /** The slice of the query engine this module drives: register a live query
1066
+ * locally, ask for its remote registration, subscribe to its rows. */
1067
+ interface LiveQueryPort {
1068
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
1069
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
1070
+ immediate?: boolean;
1071
+ }): () => void;
1072
+ }
1073
+ interface RemoteRegisterPort {
1074
+ enqueueDownEvent(event: {
1075
+ type: 'register';
1076
+ payload: {
1077
+ hash: string;
1078
+ };
1079
+ }): void;
1080
+ }
1081
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
1082
+ dataModule: LiveQueryPort;
1083
+ sync: RemoteRegisterPort;
1084
+ auth: Pick<AuthService<S>, 'subscribe'>;
1085
+ logger: Logger$1;
1086
+ }
1087
+ declare class AppReleaseModule<S extends SchemaStructure> {
1088
+ private deps;
1089
+ private logger;
1090
+ private handles;
1091
+ private authUnsubscribe;
1092
+ private lastUserId;
1093
+ private querySubscription;
1094
+ private starting;
1095
+ private ttl;
1096
+ private snapshots;
1097
+ private loaded;
1098
+ constructor(deps: AppReleaseModuleDeps<S>);
1099
+ init(): void;
1100
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
1101
+ closeAll(): Promise<void>;
1102
+ private refresh;
1103
+ private teardownQuery;
1104
+ private ensureStarted;
1105
+ private applyRecords;
1106
+ }
1107
+ //#endregion
1108
+ //#region src/kernel/events.d.ts
1109
+ /**
1110
+ * Inbound events. Everything that can start a saga arrives as one of these
1111
+ * through the runtime router: public API calls, adapter callbacks, timers,
1112
+ * and `dispatch` effects from other sagas.
1113
+ */
1114
+ type RuntimeEvent = {
1115
+ type: 'EnsureRegistered';
1116
+ requireAuth?: boolean;
1117
+ attempt?: number;
1118
+ } | {
1119
+ type: 'RegisterRemote';
1120
+ hash: QueryHash;
1121
+ retry?: boolean;
1122
+ } | {
1123
+ type: 'SyncOutcome';
1124
+ ok: boolean;
1125
+ error?: unknown;
1126
+ } | {
1127
+ type: 'AckPrune';
1128
+ } | {
1129
+ type: 'ReadDirtyMembership';
1130
+ } | {
1131
+ type: 'ReadMembership';
1132
+ hashes: QueryHash[];
1133
+ } | {
1134
+ type: 'FetchRows';
1135
+ } | {
1136
+ type: 'Materialize';
1137
+ hash: QueryHash;
1138
+ } | {
1139
+ type: 'MaterializeDirty';
1140
+ } | {
1141
+ type: 'LifecycleTick';
1142
+ } | {
1143
+ type: 'GcTick';
1144
+ } | {
1145
+ type: 'Drain';
1146
+ } | {
1147
+ type: 'FlushWrite';
1148
+ key: string;
1149
+ } | {
1150
+ type: 'PollTick';
1151
+ } | {
1152
+ type: 'SelfHealTick';
1153
+ } | {
1154
+ type: 'HeartbeatNow';
1155
+ } | {
1156
+ type: 'StartRemote';
1157
+ } | {
1158
+ type: 'PrimeCircuit';
1159
+ } | {
1160
+ type: 'VersionsPrimed';
1161
+ entries: Array<readonly [string, number]>;
1162
+ } | {
1163
+ type: 'WarmBlobs';
1164
+ } | {
1165
+ type: 'AuthFlip';
1166
+ userId: string | null;
1167
+ } | {
1168
+ type: 'BucketSwitch';
1169
+ target: string;
1170
+ } | {
1171
+ type: 'PageHide';
1172
+ } | {
1173
+ type: 'ConnectionChanged';
1174
+ state: ConnectionState;
1175
+ } | {
1176
+ type: 'StreamUpdate';
1177
+ update: StreamUpdate;
1178
+ } | {
1179
+ type: 'LiveStart';
1180
+ } | {
1181
+ type: 'LiveChange';
1182
+ hashes: QueryHash[];
1183
+ } | {
1184
+ type: 'TabRole';
1185
+ role: 'solo' | 'leader' | 'follower';
1186
+ } | {
1187
+ type: 'TabMessage';
1188
+ message: unknown;
1189
+ };
1190
+ type OutEvent = {
1191
+ type: 'query:records';
1192
+ hash: QueryHash;
1193
+ records: ReadonlyArray<Record<string, unknown>>;
1194
+ } | {
1195
+ type: 'query:status';
1196
+ hash: QueryHash;
1197
+ status: QueryStatus;
1198
+ } | {
1199
+ type: 'query:authority';
1200
+ hash: QueryHash;
1201
+ known: boolean;
1202
+ } | {
1203
+ type: 'query:view-lost';
1204
+ hash: QueryHash;
1205
+ } | {
1206
+ type: 'query:evicted';
1207
+ hash: QueryHash;
1208
+ } | {
1209
+ type: 'mutation:event';
1210
+ event: unknown;
1211
+ } | {
1212
+ type: 'mutation:settled';
1213
+ mutationId: string;
1214
+ recordId: string;
1215
+ eventType: string;
1216
+ } | {
1217
+ type: 'mutation:rolled-back';
1218
+ mutationId: string;
1219
+ recordId: string;
1220
+ eventType: string;
1221
+ error: string;
1222
+ } | {
1223
+ type: 'tray:changed';
1224
+ count: number;
1225
+ } | {
1226
+ type: 'health:changed';
1227
+ health: SyncHealth;
1228
+ } | {
1229
+ type: 'activity:changed';
1230
+ fetching: number;
1231
+ pending: number;
1232
+ } | {
1233
+ type: 'tabs:broadcast';
1234
+ message: unknown;
1235
+ } | {
1236
+ type: 'tabs:sendTo';
1237
+ tabId: string;
1238
+ message: unknown;
1239
+ } | {
1240
+ type: 'devtools';
1241
+ name: string;
1242
+ data?: unknown;
1243
+ } | {
1244
+ type: 'log';
1245
+ level: 'debug' | 'info' | 'warn' | 'error';
1246
+ message: string;
1247
+ data?: unknown;
1248
+ };
1249
+ //#endregion
1250
+ //#region src/state/lifecycle.d.ts
1251
+ /**
1252
+ * The query lifecycle as one explicit machine.
1253
+ *
1254
+ * `phase` answers "where do this query's rows come from":
1255
+ * - `cold` never resolved on this device: rows come from a local
1256
+ * predicate scan (or the SSP local window), bindings show a loader.
1257
+ * - `cached` a durable `_00_view` row was found: rows come from that id-set.
1258
+ * - `live` a server membership set was accepted this session.
1259
+ * - `view-lost` the server's `_00_query` row vanished while we held
1260
+ * membership; rows are kept, a re-registration is under way.
1261
+ *
1262
+ * `remote` tracks the server-side registration, `fetchDepth` is the refcount
1263
+ * behind `status: 'fetching'`, `notified` says whether subscribers received
1264
+ * at least one materialization this registration.
1265
+ */
1266
+ type QueryPhase = 'cold' | 'cached' | 'live' | 'view-lost';
1267
+ type RemotePhase = 'unregistered' | 'registering' | 'registered' | 'failed';
1268
+ interface QueryLifecycle {
1269
+ readonly phase: QueryPhase;
1270
+ readonly remote: RemotePhase;
1271
+ readonly fetchDepth: number;
1272
+ readonly notified: boolean;
1273
+ }
1274
+ //#endregion
1275
+ //#region src/kernel/effects.d.ts
1276
+ type Vars = Record<string, unknown>;
1277
+ /** What the in-browser SSP needs to build a local view. */
1278
+ interface RegisterPlan {
1279
+ queryHash: string;
1280
+ surql: string;
1281
+ params: Vars;
1282
+ ttl: string;
1283
+ tableName: string;
1284
+ involvedTables?: string[];
1285
+ }
1286
+ /** One statement's outcome of a multi-statement remote request. */
1287
+ type StatementResult = {
1288
+ status: 'OK';
1289
+ result: unknown;
1290
+ } | {
1291
+ status: 'ERR';
1292
+ error: string;
1293
+ };
1294
+ /** One entry of an `all` fan-out result (allSettled semantics). */
1295
+
1296
+ /**
1297
+ * Effects are data. A saga yields one and gets its result back on the next
1298
+ * `next()`; the interpreter (client/runtime) is the only place they execute.
1299
+ */
1300
+ type Effect = {
1301
+ kind: 'local.query';
1302
+ sql: string;
1303
+ vars?: Vars;
1304
+ epoch?: number;
1305
+ } | {
1306
+ kind: 'local.select';
1307
+ plan: QueryPlan;
1308
+ params?: Vars;
1309
+ } | {
1310
+ kind: 'local.execute';
1311
+ query: SealedQuery<unknown>;
1312
+ vars?: Vars;
1313
+ epoch?: number;
1314
+ } | {
1315
+ kind: 'local.getById';
1316
+ table: string;
1317
+ id: unknown;
1318
+ } | {
1319
+ kind: 'local.upsert';
1320
+ table: string;
1321
+ id: unknown;
1322
+ data: Record<string, unknown>;
1323
+ mode: 'replace' | 'merge';
1324
+ } | {
1325
+ kind: 'local.delete';
1326
+ table: string;
1327
+ id: unknown;
1328
+ } | {
1329
+ kind: 'local.epoch';
1330
+ } | {
1331
+ kind: 'remote.query';
1332
+ sql: string;
1333
+ vars?: Vars;
1334
+ timeoutMs?: number;
1335
+ } | {
1336
+ kind: 'remote.live';
1337
+ table: string;
1338
+ } | {
1339
+ kind: 'remote.kill';
1340
+ uuid: string;
1341
+ } | {
1342
+ kind: 'ssp.register';
1343
+ plan: RegisterPlan;
1344
+ } | {
1345
+ kind: 'ssp.unregister';
1346
+ hash: string;
1347
+ } | {
1348
+ kind: 'ssp.ingest';
1349
+ records: IngestRecord[];
1350
+ } | {
1351
+ kind: 'timer.set';
1352
+ key: string;
1353
+ ms: number;
1354
+ event: RuntimeEvent;
1355
+ } | {
1356
+ kind: 'timer.clear';
1357
+ key: string;
1358
+ } | {
1359
+ kind: 'state.read';
1360
+ select: (s: ClientState) => unknown;
1361
+ } | {
1362
+ kind: 'state.update';
1363
+ fn: (s: ClientState) => ClientState;
1364
+ } | {
1365
+ kind: 'state.wait';
1366
+ until: (s: ClientState) => boolean;
1367
+ } | {
1368
+ kind: 'now';
1369
+ } | {
1370
+ kind: 'id';
1371
+ scope: 'mutation' | 'salt';
1372
+ } | {
1373
+ kind: 'hash';
1374
+ input: string;
1375
+ } | {
1376
+ kind: 'emit';
1377
+ event: OutEvent;
1378
+ } | {
1379
+ kind: 'dispatch';
1380
+ event: RuntimeEvent;
1381
+ } | {
1382
+ kind: 'all';
1383
+ effects: Effect[];
1384
+ } | {
1385
+ kind: 'service';
1386
+ name: ServiceName;
1387
+ args: unknown[];
1388
+ };
1389
+ /**
1390
+ * Calls into the legacy services that are adapters, not state: auth, tabs,
1391
+ * blobs, migrator, crdt, persistence, the SSP lifecycle, the remote socket.
1392
+ * A saga names the call; the runtime binds it to the real service.
1393
+ */
1394
+ interface ServiceCalls {
1395
+ 'hint.read': () => string | null;
1396
+ 'hint.write': (bucketId: string) => void;
1397
+ 'local.connect': (bucketId: string) => Promise<void>;
1398
+ 'local.switchStore': (bucketId: string) => Promise<void>;
1399
+ 'local.beginSwitch': () => () => void;
1400
+ 'local.currentBucketId': () => string;
1401
+ 'local.usesSurqlSchema': () => boolean;
1402
+ 'migrator.provision': () => Promise<void>;
1403
+ 'blobs.start': (bucketId: string) => Promise<void>;
1404
+ 'blobs.setNamespace': (bucketId: string) => Promise<void>;
1405
+ 'blobs.clear': () => Promise<void>;
1406
+ 'ssp.init': () => Promise<void>;
1407
+ 'ssp.setPermissions': () => void;
1408
+ 'ssp.setSessionAuth': (authId: string | null, access: string | null) => void;
1409
+ 'ssp.prime': (pendingIds: string[]) => Promise<void>;
1410
+ 'ssp.reset': () => Promise<void>;
1411
+ 'ssp.setPersistence': (enabled: boolean) => void;
1412
+ 'auth.restoreSession': () => Promise<string | null>;
1413
+ 'auth.init': () => Promise<void>;
1414
+ 'auth.sessionAuthId': () => string | null;
1415
+ 'auth.access': () => string | null;
1416
+ 'auth.token': () => string | null;
1417
+ 'auth.currentUser': () => Record<string, unknown> | null;
1418
+ 'remote.connect': () => Promise<void>;
1419
+ 'remote.releaseViews': (ids: unknown[]) => void;
1420
+ 'supervisor.start': () => void;
1421
+ 'tabs.start': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1422
+ 'tabs.moveToBucket': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1423
+ 'crdt.setSessionId': (sessionId: string) => void;
1424
+ 'crdt.closeAll': (flush: boolean) => void;
1425
+ 'persistence.set': (key: string, value: unknown) => Promise<void>;
1426
+ 'features.init': () => void;
1427
+ 'releases.init': () => void;
1428
+ 'window.attach': () => void;
1429
+ }
1430
+ type ServiceName = keyof ServiceCalls;
1431
+ /** Typed constructors. Each is one line so the saga reads like the plan. */
1432
+ //#endregion
1433
+ //#region src/kernel/saga.d.ts
1434
+ /**
1435
+ * A saga is a generator that yields effects and receives their results. It
1436
+ * holds no references to adapters or state, so it can be driven by the real
1437
+ * interpreter or by `testing/run-pure` with canned results.
1438
+ */
1439
+ type Saga<R> = Generator<Effect, R, any>;
1440
+ /**
1441
+ * Lanes bound concurrency without a queue object per lane:
1442
+ * - `serial`: runs strictly one at a time per key, in arrival order.
1443
+ * - `dedupe`: a request while one run is active joins that run instead of
1444
+ * starting another.
1445
+ * The bookkeeping is a pure value so the policy is unit-testable; the runtime
1446
+ * owns the promises.
1447
+ */
1448
+ type Lane = {
1449
+ kind: 'serial';
1450
+ key: string;
1451
+ } | {
1452
+ kind: 'dedupe';
1453
+ key: string;
1454
+ };
1455
+ interface LaneState {
1456
+ readonly running: ReadonlySet<string>;
1457
+ readonly waiting: ReadonlyMap<string, number>;
1458
+ }
1459
+ //#endregion
1460
+ //#region src/state/client-state.d.ts
1461
+ type Row = Record<string, unknown>;
1462
+ /** Everything a query is, minus anything that changes after registration. */
1463
+ interface QueryDefinition {
1464
+ /** Session-salted `_00_query:<hash>` record id: the remote view id. */
1465
+ readonly id: RecordId<string>;
1466
+ readonly hash: QueryHash;
1467
+ /** Unsalted `sha256({surql, params})`: key of the durable `_00_view` row. */
1468
+ readonly viewKey: string;
1469
+ readonly surql: string;
1470
+ readonly params: Readonly<Record<string, unknown>>;
1471
+ readonly plan?: QueryPlan;
1472
+ readonly ttl: QueryTimeToLive;
1473
+ readonly ttlMs: number;
1474
+ readonly tableName: string;
1475
+ readonly createdAt: number;
1476
+ }
1477
+ type ServerViewState = 'materializing' | 'ready' | null;
1478
+ interface QueryTelemetry {
1479
+ readonly updateCount: number;
1480
+ readonly errorCount: number;
1481
+ readonly lastUpdatedAt: number | null;
1482
+ readonly materializationSamples: ReadonlyArray<number>;
1483
+ readonly lastIngestLatencyMs: number | null;
1484
+ readonly phaseSamples: Readonly<Record<string, ReadonlyArray<number>>>;
1485
+ readonly phaseLast: Readonly<Record<string, number | null>>;
1486
+ readonly registrationTimings: RegistrationTimings;
1487
+ }
1488
+ interface QueryEntry {
1489
+ readonly def: QueryDefinition;
1490
+ readonly lifecycle: QueryLifecycle;
1491
+ /** Server membership (ids + versions) or the durable seed. */
1492
+ readonly remoteArray: RecordVersionArray;
1493
+ /** The in-browser SSP view's id-set: local truth for "does this row match". */
1494
+ readonly localArray: RecordVersionArray;
1495
+ readonly subqueryRemoteArray: RecordVersionArray;
1496
+ readonly records: ReadonlyArray<Row>;
1497
+ readonly serverState: ServerViewState;
1498
+ readonly subscribers: number;
1499
+ readonly lastSubscriberLeftAt: number | null;
1500
+ readonly lastHeartbeatAt: number | null;
1501
+ readonly lastPolledAt: number | null;
1502
+ readonly registerAttempts: number;
1503
+ readonly telemetry: QueryTelemetry;
1504
+ }
1505
+ type OutboxStatus = 'pending' | 'acked';
1506
+ /** In-memory mirror of one `_00_pending_mutations` row plus its push progress. */
1507
+ interface OutboxItem {
1508
+ readonly id: string;
1509
+ readonly type: MutationEventType;
1510
+ readonly recordId: string;
1511
+ readonly table: string;
1512
+ readonly status: OutboxStatus;
1513
+ readonly ackedAt: number | null;
1514
+ readonly attempts: number;
1515
+ }
1516
+ type TabRole = 'solo' | 'leader' | 'follower';
1517
+ /** A debounced update accumulating locally until its flush writes the outbox row. */
1518
+ interface PendingWrite {
1519
+ readonly key: string;
1520
+ readonly table: string;
1521
+ readonly recordId: string;
1522
+ readonly data: Readonly<Record<string, unknown>>;
1523
+ readonly before: Readonly<Record<string, unknown>> | null;
1524
+ readonly firstAt: number;
1525
+ }
1526
+ interface SyncSlice {
1527
+ readonly health: SyncHealth;
1528
+ readonly consecutiveFailures: number;
1529
+ readonly hasSyncedOnce: boolean;
1530
+ readonly selfHealAttempts: number;
1531
+ readonly pollIdleStreak: number;
1532
+ readonly lastReconnectRefetchAt: number | null;
1533
+ readonly needsResubscribe: boolean;
1534
+ readonly fetchAttempts: number;
1535
+ readonly liveUuid: string | null;
1536
+ readonly liveTable: string | null;
1537
+ readonly lanes: LaneState;
1538
+ }
1539
+ interface ClientState {
1540
+ readonly sessionId: string | null;
1541
+ readonly userId: string | null;
1542
+ /** The principal the current session salt was minted for. */
1543
+ readonly saltUserId: string | null;
1544
+ /** Latest bucket-switch target; an older switch that wakes up to a newer target skips. */
1545
+ readonly pendingBucket: string | null;
1546
+ readonly tabId: string;
1547
+ readonly tabRole: TabRole;
1548
+ readonly bucketId: string | null;
1549
+ readonly localReady: boolean;
1550
+ readonly primed: boolean;
1551
+ readonly queries: ReadonlyMap<QueryHash, QueryEntry>;
1552
+ /** Hashes whose local registration is in flight (dedupes concurrent `query()` calls). */
1553
+ readonly registering: ReadonlySet<QueryHash>;
1554
+ /** Re-read attempts per hash while the server reports a view as `materializing`. */
1555
+ readonly membershipReread: ReadonlyMap<QueryHash, number>;
1556
+ /** Local body versions (`_00_rv`) by encoded record id. */
1557
+ readonly versions: ReadonlyMap<string, number>;
1558
+ readonly outbox: ReadonlyArray<OutboxItem>;
1559
+ readonly pendingWrites: ReadonlyMap<string, PendingWrite>;
1560
+ readonly failedCount: number;
1561
+ /** Queries whose render inputs changed since their last materialization. */
1562
+ readonly dirty: ReadonlySet<QueryHash>;
1563
+ /** Queries whose server membership must be re-read. */
1564
+ readonly membershipDirty: ReadonlySet<QueryHash>;
1565
+ readonly sync: SyncSlice;
1566
+ }
1567
+ //#endregion
1568
+ //#region src/modules/ref-tables.d.ts
1569
+ type RefMode = 'single' | 'dedicated';
1570
+ /**
1571
+ * Sentinel user id for unauthenticated clients when anonymous live queries are
1572
+ * enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
1573
+ * so it can never collide with a real user id (those arrive as `user:<id>`);
1574
+ * both sides resolve it to the shared `_00_list_ref_anon` table.
1575
+ */
1576
+ //#endregion
1577
+ //#region src/query/env.d.ts
1578
+ /**
1579
+ * Static configuration the sagas read. Plain data, built once by the runtime
1580
+ * from `Sp00kyConfig`; sagas never see the config object itself.
1581
+ */
1582
+ interface SagaEnv {
1583
+ readonly schema: SchemaStructure;
1584
+ readonly refMode: RefMode;
1585
+ readonly anonLive: boolean;
1586
+ readonly remoteTimeoutMs: number;
1587
+ readonly pushTimeoutMs: number;
1588
+ readonly outboxBatchSize: number;
1589
+ readonly degradeAfter: number;
1590
+ readonly materializeDebounceMs: number;
1591
+ readonly pollBaseMs: number;
1592
+ readonly defaultTtlMs: number;
2304
1593
  }
2305
- interface AppReleaseOptions {
2306
- ttl?: QueryTimeToLive;
1594
+ //#endregion
1595
+ //#region src/mutation/rows.d.ts
1596
+ interface FailedMutationRow {
1597
+ id: string;
1598
+ mutationType: MutationEventType;
1599
+ recordId: string;
1600
+ tableName: string;
1601
+ data?: Record<string, unknown>;
1602
+ beforeRecord?: Record<string, unknown> | null;
1603
+ error: {
1604
+ message: string;
1605
+ kind: 'application' | 'unreplayable';
1606
+ };
1607
+ attempts: number;
1608
+ createdAt: number;
1609
+ failedAt: number;
1610
+ revert: 'full' | 'partial' | 'none';
2307
1611
  }
2308
- declare class AppReleaseHandle {
2309
- readonly app: string;
2310
- private latest;
2311
- private listeners;
2312
- private onCloseFn;
2313
- private closed;
2314
- constructor(app: string);
2315
- set(snapshot: AppReleaseSnapshot): void;
2316
- snapshot(): AppReleaseSnapshot;
2317
- version(): string | undefined;
2318
- /** True when the announced version is semver-newer than `currentVersion`. */
2319
- updateAvailable(currentVersion: string): boolean;
2320
- subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
2321
- onClose(cb: () => void): void;
2322
- close(): void;
1612
+ /**
1613
+ * Parse a record id READ BACK FROM THE STORE, stripping SurrealDB's `⟨⟩`
1614
+ * escaping (outbox ids contain `_`, so they come back escaped).
1615
+ */
1616
+ //#endregion
1617
+ //#region src/kernel/interpreter.d.ts
1618
+ /** The five adapters plus the pure ports, as the interpreter sees them. */
1619
+ interface Adapters {
1620
+ local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'getById' | 'upsert' | 'delete'> & {
1621
+ readonly epoch: number;
1622
+ };
1623
+ remote: {
1624
+ queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
1625
+ /** Subscribe to `LIVE SELECT * FROM <table>`; the callback receives the changed query hashes. */
1626
+ live(table: string, onChange: (hashes: string[]) => void): Promise<string>;
1627
+ kill(uuid: string): Promise<void>;
1628
+ };
1629
+ ssp: {
1630
+ registerQueryPlan(plan: {
1631
+ queryHash: string;
1632
+ surql: string;
1633
+ params: Record<string, unknown>;
1634
+ ttl: Duration;
1635
+ lastActiveAt: Date;
1636
+ localArray: [];
1637
+ remoteArray: [];
1638
+ meta: {
1639
+ tableName: string;
1640
+ involvedTables?: string[];
1641
+ };
1642
+ }): StreamUpdate | undefined;
1643
+ unregisterQueryPlan(hash: string): void;
1644
+ ingestMany(records: IngestRecord[]): unknown;
1645
+ };
1646
+ timers: {
1647
+ set(key: string, ms: number, fire: () => void): void;
1648
+ clear(key: string): void;
1649
+ };
1650
+ clock: {
1651
+ now(): number;
1652
+ };
1653
+ ids: {
1654
+ mutation(): string;
1655
+ salt(): string;
1656
+ };
1657
+ hash(input: string): Promise<string>;
1658
+ services: ServiceCalls;
2323
1659
  }
2324
- interface AppReleaseModuleDeps<S extends SchemaStructure> {
2325
- dataModule: DataModule<S>;
2326
- sync: Sp00kySync<S>;
2327
- auth: AuthService<S>;
1660
+ /** What the interpreter needs from the runtime: state, waiting, emitting, dispatching. */
1661
+ //#endregion
1662
+ //#region src/client/runtime.d.ts
1663
+ interface RuntimeOptions {
1664
+ env: SagaEnv;
1665
+ adapters: Adapters;
2328
1666
  logger: Logger$1;
1667
+ tabId: string;
1668
+ initialState?: ClientState;
2329
1669
  }
2330
- declare class AppReleaseModule<S extends SchemaStructure> {
2331
- private deps;
1670
+ /**
1671
+ * The one effectful object of the engine: holds the state, runs sagas on
1672
+ * lanes, fires timers, fans events out to subscribers and schedules
1673
+ * materialization for dirty queries. No decision logic lives here.
1674
+ */
1675
+ declare class Runtime {
1676
+ private stateValue;
1677
+ private readonly interpret;
1678
+ private readonly env;
1679
+ private readonly adapters;
1680
+ private readonly logger;
1681
+ private readonly serialLanes;
1682
+ private readonly dedupeLanes;
1683
+ private readonly waiters;
1684
+ private readonly recordSubs;
1685
+ private readonly statusSubs;
1686
+ private readonly authoritySubs;
1687
+ private readonly lastStatus;
1688
+ private readonly listeners;
1689
+ private readonly scheduledMaterialize;
1690
+ private readonly timerKeys;
1691
+ private lastActivity;
1692
+ private lastHealth;
1693
+ private disposed;
1694
+ constructor(opts: RuntimeOptions);
1695
+ get state(): ClientState;
1696
+ /** Run a saga, optionally on a lane. Rejections propagate to the caller. */
1697
+ run<R>(saga: Saga<R>, opts?: {
1698
+ lane?: Lane;
1699
+ signal?: AbortSignal;
1700
+ }): Promise<R>;
1701
+ /** Route an event to its saga. Never rejects: failures are logged. */
1702
+ dispatch(event: RuntimeEvent): Promise<void>;
1703
+ private setState;
1704
+ waitFor(until: (s: ClientState) => boolean, signal?: AbortSignal): Promise<void>;
1705
+ /** Deliver an outbound event to its subscribers and listeners. */
1706
+ emit(event: OutEvent): void;
1707
+ private notify;
1708
+ private safely;
1709
+ /** Observe outbound events by type (`'*'` for all). */
1710
+ on(type: OutEvent['type'] | '*', cb: (event: OutEvent) => void): () => void;
1711
+ subscribe(hash: QueryHash, cb: QueryUpdateCallback, options?: {
1712
+ immediate?: boolean;
1713
+ }): () => void;
1714
+ subscribeStatus(hash: QueryHash, cb: QueryStatusCallback, options?: {
1715
+ immediate?: boolean;
1716
+ }): () => void;
1717
+ subscribeAuthority(hash: QueryHash, cb: QueryAuthorityCallback, options?: {
1718
+ immediate?: boolean;
1719
+ }): () => void;
1720
+ /** Apply a reducer outside a saga (facade conveniences such as timing reports). */
1721
+ update(reducer: (s: ClientState) => ClientState): void;
1722
+ dispose(): void;
1723
+ }
1724
+ //#endregion
1725
+ //#region src/services/tabs/coordinator.d.ts
1726
+ interface CoordinatorHooks {
1727
+ /** Become the store owner: spawn the worker, open the pool under the given
1728
+ * per-leadership lock. Returns the resulting health for db-ready relays.
1729
+ * `resumeHeld` = keep the existing live worker (broker-restart path). */
1730
+ adoptOwner(bucketId: string, opts: {
1731
+ workerLockName: string;
1732
+ allowMemoryFallback: boolean;
1733
+ forceTakeover: boolean;
1734
+ resumeHeld: boolean;
1735
+ }): Promise<StorageHealth>;
1736
+ /** Attach to a leader's worker through `dbPort`. */
1737
+ adoptAttached(dbPort: MessagePort, snapshot: {
1738
+ bucketId: string;
1739
+ storageHealth: StorageHealth;
1740
+ leadershipId: number;
1741
+ }): Promise<void>;
1742
+ /** We were leader and got demoted (zombie thaw / stale promotion): tear the
1743
+ * owned worker down so its SAH handles free up. */
1744
+ releaseOwnership(): Promise<void>;
1745
+ /** The leader (or its port) is gone; queue/park ops until a new role lands. */
1746
+ onLeaderLost(reason: string): void;
1747
+ /** Leader side: forward a follower's dbPort into the owned worker. */
1748
+ exposeClientPort(clientId: string, port: MessagePort): Promise<void>;
1749
+ removeClientPort(clientId: string): Promise<void>;
1750
+ /** Sync layer role changes (implemented in the sync module). */
1751
+ /** Synchronous leader WIRING. Must not block: the role is published and
1752
+ * `leader-ready` is sent right after it returns. */
1753
+ becomeSyncLeader(hub: LeaderSyncHub): void;
1754
+ /** The blocking half of the leader handover (outbox drain, LIVE restart),
1755
+ * run in the background once the tab is already a working leader. */
1756
+ resumeSyncLeaderDuties(): Promise<void>;
1757
+ becomeSyncFollower(forwarder: SyncForwarder): void;
1758
+ becomeSyncSolo(): void;
1759
+ /** Current storage health, for db-ready sent to late-joining followers. */
1760
+ currentStorageHealth(): StorageHealth;
1761
+ }
1762
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
1763
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
1764
+ declare class LeaderSyncHub {
1765
+ readonly leadershipId: number;
2332
1766
  private logger;
2333
- private handles;
2334
- private authUnsubscribe;
2335
- private lastUserId;
2336
- private querySubscription;
2337
- private starting;
2338
- private ttl;
2339
- private snapshots;
2340
- private loaded;
2341
- constructor(deps: AppReleaseModuleDeps<S>);
2342
- init(): void;
2343
- release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2344
- closeAll(): Promise<void>;
2345
- private refresh;
2346
- private teardownQuery;
2347
- private ensureStarted;
2348
- private applyRecords;
1767
+ private followers;
1768
+ private seq;
1769
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1770
+ onFollowerDetached: ((tabId: TabId) => void) | null;
1771
+ constructor(leadershipId: number, logger: Logger$1);
1772
+ attach(tabId: TabId, port: MessagePort): void;
1773
+ detach(tabId: TabId): void;
1774
+ detachAll(): void;
1775
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1776
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1777
+ /** Stamped ingest relay; seq lets followers detect gaps. */
1778
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1779
+ get followerCount(): number;
1780
+ get relayedBatches(): number;
1781
+ }
1782
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
1783
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
1784
+ * backstopped by the new leader reloading the shared outbox from the store. */
1785
+ declare class SyncForwarder {
1786
+ private tabId;
1787
+ private port;
1788
+ private queued;
1789
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1790
+ constructor(tabId: TabId);
1791
+ rebind(port: MessagePort): void;
1792
+ unbind(): void;
1793
+ private post;
1794
+ mutationEnqueued(mutationId: string): void;
1795
+ /** An optimistic write this tab just ingested. Deliberately NOT queued while
1796
+ * detached: a new leader primes its circuit from the shared store, which
1797
+ * already holds the row, and replaying a stale tuple at it later would put
1798
+ * an older `_00_rv` in its version memo. */
1799
+ ingest(tuples: IngestTuple[]): void;
1800
+ requestPoll(): void;
1801
+ }
1802
+ declare class TabsCoordinator {
1803
+ private deps;
1804
+ role: TabRole$1;
1805
+ leadershipId: number;
1806
+ leaderTabId: TabId | null;
1807
+ brokerRole: 'pending' | TabRole$1;
1808
+ /** Wall time from `become-leader` to `leader-ready` on the last promotion.
1809
+ * Reported in the DevTools role-change event: a slow store adopt (OPFS pool
1810
+ * contention after the previous leader died) shows up here as seconds. */
1811
+ lastPromotionMs: number | null;
1812
+ private fingerprint;
1813
+ private bucketId;
1814
+ private broker;
1815
+ private hub;
1816
+ private forwarder;
1817
+ private roleListeners;
1818
+ private startResolve;
1819
+ private startReject;
1820
+ /** Ports received before start() resolves or between roles. */
1821
+ private promotionChain;
1822
+ private closed;
1823
+ constructor(deps: {
1824
+ tabId: TabId;
1825
+ fingerprint: string;
1826
+ hooks: CoordinatorHooks;
1827
+ logger: Logger$1;
1828
+ /** Fired on pagehide while this tab leads: last-chance OPFS release. */
1829
+ onLeaderPageHide?: () => void;
1830
+ });
1831
+ /** Serialize role transitions; each is small but async (worker opens). */
1832
+ private enqueue;
1833
+ onRoleChange(cb: (role: TabRole$1) => void): () => void;
1834
+ private setRole;
1835
+ /** Connect the broker and resolve once this tab has a usable store role.
1836
+ * Rejects when no role lands in time; the caller then boots solo. */
1837
+ start(bucketId: string): Promise<TabRole$1>;
1838
+ /** Bucket switch: leave the old namespace, join the new one. Resolves when
1839
+ * a role lands in the new namespace. */
1840
+ moveToBucket(bucketId: string): Promise<TabRole$1>;
1841
+ private promote;
1842
+ private demote;
1843
+ private tabLock;
1844
+ private teardownLeader;
1845
+ private teardownFollower;
1846
+ private serveFollower;
1847
+ private attachToLeader;
1848
+ private handleLeaderGone;
1849
+ private fallbackToSolo;
1850
+ get syncHub(): LeaderSyncHub | null;
1851
+ get syncForwarder(): SyncForwarder | null;
1852
+ get tabId(): TabId;
1853
+ stop(): Promise<void>;
2349
1854
  }
2350
1855
  //#endregion
2351
1856
  //#region src/services/blobs/blob-store.d.ts
@@ -2597,6 +2102,25 @@ declare class BlobCache {
2597
2102
  stats(): BlobCacheStats;
2598
2103
  }
2599
2104
  //#endregion
2105
+ //#region src/client/services.d.ts
2106
+ /** Everything the facade talks to besides the runtime. */
2107
+ interface Services<S extends SchemaStructure> {
2108
+ logger: Logger$1;
2109
+ local: LocalStore;
2110
+ remote: RemoteDatabaseService;
2111
+ connectionSupervisor: ConnectionSupervisor;
2112
+ blobs: BlobCache;
2113
+ persistence: PersistenceClient;
2114
+ streamProcessor: StreamProcessorService;
2115
+ migrator: LocalMigrator;
2116
+ crdt: CrdtManager;
2117
+ auth: AuthService<S>;
2118
+ tabs: TabsCoordinator | null;
2119
+ tabsUnsupportedReason: string | undefined;
2120
+ tabId: string;
2121
+ }
2122
+ /** What the services need back from the runtime once it exists. */
2123
+ //#endregion
2600
2124
  //#region src/utils/blurhash.d.ts
2601
2125
  /**
2602
2126
  * Blurhash generation settings. `true` enables with the defaults below, `false`
@@ -2627,7 +2151,7 @@ declare function isImagePath(path: string): boolean;
2627
2151
  */
2628
2152
  declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
2629
2153
  //#endregion
2630
- //#region src/sp00ky.d.ts
2154
+ //#region src/client/bucket-handle.d.ts
2631
2155
  /** Coerce whatever the `.get()` RPC hands back into a Blob. */
2632
2156
  declare function bucketContentToBlob(content: unknown): Blob | null;
2633
2157
  interface BucketPutOptions {
@@ -2690,333 +2214,99 @@ declare class BucketHandle {
2690
2214
  rename(sourcePath: string, targetPath: string): Promise<void>;
2691
2215
  list(prefix?: string): Promise<string[]>;
2692
2216
  }
2217
+ //#endregion
2218
+ //#region src/client/sp00ky-client.d.ts
2219
+ interface Sp00kyClientDeps<S extends SchemaStructure> {
2220
+ services?: Services<S>;
2221
+ runtime?: Runtime;
2222
+ env?: Partial<SagaEnv>;
2223
+ }
2224
+ /**
2225
+ * The public client. Every method is a thin translation into a saga run, a
2226
+ * state read, or a subscription on the runtime; the engine's behaviour lives
2227
+ * in the sagas.
2228
+ */
2693
2229
  declare class Sp00kyClient<S extends SchemaStructure> {
2694
- private config;
2695
- private local;
2696
- private remote;
2697
- private blobs;
2698
- private connectionSupervisor;
2699
- private persistenceClient;
2700
- private migrator;
2701
- private cache;
2702
- private dataModule;
2703
- private sync;
2704
- private devTools;
2705
- private crdtManager;
2706
- /**
2707
- * True once the LOCAL half of boot is done and the client can serve reads
2708
- * from the local store. Distinct from being connected: `syncHealth` covers
2709
- * reaching the server and `storageHealth` covers whether the local store is
2710
- * durable, but neither says "usable". Consumers gate their first paint on
2711
- * this, which is what makes a warm boot instant and an offline boot possible.
2712
- */
2713
- private localReady;
2714
- private saltUserId;
2715
- private featureFlags;
2716
- private appReleases;
2717
- private preloadedHashes;
2718
- private pendingQueryInits;
2719
- private logger;
2720
- auth: AuthService<S>;
2721
- streamProcessor: StreamProcessorService;
2722
- private tabsCoordinator;
2230
+ private readonly config;
2231
+ readonly auth: AuthService<S>;
2232
+ readonly streamProcessor: StreamProcessorService;
2233
+ private readonly services;
2234
+ private readonly env;
2235
+ private readonly runtime;
2236
+ private readonly featureFlags;
2237
+ private readonly appReleases;
2238
+ private readonly devTools;
2239
+ private hub;
2240
+ private forwarder;
2241
+ private detachWindow;
2723
2242
  private sharedActive;
2724
- /** Current shared-tabs role, or null when the feature is off/fell back. */
2725
- get tabRole(): TabRole | null;
2726
- get remoteClient(): surrealdb0.Surreal;
2727
- get localClient(): unknown;
2728
- get pendingMutationCount(): number;
2729
- /** Number of times the initial list_ref LIVE subscription retried on
2730
- * the most recent `setCurrentUserId` call. 0 when the SSP's
2731
- * pre-emptive user-table creation got there first; >0 when LIVE
2732
- * registration hit a "table not found" race. Exposed so the e2e
2733
- * suite can guard the pre-emptive path against regression. */
2734
- get liveRetryCount(): number;
2735
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
2736
- /** Number of queries mid-fetch right now. See {@link subscribeToFetchActivity}. */
2737
- get fetchingQueryCount(): number;
2738
- /**
2739
- * Observe how many queries are fetching from the server. Fires immediately
2740
- * with the current count and again on every change, so one subscription can
2741
- * drive a "downloading" indicator for the whole app. Pair with
2742
- * {@link subscribeToPendingMutations} for the "uploading" half.
2743
- */
2744
- subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
2745
- /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
2746
- get syncHealth(): SyncHealth;
2747
- /**
2748
- * Observe sync health. Fires immediately with the current status and again
2749
- * on every healthy↔degraded transition. Returns an unsubscribe.
2750
- */
2751
- subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2752
- /** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
2753
- * engines that don't report it. */
2754
- get storageHealth(): StorageHealth;
2755
- /**
2756
- * Observe local-store durability. Fires immediately with the current snapshot
2757
- * and again on every change (at most once per bucket open in practice).
2758
- * Returns an unsubscribe.
2759
- */
2760
- subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2761
- constructor(config: Sp00kyConfig<S>);
2762
- /** The shared-tabs role machinery, wired to this client's modules. */
2763
- private buildTabsCoordinator;
2764
- /**
2765
- * Setup direct callbacks instead of event subscriptions
2766
- */
2767
- private setupCallbacks;
2243
+ constructor(config: Sp00kyConfig<S>, deps?: Sp00kyClientDeps<S>);
2244
+ /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
2245
+ private wireAdapters;
2246
+ private forwardToDevTools;
2768
2247
  init(): Promise<void>;
2769
- /**
2770
- * The network half of boot: connect, verify the restored session, and let the
2771
- * sync engine catch up. Runs in the background after `init()` has already
2772
- * resolved, so nothing here is on the paint path.
2773
- *
2774
- * Every step is best-effort. A failure leaves the client in exactly the state
2775
- * a warm offline boot is in - local reads working, writes queued in the
2776
- * outbox - and the connection supervisor keeps retrying underneath.
2777
- */
2778
- private initRemote;
2779
- /**
2780
- * Write the signed-in user's own row, as the SERVER just returned it, into
2781
- * the local store.
2782
- *
2783
- * `AuthService.check()` (boot verification, sign-in, an app-driven refresh)
2784
- * runs `SELECT * FROM ONLY $auth.id` and keeps the answer on
2785
- * `auth.currentUser`; nothing consumed it beyond the id. Meanwhile the app's
2786
- * own `user` query paints local-first from whatever body the store holds,
2787
- * and that body is only refreshed when the server's row version reaches
2788
- * this client through membership (`_00_list_ref`). While the SSP is down or
2789
- * bootstrapping that never happens, so a device that registered before the
2790
- * account was verified kept rendering a row without `email_verified` and
2791
- * the app parked the user on "Verify your email" over a server that said
2792
- * "already verified". The authoritative row was already in hand.
2793
- *
2794
- * MERGE semantics (`CacheModule.saveBatch`) keep local-only fields, and
2795
- * re-using the memoized version keeps the sync dedup honest: this is a
2796
- * field refresh, not a version claim. `notifyTableQueries` re-materializes
2797
- * the `user` queries so the gate flips without waiting for a stream update.
2798
- * Best-effort: a failure here leaves things exactly as they were.
2799
- */
2800
- private persistVerifiedUser;
2801
- private bucketSwitchChain;
2802
- private pendingBucketTarget;
2803
- /**
2804
- * Ensure the local store is this user's bucket, switching if needed. Called
2805
- * from the auth listener on every auth flip; concurrent calls are chained
2806
- * and superseded intermediates are skipped (latest target wins).
2807
- */
2808
- private ensureLocalBucket;
2809
- /**
2810
- * The bucket-switch choreography: drain → swap → rebind.
2811
- *
2812
- * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
2813
- * outbox delete lands in the OLD bucket, debounce timers cancelled),
2814
- * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
2815
- * (the remote session already belongs to the next user).
2816
- *
2817
- * Swap: gate closes so any local query issued mid-switch (sibling auth
2818
- * subscribers, FeatureFlagModule) waits and then runs against the NEW
2819
- * bucket; store swaps open-new-before-close-old; schema provisions
2820
- * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
2821
- * sessionId-salted hashes with stale arrays — record bodies stay warm);
2822
- * SSP resets to a fresh circuit with re-seeded permissions.
2823
- *
2824
- * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
2825
- * into the OLD bucket's `_00_kv` before this listener ran), active queries
2826
- * re-homed keeping their hashes, sync resumed on the new bucket's own
2827
- * outbox, and every query re-registered remotely to refill from the server.
2828
- */
2829
- private doSwitchBucket;
2830
- /** Removes the `pagehide` listener installed in `init`; see `close`. */
2831
- private detachUnloadRelease;
2832
2248
  close(): Promise<void>;
2833
- /**
2834
- * Subscribe to a feature flag for the current user. Returns a
2835
- * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
2836
- * accessors reflect the latest assignment from `_00_user_feature`,
2837
- * and whose `subscribe(cb)` fires whenever that assignment changes.
2838
- *
2839
- * Permissions are enforced by SurrealDB: a client can only ever see
2840
- * its own row, and cannot create or modify assignments.
2841
- */
2842
- feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2843
- /**
2844
- * Force a feature flag to `variant` in THIS browser only; `null` clears it.
2845
- *
2846
- * Nothing is sent to the server — the `_00_user_feature` assignment is
2847
- * untouched, so clearing restores whatever the server says. Persisted to
2848
- * localStorage, survives reloads, and applies while signed out. Backs the
2849
- * DevTools Access tab, and is a convenient hook for tests.
2850
- *
2851
- * To change a flag for OTHER users you need admin rights (`spky admin add`)
2852
- * and the DevTools Access tab, or `spky flag`.
2853
- */
2854
- setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2855
- /** Drop every local feature flag override set via `setFeatureOverride`. */
2856
- clearFeatureOverrides(): void;
2857
- /** The local feature flag overrides currently in effect, keyed by flag. */
2858
- getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2859
- /**
2860
- * Observe the announced release of an app (`_00_app_release:<app>`, written
2861
- * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
2862
- * announced version plus the cache-bust/mandatory flags, and
2863
- * `updateAvailable(currentVersion)` compares it semver-wise against the
2864
- * running build. World-readable; writes are root-only.
2865
- */
2866
- appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2867
- authenticate(token: string): Promise<surrealdb0.Tokens>;
2868
- /**
2869
- * Open a CRDT field for collaborative editing.
2870
- * Returns a CrdtField with a LoroDoc that can be bound to any editor.
2871
- * Also starts a LIVE SELECT on the parent table for real-time sync;
2872
- * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
2873
- */
2874
- openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2875
- /**
2876
- * Close a CRDT field when editing is done.
2877
- */
2878
- closeCrdtField(table: string, recordId: string, field: string): void;
2879
- deauthenticate(): Promise<void>;
2249
+ isLocalReady(): boolean;
2880
2250
  query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
2251
+ private registerInput;
2881
2252
  private initQuery;
2253
+ queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
2882
2254
  /**
2883
- * Background tail of {@link initQuery}: enqueue the `register` down-event,
2884
- * then instant-hydrate (opt-in via `config.instantHydrate`, and only when
2885
- * the query is cold). Never rejects — both halves catch and log, so
2886
- * `void`-ing the returned promise can't produce an unhandled rejection. By
2887
- * default (hydrate off) the register lifecycle is the single freshness path;
2888
- * the one-shot fetch is an optimization apps enable explicitly, and it runs
2889
- * regardless of preload state — cache-first delivery never depends on WHY
2890
- * rows are cached.
2891
- *
2892
- * Register goes first on purpose. The hydrate used to run strictly before
2893
- * the enqueue, so a windowed list's one-shot read (a full-table scan when
2894
- * the app has no matching index) held its own registration back by seconds
2895
- * per window. Now whichever answer lands first paints; a hydrate that
2896
- * arrives after the registration is dropped (`applyHydration`).
2897
- */
2898
- private finishQueryInit;
2899
- /**
2900
- * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
2901
- * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
2902
- *
2903
- * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
2904
- * - COLD (never preloaded in this bucket): fetch the query one-shot from the
2905
- * remote, persist the rows (+ embedded `.related()` children), stamp the
2906
- * marker — and AWAIT it. This is the "smart waiting" first load: callers can
2907
- * `await db.preload(...)` to hold the UI until the data is ready.
2908
- * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
2909
- * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
2910
- * Default `onUse` does nothing; the data freshens when the real `useQuery`
2911
- * mounts and registers its live view.
2912
- *
2913
- * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
2914
- * written, so it's retried next load). Deduped per session by query hash.
2255
+ * Preload = register a query nobody subscribes to. Resolved before on this
2256
+ * device: returns at once. Never resolved: resolves when the server's
2257
+ * membership and every body are local. `signal` aborts the wait.
2915
2258
  */
2916
2259
  preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
2917
- /**
2918
- * One-shot remote fetch + local persist for a preload query. Returns the row
2919
- * count on success, or -1 on failure (best-effort: logged, never thrown) so
2920
- * the caller skips stamping the freshness marker and retries next load.
2921
- */
2922
- private fetchAndPersist;
2923
- queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
2924
2260
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
2925
2261
  immediate?: boolean;
2926
2262
  }): Promise<() => void>;
2927
- /**
2928
- * Opt-in eager teardown for a query whose last subscriber has gone away
2929
- * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
2930
- * while any subscriber remains. Tears down the remote `_00_query` view +
2931
- * local WASM view instead of waiting for the TTL sweep. Default behavior
2932
- * (no call here) keeps the view resident for cheap re-subscription.
2933
- */
2934
2263
  deregisterQuery(queryHash: string): void;
2935
- /**
2936
- * Subscribe to a query's fetch-status changes (idle/fetching). With
2937
- * `{ immediate: true }` the callback fires synchronously with the current
2938
- * status. Powers the `useQuery` hook's `isFetching()` accessor.
2939
- */
2940
2264
  subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
2941
2265
  immediate?: boolean;
2942
2266
  }): () => void;
2943
- /**
2944
- * Subscribe to a query's authority flips: `true` once server membership is
2945
- * known for it (a registration or poll landed, or a durable `_00_window`
2946
- * seed was read on boot), `false` when it is reset (bucket switch). With
2947
- * `{ immediate: true }` the callback fires synchronously with the current
2948
- * value. Powers the bindings' `isAuthoritative()` / cold-only `isLoading()`.
2949
- */
2950
2267
  subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
2951
2268
  immediate?: boolean;
2952
2269
  }): () => void;
2953
- /**
2954
- * Report the frontend processing time (ms) a client framework spent applying
2955
- * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
2956
- * surface the "frontend" phase of the per-query timing breakdown.
2957
- */
2958
2270
  reportFrontendTiming(queryHash: string, ms: number): void;
2271
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
2272
+ update<T extends Record<string, unknown>>(_table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
2273
+ delete(_table: string, id: string): Promise<void>;
2959
2274
  run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
2960
- bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2961
- /** Cache-free handle. The blob cache reads the remote through this, so a
2962
- * cache miss can't loop back into the cache. */
2963
- private rawBucket;
2964
- /** Blob cache counters for DevTools. */
2965
- getBlobCacheStats(): BlobCacheStats;
2966
- create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
2967
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
2968
- [x: string]: /*elided*/any;
2969
- }>;
2970
- delete(table: string, id: string): Promise<void>;
2971
- /**
2972
- * Whether the local store is initialized and reads can be served. See the
2973
- * `localReady` field: this is deliberately independent of connectivity.
2974
- */
2975
- isLocalReady(): boolean;
2275
+ get failedMutationCount(): number;
2276
+ subscribeToFailedMutations(cb: (count: number) => void): () => void;
2277
+ listFailedMutations(): Promise<FailedMutationRow[]>;
2278
+ retryFailedMutation(mutationId: string): Promise<boolean>;
2279
+ discardFailedMutation(mutationId: string): Promise<boolean>;
2280
+ get tabRole(): TabRole$1 | null;
2281
+ get remoteClient(): Surreal;
2282
+ get localClient(): unknown;
2283
+ get pendingMutationCount(): number;
2284
+ /** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
2285
+ get liveRetryCount(): number;
2286
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
2287
+ get fetchingQueryCount(): number;
2288
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
2289
+ get syncHealth(): SyncHealth;
2290
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2291
+ get storageHealth(): StorageHealth;
2292
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2293
+ /** The engine state, read-only. For tests and DevTools. */
2294
+ get state(): ClientState;
2295
+ /** Feed an event into the engine. For adapters, tests and DevTools. */
2296
+ dispatch(event: RuntimeEvent): Promise<void>;
2297
+ authenticate(token: string): Promise<surrealdb0.Tokens>;
2298
+ deauthenticate(): Promise<void>;
2976
2299
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
2977
- /**
2978
- * Run one raw SurrealQL statement on the remote through the client's own
2979
- * query path: the connect gate (it never runs on a socket whose namespace
2980
- * and token are not applied yet), the per-statement timeout and the
2981
- * concurrency limit. Prefer this over {@link useRemote} for one-shot reads
2982
- * such as counts; `useRemote` hands out the bare SDK client and raced a
2983
- * reconnect with "Specify a namespace to use".
2984
- */
2985
2300
  remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
2986
- /**
2987
- * Mint the salt used for query-id hashing, so two sessions registering the
2988
- * same logical query get distinct `_00_query` rows.
2989
- *
2990
- * Generated LOCALLY, deliberately. This used to be `RETURN <string>session::id()`,
2991
- * which cost a serial round trip on the critical boot path and resolved to
2992
- * `''` offline. The value never needed to come from the server: the server
2993
- * derives its own `clientId` inside `fn::query::register` and *ignores*
2994
- * whatever the caller passed, and the permission rules that matter gate on
2995
- * `auth_id = $auth.id` rather than the session (`_00_list_ref`). Session
2996
- * scoping via `clientId = session::id()` was in fact removed upstream because
2997
- * it broke a user with two tabs open. All this value has to be is unique per
2998
- * browser session, which `randomUUID` gives us for free and offline.
2999
- */
3000
- /**
3001
- * The current principal as the `"table:id"` string the in-browser SSP wants
3002
- * for `$auth.id`, or null when signed out.
3003
- *
3004
- * Tolerates BOTH shapes `currentUser.id` can take, which is the point:
3005
- * a session restored from the cached token carries a plain string (the JWT's
3006
- * `ID` claim), while one verified by the server carries a RecordId. Passing
3007
- * the former to `encodeRecordId` reads `.table` off a string and throws
3008
- * during boot.
3009
- */
3010
- /**
3011
- * Prime the in-browser circuit from the local store. Builds the context the
3012
- * stream processor needs: every synced table (the app schema plus the
3013
- * server-written meta tables that sync down), a schema hash so a snapshot
3014
- * projected under another schema is not trusted, and the ids whose local
3015
- * `_00_rv` was bumped by an unsettled mutation.
3016
- */
3017
- private primeCircuit;
3018
- private sessionAuthId;
3019
- private mintSessionSalt;
2301
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2302
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2303
+ clearFeatureOverrides(): void;
2304
+ getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2305
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2306
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2307
+ closeCrdtField(table: string, recordId: string, field: string): void;
2308
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2309
+ getBlobCacheStats(): BlobCacheStats;
3020
2310
  }
3021
2311
  //#endregion
3022
2312
  //#region src/utils/semver.d.ts
@@ -3065,4 +2355,4 @@ declare function textToHtml(text: string): string;
3065
2355
  */
3066
2356
 
3067
2357
  //#endregion
3068
- export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, ServerViewMeta, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, isBlurhashValid, isImagePath, semverGt, textToHtml };
2358
+ export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, ServerViewMeta, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, isBlurhashValid, isImagePath, semverGt, textToHtml };