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

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