@livestore/common 0.4.0 → 0.5.0-dev.1

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 (501) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/ClientSessionLeaderThreadProxy.d.ts +1 -1
  3. package/dist/ClientSessionLeaderThreadProxy.d.ts.map +1 -1
  4. package/dist/MaterializationJournal.d.ts +44 -0
  5. package/dist/MaterializationJournal.d.ts.map +1 -0
  6. package/dist/MaterializationJournal.js +112 -0
  7. package/dist/MaterializationJournal.js.map +1 -0
  8. package/dist/StateHead.d.ts +26 -0
  9. package/dist/StateHead.d.ts.map +1 -0
  10. package/dist/StateHead.js +50 -0
  11. package/dist/StateHead.js.map +1 -0
  12. package/dist/WorkerTransportError.d.ts +3 -3
  13. package/dist/WorkerTransportError.d.ts.map +1 -1
  14. package/dist/WorkerTransportError.js +3 -3
  15. package/dist/WorkerTransportError.js.map +1 -1
  16. package/dist/__tests__/fixture.d.ts +8 -8
  17. package/dist/__tests__/fixture.d.ts.map +1 -1
  18. package/dist/__tests__/fixture.js +4 -4
  19. package/dist/__tests__/fixture.js.map +1 -1
  20. package/dist/adapter-types.d.ts +33 -57
  21. package/dist/adapter-types.d.ts.map +1 -1
  22. package/dist/adapter-types.js +24 -41
  23. package/dist/adapter-types.js.map +1 -1
  24. package/dist/bounded-collections.d.ts.map +1 -1
  25. package/dist/bounded-collections.js.map +1 -1
  26. package/dist/debug-info.d.ts +56 -56
  27. package/dist/debug-info.d.ts.map +1 -1
  28. package/dist/debug-info.js +32 -44
  29. package/dist/debug-info.js.map +1 -1
  30. package/dist/defs.d.ts +9 -9
  31. package/dist/defs.js +2 -2
  32. package/dist/devtools/devtools-compatibility.test.js +2 -1
  33. package/dist/devtools/devtools-compatibility.test.js.map +1 -1
  34. package/dist/devtools/devtools-messages-client-session.d.ts +522 -334
  35. package/dist/devtools/devtools-messages-client-session.d.ts.map +1 -1
  36. package/dist/devtools/devtools-messages-client-session.js +80 -78
  37. package/dist/devtools/devtools-messages-client-session.js.map +1 -1
  38. package/dist/devtools/devtools-messages-common.d.ts +27 -27
  39. package/dist/devtools/devtools-messages-common.d.ts.map +1 -1
  40. package/dist/devtools/devtools-messages-common.js +6 -6
  41. package/dist/devtools/devtools-messages-common.js.map +1 -1
  42. package/dist/devtools/devtools-messages-leader.d.ts +410 -348
  43. package/dist/devtools/devtools-messages-leader.d.ts.map +1 -1
  44. package/dist/devtools/devtools-messages-leader.js +105 -93
  45. package/dist/devtools/devtools-messages-leader.js.map +1 -1
  46. package/dist/devtools/devtools-messages.js +3 -3
  47. package/dist/devtools/devtools-sessioninfo.d.ts +18 -19
  48. package/dist/devtools/devtools-sessioninfo.d.ts.map +1 -1
  49. package/dist/devtools/devtools-sessioninfo.js +8 -5
  50. package/dist/devtools/devtools-sessioninfo.js.map +1 -1
  51. package/dist/devtools/mod.d.ts +4 -5
  52. package/dist/devtools/mod.d.ts.map +1 -1
  53. package/dist/devtools/mod.js +12 -8
  54. package/dist/devtools/mod.js.map +1 -1
  55. package/dist/errors.d.ts +45 -69
  56. package/dist/errors.d.ts.map +1 -1
  57. package/dist/errors.js +19 -17
  58. package/dist/errors.js.map +1 -1
  59. package/dist/index.d.ts +4 -1
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +22 -19
  62. package/dist/index.js.map +1 -1
  63. package/dist/leader-thread/LeaderSyncProcessor.d.ts +87 -18
  64. package/dist/leader-thread/LeaderSyncProcessor.d.ts.map +1 -1
  65. package/dist/leader-thread/LeaderSyncProcessor.js +548 -480
  66. package/dist/leader-thread/LeaderSyncProcessor.js.map +1 -1
  67. package/dist/leader-thread/RejectedPushError.d.ts +72 -41
  68. package/dist/leader-thread/RejectedPushError.d.ts.map +1 -1
  69. package/dist/leader-thread/RejectedPushError.js +25 -6
  70. package/dist/leader-thread/RejectedPushError.js.map +1 -1
  71. package/dist/leader-thread/connection.d.ts +1 -0
  72. package/dist/leader-thread/connection.d.ts.map +1 -1
  73. package/dist/leader-thread/connection.js +11 -10
  74. package/dist/leader-thread/connection.js.map +1 -1
  75. package/dist/leader-thread/eventlog.d.ts +15 -5
  76. package/dist/leader-thread/eventlog.d.ts.map +1 -1
  77. package/dist/leader-thread/eventlog.js +19 -19
  78. package/dist/leader-thread/eventlog.js.map +1 -1
  79. package/dist/leader-thread/leader-worker-devtools.d.ts +1 -1
  80. package/dist/leader-thread/leader-worker-devtools.d.ts.map +1 -1
  81. package/dist/leader-thread/leader-worker-devtools.js +36 -20
  82. package/dist/leader-thread/leader-worker-devtools.js.map +1 -1
  83. package/dist/leader-thread/make-leader-thread-layer.d.ts +15 -5
  84. package/dist/leader-thread/make-leader-thread-layer.d.ts.map +1 -1
  85. package/dist/leader-thread/make-leader-thread-layer.js +62 -58
  86. package/dist/leader-thread/make-leader-thread-layer.js.map +1 -1
  87. package/dist/leader-thread/make-leader-thread-layer.test.js +9 -9
  88. package/dist/leader-thread/make-leader-thread-layer.test.js.map +1 -1
  89. package/dist/leader-thread/materialize-event.d.ts +2 -1
  90. package/dist/leader-thread/materialize-event.d.ts.map +1 -1
  91. package/dist/leader-thread/materialize-event.js +12 -8
  92. package/dist/leader-thread/materialize-event.js.map +1 -1
  93. package/dist/leader-thread/mod.js +9 -9
  94. package/dist/leader-thread/recreate-db.d.ts +5 -1
  95. package/dist/leader-thread/recreate-db.d.ts.map +1 -1
  96. package/dist/leader-thread/recreate-db.js +34 -59
  97. package/dist/leader-thread/recreate-db.js.map +1 -1
  98. package/dist/leader-thread/shutdown-channel.d.ts +2 -6
  99. package/dist/leader-thread/shutdown-channel.d.ts.map +1 -1
  100. package/dist/leader-thread/shutdown-channel.js +2 -3
  101. package/dist/leader-thread/shutdown-channel.js.map +1 -1
  102. package/dist/leader-thread/stream-events.d.ts +4 -7
  103. package/dist/leader-thread/stream-events.d.ts.map +1 -1
  104. package/dist/leader-thread/stream-events.js +16 -21
  105. package/dist/leader-thread/stream-events.js.map +1 -1
  106. package/dist/leader-thread/types.d.ts +38 -73
  107. package/dist/leader-thread/types.d.ts.map +1 -1
  108. package/dist/leader-thread/types.js +10 -6
  109. package/dist/leader-thread/types.js.map +1 -1
  110. package/dist/logging.d.ts +5 -30
  111. package/dist/logging.d.ts.map +1 -1
  112. package/dist/logging.js +1 -32
  113. package/dist/logging.js.map +1 -1
  114. package/dist/make-client-session.d.ts +2 -3
  115. package/dist/make-client-session.d.ts.map +1 -1
  116. package/dist/make-client-session.js +5 -5
  117. package/dist/make-client-session.js.map +1 -1
  118. package/dist/materializer-helper.d.ts +0 -1
  119. package/dist/materializer-helper.d.ts.map +1 -1
  120. package/dist/materializer-helper.js +9 -37
  121. package/dist/materializer-helper.js.map +1 -1
  122. package/dist/otel.d.ts +2 -3
  123. package/dist/otel.d.ts.map +1 -1
  124. package/dist/otel.js +2 -7
  125. package/dist/otel.js.map +1 -1
  126. package/dist/rematerialize-from-eventlog.d.ts +3 -1
  127. package/dist/rematerialize-from-eventlog.d.ts.map +1 -1
  128. package/dist/rematerialize-from-eventlog.js +42 -33
  129. package/dist/rematerialize-from-eventlog.js.map +1 -1
  130. package/dist/schema/EventDef/define.d.ts +6 -6
  131. package/dist/schema/EventDef/define.d.ts.map +1 -1
  132. package/dist/schema/EventDef/define.js +5 -5
  133. package/dist/schema/EventDef/define.js.map +1 -1
  134. package/dist/schema/EventDef/define.test.d.ts +2 -0
  135. package/dist/schema/EventDef/define.test.d.ts.map +1 -0
  136. package/dist/schema/EventDef/define.test.js +23 -0
  137. package/dist/schema/EventDef/define.test.js.map +1 -0
  138. package/dist/schema/EventDef/deprecated.d.ts +8 -13
  139. package/dist/schema/EventDef/deprecated.d.ts.map +1 -1
  140. package/dist/schema/EventDef/deprecated.js +12 -13
  141. package/dist/schema/EventDef/deprecated.js.map +1 -1
  142. package/dist/schema/EventDef/deprecated.test.js +3 -3
  143. package/dist/schema/EventDef/deprecated.test.js.map +1 -1
  144. package/dist/schema/EventDef/event-def.d.ts +1 -1
  145. package/dist/schema/EventDef/event-def.d.ts.map +1 -1
  146. package/dist/schema/EventDef/facts.d.ts.map +1 -1
  147. package/dist/schema/EventDef/materializer.d.ts +2 -2
  148. package/dist/schema/EventDef/materializer.d.ts.map +1 -1
  149. package/dist/schema/EventDef/mod.js +5 -5
  150. package/dist/schema/EventSequenceNumber/client.d.ts +12 -17
  151. package/dist/schema/EventSequenceNumber/client.d.ts.map +1 -1
  152. package/dist/schema/EventSequenceNumber/client.js +20 -24
  153. package/dist/schema/EventSequenceNumber/client.js.map +1 -1
  154. package/dist/schema/EventSequenceNumber/global.d.ts +2 -2
  155. package/dist/schema/EventSequenceNumber/global.d.ts.map +1 -1
  156. package/dist/schema/EventSequenceNumber/global.js +1 -1
  157. package/dist/schema/EventSequenceNumber/global.js.map +1 -1
  158. package/dist/schema/EventSequenceNumber/mod.js +2 -2
  159. package/dist/schema/EventSequenceNumber.test.js +6 -6
  160. package/dist/schema/EventSequenceNumber.test.js.map +1 -1
  161. package/dist/schema/LiveStoreEvent/client.d.ts +58 -187
  162. package/dist/schema/LiveStoreEvent/client.d.ts.map +1 -1
  163. package/dist/schema/LiveStoreEvent/client.js +33 -30
  164. package/dist/schema/LiveStoreEvent/client.js.map +1 -1
  165. package/dist/schema/LiveStoreEvent/client.test.js +13 -4
  166. package/dist/schema/LiveStoreEvent/client.test.js.map +1 -1
  167. package/dist/schema/LiveStoreEvent/for-event-def.d.ts +7 -7
  168. package/dist/schema/LiveStoreEvent/for-event-def.d.ts.map +1 -1
  169. package/dist/schema/LiveStoreEvent/global.d.ts +6 -6
  170. package/dist/schema/LiveStoreEvent/global.d.ts.map +1 -1
  171. package/dist/schema/LiveStoreEvent/global.js +2 -2
  172. package/dist/schema/LiveStoreEvent/global.js.map +1 -1
  173. package/dist/schema/LiveStoreEvent/input.d.ts +6 -6
  174. package/dist/schema/LiveStoreEvent/input.d.ts.map +1 -1
  175. package/dist/schema/LiveStoreEvent/input.js +3 -3
  176. package/dist/schema/LiveStoreEvent/input.js.map +1 -1
  177. package/dist/schema/LiveStoreEvent/mod.js +4 -4
  178. package/dist/schema/events.js +1 -1
  179. package/dist/schema/mod.d.ts +1 -0
  180. package/dist/schema/mod.d.ts.map +1 -1
  181. package/dist/schema/mod.js +11 -10
  182. package/dist/schema/mod.js.map +1 -1
  183. package/dist/schema/schema.d.ts +1 -1
  184. package/dist/schema/schema.d.ts.map +1 -1
  185. package/dist/schema/schema.js +6 -5
  186. package/dist/schema/schema.js.map +1 -1
  187. package/dist/schema/state/mod.js +2 -2
  188. package/dist/schema/state/sqlite/client-document-def.d.ts +13 -18
  189. package/dist/schema/state/sqlite/client-document-def.d.ts.map +1 -1
  190. package/dist/schema/state/sqlite/client-document-def.js +30 -27
  191. package/dist/schema/state/sqlite/client-document-def.js.map +1 -1
  192. package/dist/schema/state/sqlite/client-document-def.test.js +53 -18
  193. package/dist/schema/state/sqlite/client-document-def.test.js.map +1 -1
  194. package/dist/schema/state/sqlite/column-annotations.d.ts +13 -13
  195. package/dist/schema/state/sqlite/column-annotations.d.ts.map +1 -1
  196. package/dist/schema/state/sqlite/column-annotations.js +13 -15
  197. package/dist/schema/state/sqlite/column-annotations.js.map +1 -1
  198. package/dist/schema/state/sqlite/column-annotations.test.js +19 -43
  199. package/dist/schema/state/sqlite/column-annotations.test.js.map +1 -1
  200. package/dist/schema/state/sqlite/column-def.d.ts +1 -1
  201. package/dist/schema/state/sqlite/column-def.d.ts.map +1 -1
  202. package/dist/schema/state/sqlite/column-def.js +73 -33
  203. package/dist/schema/state/sqlite/column-def.js.map +1 -1
  204. package/dist/schema/state/sqlite/column-def.test.js +176 -75
  205. package/dist/schema/state/sqlite/column-def.test.js.map +1 -1
  206. package/dist/schema/state/sqlite/column-spec.d.ts.map +1 -1
  207. package/dist/schema/state/sqlite/column-spec.js +1 -1
  208. package/dist/schema/state/sqlite/column-spec.js.map +1 -1
  209. package/dist/schema/state/sqlite/column-spec.test.js +4 -4
  210. package/dist/schema/state/sqlite/column-spec.test.js.map +1 -1
  211. package/dist/schema/state/sqlite/db-schema/ast/fingerprint-digest.d.ts +3 -0
  212. package/dist/schema/state/sqlite/db-schema/ast/fingerprint-digest.d.ts.map +1 -0
  213. package/dist/schema/state/sqlite/db-schema/ast/fingerprint-digest.js +5 -0
  214. package/dist/schema/state/sqlite/db-schema/ast/fingerprint-digest.js.map +1 -0
  215. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.d.ts +5 -0
  216. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.d.ts.map +1 -0
  217. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js +183 -0
  218. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js.map +1 -0
  219. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.d.ts +2 -0
  220. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.d.ts.map +1 -0
  221. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.js +142 -0
  222. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.js.map +1 -0
  223. package/dist/schema/state/sqlite/db-schema/ast/sqlite.d.ts +3 -8
  224. package/dist/schema/state/sqlite/db-schema/ast/sqlite.d.ts.map +1 -1
  225. package/dist/schema/state/sqlite/db-schema/ast/sqlite.js +1 -73
  226. package/dist/schema/state/sqlite/db-schema/ast/sqlite.js.map +1 -1
  227. package/dist/schema/state/sqlite/db-schema/ast/validate.d.ts.map +1 -1
  228. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.d.ts +9 -9
  229. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.d.ts.map +1 -1
  230. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.js +9 -13
  231. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.js.map +1 -1
  232. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.test.js +28 -17
  233. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.test.js.map +1 -1
  234. package/dist/schema/state/sqlite/db-schema/dsl/mod.d.ts +13 -11
  235. package/dist/schema/state/sqlite/db-schema/dsl/mod.d.ts.map +1 -1
  236. package/dist/schema/state/sqlite/db-schema/dsl/mod.js +6 -4
  237. package/dist/schema/state/sqlite/db-schema/dsl/mod.js.map +1 -1
  238. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts +3 -0
  239. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts.map +1 -0
  240. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js +6 -0
  241. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js.map +1 -0
  242. package/dist/schema/state/sqlite/db-schema/mod.js +2 -2
  243. package/dist/schema/state/sqlite/mod.d.ts +1 -3
  244. package/dist/schema/state/sqlite/mod.d.ts.map +1 -1
  245. package/dist/schema/state/sqlite/mod.js +11 -10
  246. package/dist/schema/state/sqlite/mod.js.map +1 -1
  247. package/dist/schema/state/sqlite/persistence.d.ts +11 -0
  248. package/dist/schema/state/sqlite/persistence.d.ts.map +1 -0
  249. package/dist/schema/state/sqlite/persistence.js +10 -0
  250. package/dist/schema/state/sqlite/persistence.js.map +1 -0
  251. package/dist/schema/state/sqlite/query-builder/api.d.ts +7 -7
  252. package/dist/schema/state/sqlite/query-builder/api.d.ts.map +1 -1
  253. package/dist/schema/state/sqlite/query-builder/astToSql.d.ts.map +1 -1
  254. package/dist/schema/state/sqlite/query-builder/astToSql.js +22 -23
  255. package/dist/schema/state/sqlite/query-builder/astToSql.js.map +1 -1
  256. package/dist/schema/state/sqlite/query-builder/impl.d.ts +1 -1
  257. package/dist/schema/state/sqlite/query-builder/impl.d.ts.map +1 -1
  258. package/dist/schema/state/sqlite/query-builder/impl.js +18 -16
  259. package/dist/schema/state/sqlite/query-builder/impl.js.map +1 -1
  260. package/dist/schema/state/sqlite/query-builder/impl.test.js +364 -598
  261. package/dist/schema/state/sqlite/query-builder/impl.test.js.map +1 -1
  262. package/dist/schema/state/sqlite/query-builder/mod.js +2 -2
  263. package/dist/schema/state/sqlite/schema-helpers.d.ts.map +1 -1
  264. package/dist/schema/state/sqlite/schema-helpers.js +2 -2
  265. package/dist/schema/state/sqlite/schema-helpers.js.map +1 -1
  266. package/dist/schema/state/sqlite/schema-helpers.test.js +2 -2
  267. package/dist/schema/state/sqlite/system-tables/eventlog-tables.d.ts +102 -134
  268. package/dist/schema/state/sqlite/system-tables/eventlog-tables.d.ts.map +1 -1
  269. package/dist/schema/state/sqlite/system-tables/eventlog-tables.js +5 -5
  270. package/dist/schema/state/sqlite/system-tables/eventlog-tables.js.map +1 -1
  271. package/dist/schema/state/sqlite/system-tables/mod.js +2 -2
  272. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts +380 -115
  273. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts.map +1 -1
  274. package/dist/schema/state/sqlite/system-tables/state-tables.js +47 -6
  275. package/dist/schema/state/sqlite/system-tables/state-tables.js.map +1 -1
  276. package/dist/schema/state/sqlite/table-def.d.ts +17 -20
  277. package/dist/schema/state/sqlite/table-def.d.ts.map +1 -1
  278. package/dist/schema/state/sqlite/table-def.js +72 -6
  279. package/dist/schema/state/sqlite/table-def.js.map +1 -1
  280. package/dist/schema/state/sqlite/table-def.test.js +207 -37
  281. package/dist/schema/state/sqlite/table-def.test.js.map +1 -1
  282. package/dist/schema/unknown-events.d.ts.map +1 -1
  283. package/dist/schema/unknown-events.js +3 -2
  284. package/dist/schema/unknown-events.js.map +1 -1
  285. package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js +28 -6
  286. package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js.map +1 -1
  287. package/dist/schema-management/common.d.ts.map +1 -1
  288. package/dist/schema-management/common.js +2 -2
  289. package/dist/schema-management/migrations.d.ts +4 -4
  290. package/dist/schema-management/migrations.d.ts.map +1 -1
  291. package/dist/schema-management/migrations.js +9 -9
  292. package/dist/schema-management/migrations.js.map +1 -1
  293. package/dist/schema-management/validate-schema.d.ts.map +1 -1
  294. package/dist/schema-management/validate-schema.js +1 -1
  295. package/dist/session-id-symbol.d.ts +29 -0
  296. package/dist/session-id-symbol.d.ts.map +1 -0
  297. package/dist/session-id-symbol.js +44 -0
  298. package/dist/session-id-symbol.js.map +1 -0
  299. package/dist/sql-queries/index.js +3 -3
  300. package/dist/sql-queries/sql-queries.d.ts.map +1 -1
  301. package/dist/sql-queries/sql-queries.js +11 -13
  302. package/dist/sql-queries/sql-queries.js.map +1 -1
  303. package/dist/sql-queries/sql-query-builder.d.ts.map +1 -1
  304. package/dist/sql-queries/sql-query-builder.js +1 -1
  305. package/dist/sql-queries/types.d.ts +6 -7
  306. package/dist/sql-queries/types.d.ts.map +1 -1
  307. package/dist/sql-queries/types.js.map +1 -1
  308. package/dist/sqlite-db-helper.d.ts +23 -3
  309. package/dist/sqlite-db-helper.d.ts.map +1 -1
  310. package/dist/sqlite-db-helper.js +39 -4
  311. package/dist/sqlite-db-helper.js.map +1 -1
  312. package/dist/sqlite-types.d.ts +3 -6
  313. package/dist/sqlite-types.d.ts.map +1 -1
  314. package/dist/sqlite-types.js +3 -3
  315. package/dist/sqlite-types.js.map +1 -1
  316. package/dist/sync/ClientSessionSyncProcessor.d.ts +41 -19
  317. package/dist/sync/ClientSessionSyncProcessor.d.ts.map +1 -1
  318. package/dist/sync/ClientSessionSyncProcessor.js +200 -70
  319. package/dist/sync/ClientSessionSyncProcessor.js.map +1 -1
  320. package/dist/sync/errors.d.ts +12 -18
  321. package/dist/sync/errors.d.ts.map +1 -1
  322. package/dist/sync/errors.js +3 -3
  323. package/dist/sync/errors.js.map +1 -1
  324. package/dist/sync/index.js +6 -6
  325. package/dist/sync/mock-sync-backend.d.ts +2 -3
  326. package/dist/sync/mock-sync-backend.d.ts.map +1 -1
  327. package/dist/sync/mock-sync-backend.js +58 -37
  328. package/dist/sync/mock-sync-backend.js.map +1 -1
  329. package/dist/sync/mock-sync-backend.test.d.ts +2 -0
  330. package/dist/sync/mock-sync-backend.test.d.ts.map +1 -0
  331. package/dist/sync/mock-sync-backend.test.js +49 -0
  332. package/dist/sync/mock-sync-backend.test.js.map +1 -0
  333. package/dist/sync/next/compact-events.d.ts.map +1 -1
  334. package/dist/sync/next/compact-events.js +3 -3
  335. package/dist/sync/next/facts.d.ts.map +1 -1
  336. package/dist/sync/next/facts.js +1 -1
  337. package/dist/sync/next/history-dag-common.d.ts +5 -1
  338. package/dist/sync/next/history-dag-common.d.ts.map +1 -1
  339. package/dist/sync/next/history-dag-common.js +53 -32
  340. package/dist/sync/next/history-dag-common.js.map +1 -1
  341. package/dist/sync/next/history-dag.d.ts.map +1 -1
  342. package/dist/sync/next/history-dag.js +5 -4
  343. package/dist/sync/next/history-dag.js.map +1 -1
  344. package/dist/sync/next/mod.js +5 -5
  345. package/dist/sync/next/rebase-events.d.ts.map +1 -1
  346. package/dist/sync/next/rebase-events.js +2 -2
  347. package/dist/sync/next/test/compact-events.calculator.test.js +6 -6
  348. package/dist/sync/next/test/compact-events.test.js +4 -4
  349. package/dist/sync/next/test/event-fixtures.d.ts +8 -8
  350. package/dist/sync/next/test/event-fixtures.d.ts.map +1 -1
  351. package/dist/sync/next/test/event-fixtures.js +6 -6
  352. package/dist/sync/next/test/event-fixtures.js.map +1 -1
  353. package/dist/sync/next/test/history-dag-common.test.d.ts +2 -0
  354. package/dist/sync/next/test/history-dag-common.test.d.ts.map +1 -0
  355. package/dist/sync/next/test/history-dag-common.test.js +73 -0
  356. package/dist/sync/next/test/history-dag-common.test.js.map +1 -0
  357. package/dist/sync/next/test/mod.js +1 -1
  358. package/dist/sync/sync-backend-kv.d.ts.map +1 -1
  359. package/dist/sync/sync-backend-kv.js +5 -3
  360. package/dist/sync/sync-backend-kv.js.map +1 -1
  361. package/dist/sync/sync-backend.d.ts +15 -15
  362. package/dist/sync/sync-backend.d.ts.map +1 -1
  363. package/dist/sync/sync-backend.js +10 -6
  364. package/dist/sync/sync-backend.js.map +1 -1
  365. package/dist/sync/sync.d.ts +1 -1
  366. package/dist/sync/sync.d.ts.map +1 -1
  367. package/dist/sync/sync.js +2 -2
  368. package/dist/sync/syncstate.d.ts +100 -176
  369. package/dist/sync/syncstate.d.ts.map +1 -1
  370. package/dist/sync/syncstate.js +36 -39
  371. package/dist/sync/syncstate.js.map +1 -1
  372. package/dist/sync/syncstate.test.js +103 -64
  373. package/dist/sync/syncstate.test.js.map +1 -1
  374. package/dist/sync/transport-chunking.d.ts +15 -16
  375. package/dist/sync/transport-chunking.d.ts.map +1 -1
  376. package/dist/sync/transport-chunking.js +23 -32
  377. package/dist/sync/transport-chunking.js.map +1 -1
  378. package/dist/sync/validate-push-payload.d.ts.map +1 -1
  379. package/dist/sync/validate-push-payload.js +2 -2
  380. package/dist/testing/event-factory.d.ts.map +1 -1
  381. package/dist/testing/event-factory.js +2 -2
  382. package/dist/testing/event-factory.js.map +1 -1
  383. package/dist/testing/mod.js +1 -1
  384. package/dist/util.d.ts +11 -4
  385. package/dist/util.d.ts.map +1 -1
  386. package/dist/util.js +20 -2
  387. package/dist/util.js.map +1 -1
  388. package/dist/version.d.ts.map +1 -1
  389. package/dist/version.js.map +1 -1
  390. package/package.json +40 -57
  391. package/src/ClientSessionLeaderThreadProxy.ts +1 -1
  392. package/src/MaterializationJournal.ts +184 -0
  393. package/src/StateHead.ts +80 -0
  394. package/src/WorkerTransportError.ts +4 -4
  395. package/src/__tests__/fixture.ts +3 -3
  396. package/src/adapter-types.ts +28 -61
  397. package/src/debug-info.ts +53 -70
  398. package/src/defs.ts +2 -2
  399. package/src/devtools/devtools-compatibility.test.ts +1 -0
  400. package/src/devtools/devtools-messages-client-session.ts +56 -65
  401. package/src/devtools/devtools-messages-common.ts +12 -11
  402. package/src/devtools/devtools-messages-leader.ts +71 -69
  403. package/src/devtools/devtools-sessioninfo.ts +13 -11
  404. package/src/devtools/mod.ts +4 -5
  405. package/src/errors.ts +46 -34
  406. package/src/index.ts +8 -1
  407. package/src/leader-thread/LeaderSyncProcessor.ts +777 -650
  408. package/src/leader-thread/RejectedPushError.ts +40 -27
  409. package/src/leader-thread/connection.ts +12 -8
  410. package/src/leader-thread/eventlog.ts +20 -12
  411. package/src/leader-thread/leader-worker-devtools.ts +38 -20
  412. package/src/leader-thread/make-leader-thread-layer.test.ts +7 -7
  413. package/src/leader-thread/make-leader-thread-layer.ts +100 -71
  414. package/src/leader-thread/materialize-event.ts +13 -8
  415. package/src/leader-thread/recreate-db.ts +41 -75
  416. package/src/leader-thread/shutdown-channel.ts +3 -14
  417. package/src/leader-thread/stream-events.ts +102 -101
  418. package/src/leader-thread/types.ts +29 -62
  419. package/src/logging.ts +5 -52
  420. package/src/make-client-session.ts +6 -6
  421. package/src/materializer-helper.ts +7 -36
  422. package/src/otel.ts +5 -14
  423. package/src/rematerialize-from-eventlog.ts +116 -98
  424. package/src/schema/EventDef/define.test.ts +28 -0
  425. package/src/schema/EventDef/define.ts +20 -19
  426. package/src/schema/EventDef/deprecated.test.ts +1 -8
  427. package/src/schema/EventDef/deprecated.ts +17 -20
  428. package/src/schema/EventDef/event-def.ts +2 -4
  429. package/src/schema/EventSequenceNumber/client.ts +20 -24
  430. package/src/schema/EventSequenceNumber/global.ts +1 -1
  431. package/src/schema/EventSequenceNumber.test.ts +5 -5
  432. package/src/schema/LiveStoreEvent/client.test.ts +17 -4
  433. package/src/schema/LiveStoreEvent/client.ts +36 -35
  434. package/src/schema/LiveStoreEvent/for-event-def.ts +7 -7
  435. package/src/schema/LiveStoreEvent/global.ts +1 -1
  436. package/src/schema/LiveStoreEvent/input.ts +6 -6
  437. package/src/schema/mod.ts +1 -0
  438. package/src/schema/schema.ts +4 -3
  439. package/src/schema/state/sqlite/client-document-def.test.ts +55 -20
  440. package/src/schema/state/sqlite/client-document-def.ts +95 -80
  441. package/src/schema/state/sqlite/column-annotations.test.ts +26 -45
  442. package/src/schema/state/sqlite/column-annotations.ts +26 -30
  443. package/src/schema/state/sqlite/column-def.test.ts +213 -77
  444. package/src/schema/state/sqlite/column-def.ts +87 -37
  445. package/src/schema/state/sqlite/column-spec.test.ts +2 -2
  446. package/src/schema/state/sqlite/column-spec.ts +3 -2
  447. package/src/schema/state/sqlite/db-schema/ast/fingerprint-digest.ts +6 -0
  448. package/src/schema/state/sqlite/db-schema/ast/fingerprint.test.ts +209 -0
  449. package/src/schema/state/sqlite/db-schema/ast/fingerprint.ts +225 -0
  450. package/src/schema/state/sqlite/db-schema/ast/sqlite.ts +2 -81
  451. package/src/schema/state/sqlite/db-schema/dsl/__snapshots__/field-defs.test.ts.snap +123 -63
  452. package/src/schema/state/sqlite/db-schema/dsl/field-defs.test.ts +35 -16
  453. package/src/schema/state/sqlite/db-schema/dsl/field-defs.ts +26 -31
  454. package/src/schema/state/sqlite/db-schema/dsl/mod.ts +35 -21
  455. package/src/schema/state/sqlite/db-schema/has-json-string-encoding.ts +9 -0
  456. package/src/schema/state/sqlite/mod.ts +4 -5
  457. package/src/schema/state/sqlite/persistence.ts +11 -0
  458. package/src/schema/state/sqlite/query-builder/api.ts +9 -9
  459. package/src/schema/state/sqlite/query-builder/astToSql.ts +24 -26
  460. package/src/schema/state/sqlite/query-builder/impl.test.ts +433 -669
  461. package/src/schema/state/sqlite/query-builder/impl.ts +19 -15
  462. package/src/schema/state/sqlite/schema-helpers.ts +1 -1
  463. package/src/schema/state/sqlite/system-tables/eventlog-tables.ts +2 -2
  464. package/src/schema/state/sqlite/system-tables/state-tables.ts +54 -3
  465. package/src/schema/state/sqlite/table-def.test.ts +270 -66
  466. package/src/schema/state/sqlite/table-def.ts +112 -45
  467. package/src/schema/unknown-events.ts +3 -2
  468. package/src/schema-management/__tests__/migrations-autoincrement-quoting.test.ts +35 -4
  469. package/src/schema-management/migrations.ts +7 -6
  470. package/src/session-id-symbol.ts +59 -0
  471. package/src/sql-queries/sql-queries.ts +9 -13
  472. package/src/sql-queries/types.ts +6 -7
  473. package/src/sqlite-db-helper.ts +64 -2
  474. package/src/sqlite-types.ts +5 -8
  475. package/src/sync/ClientSessionSyncProcessor.ts +303 -119
  476. package/src/sync/errors.ts +14 -12
  477. package/src/sync/mock-sync-backend.test.ts +78 -0
  478. package/src/sync/mock-sync-backend.ts +93 -47
  479. package/src/sync/next/history-dag-common.ts +60 -34
  480. package/src/sync/next/history-dag.ts +4 -1
  481. package/src/sync/next/test/compact-events.calculator.test.ts +2 -2
  482. package/src/sync/next/test/event-fixtures.ts +1 -1
  483. package/src/sync/next/test/history-dag-common.test.ts +87 -0
  484. package/src/sync/sync-backend-kv.ts +4 -2
  485. package/src/sync/sync-backend.ts +15 -15
  486. package/src/sync/sync.ts +1 -1
  487. package/src/sync/syncstate.test.ts +191 -140
  488. package/src/sync/syncstate.ts +63 -53
  489. package/src/sync/transport-chunking.ts +34 -39
  490. package/src/util.ts +19 -9
  491. package/src/version.ts +1 -2
  492. package/dist/schema/state/sqlite/db-schema/hash.d.ts +0 -2
  493. package/dist/schema/state/sqlite/db-schema/hash.d.ts.map +0 -1
  494. package/dist/schema/state/sqlite/db-schema/hash.js +0 -15
  495. package/dist/schema/state/sqlite/db-schema/hash.js.map +0 -1
  496. package/dist/sql-queries/misc.d.ts +0 -2
  497. package/dist/sql-queries/misc.d.ts.map +0 -1
  498. package/dist/sql-queries/misc.js +0 -2
  499. package/dist/sql-queries/misc.js.map +0 -1
  500. package/src/schema/state/sqlite/db-schema/hash.ts +0 -13
  501. package/src/sql-queries/misc.ts +0 -2
@@ -1,12 +1,15 @@
1
1
  import { omitUndefineds, shouldNeverHappen } from '@livestore/utils'
2
- import type { HttpClient, Scope } from '@livestore/utils/effect'
3
2
  import {
3
+ type HttpClient,
4
+ type Scope,
4
5
  Deferred,
5
6
  Effect,
6
7
  KeyValueStore,
8
+ Latch,
7
9
  Layer,
8
- PlatformError,
10
+ Option,
9
11
  Queue,
12
+ ReadonlyArray,
10
13
  Schema,
11
14
  Stream,
12
15
  Subscribable,
@@ -24,14 +27,16 @@ import type { MigrationsReport } from '../defs.ts'
24
27
  import type * as Devtools from '../devtools/mod.ts'
25
28
  import type { LiveStoreSchema } from '../schema/mod.ts'
26
29
  import { EventSequenceNumber, LiveStoreEvent, SystemTables } from '../schema/mod.ts'
30
+ import type * as StateHead from '../StateHead.ts'
27
31
  import type { SyncBackend, SyncOptions } from '../sync/sync.ts'
28
32
  import { SyncState } from '../sync/syncstate.ts'
29
33
  import { sql } from '../util.ts'
34
+ import { configureConnection } from './connection.ts'
30
35
  import * as Eventlog from './eventlog.ts'
31
- import { makeLeaderSyncProcessor } from './LeaderSyncProcessor.ts'
32
36
  import { bootDevtools } from './leader-worker-devtools.ts'
37
+ import * as LeaderSyncProcessor from './LeaderSyncProcessor.ts'
33
38
  import { makeMaterializeEvent } from './materialize-event.ts'
34
- import { recreateDb } from './recreate-db.ts'
39
+ import { hasCompletedState, recreateDb } from './recreate-db.ts'
35
40
  import type { ShutdownChannel } from './shutdown-channel.ts'
36
41
  import type {
37
42
  DevtoolsContext,
@@ -45,8 +50,8 @@ import { LeaderThreadCtx } from './types.ts'
45
50
 
46
51
  export interface MakeLeaderThreadLayerParams {
47
52
  storeId: string
48
- syncPayloadSchema: Schema.Schema<any> | undefined
49
- syncPayloadEncoded: Schema.JsonValue | undefined
53
+ syncPayloadSchema: Schema.Decoder<Schema.Json> | undefined
54
+ syncPayloadEncoded: Schema.Json | undefined
50
55
  clientId: string
51
56
  schema: LiveStoreSchema
52
57
  makeSqliteDb: MakeSqliteDb
@@ -60,11 +65,17 @@ export interface MakeLeaderThreadLayerParams {
60
65
  params?: {
61
66
  localPushBatchSize?: number
62
67
  backendPushBatchSize?: number
68
+ stateRebuildBatchSize?: number
63
69
  }
64
70
  testing?: {
65
71
  syncProcessor?: {
66
72
  delays?: {
67
73
  localPushProcessing?: Effect.Effect<void>
74
+ backendPullReconnect?: (fallbackMs: number) => number
75
+ }
76
+ hooks?: {
77
+ localPushAdmitted?: (events: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta>) => Effect.Effect<void>
78
+ backendPullReconnectWait?: (state: { isConnected: boolean; fallbackMs: number }) => Effect.Effect<void>
68
79
  }
69
80
  }
70
81
  }
@@ -74,7 +85,7 @@ export const makeLeaderThreadLayer = ({
74
85
  schema,
75
86
  storeId,
76
87
  clientId,
77
- syncPayloadSchema = Schema.JsonValue,
88
+ syncPayloadSchema = Schema.Json,
78
89
  syncPayloadEncoded,
79
90
  makeSqliteDb,
80
91
  syncOptions,
@@ -85,12 +96,16 @@ export const makeLeaderThreadLayer = ({
85
96
  bootWarning,
86
97
  params,
87
98
  testing,
88
- }: MakeLeaderThreadLayerParams): Layer.Layer<LeaderThreadCtx, UnknownError, Scope.Scope | HttpClient.HttpClient> =>
99
+ }: MakeLeaderThreadLayerParams): Layer.Layer<
100
+ LeaderThreadCtx,
101
+ UnknownError,
102
+ Scope.Scope | HttpClient.HttpClient | StateHead.StateHead
103
+ > =>
89
104
  Effect.gen(function* () {
90
105
  const syncPayloadDecoded =
91
- syncPayloadEncoded === undefined ? undefined : yield* Schema.decodeUnknown(syncPayloadSchema)(syncPayloadEncoded)
106
+ syncPayloadEncoded === undefined ? undefined : yield* Schema.decodeEffect(syncPayloadSchema)(syncPayloadEncoded)
92
107
 
93
- const bootStatusQueue = yield* Queue.unbounded<BootStatus>().pipe(Effect.acquireRelease(Queue.shutdown))
108
+ const bootStatusQueue = yield* Effect.acquireRelease(Queue.unbounded<BootStatus>(), Queue.shutdown)
94
109
 
95
110
  // Emit boot warning if present (e.g., OPFS unavailable in private browsing)
96
111
  if (bootWarning !== undefined) {
@@ -99,8 +114,20 @@ export const makeLeaderThreadLayer = ({
99
114
 
100
115
  const dbEventlogMissing = !hasEventlogTables(dbEventlog)
101
116
 
102
- // Either happens on initial boot or if schema changes
103
- const dbStateMissing = !hasStateTables(dbState)
117
+ const stateNeedsRebuild = !hasCompletedState(dbState)
118
+
119
+ if (stateNeedsRebuild === true) {
120
+ // Import also clears hook-created objects while preserving the open connection.
121
+ yield* Effect.acquireUseRelease(
122
+ makeSqliteDb({ _tag: 'in-memory' }),
123
+ (emptyDb) =>
124
+ configureConnection(emptyDb, { foreignKeys: false }).pipe(
125
+ Effect.andThen(Effect.sync(() => dbState.import(emptyDb))),
126
+ UnknownError.mapToUnknownError,
127
+ ),
128
+ (emptyDb) => Effect.sync(() => emptyDb.close()),
129
+ )
130
+ }
104
131
 
105
132
  yield* Eventlog.initEventlogDb(dbEventlog)
106
133
 
@@ -114,29 +141,30 @@ export const makeLeaderThreadLayer = ({
114
141
  KeyValueStore.makeStringOnly({
115
142
  get: (_key) =>
116
143
  Effect.sync(() => Eventlog.getBackendIdFromDb(dbEventlog)).pipe(
117
- Effect.catchAllDefect((cause) =>
118
- PlatformError.BadArgument.make({
119
- method: 'getBackendIdFromDb',
120
- description: 'Failed to get backendId',
121
- module: 'KeyValueStore',
122
- cause,
123
- }),
144
+ Effect.map(Option.getOrUndefined),
145
+ Effect.catchDefect(
146
+ (cause) =>
147
+ new KeyValueStore.KeyValueStoreError({
148
+ method: 'getBackendIdFromDb',
149
+ message: 'Failed to get backendId',
150
+ cause,
151
+ }),
124
152
  ),
125
153
  ),
126
154
  set: (_key, value) =>
127
155
  Effect.sync(() => Eventlog.updateBackendId(dbEventlog, value)).pipe(
128
- Effect.catchAllDefect((cause) =>
129
- PlatformError.BadArgument.make({
130
- method: 'updateBackendId',
131
- module: 'KeyValueStore',
132
- description: 'Failed to update backendId',
133
- cause,
134
- }),
156
+ Effect.catchDefect(
157
+ (cause) =>
158
+ new KeyValueStore.KeyValueStoreError({
159
+ method: 'updateBackendId',
160
+ message: 'Failed to update backendId',
161
+ cause,
162
+ }),
135
163
  ),
136
164
  ),
137
- clear: Effect.dieMessage(`Not implemented. Should never be used.`),
138
- remove: () => Effect.dieMessage(`Not implemented. Should never be used.`),
139
- size: Effect.dieMessage(`Not implemented. Should never be used.`),
165
+ clear: Effect.die(new Error(`Not implemented. Should never be used.`)),
166
+ remove: () => Effect.die(new Error(`Not implemented. Should never be used.`)),
167
+ size: Effect.die(new Error(`Not implemented. Should never be used.`)),
140
168
  }),
141
169
  ),
142
170
  ),
@@ -157,13 +185,39 @@ export const makeLeaderThreadLayer = ({
157
185
  // Recreate state database if needed BEFORE creating sync processor
158
186
  // This ensures all system tables exist before any queries are made
159
187
  const { migrationsReport } =
160
- dbStateMissing === true
161
- ? yield* recreateDb({ dbState, dbEventlog, schema, bootStatusQueue, materializeEvent })
188
+ stateNeedsRebuild === true
189
+ ? yield* recreateDb({
190
+ dbState,
191
+ dbEventlog,
192
+ schema,
193
+ bootStatusQueue,
194
+ materializeEvent,
195
+ ...omitUndefineds({ stateRebuildBatchSize: params?.stateRebuildBatchSize }),
196
+ })
162
197
  : { migrationsReport: { migrations: [] } }
163
198
 
164
- const syncProcessor = yield* makeLeaderSyncProcessor({
199
+ const devtoolsContext =
200
+ devtoolsOptions.enabled === true
201
+ ? {
202
+ enabled: true as const,
203
+ syncBackendLatch: yield* Latch.make(true),
204
+ syncBackendLatchState: yield* SubscriptionRef.make<{ latchClosed: boolean }>({ latchClosed: false }),
205
+ }
206
+ : { enabled: false as const }
207
+
208
+ const span = yield* Effect.currentSpan.pipe(Effect.option, Effect.map(Option.getOrUndefined))
209
+
210
+ const syncProcessor = yield* LeaderSyncProcessor.make({
165
211
  schema,
166
- dbState,
212
+ runtime: {
213
+ dbState,
214
+ dbEventlog,
215
+ materializeEvent,
216
+ syncBackend,
217
+ shutdownChannel,
218
+ devtoolsLatch: devtoolsContext.enabled === true ? devtoolsContext.syncBackendLatch : undefined,
219
+ span,
220
+ },
167
221
  initialSyncState: getInitialSyncState({ dbEventlog, dbState, dbEventlogMissing }),
168
222
  initialBlockingSyncContext,
169
223
  onError: syncOptions?.onSyncError ?? 'ignore',
@@ -176,23 +230,15 @@ export const makeLeaderThreadLayer = ({
176
230
  }),
177
231
  },
178
232
  testing: {
179
- ...omitUndefineds({ delays: testing?.syncProcessor?.delays }),
233
+ ...omitUndefineds({ delays: testing?.syncProcessor?.delays, hooks: testing?.syncProcessor?.hooks }),
180
234
  },
181
235
  })
182
236
 
183
- const extraIncomingMessagesQueue = yield* Queue.unbounded<Devtools.Leader.MessageToApp>().pipe(
184
- Effect.acquireRelease(Queue.shutdown),
237
+ const extraIncomingMessagesQueue = yield* Effect.acquireRelease(
238
+ Queue.unbounded<Devtools.Leader.MessageToApp>(),
239
+ Queue.shutdown,
185
240
  )
186
241
 
187
- const devtoolsContext =
188
- devtoolsOptions.enabled === true
189
- ? {
190
- enabled: true as const,
191
- syncBackendLatch: yield* Effect.makeLatch(true),
192
- syncBackendLatchState: yield* SubscriptionRef.make<{ latchClosed: boolean }>({ latchClosed: false }),
193
- }
194
- : { enabled: false as const }
195
-
196
242
  const networkStatus = yield* makeNetworkStatusSubscribable({ syncBackend, devtoolsContext })
197
243
 
198
244
  const ctx = {
@@ -213,13 +259,13 @@ export const makeLeaderThreadLayer = ({
213
259
  devtools: devtoolsContext,
214
260
  networkStatus,
215
261
  // State will be set during `bootLeaderThread`
216
- initialState: {} as any as LeaderThreadCtx['Type']['initialState'],
217
- } satisfies typeof LeaderThreadCtx.Service
262
+ initialState: {} as any as LeaderThreadCtx['Service']['initialState'],
263
+ } satisfies LeaderThreadCtx['Service']
218
264
 
219
265
  // @ts-expect-error For debugging purposes
220
266
  globalThis.__leaderThreadCtx = ctx
221
267
 
222
- const layer = Layer.succeed(LeaderThreadCtx, ctx)
268
+ const layer = Layer.succeed(LeaderThreadCtx, LeaderThreadCtx.of(ctx))
223
269
 
224
270
  ctx.initialState = yield* bootLeaderThread({
225
271
  migrationsReport,
@@ -233,29 +279,12 @@ export const makeLeaderThreadLayer = ({
233
279
  Effect.withSpanScoped('@livestore/common:leader-thread'),
234
280
  UnknownError.mapToUnknownError,
235
281
  Effect.tapCauseLogPretty,
236
- Layer.unwrapScoped,
282
+ Layer.unwrap,
237
283
  )
238
284
 
239
285
  const hasEventlogTables = (db: SqliteDb) => {
240
286
  const tableNames = new Set(db.select<{ name: string }>(sql`select name from sqlite_master`).map((_) => _.name))
241
- const eventlogTables = new Set(SystemTables.eventlogSystemTables.map((_) => _.sqliteDef.name))
242
- return isSubsetOf(eventlogTables, tableNames)
243
- }
244
-
245
- const hasStateTables = (db: SqliteDb) => {
246
- const tableNames = new Set(db.select<{ name: string }>(sql`select name from sqlite_master`).map((_) => _.name))
247
- const stateTables = new Set(SystemTables.stateSystemTables.map((_) => _.sqliteDef.name))
248
- return isSubsetOf(stateTables, tableNames)
249
- }
250
-
251
- const isSubsetOf = (a: Set<string>, b: Set<string>): boolean => {
252
- for (const item of a) {
253
- if (b.has(item) === false) {
254
- return false
255
- }
256
- }
257
-
258
- return true
287
+ return ReadonlyArray.every(SystemTables.eventlogSystemTables, (_) => tableNames.has(_.sqliteDef.name))
259
288
  }
260
289
 
261
290
  const getInitialSyncState = ({
@@ -361,7 +390,7 @@ const bootLeaderThread = ({
361
390
  initialBlockingSyncContext: InitialBlockingSyncContext
362
391
  devtoolsOptions: DevtoolsOptions
363
392
  }): Effect.Effect<
364
- LeaderThreadCtx['Type']['initialState'],
393
+ LeaderThreadCtx['Service']['initialState'],
365
394
  UnknownError | MaterializerHashMismatchError,
366
395
  LeaderThreadCtx | Scope.Scope | HttpClient.HttpClient
367
396
  > =>
@@ -378,7 +407,7 @@ const bootLeaderThread = ({
378
407
  progress: { done: 0, total: -1 },
379
408
  })
380
409
 
381
- yield* initialBlockingSyncContext.blockingDeferred.pipe(
410
+ yield* Deferred.await(initialBlockingSyncContext.blockingDeferred).pipe(
382
411
  Effect.withSpan('@livestore/common:leader-thread:initial-sync-blocking'),
383
412
  )
384
413
  }
@@ -421,7 +450,7 @@ export const makeNetworkStatusSubscribable = ({
421
450
  }))
422
451
 
423
452
  if (syncBackend !== undefined) {
424
- yield* syncBackend.isConnected.changes.pipe(
453
+ yield* SubscriptionRef.changes(syncBackend.isConnected).pipe(
425
454
  Stream.tap((isConnected) => updateNetworkStatus({ isConnected })),
426
455
  Stream.runDrain,
427
456
  Effect.interruptible,
@@ -431,7 +460,7 @@ export const makeNetworkStatusSubscribable = ({
431
460
  }
432
461
 
433
462
  if (devtoolsContext.enabled === true) {
434
- yield* devtoolsContext.syncBackendLatchState.changes.pipe(
463
+ yield* SubscriptionRef.changes(devtoolsContext.syncBackendLatchState).pipe(
435
464
  Stream.tap(({ latchClosed }) => updateNetworkStatus({ latchClosed })),
436
465
  Stream.runDrain,
437
466
  Effect.interruptible,
@@ -7,6 +7,7 @@ import { logDeprecationWarnings } from '../schema/EventDef/deprecated.ts'
7
7
  import type { LiveStoreSchema } from '../schema/mod.ts'
8
8
  import { EventSequenceNumber, resolveEventDef, SystemTables, UNKNOWN_EVENT_SCHEMA_HASH } from '../schema/mod.ts'
9
9
  import { insertRow } from '../sql-queries/index.ts'
10
+ import * as StateHead from '../StateHead.ts'
10
11
  import { sql } from '../util.ts'
11
12
  import { execSql, execSqlPrepared } from './connection.ts'
12
13
  import * as Eventlog from './eventlog.ts'
@@ -21,8 +22,9 @@ export const makeMaterializeEvent = ({
21
22
  schema: LiveStoreSchema
22
23
  dbState: SqliteDb
23
24
  dbEventlog: SqliteDb
24
- }): Effect.Effect<MaterializeEvent> =>
25
+ }): Effect.Effect<MaterializeEvent, never, StateHead.StateHead> =>
25
26
  Effect.gen(function* () {
27
+ const stateHead = yield* StateHead.StateHead
26
28
  const eventDefSchemaHashMap = new Map(
27
29
  // TODO Running `Schema.hash` can be a bottleneck for larger schemas. There is an opportunity to run this
28
30
  // at build time and lookup the pre-computed hash at runtime.
@@ -53,6 +55,7 @@ export const makeMaterializeEvent = ({
53
55
  )
54
56
  }
55
57
 
58
+ yield* stateHead.set(eventEncoded.seqNum)
56
59
  dbState.debug.head = eventEncoded.seqNum
57
60
 
58
61
  return {
@@ -123,6 +126,7 @@ export const makeMaterializeEvent = ({
123
126
  },
124
127
  }),
125
128
  )
129
+ yield* stateHead.set(eventEncoded.seqNum)
126
130
 
127
131
  // console.groupEnd()
128
132
 
@@ -144,13 +148,14 @@ export const makeMaterializeEvent = ({
144
148
  }
145
149
 
146
150
  return {
147
- sessionChangeset: changeset !== undefined
148
- ? {
149
- _tag: 'sessionChangeset' as const,
150
- data: changeset,
151
- debug: LS_DEV === true ? execArgsArr : null,
152
- }
153
- : { _tag: 'no-op' as const },
151
+ sessionChangeset:
152
+ changeset !== undefined
153
+ ? {
154
+ _tag: 'sessionChangeset' as const,
155
+ data: changeset,
156
+ debug: LS_DEV === true ? execArgsArr : null,
157
+ }
158
+ : { _tag: 'no-op' as const },
154
159
  hash: materializerHash,
155
160
  }
156
161
  }).pipe(
@@ -1,11 +1,9 @@
1
- import { casesHandled } from '@livestore/utils'
2
1
  import { Effect, Queue } from '@livestore/utils/effect'
3
2
 
4
3
  import type { MigrationsReport } from '../defs.ts'
5
4
  import {
6
5
  type BootStatus,
7
6
  type MaterializeError,
8
- type MigrationHooks,
9
7
  migrateDb,
10
8
  rematerializeFromEventlog,
11
9
  type SqliteDb,
@@ -13,8 +11,22 @@ import {
13
11
  UnknownError,
14
12
  } from '../index.ts'
15
13
  import type { LiveStoreSchema } from '../schema/mod.ts'
16
- import { configureConnection } from './connection.ts'
14
+ import { SystemTables } from '../schema/mod.ts'
15
+ import { configureConnection, execSql } from './connection.ts'
17
16
  import type { MaterializeEvent } from './types.ts'
17
+ import { STATE_REBUILD_BATCH_SIZE_DEFAULT } from './types.ts'
18
+
19
+ export const hasCompletedState = (db: SqliteDb): boolean => {
20
+ const tableNames = new Set(db.select<{ name: string }>('SELECT name FROM sqlite_master').map((_) => _.name))
21
+ return (
22
+ SystemTables.stateSystemTables.every((table) => tableNames.has(table.sqliteDef.name)) &&
23
+ db.select(`SELECT id FROM ${SystemTables.REBUILD_META_TABLE} WHERE id = 1`).length === 1
24
+ )
25
+ }
26
+
27
+ /** Marks a successfully prepared state database as safe to use without rebuilding it. */
28
+ export const markStateAsCompleted = (db: SqliteDb): Effect.Effect<void, SqliteError> =>
29
+ execSql(db, `INSERT OR IGNORE INTO ${SystemTables.REBUILD_META_TABLE} (id) VALUES (1)`, {})
18
30
 
19
31
  export const recreateDb = ({
20
32
  dbState,
@@ -22,16 +34,17 @@ export const recreateDb = ({
22
34
  schema,
23
35
  bootStatusQueue,
24
36
  materializeEvent,
37
+ stateRebuildBatchSize = STATE_REBUILD_BATCH_SIZE_DEFAULT,
25
38
  }: {
26
39
  dbState: SqliteDb
27
40
  dbEventlog: SqliteDb
28
41
  schema: LiveStoreSchema
29
42
  bootStatusQueue: Queue.Queue<BootStatus>
30
43
  materializeEvent: MaterializeEvent
44
+ stateRebuildBatchSize?: number
31
45
  }): Effect.Effect<{ migrationsReport: MigrationsReport }, UnknownError | MaterializeError | SqliteError> =>
32
46
  Effect.gen(function* () {
33
- const migrationOptions = schema.state.sqlite.migrations
34
- let migrationsReport: MigrationsReport = { migrations: [] }
47
+ const hooks = schema.state.sqlite.migrations.hooks
35
48
 
36
49
  yield* Effect.addFinalizer(
37
50
  Effect.fn('recreateDb:finalizer')(function* (ex) {
@@ -39,82 +52,35 @@ export const recreateDb = ({
39
52
  }),
40
53
  )
41
54
 
42
- // NOTE to speed up the operations below, we're creating a temporary in-memory database
43
- // and later we'll overwrite the persisted database with the new data
44
- // TODO bring back this optimization
45
- // const tmpDb = yield* makeSqliteDb({ _tag: 'in-memory' })
46
- const tmpDb = dbState
47
- yield* configureConnection(tmpDb, { foreignKeys: true })
48
-
49
- const initDb = (hooks: Partial<MigrationHooks> | undefined) =>
50
- Effect.gen(function* () {
51
- yield* Effect.tryAll(() => hooks?.init?.(tmpDb)).pipe(UnknownError.mapToUnknownError)
52
-
53
- const migrationsReport = yield* migrateDb({
54
- db: tmpDb,
55
- schema,
56
- onProgress: ({ done, total }) =>
57
- Queue.offer(bootStatusQueue, { stage: 'migrating', progress: { done, total } }),
58
- })
59
-
60
- yield* Effect.tryAll(() => hooks?.pre?.(tmpDb)).pipe(UnknownError.mapToUnknownError)
61
-
62
- return { migrationsReport, tmpDb }
63
- })
64
-
65
- switch (migrationOptions.strategy) {
66
- case 'auto': {
67
- const hooks = migrationOptions.hooks
68
- const initResult = yield* initDb(hooks)
69
-
70
- migrationsReport = initResult.migrationsReport
71
-
72
- yield* rematerializeFromEventlog({
73
- // db: initResult.tmpDb,
74
- dbEventlog,
75
- schema,
76
- materializeEvent,
77
- onProgress: ({ done, total }) =>
78
- Queue.offer(bootStatusQueue, { stage: 'rehydrating', progress: { done, total } }),
79
- })
80
-
81
- yield* Effect.tryAll(() => hooks?.post?.(initResult.tmpDb)).pipe(UnknownError.mapToUnknownError)
82
-
83
- break
84
- }
85
- case 'manual': {
86
- const oldDbData = dbState.export()
87
-
88
- migrationsReport = { migrations: [] }
89
-
90
- const newDbData = yield* Effect.tryAll(() => migrationOptions.migrate(oldDbData)).pipe(
91
- UnknownError.mapToUnknownError,
92
- )
55
+ yield* configureConnection(dbState, { foreignKeys: true })
93
56
 
94
- tmpDb.import(newDbData)
57
+ // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- user hook errors are immediately normalized to LiveStore UnknownError
58
+ yield* Effect.trySyncOrPromiseOrEffect(() => hooks?.init?.(dbState)).pipe(UnknownError.mapToUnknownError)
95
59
 
96
- // TODO validate schema
60
+ const migrationsReport = yield* migrateDb({
61
+ db: dbState,
62
+ schema,
63
+ onProgress: ({ done, total }) => Queue.offer(bootStatusQueue, { stage: 'migrating', progress: { done, total } }),
64
+ })
97
65
 
98
- break
99
- }
100
- default: {
101
- casesHandled(migrationOptions)
102
- }
103
- }
66
+ // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- user hook errors are immediately normalized to LiveStore UnknownError
67
+ yield* Effect.trySyncOrPromiseOrEffect(() => hooks?.pre?.(dbState)).pipe(UnknownError.mapToUnknownError)
104
68
 
105
- // TODO bring back
106
- // Import the temporary in-memory database into the persistent database
107
- // yield* Effect.sync(() => db.import(tmpDb)).pipe(
108
- // Effect.withSpan('@livestore/common:leader-thread:recreateDb:import'),
109
- // )
69
+ yield* rematerializeFromEventlog({
70
+ dbEventlog,
71
+ dbState,
72
+ schema,
73
+ materializeEvent,
74
+ batchSize: stateRebuildBatchSize,
75
+ onProgress: ({ done, total }) =>
76
+ Queue.offer(bootStatusQueue, { stage: 'rehydrating', progress: { done, total } }),
77
+ })
110
78
 
111
- // TODO maybe bring back re-using this initial snapshot to avoid calling `.export()` again
112
- // We've disabled this for now as it made the code too complex, as we often run syncing right after
113
- // so the snapshot is no longer up to date
114
- // const snapshotFromTmpDb = tmpDb.export()
79
+ // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- user hook errors are immediately normalized to LiveStore UnknownError
80
+ yield* Effect.trySyncOrPromiseOrEffect(() => hooks?.post?.(dbState)).pipe(UnknownError.mapToUnknownError)
115
81
 
116
- // TODO bring back
117
- // tmpDb.close()
82
+ // Keep this out of finalizers, which also run on failure and interruption.
83
+ yield* markStateAsCompleted(dbState)
118
84
 
119
85
  return { migrationsReport }
120
86
  }).pipe(
@@ -1,19 +1,8 @@
1
- import type { WebChannel } from '@livestore/utils/effect'
2
- import { Schema } from '@livestore/utils/effect'
1
+ import { type WebChannel, Schema } from '@livestore/utils/effect'
3
2
 
4
- import {
5
- BackendIdMismatchError,
6
- IntentionalShutdownCause,
7
- MaterializeError,
8
- UnknownError,
9
- } from '../index.ts'
3
+ import { BackendIdMismatchError, IntentionalShutdownCause, MaterializeError, UnknownError } from '../index.ts'
10
4
 
11
- export class All extends Schema.Union(
12
- IntentionalShutdownCause,
13
- UnknownError,
14
- BackendIdMismatchError,
15
- MaterializeError,
16
- ) {}
5
+ export const All = Schema.Union([IntentionalShutdownCause, UnknownError, BackendIdMismatchError, MaterializeError])
17
6
 
18
7
  /**
19
8
  * Used internally by an adapter to shutdown gracefully.