@terreno/syncdb 56.0.0-beta.0

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 (317) hide show
  1. package/README.md +419 -0
  2. package/dist/auth/betterAuthAdapter.d.ts +22 -0
  3. package/dist/auth/betterAuthAdapter.d.ts.map +1 -0
  4. package/dist/auth/betterAuthAdapter.js +181 -0
  5. package/dist/auth/betterAuthAdapter.js.map +1 -0
  6. package/dist/auth/betterAuthAdapter.test.d.ts +2 -0
  7. package/dist/auth/betterAuthAdapter.test.d.ts.map +1 -0
  8. package/dist/auth/betterAuthAdapter.test.js +350 -0
  9. package/dist/auth/betterAuthAdapter.test.js.map +1 -0
  10. package/dist/auth/types.d.ts +42 -0
  11. package/dist/auth/types.d.ts.map +1 -0
  12. package/dist/auth/types.js +9 -0
  13. package/dist/auth/types.js.map +1 -0
  14. package/dist/client.d.ts +246 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +1415 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/client.test.d.ts +2 -0
  19. package/dist/client.test.d.ts.map +1 -0
  20. package/dist/client.test.js +2310 -0
  21. package/dist/client.test.js.map +1 -0
  22. package/dist/crypto/aesGcmCodec.d.ts +33 -0
  23. package/dist/crypto/aesGcmCodec.d.ts.map +1 -0
  24. package/dist/crypto/aesGcmCodec.js +80 -0
  25. package/dist/crypto/aesGcmCodec.js.map +1 -0
  26. package/dist/crypto/aesGcmCodec.test.d.ts +2 -0
  27. package/dist/crypto/aesGcmCodec.test.d.ts.map +1 -0
  28. package/dist/crypto/aesGcmCodec.test.js +83 -0
  29. package/dist/crypto/aesGcmCodec.test.js.map +1 -0
  30. package/dist/crypto/identityCodec.d.ts +7 -0
  31. package/dist/crypto/identityCodec.d.ts.map +1 -0
  32. package/dist/crypto/identityCodec.js +9 -0
  33. package/dist/crypto/identityCodec.js.map +1 -0
  34. package/dist/crypto/keyProviders.d.ts +34 -0
  35. package/dist/crypto/keyProviders.d.ts.map +1 -0
  36. package/dist/crypto/keyProviders.js +102 -0
  37. package/dist/crypto/keyProviders.js.map +1 -0
  38. package/dist/crypto/keyProviders.test.d.ts +2 -0
  39. package/dist/crypto/keyProviders.test.d.ts.map +1 -0
  40. package/dist/crypto/keyProviders.test.js +189 -0
  41. package/dist/crypto/keyProviders.test.js.map +1 -0
  42. package/dist/crypto/types.d.ts +24 -0
  43. package/dist/crypto/types.d.ts.map +1 -0
  44. package/dist/crypto/types.js +8 -0
  45. package/dist/crypto/types.js.map +1 -0
  46. package/dist/debug/debugChannel.d.ts +52 -0
  47. package/dist/debug/debugChannel.d.ts.map +1 -0
  48. package/dist/debug/debugChannel.js +73 -0
  49. package/dist/debug/debugChannel.js.map +1 -0
  50. package/dist/debug/debugChannel.test.d.ts +2 -0
  51. package/dist/debug/debugChannel.test.d.ts.map +1 -0
  52. package/dist/debug/debugChannel.test.js +105 -0
  53. package/dist/debug/debugChannel.test.js.map +1 -0
  54. package/dist/debug/debugLog.d.ts +111 -0
  55. package/dist/debug/debugLog.d.ts.map +1 -0
  56. package/dist/debug/debugLog.js +150 -0
  57. package/dist/debug/debugLog.js.map +1 -0
  58. package/dist/debug/debugLog.test.d.ts +2 -0
  59. package/dist/debug/debugLog.test.d.ts.map +1 -0
  60. package/dist/debug/debugLog.test.js +121 -0
  61. package/dist/debug/debugLog.test.js.map +1 -0
  62. package/dist/index.d.ts +46 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +51 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts +2 -0
  67. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts.map +1 -0
  68. package/dist/isolated/defaultPersisterFactoryNative.isolated.js +38 -0
  69. package/dist/isolated/defaultPersisterFactoryNative.isolated.js.map +1 -0
  70. package/dist/mutations/conflicts.d.ts +31 -0
  71. package/dist/mutations/conflicts.d.ts.map +1 -0
  72. package/dist/mutations/conflicts.js +73 -0
  73. package/dist/mutations/conflicts.js.map +1 -0
  74. package/dist/mutations/outbox.d.ts +174 -0
  75. package/dist/mutations/outbox.d.ts.map +1 -0
  76. package/dist/mutations/outbox.js +385 -0
  77. package/dist/mutations/outbox.js.map +1 -0
  78. package/dist/mutations/outbox.test.d.ts +2 -0
  79. package/dist/mutations/outbox.test.d.ts.map +1 -0
  80. package/dist/mutations/outbox.test.js +643 -0
  81. package/dist/mutations/outbox.test.js.map +1 -0
  82. package/dist/mutations/resolveConflict.d.ts +32 -0
  83. package/dist/mutations/resolveConflict.d.ts.map +1 -0
  84. package/dist/mutations/resolveConflict.js +101 -0
  85. package/dist/mutations/resolveConflict.js.map +1 -0
  86. package/dist/mutations/resolveConflict.test.d.ts +2 -0
  87. package/dist/mutations/resolveConflict.test.d.ts.map +1 -0
  88. package/dist/mutations/resolveConflict.test.js +282 -0
  89. package/dist/mutations/resolveConflict.test.js.map +1 -0
  90. package/dist/persisters/defaultPersisterFactory.d.ts +9 -0
  91. package/dist/persisters/defaultPersisterFactory.d.ts.map +1 -0
  92. package/dist/persisters/defaultPersisterFactory.js +9 -0
  93. package/dist/persisters/defaultPersisterFactory.js.map +1 -0
  94. package/dist/persisters/defaultPersisterFactory.native.d.ts +10 -0
  95. package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -0
  96. package/dist/persisters/defaultPersisterFactory.native.js +44 -0
  97. package/dist/persisters/defaultPersisterFactory.native.js.map +1 -0
  98. package/dist/persisters/defaultPersisterFactory.test.d.ts +2 -0
  99. package/dist/persisters/defaultPersisterFactory.test.d.ts.map +1 -0
  100. package/dist/persisters/defaultPersisterFactory.test.js +177 -0
  101. package/dist/persisters/defaultPersisterFactory.test.js.map +1 -0
  102. package/dist/persisters/defaultPersisterFactory.web.d.ts +17 -0
  103. package/dist/persisters/defaultPersisterFactory.web.d.ts.map +1 -0
  104. package/dist/persisters/defaultPersisterFactory.web.js +65 -0
  105. package/dist/persisters/defaultPersisterFactory.web.js.map +1 -0
  106. package/dist/persisters/encryptedIndexedDbPersister.d.ts +46 -0
  107. package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -0
  108. package/dist/persisters/encryptedIndexedDbPersister.js +171 -0
  109. package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -0
  110. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts +2 -0
  111. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts.map +1 -0
  112. package/dist/persisters/encryptedIndexedDbPersister.test.js +352 -0
  113. package/dist/persisters/encryptedIndexedDbPersister.test.js.map +1 -0
  114. package/dist/persisters/memoryPersister.d.ts +19 -0
  115. package/dist/persisters/memoryPersister.d.ts.map +1 -0
  116. package/dist/persisters/memoryPersister.js +31 -0
  117. package/dist/persisters/memoryPersister.js.map +1 -0
  118. package/dist/persisters/memoryPersister.test.d.ts +2 -0
  119. package/dist/persisters/memoryPersister.test.d.ts.map +1 -0
  120. package/dist/persisters/memoryPersister.test.js +113 -0
  121. package/dist/persisters/memoryPersister.test.js.map +1 -0
  122. package/dist/persisters/types.d.ts +65 -0
  123. package/dist/persisters/types.d.ts.map +1 -0
  124. package/dist/persisters/types.js +2 -0
  125. package/dist/persisters/types.js.map +1 -0
  126. package/dist/react/hooks.d.ts +132 -0
  127. package/dist/react/hooks.d.ts.map +1 -0
  128. package/dist/react/hooks.js +269 -0
  129. package/dist/react/hooks.js.map +1 -0
  130. package/dist/react/hooks.test.d.ts +2 -0
  131. package/dist/react/hooks.test.d.ts.map +1 -0
  132. package/dist/react/hooks.test.js +645 -0
  133. package/dist/react/hooks.test.js.map +1 -0
  134. package/dist/react/index.d.ts +11 -0
  135. package/dist/react/index.d.ts.map +1 -0
  136. package/dist/react/index.js +11 -0
  137. package/dist/react/index.js.map +1 -0
  138. package/dist/react/provider.d.ts +11 -0
  139. package/dist/react/provider.d.ts.map +1 -0
  140. package/dist/react/provider.js +17 -0
  141. package/dist/react/provider.js.map +1 -0
  142. package/dist/storage/idb.d.ts +27 -0
  143. package/dist/storage/idb.d.ts.map +1 -0
  144. package/dist/storage/idb.js +72 -0
  145. package/dist/storage/idb.js.map +1 -0
  146. package/dist/storage/idb.test.d.ts +2 -0
  147. package/dist/storage/idb.test.d.ts.map +1 -0
  148. package/dist/storage/idb.test.js +100 -0
  149. package/dist/storage/idb.test.js.map +1 -0
  150. package/dist/storage/purgeUnknownStream.test.d.ts +2 -0
  151. package/dist/storage/purgeUnknownStream.test.d.ts.map +1 -0
  152. package/dist/storage/purgeUnknownStream.test.js +64 -0
  153. package/dist/storage/purgeUnknownStream.test.js.map +1 -0
  154. package/dist/storage/schema.d.ts +33 -0
  155. package/dist/storage/schema.d.ts.map +1 -0
  156. package/dist/storage/schema.js +92 -0
  157. package/dist/storage/schema.js.map +1 -0
  158. package/dist/storage/store.d.ts +136 -0
  159. package/dist/storage/store.d.ts.map +1 -0
  160. package/dist/storage/store.js +275 -0
  161. package/dist/storage/store.js.map +1 -0
  162. package/dist/storage/store.test.d.ts +2 -0
  163. package/dist/storage/store.test.d.ts.map +1 -0
  164. package/dist/storage/store.test.js +357 -0
  165. package/dist/storage/store.test.js.map +1 -0
  166. package/dist/storage/types.d.ts +146 -0
  167. package/dist/storage/types.d.ts.map +1 -0
  168. package/dist/storage/types.js +32 -0
  169. package/dist/storage/types.js.map +1 -0
  170. package/dist/storage/wipe.d.ts +22 -0
  171. package/dist/storage/wipe.d.ts.map +1 -0
  172. package/dist/storage/wipe.js +43 -0
  173. package/dist/storage/wipe.js.map +1 -0
  174. package/dist/storage/wipe.test.d.ts +2 -0
  175. package/dist/storage/wipe.test.d.ts.map +1 -0
  176. package/dist/storage/wipe.test.js +95 -0
  177. package/dist/storage/wipe.test.js.map +1 -0
  178. package/dist/sync/bootstrap.d.ts +64 -0
  179. package/dist/sync/bootstrap.d.ts.map +1 -0
  180. package/dist/sync/bootstrap.js +160 -0
  181. package/dist/sync/bootstrap.js.map +1 -0
  182. package/dist/sync/bootstrap.test.d.ts +2 -0
  183. package/dist/sync/bootstrap.test.d.ts.map +1 -0
  184. package/dist/sync/bootstrap.test.js +447 -0
  185. package/dist/sync/bootstrap.test.js.map +1 -0
  186. package/dist/sync/cursor.d.ts +67 -0
  187. package/dist/sync/cursor.d.ts.map +1 -0
  188. package/dist/sync/cursor.js +74 -0
  189. package/dist/sync/cursor.js.map +1 -0
  190. package/dist/sync/cursor.test.d.ts +2 -0
  191. package/dist/sync/cursor.test.d.ts.map +1 -0
  192. package/dist/sync/cursor.test.js +73 -0
  193. package/dist/sync/cursor.test.js.map +1 -0
  194. package/dist/sync/deltaApplier.d.ts +30 -0
  195. package/dist/sync/deltaApplier.d.ts.map +1 -0
  196. package/dist/sync/deltaApplier.js +61 -0
  197. package/dist/sync/deltaApplier.js.map +1 -0
  198. package/dist/sync/deltaApplier.test.d.ts +2 -0
  199. package/dist/sync/deltaApplier.test.d.ts.map +1 -0
  200. package/dist/sync/deltaApplier.test.js +212 -0
  201. package/dist/sync/deltaApplier.test.js.map +1 -0
  202. package/dist/sync/entityRepair.d.ts +45 -0
  203. package/dist/sync/entityRepair.d.ts.map +1 -0
  204. package/dist/sync/entityRepair.js +91 -0
  205. package/dist/sync/entityRepair.js.map +1 -0
  206. package/dist/sync/entityRepair.test.d.ts +2 -0
  207. package/dist/sync/entityRepair.test.d.ts.map +1 -0
  208. package/dist/sync/entityRepair.test.js +146 -0
  209. package/dist/sync/entityRepair.test.js.map +1 -0
  210. package/dist/sync/httpChannel.d.ts +74 -0
  211. package/dist/sync/httpChannel.d.ts.map +1 -0
  212. package/dist/sync/httpChannel.js +123 -0
  213. package/dist/sync/httpChannel.js.map +1 -0
  214. package/dist/sync/httpChannel.test.d.ts +2 -0
  215. package/dist/sync/httpChannel.test.d.ts.map +1 -0
  216. package/dist/sync/httpChannel.test.js +215 -0
  217. package/dist/sync/httpChannel.test.js.map +1 -0
  218. package/dist/sync/replayCoordinator.d.ts +212 -0
  219. package/dist/sync/replayCoordinator.d.ts.map +1 -0
  220. package/dist/sync/replayCoordinator.js +1110 -0
  221. package/dist/sync/replayCoordinator.js.map +1 -0
  222. package/dist/sync/replayCoordinator.test.d.ts +2 -0
  223. package/dist/sync/replayCoordinator.test.d.ts.map +1 -0
  224. package/dist/sync/replayCoordinator.test.js +1496 -0
  225. package/dist/sync/replayCoordinator.test.js.map +1 -0
  226. package/dist/sync/socketTransport.d.ts +56 -0
  227. package/dist/sync/socketTransport.d.ts.map +1 -0
  228. package/dist/sync/socketTransport.js +292 -0
  229. package/dist/sync/socketTransport.js.map +1 -0
  230. package/dist/sync/socketTransport.test.d.ts +2 -0
  231. package/dist/sync/socketTransport.test.d.ts.map +1 -0
  232. package/dist/sync/socketTransport.test.js +346 -0
  233. package/dist/sync/socketTransport.test.js.map +1 -0
  234. package/dist/sync/transport.d.ts +80 -0
  235. package/dist/sync/transport.d.ts.map +1 -0
  236. package/dist/sync/transport.js +5 -0
  237. package/dist/sync/transport.js.map +1 -0
  238. package/dist/testing/fakeTransport.d.ts +55 -0
  239. package/dist/testing/fakeTransport.d.ts.map +1 -0
  240. package/dist/testing/fakeTransport.js +139 -0
  241. package/dist/testing/fakeTransport.js.map +1 -0
  242. package/dist/testing/fakeTransport.test.d.ts +2 -0
  243. package/dist/testing/fakeTransport.test.d.ts.map +1 -0
  244. package/dist/testing/fakeTransport.test.js +112 -0
  245. package/dist/testing/fakeTransport.test.js.map +1 -0
  246. package/dist/testing/index.d.ts +13 -0
  247. package/dist/testing/index.d.ts.map +1 -0
  248. package/dist/testing/index.js +13 -0
  249. package/dist/testing/index.js.map +1 -0
  250. package/dist/types.d.ts +271 -0
  251. package/dist/types.d.ts.map +1 -0
  252. package/dist/types.js +9 -0
  253. package/dist/types.js.map +1 -0
  254. package/package.json +71 -0
  255. package/src/auth/betterAuthAdapter.test.ts +455 -0
  256. package/src/auth/betterAuthAdapter.ts +214 -0
  257. package/src/auth/types.ts +49 -0
  258. package/src/client.test.ts +2670 -0
  259. package/src/client.ts +1748 -0
  260. package/src/crypto/aesGcmCodec.test.ts +103 -0
  261. package/src/crypto/aesGcmCodec.ts +98 -0
  262. package/src/crypto/identityCodec.ts +10 -0
  263. package/src/crypto/keyProviders.test.ts +228 -0
  264. package/src/crypto/keyProviders.ts +153 -0
  265. package/src/crypto/types.ts +23 -0
  266. package/src/debug/debugChannel.test.ts +121 -0
  267. package/src/debug/debugChannel.ts +112 -0
  268. package/src/debug/debugLog.test.ts +139 -0
  269. package/src/debug/debugLog.ts +272 -0
  270. package/src/index.ts +157 -0
  271. package/src/isolated/defaultPersisterFactoryNative.isolated.ts +45 -0
  272. package/src/mutations/conflicts.ts +108 -0
  273. package/src/mutations/outbox.test.ts +754 -0
  274. package/src/mutations/outbox.ts +585 -0
  275. package/src/mutations/resolveConflict.test.ts +338 -0
  276. package/src/mutations/resolveConflict.ts +115 -0
  277. package/src/persisters/defaultPersisterFactory.native.ts +53 -0
  278. package/src/persisters/defaultPersisterFactory.test.ts +207 -0
  279. package/src/persisters/defaultPersisterFactory.ts +12 -0
  280. package/src/persisters/defaultPersisterFactory.web.ts +78 -0
  281. package/src/persisters/encryptedIndexedDbPersister.test.ts +381 -0
  282. package/src/persisters/encryptedIndexedDbPersister.ts +218 -0
  283. package/src/persisters/memoryPersister.test.ts +136 -0
  284. package/src/persisters/memoryPersister.ts +52 -0
  285. package/src/persisters/types.ts +71 -0
  286. package/src/react/hooks.test.tsx +761 -0
  287. package/src/react/hooks.ts +409 -0
  288. package/src/react/index.ts +11 -0
  289. package/src/react/provider.tsx +27 -0
  290. package/src/storage/idb.test.ts +116 -0
  291. package/src/storage/idb.ts +112 -0
  292. package/src/storage/purgeUnknownStream.test.ts +74 -0
  293. package/src/storage/schema.ts +103 -0
  294. package/src/storage/store.test.ts +424 -0
  295. package/src/storage/store.ts +461 -0
  296. package/src/storage/types.ts +159 -0
  297. package/src/storage/wipe.test.ts +111 -0
  298. package/src/storage/wipe.ts +58 -0
  299. package/src/sync/bootstrap.test.ts +486 -0
  300. package/src/sync/bootstrap.ts +217 -0
  301. package/src/sync/cursor.test.ts +84 -0
  302. package/src/sync/cursor.ts +113 -0
  303. package/src/sync/deltaApplier.test.ts +237 -0
  304. package/src/sync/deltaApplier.ts +84 -0
  305. package/src/sync/entityRepair.test.ts +161 -0
  306. package/src/sync/entityRepair.ts +124 -0
  307. package/src/sync/httpChannel.test.ts +265 -0
  308. package/src/sync/httpChannel.ts +220 -0
  309. package/src/sync/replayCoordinator.test.ts +1709 -0
  310. package/src/sync/replayCoordinator.ts +1370 -0
  311. package/src/sync/socketTransport.test.ts +413 -0
  312. package/src/sync/socketTransport.ts +379 -0
  313. package/src/sync/transport.ts +76 -0
  314. package/src/testing/fakeTransport.test.ts +125 -0
  315. package/src/testing/fakeTransport.ts +206 -0
  316. package/src/testing/index.ts +18 -0
  317. package/src/types.ts +284 -0
package/src/client.ts ADDED
@@ -0,0 +1,1748 @@
1
+ import {DateTime} from "luxon";
2
+ import type {AnyPersister} from "tinybase/persisters";
3
+
4
+ import {createServerKeyProvider, DEFAULT_KEY_CACHE_DB_NAME} from "./crypto/keyProviders";
5
+ import type {KeyProvider} from "./crypto/types";
6
+ import {attachDebugChannel, type DebugChannelBridge} from "./debug/debugChannel";
7
+ import {resolveDebugLog, type SyncDebugLog, type SyncDebugLogOptions} from "./debug/debugLog";
8
+ import {listConflicts, pruneGhostConflicts} from "./mutations/conflicts";
9
+ import {createOutbox, generateMutationId, type Outbox} from "./mutations/outbox";
10
+ import {resolveConflict as applyConflictResolution} from "./mutations/resolveConflict";
11
+ import {createDefaultPersisterFactory} from "./persisters/defaultPersisterFactory";
12
+ import type {DefaultPersisterFactoryConfig, PersisterFactory} from "./persisters/types";
13
+ import {SYNC_SCHEMA_VERSION} from "./storage/schema";
14
+ import {createSyncStore, type SyncStore} from "./storage/store";
15
+ import {CURSORS_TABLE, KNOWN_STREAMS_TABLE} from "./storage/types";
16
+ import {wipeLocalData} from "./storage/wipe";
17
+ import {bootstrapStream} from "./sync/bootstrap";
18
+ import {getAllCursors} from "./sync/cursor";
19
+ import {applyDelta} from "./sync/deltaApplier";
20
+ import {repairMarkedEntities} from "./sync/entityRepair";
21
+ import {AuthRequiredError, createHttpChannel, type HttpChannel} from "./sync/httpChannel";
22
+ import {createReplayCoordinator, type ReplayCoordinator} from "./sync/replayCoordinator";
23
+ import {createSocketTransport} from "./sync/socketTransport";
24
+ import type {SendMutationBatchResult, SendMutationResult, SyncTransport} from "./sync/transport";
25
+ import type {
26
+ AuthProvider,
27
+ ConflictResolutionStrategy,
28
+ SyncCollectionStatus,
29
+ SyncConflict,
30
+ SyncDelta,
31
+ SyncMutateBatchRequest,
32
+ SyncMutateRequest,
33
+ SyncMutationOperation,
34
+ SyncStatus,
35
+ } from "./types";
36
+
37
+ /** Periodic reconcile interval when not configured (5 minutes). */
38
+ export const DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;
39
+
40
+ /** Minimum interval between seq-jump-triggered reconciles per stream (30s). */
41
+ export const DEFAULT_SEQ_JUMP_RECONCILE_MIN_INTERVAL_MS = 30_000;
42
+
43
+ /** E5: default local tombstone retention window (90 days), matching the server's (C7). */
44
+ export const DEFAULT_TOMBSTONE_RETENTION_MS = 90 * 24 * 60 * 60 * 1_000;
45
+
46
+ /**
47
+ * `start()` auth-resolution retry defaults. A host app only calls `start()` once it
48
+ * already believes the user is authenticated (e.g. right after its own login flow
49
+ * resolved), so a `null` from `authProvider.getUserId()` on the first attempt is far
50
+ * more likely a transient hiccup — the session cookie/token not yet queryable, or a
51
+ * one-off fetch failure racing a just-completed navigation — than a genuine
52
+ * logged-out state. Retrying briefly avoids `start()` giving up permanently on a call
53
+ * site that (by design, see the client.ts start() doc) never retries itself.
54
+ */
55
+ export const DEFAULT_START_AUTH_RETRY_ATTEMPTS = 3;
56
+ export const DEFAULT_START_AUTH_RETRY_DELAY_MS = 250;
57
+
58
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
59
+
60
+ export interface SyncDbConfig {
61
+ /** App/store name; used as the persisted database name. */
62
+ name: string;
63
+ /** Collections to sync (become local entity tables and subscriptions). */
64
+ collections: string[];
65
+ authProvider: AuthProvider;
66
+ /** Server origin; required unless both transport and httpChannel are injected. */
67
+ baseUrl?: string;
68
+ /** Transport override (tests inject a fake; default is the socket transport). */
69
+ transport?: SyncTransport;
70
+ /** HTTP channel override (default is built from baseUrl when present). */
71
+ httpChannel?: HttpChannel;
72
+ /** Persister factory override (default is the platform default factory). */
73
+ persisterFactory?: PersisterFactory;
74
+ /** Encryption key provider forwarded to the default persister factory (web). */
75
+ keyProvider?: KeyProvider;
76
+ /**
77
+ * Test-only IndexedDB read/write overrides forwarded to the default web
78
+ * persister factory (e.g. to simulate a read error or a quota-exceeded
79
+ * write in tests without a real broken IndexedDB). Ignored on native and
80
+ * ignored entirely when `persisterFactory` is overridden.
81
+ */
82
+ idbGetImpl?: DefaultPersisterFactoryConfig["idbGetImpl"];
83
+ idbSetImpl?: DefaultPersisterFactoryConfig["idbSetImpl"];
84
+ /** Periodic reconcile interval in ms; 0 disables (default 5 minutes). */
85
+ reconcileIntervalMs?: number;
86
+ /** Rate limit for seq-jump-triggered reconciles per stream (default 30s). */
87
+ seqJumpReconcileMinIntervalMs?: number;
88
+ /** Millisecond clock, injectable for deterministic rate-limit tests. */
89
+ now?: () => number;
90
+ /** Random source in [0, 1), injectable for deterministic backoff-jitter tests. */
91
+ random?: () => number;
92
+ /**
93
+ * Enable the in-memory debug event log (patches, mutations, acks/nacks,
94
+ * conflicts, reconcile/replay, connectivity). `true` uses defaults; pass
95
+ * options to size the buffer. Off by default — zero overhead when disabled.
96
+ * Powers the sync debugger UI and the future MCP introspection surface.
97
+ */
98
+ debug?: boolean | SyncDebugLogOptions;
99
+ /**
100
+ * Fired at most once per auth-pause episode when the client enters
101
+ * `paused: "auth"` (INV-2), so the host app can show a re-login prompt.
102
+ * Clears and can fire again after a subsequent pause episode.
103
+ */
104
+ onAuthRequired?: () => void;
105
+ /**
106
+ * When true, `client.signOut()` wipes local data for the current user (in
107
+ * addition to clearing auth state). Local data is otherwise NEVER wiped on
108
+ * logout or 401 (INV-2) — only on a confirmed different-user login, or via
109
+ * this explicit, host-app-initiated opt-in.
110
+ */
111
+ wipeOnSignOut?: boolean;
112
+ /** Max mutations per batched drain send (B3, default 50; server caps at 100). */
113
+ batchSize?: number;
114
+ /**
115
+ * B4: when true, a conflict halts the ENTIRE drain instead of just blocking
116
+ * its entity. Default false (per-entity blocking — see README "Conflict
117
+ * handling modes").
118
+ */
119
+ haltQueueOnConflict?: boolean;
120
+ /**
121
+ * E3(b): invoked when persisted local data cannot be decrypted (web only —
122
+ * corrupt data, or a rotated/lost encryption key). DEFAULT BEHAVIOR when
123
+ * omitted: wipe all local data for the current user, re-stamp the schema
124
+ * version, and run a full snapshot re-bootstrap — always preceded by a
125
+ * `console.warn`. Pass this to override that default (e.g. to prompt the
126
+ * user before wiping); when provided, the client's own wipe/re-bootstrap is
127
+ * skipped and the host app is fully responsible for recovery.
128
+ */
129
+ onDecryptFailure?: () => void;
130
+ /**
131
+ * E5: client-side compaction — local tombstone rows (`deleted: true`) older
132
+ * than this window (from their `deletedAt` stamp) are deleted after each
133
+ * successful reconcile. Default 90 days, matching the server's own
134
+ * tombstone retention (C7); keep the two in sync — compacting locally
135
+ * before the server's retention window elapses risks a client permanently
136
+ * missing a delete it hasn't converged on yet. 0 disables compaction.
137
+ */
138
+ tombstoneRetentionMs?: number;
139
+ /**
140
+ * Number of `authProvider.getUserId()` attempts `start()` makes before giving up
141
+ * with "requires an authenticated user" (default {@link DEFAULT_START_AUTH_RETRY_ATTEMPTS}).
142
+ * A host app calls `start()` only once it believes the user is signed in, so an
143
+ * initial `null` is usually a transient auth-provider hiccup (e.g. a session fetch
144
+ * racing a just-completed login) rather than a real logged-out state — retrying
145
+ * a few times avoids `start()` permanently failing on that race. Set to 1 to
146
+ * disable retrying.
147
+ */
148
+ startAuthRetryAttempts?: number;
149
+ /** Delay between `start()` auth-resolution retries (default {@link DEFAULT_START_AUTH_RETRY_DELAY_MS}). */
150
+ startAuthRetryDelayMs?: number;
151
+ }
152
+
153
+ /**
154
+ * Why a {@link SyncDb.forceResync} call could not run (or could not finish).
155
+ *
156
+ * `"superseded"` means a `stop()`/`start()` cycle or a different-user login took over
157
+ * mid-flight, so the resync abandoned its work rather than writing into a store that
158
+ * now belongs to another lifecycle or user — distinct from `"noStreams"` (the server
159
+ * reported no streams for this user, and there was no local set to fall back on),
160
+ * which is a stable outcome that retrying will reproduce.
161
+ */
162
+ export type ForceResyncSkipReason =
163
+ | "noHttpChannel"
164
+ | "offline"
165
+ | "authPaused"
166
+ | "noStreams"
167
+ | "superseded";
168
+
169
+ /** Outcome of a {@link SyncDb.forceResync} call. */
170
+ export interface ForceResyncResult {
171
+ /** False when the resync could not run at all; `reason` explains why. */
172
+ ok: boolean;
173
+ reason?: ForceResyncSkipReason;
174
+ /** Streams purged and re-bootstrapped. */
175
+ streams: number;
176
+ /** Local entity rows deleted before re-bootstrapping. */
177
+ purged: number;
178
+ /** Entities re-fetched by the point-lookup repair pass. */
179
+ repaired: number;
180
+ }
181
+
182
+ export interface MutateArgs {
183
+ collection: string;
184
+ operation: SyncMutationOperation;
185
+ /** Target entity id; required for update/delete, generated for create. */
186
+ id?: string;
187
+ /** Fields to write (create/update). */
188
+ data?: Record<string, unknown>;
189
+ }
190
+
191
+ export interface SyncDb {
192
+ /** Local-first entity store (the UI's source of truth). */
193
+ readonly store: SyncStore;
194
+ /** Durable mutation outbox. */
195
+ readonly outbox: Outbox;
196
+ /**
197
+ * Resolve the user, run the wipe-on-user-change check, start persistence,
198
+ * connect the transport, subscribe collections, and start the periodic
199
+ * reconcile timer. Resolves even when the transport cannot connect
200
+ * (local-first: the app works offline and syncs when connectivity returns).
201
+ */
202
+ start: () => Promise<void>;
203
+ /** Disconnect, stop persistence, clear timers, and remove listeners. */
204
+ stop: () => Promise<void>;
205
+ /**
206
+ * Simulate a network outage: disconnect the transport and pause replay,
207
+ * reconcile, and the periodic timer. Unlike stop(), the resolved user and
208
+ * persistence stay alive, so mutations keep applying locally and queueing
209
+ * in the durable outbox. `getSyncStatus().isOnline` reports false until
210
+ * goOnline() (or a stop()/start() cycle) restores connectivity.
211
+ */
212
+ goOffline: () => void;
213
+ /**
214
+ * End a simulated outage: reconnect the transport, resubscribe, and restart
215
+ * the periodic timer. The reconnect status event triggers a reconcile and
216
+ * replays the queued outbox.
217
+ */
218
+ goOnline: () => Promise<void>;
219
+ /**
220
+ * Apply a mutation optimistically to the local store, enqueue it in the
221
+ * outbox, and kick off a fire-and-forget replay. Returns the generated
222
+ * mutation id and the entity id (generated for creates).
223
+ */
224
+ mutate: (args: MutateArgs) => {mutationId: string; id: string};
225
+ /** Snapshot-from-cursor catch-up for every collection (no-op without HTTP). */
226
+ reconcile: () => Promise<void>;
227
+ /**
228
+ * Purge every known stream locally and re-bootstrap from cursor 0. Use when
229
+ * devices have diverged and a full server snapshot is needed without wiping
230
+ * the outbox or conflicts. Reports what it did (or why it could not run) so a
231
+ * caller can surface the outcome instead of a silent no-op.
232
+ */
233
+ forceResync: () => Promise<ForceResyncResult>;
234
+ /** Drain queued mutations for the current user now. */
235
+ replayOutbox: () => Promise<void>;
236
+ /** Resolve a recorded conflict with the given strategy. */
237
+ resolveConflict: (args: {mutationId: string; strategy: ConflictResolutionStrategy}) => void;
238
+ /**
239
+ * B4: re-enable an entity's queued successors after a terminal validation
240
+ * failure blocked them. Does not touch unresolved conflicts (those clear
241
+ * via `resolveConflict`); kicks off a replay so the re-enabled mutations
242
+ * drain immediately rather than waiting for the next trigger.
243
+ */
244
+ retryFailed: (args: {entityId: string}) => void;
245
+ /**
246
+ * Explicit, host-app-initiated sign-out. Tears the client down like `stop()`
247
+ * (transport disconnected, listeners and timers cleared, persister flushed and
248
+ * destroyed) and clears the in-memory current-user pointer; wipes local data
249
+ * ONLY when `wipeOnSignOut` is configured (INV-2 — a bare 401/logout event
250
+ * never triggers this on its own). Safe to call whether or not the client is
251
+ * currently paused, and safe to race against `start()`/`stop()`/an auth
252
+ * change. Call `start()` again to sync as the next signed-in user.
253
+ */
254
+ signOut: () => Promise<void>;
255
+ /** Aggregate sync state for status UI. */
256
+ getSyncStatus: () => SyncStatus;
257
+ /**
258
+ * Subscribe to non-store status inputs (connectivity, syncing activity).
259
+ * `getSyncStatus()` is a snapshot; store-backed inputs (outbox, conflicts,
260
+ * cursors) already emit through TinyBase listeners on `store.raw`, but
261
+ * `isOnline`/`isSyncing` live outside the store — this hook covers them.
262
+ * Returns an unsubscribe function.
263
+ */
264
+ onStatusChange: (callback: () => void) => () => void;
265
+ /**
266
+ * In-memory debug event log when `config.debug` is enabled; otherwise
267
+ * undefined. Its `snapshot()` is a plain serializable object suitable for
268
+ * returning directly over MCP.
269
+ */
270
+ readonly debug?: SyncDebugLog;
271
+ }
272
+
273
+ /**
274
+ * Assemble the full local-first client: store + outbox + persister + transport
275
+ * + HTTP channel + replay coordinator + reconcile heuristics.
276
+ *
277
+ * Reconcile triggers: transport (re)connect, rate-limited seq-jump hints from
278
+ * deltas, and a periodic timer. Replay triggers: (re)connect, auth changes,
279
+ * and every `mutate()`.
280
+ */
281
+ export const createSyncDb = (config: SyncDbConfig): SyncDb => {
282
+ if (!config.transport && !config.baseUrl) {
283
+ throw new Error("createSyncDb requires a transport or a baseUrl");
284
+ }
285
+
286
+ const now = config.now ?? ((): number => Date.now());
287
+ const transport =
288
+ config.transport ??
289
+ createSocketTransport({
290
+ authProvider: config.authProvider,
291
+ // biome-ignore lint/style/noNonNullAssertion: guarded above — no transport implies baseUrl.
292
+ baseUrl: config.baseUrl!,
293
+ });
294
+ const httpChannel =
295
+ config.httpChannel ??
296
+ (config.baseUrl
297
+ ? createHttpChannel({authProvider: config.authProvider, baseUrl: config.baseUrl})
298
+ : undefined);
299
+
300
+ const store = createSyncStore({
301
+ collections: config.collections,
302
+ now: () => DateTime.fromMillis(now()).toISO() ?? new Date(now()).toISOString(),
303
+ });
304
+ const outbox = createOutbox({store});
305
+ const debugLog = resolveDebugLog(config.debug);
306
+ // Mirror the debug log across browser windows/tabs (web only) so a debugger
307
+ // opened in a second window sees this window's events — including local
308
+ // mutations. No-ops when BroadcastChannel is unavailable (native/SSR). The
309
+ // bridge is retained so stop()/signOut() can close the underlying
310
+ // BroadcastChannel (and drop its log subscription) instead of leaking one per
311
+ // client; start() re-attaches it.
312
+ let debugChannel: DebugChannelBridge | undefined;
313
+ const attachDebugBridge = (): void => {
314
+ if (!debugLog || debugChannel) {
315
+ return;
316
+ }
317
+ debugChannel = attachDebugChannel({log: debugLog, name: config.name});
318
+ };
319
+ const closeDebugBridge = (): void => {
320
+ debugChannel?.close();
321
+ debugChannel = undefined;
322
+ };
323
+ attachDebugBridge();
324
+
325
+ let currentUserId: string | undefined;
326
+ let persister: ReturnType<PersisterFactory> | undefined;
327
+ let connected = false;
328
+ let simulatedOffline = false;
329
+ let syncingCount = 0;
330
+ let reconcileTimer: ReturnType<typeof setInterval> | undefined;
331
+ let unsubscribers: (() => void)[] = [];
332
+ /** The reconcile pass every concurrent trigger shares; see `reconcile()`. */
333
+ let inFlightReconcile:
334
+ | {generation: number; promise: Promise<void>; userId: string | undefined}
335
+ | undefined;
336
+ const lastSeqJumpReconcileAt = new Map<string, number>();
337
+ const statusListeners = new Set<() => void>();
338
+ // A4: auth-pause state. `authPaused` gates reconcile/replay/timer triggers
339
+ // (INV-2 — nothing else may unpause except a same-user auth change).
340
+ // `refreshAttempted` tracks whether the auth adapter's one-shot silent
341
+ // refresh has already run for the CURRENT pause episode.
342
+ let authPaused = false;
343
+ let refreshAttempted = false;
344
+ // E1: lifecycle serialization. `generation` bumps on every start()/stop() so
345
+ // an in-flight operation that resumes after an await can detect it has been
346
+ // superseded (a rapid stop()-then-start() for a new user) and abort instead
347
+ // of mutating state (persister, currentUserId, listeners) that a LATER
348
+ // operation already owns. `lifecycle` is a promise-chain mutex: every call
349
+ // to start()/stop()/handleAuthChange()/runUserCheck() (the latter only ever
350
+ // invoked FROM start()/handleAuthChange(), never directly) is appended to it
351
+ // so at most one of these runs at a time, in call order — this is what
352
+ // prevents the interleaving the mutex exists to fix, not the generation
353
+ // check alone (the generation check only guards against a stale resume
354
+ // AFTER an await; the chain prevents two lifecycle ops from running
355
+ // concurrently in the first place).
356
+ let generation = 0;
357
+ let lifecycle: Promise<void> = Promise.resolve();
358
+ // The socket authenticates per connection (the handshake token is read inside
359
+ // the transport's auth callback), so a confirmed identity change must bounce
360
+ // the transport — otherwise the previous user's live socket keeps pushing that
361
+ // user's deltas into the new user's freshly wiped store and the new user's
362
+ // mutations go out under the old identity. `connectionEpoch` bumps on every
363
+ // bounce; the delta handler captures the epoch it was bound under and ignores
364
+ // anything delivered once a bounce has superseded it, so a delta the old
365
+ // connection flushes mid-bounce can never be applied.
366
+ let connectionEpoch = 0;
367
+ let unbindDeltaHandler: (() => void) | undefined;
368
+ /** True once a start() has completed without a matching stop() (E1 double-start guard). */
369
+ let isStarted = false;
370
+
371
+ /**
372
+ * Queue `op` onto the lifecycle mutex; resolves/rejects with `op`'s own
373
+ * outcome once every previously-queued op has settled. `lifecycle` itself
374
+ * NEVER rejects (see below), so chaining with a plain `.then` is safe — a
375
+ * prior op's failure never wedges the mutex or blocks later queued calls.
376
+ */
377
+ const withLifecycle = <T>(op: () => Promise<T>): Promise<T> => {
378
+ const result = lifecycle.then(op);
379
+ // Keep the chain alive regardless of this op's outcome; `result` itself
380
+ // (returned below) carries the outcome to THIS call's caller.
381
+ lifecycle = result.then(
382
+ () => {},
383
+ () => {}
384
+ );
385
+ return result;
386
+ };
387
+
388
+ const notifyStatusChange = (): void => {
389
+ for (const listener of statusListeners) {
390
+ listener();
391
+ }
392
+ };
393
+
394
+ const setConnected = (value: boolean): void => {
395
+ if (connected === value) {
396
+ return;
397
+ }
398
+ connected = value;
399
+ debugLog?.record({
400
+ direction: "system",
401
+ label: value ? "transport connected" : "transport disconnected",
402
+ type: value ? "connect" : "disconnect",
403
+ });
404
+ notifyStatusChange();
405
+ };
406
+
407
+ const addSyncing = (delta: number): void => {
408
+ const wasSyncing = syncingCount > 0;
409
+ syncingCount += delta;
410
+ if (wasSyncing !== syncingCount > 0) {
411
+ notifyStatusChange();
412
+ }
413
+ };
414
+
415
+ // Prefer the socket for mutations; fall back to HTTP while disconnected.
416
+ const sendMutation = async (request: SyncMutateRequest): Promise<SendMutationResult> => {
417
+ if (connected || !httpChannel) {
418
+ return transport.sendMutation(request);
419
+ }
420
+ return httpChannel.sendMutation(request);
421
+ };
422
+
423
+ // B3: batched sends mirror the same socket-preferred/HTTP-fallback selection.
424
+ // Omitted entirely when neither channel supports batching, so the
425
+ // coordinator falls back to sendMutation for every send.
426
+ const sendMutationBatch =
427
+ transport.sendMutationBatch || httpChannel?.sendMutationBatch
428
+ ? async (request: SyncMutateBatchRequest): Promise<SendMutationBatchResult> => {
429
+ if ((connected || !httpChannel) && transport.sendMutationBatch) {
430
+ return transport.sendMutationBatch(request);
431
+ }
432
+ if (httpChannel?.sendMutationBatch) {
433
+ return httpChannel.sendMutationBatch(request);
434
+ }
435
+ return {type: "unsupported"};
436
+ }
437
+ : undefined;
438
+
439
+ const setAuthPaused = (value: boolean): void => {
440
+ if (authPaused === value) {
441
+ return;
442
+ }
443
+ authPaused = value;
444
+ refreshAttempted = false;
445
+ if (value) {
446
+ config.onAuthRequired?.();
447
+ // A4 step 5: every pause episode gets exactly one silent refresh attempt,
448
+ // wherever the auth failure was observed — a drain nack, a reconcile 401,
449
+ // or the server's session sweep (`sync:auth-expired`). Wiring it here
450
+ // (rather than per call site) is what makes that uniform; the early return
451
+ // above plus `refreshAttempted` keep it to one attempt per episode.
452
+ void attemptAuthRecovery();
453
+ }
454
+ notifyStatusChange();
455
+ };
456
+
457
+ const warn = (message: string): ((error: unknown) => void) => {
458
+ return (error: unknown): void => {
459
+ console.warn(`[syncdb] ${message}`, error);
460
+ };
461
+ };
462
+
463
+ const coordinator: ReplayCoordinator = createReplayCoordinator({
464
+ batchSize: config.batchSize,
465
+ debug: debugLog,
466
+ haltQueueOnConflict: config.haltQueueOnConflict,
467
+ now,
468
+ // Report the pause from the coordinator hook (not a replayOutbox()
469
+ // return-value check): drain-until-empty's internal recheck/wake-timer
470
+ // continuations can be the call that actually observes the auth failure,
471
+ // orphaned from whichever replayOutbox() wrapper kicked off the original
472
+ // drain. The silent-refresh attempt is triggered by setAuthPaused itself.
473
+ onAuthPause: () => {
474
+ setAuthPaused(true);
475
+ },
476
+ onDrainPass: ({userId}) => {
477
+ outbox.prune({userId});
478
+ },
479
+ onEntityReleasedWithoutServerAck: (mutation) => {
480
+ if (!httpChannel) {
481
+ return;
482
+ }
483
+ void repairMarkedEntities({
484
+ channel: httpChannel,
485
+ collection: mutation.collection,
486
+ entityIds: [mutation.entityId],
487
+ store,
488
+ }).catch(warn("entity repair failed"));
489
+ },
490
+ onProgress: () => {
491
+ // B5: drain progress (sentThisDrain/totalThisDrain) is exposed through
492
+ // getSyncStatus() — nudge status listeners so a progress UI re-renders
493
+ // as each chunk/mutation resolves, not just at the start/end of replay.
494
+ notifyStatusChange();
495
+ },
496
+ outbox,
497
+ random: config.random,
498
+ sendMutation,
499
+ sendMutationBatch,
500
+ // Internally-scheduled drains (armed wake-up timers, the mid-drain-enqueue
501
+ // recheck) must respect the same gating as an external replayOutbox()
502
+ // call: never send while simulated-offline or auth-paused.
503
+ shouldDrain: () => !simulatedOffline && !authPaused,
504
+ store,
505
+ });
506
+
507
+ /**
508
+ * C2: discover the streams the user currently belongs to (`GET /sync/streams`), then
509
+ * diff against the persisted `_knownStreams` set to detect joins and leaves.
510
+ *
511
+ * INV-2 (the whole ballgame): the leave-purge only runs when `fetchStreams` returned
512
+ * HTTP 200. A 401 (AuthRequiredError) or any transport error is NOT a membership
513
+ * change — it enters auth-pause (401) or is rethrown (transport) with every local
514
+ * entity, cursor, and known-stream entry left intact. Joins backfill from cursor 0;
515
+ * leaves purge that stream's local entities + cursor + known-stream entry.
516
+ *
517
+ * Returns the current membership set (stream → collection) on success so the caller
518
+ * can bootstrap each; returns `undefined` when auth-paused (no membership known).
519
+ */
520
+ const syncStreams = async ({
521
+ isSuperseded,
522
+ }: {
523
+ /**
524
+ * Optional lifecycle guard checked AFTER the network fetch resolves but BEFORE any
525
+ * store mutation. A fired-and-forgotten reconcile's `fetchStreams()` await can straddle
526
+ * a stop()/start() or different-user wipe; without this, the post-await store reads and
527
+ * purges/joins below run against the swapped-in store and can resurrect wiped rows via
528
+ * TinyBase's mergeable-schema re-materialization. Returns undefined when superseded.
529
+ */
530
+ isSuperseded?: () => boolean;
531
+ } = {}): Promise<Map<string, string> | undefined> => {
532
+ if (!httpChannel) {
533
+ // No HTTP channel: fall back to the configured collections' streams are unknown;
534
+ // bootstrap cannot run. Callers treat undefined as "skip stream sync".
535
+ return undefined;
536
+ }
537
+ let serverStreams: {stream: string; collection: string}[];
538
+ try {
539
+ serverStreams = await httpChannel.fetchStreams();
540
+ } catch (error) {
541
+ if (error instanceof AuthRequiredError) {
542
+ // INV-2: a 401 is NOT a leave. Pause; leave every stream/entity intact.
543
+ setAuthPaused(true);
544
+ return undefined;
545
+ }
546
+ // Transport error: also not a membership change — leave data intact, rethrow so
547
+ // the caller's catch handles retry/backoff.
548
+ throw error;
549
+ }
550
+ if (isSuperseded?.()) {
551
+ // A newer lifecycle/user took over during the fetch — do not touch the store.
552
+ return undefined;
553
+ }
554
+
555
+ // A backend can host more collections than this client is configured to sync
556
+ // (e.g. a tenant-scoped `projects` stream exposed to org members while this
557
+ // app only subscribes to `todos`). The socket path already filters deltas by
558
+ // `config.collections` via `transport.subscribe`; mirror that here so the
559
+ // discovery/bootstrap path never tries to write an unconfigured collection
560
+ // into the store (which would throw "Unknown collection" in the store's
561
+ // schema guard). Streams for unknown collections are simply ignored.
562
+ const configuredCollections = new Set(store.collections);
563
+ const serverSet = new Map<string, string>();
564
+ for (const {stream, collection} of serverStreams) {
565
+ if (!configuredCollections.has(collection)) {
566
+ debugLog?.record({
567
+ detail: {collection, stream},
568
+ direction: "system",
569
+ label: `stream skipped (unconfigured collection): ${stream}`,
570
+ type: "reconcile",
571
+ });
572
+ continue;
573
+ }
574
+ serverSet.set(stream, collection);
575
+ }
576
+ const known = new Set(store.getKnownStreams());
577
+
578
+ // Leaves: known locally but absent from the (HTTP-200) server set → purge.
579
+ for (const stream of known) {
580
+ if (!serverSet.has(stream)) {
581
+ const purged = store.purgeStream({stream});
582
+ debugLog?.record({
583
+ detail: {purged, stream},
584
+ direction: "system",
585
+ label: `stream leave: purged ${stream} (${purged} entities)`,
586
+ type: "reconcile",
587
+ });
588
+ }
589
+ }
590
+ // Joins: in the server set but not yet known → mark known (cursor 0 bootstrap follows).
591
+ for (const [stream, collection] of serverSet) {
592
+ if (!known.has(stream)) {
593
+ store.addKnownStream({collection, stream});
594
+ debugLog?.record({
595
+ detail: {collection, stream},
596
+ direction: "system",
597
+ label: `stream join: ${stream}`,
598
+ type: "reconcile",
599
+ });
600
+ }
601
+ }
602
+ return serverSet;
603
+ };
604
+
605
+ const runReconcile = async (): Promise<void> => {
606
+ // Simulated offline severs all network activity, including the HTTP
607
+ // channel; an auth pause stands down every network trigger (INV-2) until
608
+ // the same user re-authenticates.
609
+ if (!httpChannel || simulatedOffline || authPaused) {
610
+ return;
611
+ }
612
+ // E1 + C2: reconcile is fired-and-forgotten (startup, reconnect, periodic,
613
+ // post-auth) and its network awaits below can straddle a stop()/start() (bumps
614
+ // `generation`) or a different-user switch (changes `currentUserId` + swaps the
615
+ // persister, via runUserCheck). Capture both at entry and re-check after every await
616
+ // so a stale reconcile never writes discovered streams or snapshot pages into a store
617
+ // that now belongs to a different lifecycle or user — the resurrection bug where an
618
+ // in-flight reconcile for the previous user re-materialized purged rows after a wipe.
619
+ const myGeneration = generation;
620
+ const myUserId = currentUserId;
621
+ const isSuperseded = (): boolean => generation !== myGeneration || currentUserId !== myUserId;
622
+ addSyncing(1);
623
+ const startedAt = now();
624
+ debugLog?.record({
625
+ direction: "system",
626
+ label: "reconcile start",
627
+ phase: "start",
628
+ type: "reconcile",
629
+ });
630
+ try {
631
+ const streams = await syncStreams({isSuperseded});
632
+ if (!streams || isSuperseded()) {
633
+ // Auth-paused during discovery (401 → INV-2), or superseded by a newer
634
+ // lifecycle/user while awaiting discovery.
635
+ return;
636
+ }
637
+ for (const [stream, collection] of streams) {
638
+ await bootstrapStream({channel: httpChannel, collection, store, stream});
639
+ if (isSuperseded()) {
640
+ return;
641
+ }
642
+ }
643
+ // E5: client-side compaction runs only after a successful per-stream reconcile —
644
+ // reconcile just proved the local store caught up with the server via real network
645
+ // round trips (discovery + each stream), which is the signal that it is safe to age
646
+ // out old tombstones (never on a failed/incomplete reconcile).
647
+ const retentionMs = config.tombstoneRetentionMs ?? DEFAULT_TOMBSTONE_RETENTION_MS;
648
+ if (retentionMs > 0) {
649
+ // No explicit `now` override here — compactTombstones defaults to the same
650
+ // injected clock the store itself was created with above.
651
+ const {removed} = store.compactTombstones({olderThanMs: retentionMs});
652
+ if (removed > 0) {
653
+ debugLog?.record({
654
+ detail: {removed},
655
+ direction: "system",
656
+ label: `compacted ${removed} tombstone(s)`,
657
+ type: "reconcile",
658
+ });
659
+ }
660
+ }
661
+ await repairAllMarkedEntities();
662
+ } catch (error) {
663
+ if (error instanceof AuthRequiredError) {
664
+ setAuthPaused(true);
665
+ return;
666
+ }
667
+ throw error;
668
+ } finally {
669
+ addSyncing(-1);
670
+ debugLog?.record({
671
+ direction: "system",
672
+ durationMs: now() - startedAt,
673
+ label: "reconcile end",
674
+ phase: "end",
675
+ type: "reconcile",
676
+ });
677
+ }
678
+ };
679
+
680
+ /**
681
+ * Coalesce concurrent reconcile triggers into one pass, the way the replay
682
+ * coordinator coalesces drains: startup, transport reconnect, the periodic timer, a
683
+ * rate-limited seq-jump hint, and the post-auth resume all fire independently, and
684
+ * each pass is a full stream discovery plus snapshot paging for every stream.
685
+ * Tagged with the lifecycle generation and user it belongs to, so a caller arriving
686
+ * after a stop()/start() or a user switch starts a fresh pass instead of awaiting
687
+ * one that is about to abort as superseded.
688
+ */
689
+ const reconcile = (): Promise<void> => {
690
+ const existing = inFlightReconcile;
691
+ if (existing && existing.generation === generation && existing.userId === currentUserId) {
692
+ // Joining a pass already past its discovery step can miss a stream that
693
+ // appeared moments ago; the next trigger (the periodic timer at the latest)
694
+ // catches it, and every apply is cursor-guarded and idempotent, so sharing a
695
+ // pass only ever costs latency, never convergence.
696
+ return existing.promise;
697
+ }
698
+ const promise = runReconcile().finally(() => {
699
+ if (inFlightReconcile?.promise === promise) {
700
+ inFlightReconcile = undefined;
701
+ }
702
+ });
703
+ inFlightReconcile = {generation, promise, userId: currentUserId};
704
+ return promise;
705
+ };
706
+
707
+ /**
708
+ * C2 migration: deployed clients hold legacy `snapshot:{collection}` pseudo-cursors.
709
+ * On start, delete all of them and clear `_knownStreams` so the normal discovery path
710
+ * re-bootstraps every stream from cursor 0. Idempotent upserts + seq guards make
711
+ * re-bootstrap cheap and non-destructive (existing entities keep their data). Runs once.
712
+ *
713
+ * NOTE (Phase E merge): Phase E is adding the schema-version wipe machinery in the main
714
+ * worktree. Ideally this migration gates behind that version bump so it runs exactly
715
+ * once. That hook does not exist in this worktree, so this implements the minimal
716
+ * standalone cursor-migration path — it is self-idempotent (after the first run there
717
+ * are no `snapshot:` keys left, so subsequent runs are no-ops). When merging, this can
718
+ * be moved behind the E2 version bump.
719
+ */
720
+ const migrateLegacySnapshotCursors = (): void => {
721
+ const cursorRows = store.raw.getTable(CURSORS_TABLE);
722
+ let migrated = 0;
723
+ for (const key of Object.keys(cursorRows)) {
724
+ if (key.startsWith("snapshot:")) {
725
+ store.raw.delRow(CURSORS_TABLE, key);
726
+ migrated += 1;
727
+ }
728
+ }
729
+ if (migrated > 0) {
730
+ // Clear the known-streams set so discovery re-bootstraps every stream from 0.
731
+ for (const stream of store.getKnownStreams()) {
732
+ store.removeKnownStream({stream});
733
+ }
734
+ debugLog?.record({
735
+ detail: {migrated},
736
+ direction: "system",
737
+ label: `migrated ${migrated} legacy snapshot cursors`,
738
+ type: "reconcile",
739
+ });
740
+ }
741
+ };
742
+
743
+ const repairAllMarkedEntities = async (): Promise<number> => {
744
+ if (!httpChannel) {
745
+ return 0;
746
+ }
747
+ const byCollection = new Map<string, string[]>();
748
+ for (const row of store.listNeedsRepair()) {
749
+ const ids = byCollection.get(row.collection) ?? [];
750
+ ids.push(row.entityId);
751
+ byCollection.set(row.collection, ids);
752
+ }
753
+ let repaired = 0;
754
+ for (const [collection, entityIds] of byCollection) {
755
+ repaired += await repairMarkedEntities({channel: httpChannel, collection, entityIds, store});
756
+ }
757
+ return repaired;
758
+ };
759
+
760
+ const forceResync = async (): Promise<ForceResyncResult> => {
761
+ const skip = (reason: ForceResyncSkipReason): ForceResyncResult => {
762
+ debugLog?.record({
763
+ detail: {reason},
764
+ direction: "system",
765
+ label: `force resync skipped (${reason})`,
766
+ type: "reconcile",
767
+ });
768
+ return {ok: false, purged: 0, reason, repaired: 0, streams: 0};
769
+ };
770
+ if (!httpChannel) {
771
+ return skip("noHttpChannel");
772
+ }
773
+ if (simulatedOffline) {
774
+ return skip("offline");
775
+ }
776
+ if (authPaused) {
777
+ return skip("authPaused");
778
+ }
779
+ const myGeneration = generation;
780
+ const myUserId = currentUserId;
781
+ const isSuperseded = (): boolean => generation !== myGeneration || currentUserId !== myUserId;
782
+ addSyncing(1);
783
+ const startedAt = now();
784
+ debugLog?.record({
785
+ direction: "system",
786
+ label: "force resync start",
787
+ phase: "start",
788
+ type: "reconcile",
789
+ });
790
+ let purged = 0;
791
+ let repaired = 0;
792
+ let streamInfos: Array<{stream: string; collection: string}> = [];
793
+ try {
794
+ // Always re-discover membership: a stale local `_knownStreams` set is one of
795
+ // the ways a device diverges in the first place, so it cannot be trusted as
796
+ // the authoritative list for a repair operation.
797
+ const streams = await syncStreams({isSuperseded});
798
+ if (isSuperseded()) {
799
+ return skip("superseded");
800
+ }
801
+ if (streams) {
802
+ streamInfos = [...streams].map(([stream, collection]) => ({collection, stream}));
803
+ }
804
+ if (streamInfos.length === 0) {
805
+ for (const stream of store.getKnownStreams()) {
806
+ const row = store.raw.getRow(KNOWN_STREAMS_TABLE, stream) as {collection?: string};
807
+ if (row?.collection) {
808
+ streamInfos.push({collection: row.collection, stream});
809
+ }
810
+ }
811
+ }
812
+ if (streamInfos.length === 0) {
813
+ return skip("noStreams");
814
+ }
815
+ // Drop rows with no stream provenance once per collection: phantoms from
816
+ // locally-failed creates carry `stream: ""`, so a per-stream purge alone
817
+ // leaves them behind and re-bootstrap cannot remove them (the server never
818
+ // had them). Rows still protected by a pending mutation are preserved.
819
+ for (const collection of new Set(streamInfos.map((info) => info.collection))) {
820
+ purged += store.purgeUnknownStreamEntities({collection});
821
+ }
822
+ for (const {stream, collection} of streamInfos) {
823
+ purged += store.purgeStream({stream});
824
+ store.addKnownStream({collection, stream});
825
+ await bootstrapStream({channel: httpChannel, collection, store, stream});
826
+ if (isSuperseded()) {
827
+ return {ok: false, purged, reason: "superseded", repaired, streams: streamInfos.length};
828
+ }
829
+ }
830
+ repaired = await repairAllMarkedEntities();
831
+ return {ok: true, purged, repaired, streams: streamInfos.length};
832
+ } catch (error) {
833
+ if (error instanceof AuthRequiredError) {
834
+ setAuthPaused(true);
835
+ return {ok: false, purged, reason: "authPaused", repaired, streams: streamInfos.length};
836
+ }
837
+ throw error;
838
+ } finally {
839
+ addSyncing(-1);
840
+ debugLog?.record({
841
+ detail: {purged, repaired, streams: streamInfos.length},
842
+ direction: "system",
843
+ durationMs: now() - startedAt,
844
+ label: `force resync end (${streamInfos.length} streams, ${purged} purged, ${repaired} repaired)`,
845
+ phase: "end",
846
+ type: "reconcile",
847
+ });
848
+ }
849
+ };
850
+
851
+ const replayOutbox = async (): Promise<void> => {
852
+ // While simulated-offline or auth-paused, mutations stay queued in the
853
+ // durable outbox (INV-2: an auth pause stands down replay until the same
854
+ // user re-authenticates).
855
+ if (!currentUserId || simulatedOffline || authPaused) {
856
+ return;
857
+ }
858
+ addSyncing(1);
859
+ const startedAt = now();
860
+ // A3: this listQueued scan exists purely to label a debug event — never
861
+ // pay for it when debug logging is disabled (the common case).
862
+ if (debugLog) {
863
+ const queued = outbox.listQueued({userId: currentUserId}).length;
864
+ debugLog.record({
865
+ detail: {queued},
866
+ direction: "system",
867
+ label: `replay start (${queued} queued)`,
868
+ phase: "start",
869
+ type: "replay",
870
+ });
871
+ }
872
+ try {
873
+ // Auth-pause recovery (the one-shot silent refresh) is wired through
874
+ // the coordinator's onAuthPause hook, not this return value — it fires
875
+ // reliably regardless of which internal call (this one, the wake
876
+ // timer, or the mid-drain recheck) is the one that actually observes
877
+ // the auth failure.
878
+ await coordinator.replay({userId: currentUserId});
879
+ } finally {
880
+ addSyncing(-1);
881
+ debugLog?.record({
882
+ direction: "system",
883
+ durationMs: now() - startedAt,
884
+ label: "replay end",
885
+ phase: "end",
886
+ type: "replay",
887
+ });
888
+ }
889
+ };
890
+
891
+ /**
892
+ * Give the auth adapter one chance to silently refresh before the pause is
893
+ * fully surfaced to the app (A4 step 5). Runs at most once per pause
894
+ * episode; a successful refresh immediately retries replay.
895
+ */
896
+ const attemptAuthRecovery = async (): Promise<void> => {
897
+ if (refreshAttempted || !config.authProvider.refresh) {
898
+ return;
899
+ }
900
+ if (!currentUserId) {
901
+ // An explicit logout (the auth provider reporting no user) is not an
902
+ // expired session: there is nothing to refresh silently, and a refresh
903
+ // that did succeed could only resolve some OTHER user's session, which the
904
+ // INV-2 check below would reject anyway.
905
+ return;
906
+ }
907
+ refreshAttempted = true;
908
+ try {
909
+ const refreshed = await config.authProvider.refresh();
910
+ if (!refreshed || !authPaused) {
911
+ return;
912
+ }
913
+ // INV-2: a successful refresh does NOT prove the session still belongs to
914
+ // the paused user — another tab may have signed a different user in while
915
+ // this client was paused. Unpausing then would drain the previous user's
916
+ // outbox under the new user's identity. Stay paused and let
917
+ // handleAuthChange's different-user path wipe and bounce instead.
918
+ const refreshedUserId = await config.authProvider.getUserId();
919
+ if (!refreshedUserId || refreshedUserId !== currentUserId) {
920
+ debugLog?.record({
921
+ detail: {currentUserId, refreshedUserId},
922
+ direction: "system",
923
+ label: "auth refresh resolved a different user; staying paused",
924
+ type: "connect",
925
+ });
926
+ return;
927
+ }
928
+ setAuthPaused(false);
929
+ void replayOutbox().catch(warn("post-refresh replay failed"));
930
+ } catch (error) {
931
+ warn("auth refresh attempt failed")(error);
932
+ }
933
+ };
934
+
935
+ /**
936
+ * E3(c): the web factory (`persisters/defaultPersisterFactory.web.ts`) falls
937
+ * back to the in-memory persister when `globalThis.indexedDB` is absent
938
+ * (private browsing / a locked-down embedded webview), emitting a one-time
939
+ * console.warn. That fallback is invisible to the caller unless it inspects
940
+ * the returned persister — surface it on the client's status instead so a
941
+ * host app can tell durable persistence apart from a session that silently
942
+ * never survives reload. Defaults to "durable"; a persister factory may
943
+ * report "memory" via `persister.persistenceMode` (see
944
+ * `defaultPersisterFactory.web.ts`), and a load failure (E3a) downgrades to
945
+ * "error" for the remainder of the session.
946
+ */
947
+ let persistenceMode: "durable" | "memory" | "error" = "durable";
948
+
949
+ const createAndStartPersister = async (userId: string): Promise<void> => {
950
+ // Reset per-call: a fresh persister/load attempt starts optimistic even
951
+ // if a PRIOR persister instance (e.g. before a wipe-and-rebuild) had
952
+ // flagged a load failure.
953
+ persistenceMode = "durable";
954
+ // Default key provider is SERVER-DERIVED (HKDF over GET /sync/key material) so the
955
+ // server can rotate/revoke; pass keyProvider: createLocalKeyProvider() for a purely
956
+ // device-local key with no server-side copy of the material.
957
+ const keyProvider =
958
+ config.keyProvider ??
959
+ (httpChannel
960
+ ? createServerKeyProvider({
961
+ appName: config.name,
962
+ fetchKeyMaterial: httpChannel.fetchKeyMaterial,
963
+ })
964
+ : undefined);
965
+ // E3(b): decrypt/corrupt-data failures wipe + re-bootstrap by default
966
+ // (documented behavior) unless the host app overrides via
967
+ // `config.onDecryptFailure`. Either way it always warns.
968
+ const onDecryptFailure = (): void => {
969
+ console.warn(
970
+ `[syncdb] persisted data for "${config.name}" could not be decrypted; wiping and re-bootstrapping`
971
+ );
972
+ if (config.onDecryptFailure) {
973
+ config.onDecryptFailure();
974
+ return;
975
+ }
976
+ void wipeAndRebootstrap(userId).catch(warn("post-decrypt-failure wipe/rebootstrap failed"));
977
+ };
978
+ // E3(a): a read ERROR (not "no data") must never be treated as a fresh
979
+ // store — flag it so the caller skips autosave (which would otherwise
980
+ // overwrite the still-good persisted blob with an empty in-memory store).
981
+ const onLoadFailure = (): void => {
982
+ persistenceMode = "error";
983
+ console.warn(
984
+ `[syncdb] failed to read persisted data for "${config.name}"; leaving the stored snapshot untouched this session`
985
+ );
986
+ notifyStatusChange();
987
+ };
988
+ // E3(a): a save (write) failure — e.g. IndexedDB quota exceeded — is
989
+ // surfaced the same way: local writes are no longer reliably durable this
990
+ // session, so the host app should warn the user rather than silently
991
+ // losing data. Unlike a load failure this does NOT skip future save
992
+ // attempts (a transient quota issue may clear once the user frees space).
993
+ const onSaveFailure = (error: unknown): void => {
994
+ persistenceMode = "error";
995
+ console.warn(`[syncdb] failed to persist local data for "${config.name}"`, error);
996
+ notifyStatusChange();
997
+ };
998
+ const factory =
999
+ config.persisterFactory ??
1000
+ createDefaultPersisterFactory({
1001
+ idbGetImpl: config.idbGetImpl,
1002
+ idbSetImpl: config.idbSetImpl,
1003
+ keyProvider,
1004
+ onDecryptFailure,
1005
+ onLoadFailure,
1006
+ onSaveFailure,
1007
+ userId,
1008
+ });
1009
+ // `hooks` is always passed (even to a custom persisterFactory) so a host
1010
+ // app supplying its own storage backend can still opt into E3 SyncStatus
1011
+ // surfacing; the default factory already received the same callbacks
1012
+ // above (at creation time) and ignores this second copy.
1013
+ persister = factory({
1014
+ databaseName: config.name,
1015
+ hooks: {onDecryptFailure, onLoadFailure, onSaveFailure},
1016
+ store: store.raw,
1017
+ });
1018
+ await persister.startAutoLoad();
1019
+ // Read through a function call: `onLoadFailure` (invoked synchronously
1020
+ // from inside `startAutoLoad()`, not after it returns) mutates
1021
+ // `persistenceMode` by closure, which TypeScript's control-flow narrowing
1022
+ // cannot see across the awaited call above — without this indirection it
1023
+ // would (wrongly) treat the "durable" assignment at the top of this
1024
+ // function as still in effect here.
1025
+ const getPersistenceMode = (): typeof persistenceMode => persistenceMode;
1026
+ if (getPersistenceMode() === "error") {
1027
+ // Do NOT startAutoSave(): the in-memory store is empty (load bailed out
1028
+ // before touching it) and autosaving now would clobber the real blob.
1029
+ return;
1030
+ }
1031
+ // E3(c): the web factory tags its returned persister with a
1032
+ // `persistenceMode` marker when it fell back to in-memory (no
1033
+ // globalThis.indexedDB) — surface that on SyncStatus.
1034
+ const reportedMode = (persister as AnyPersister & {persistenceMode?: "durable" | "memory"})
1035
+ .persistenceMode;
1036
+ if (reportedMode === "memory") {
1037
+ persistenceMode = "memory";
1038
+ notifyStatusChange();
1039
+ }
1040
+ await persister.startAutoSave();
1041
+ };
1042
+
1043
+ /**
1044
+ * Sanctioned wipe + fresh start for `userId`: clears every local table and
1045
+ * the persisted databases (including cached encryption keys — E3f), stamps
1046
+ * the current schema version and userId on the now-empty store, rebuilds
1047
+ * the persister, and — when an HTTP channel is available — runs a full
1048
+ * snapshot re-bootstrap so the app is immediately usable again rather than
1049
+ * waiting for the next reconcile trigger. Shared by the E2 schema-mismatch
1050
+ * path and the E3(b) decrypt-failure default handler; NOT used for the
1051
+ * different-user wipe (that path's re-bootstrap comes from the caller's own
1052
+ * subsequent reconcile()/replayOutbox() calls, matching pre-E2 behavior).
1053
+ */
1054
+ const wipeAndRebootstrap = async (userId: string): Promise<void> => {
1055
+ coordinator.reset();
1056
+ await wipeLocalData({
1057
+ databaseNames: [config.name],
1058
+ keyCacheDbNames: [DEFAULT_KEY_CACHE_DB_NAME],
1059
+ persister,
1060
+ store,
1061
+ });
1062
+ lastSeqJumpReconcileAt.clear();
1063
+ persistenceMode = "durable";
1064
+ await createAndStartPersister(userId);
1065
+ store.raw.setValue("schemaVersion", SYNC_SCHEMA_VERSION);
1066
+ store.setLastUserId({userId});
1067
+ currentUserId = userId;
1068
+ if (httpChannel) {
1069
+ // C2: after a wipe the known-streams set is empty, so discover the user's current
1070
+ // stream membership and bootstrap each from cursor 0. syncStreams() handles the
1071
+ // INV-2 auth-pause case (returns undefined on a 401) — skip bootstrap then.
1072
+ const streams = await syncStreams();
1073
+ if (streams) {
1074
+ for (const [stream, collection] of streams) {
1075
+ await bootstrapStream({channel: httpChannel, collection, store, stream});
1076
+ }
1077
+ }
1078
+ }
1079
+ };
1080
+
1081
+ /**
1082
+ * Wipe-on-user-change: when the persisted `lastUserId` differs from the
1083
+ * authenticated user, destroy all local data (entities, outbox, cursors,
1084
+ * conflicts, persisted databases) and start fresh for the new user.
1085
+ *
1086
+ * E2: also checked here (after the persister's autoload has populated the
1087
+ * store from disk) is the persisted schema version — a mismatch is a
1088
+ * sanctioned wipe (schema migration, not an auth event) distinct from the
1089
+ * user-change wipe above, so it runs regardless of whether the user changed.
1090
+ *
1091
+ * Reports whether the wipe-on-user-change branch ran so the caller can bounce
1092
+ * the transport for the new identity (9.4).
1093
+ */
1094
+ const runUserCheck = async (userId: string): Promise<{userChanged: boolean}> => {
1095
+ const lastUserId = store.getLastUserId();
1096
+ const userChanged = lastUserId !== undefined && lastUserId !== userId;
1097
+ if (userChanged) {
1098
+ // FIX 3: a different-user login must not let the PREVIOUS user's
1099
+ // in-memory coordinator state (validationBlockedEntities keyed
1100
+ // user-scoped, retry/backoff bookkeeping, the batch-capability latch,
1101
+ // armed timers) leak into the new user's session — reset before the
1102
+ // new user's persister/outbox come online.
1103
+ coordinator.reset();
1104
+ // E3(f): also clear the cached derived encryption key for the key-cache
1105
+ // database — the same rationale as wiping local data: nothing from the
1106
+ // previous user's session should linger once a different user has
1107
+ // authenticated (the new user's persister derives/caches its own key
1108
+ // fresh via createAndStartPersister below).
1109
+ await wipeLocalData({
1110
+ databaseNames: [config.name],
1111
+ keyCacheDbNames: [DEFAULT_KEY_CACHE_DB_NAME],
1112
+ persister,
1113
+ store,
1114
+ });
1115
+ lastSeqJumpReconcileAt.clear();
1116
+ await createAndStartPersister(userId);
1117
+ }
1118
+ // E2: schema version check. `getSchemaVersion()` reads the persisted
1119
+ // value with a same-as-current default (so a genuinely fresh store never
1120
+ // trips this), meaning a real mismatch can only come from a persisted
1121
+ // store written under an OLDER `SYNC_SCHEMA_VERSION`. Always stamp the
1122
+ // current version afterward so a fresh store (and one just wiped above)
1123
+ // is never mistaken for stale on the next start().
1124
+ const persistedVersion = store.getSchemaVersion();
1125
+ if (persistedVersion !== SYNC_SCHEMA_VERSION) {
1126
+ await wipeAndRebootstrap(userId);
1127
+ return {userChanged};
1128
+ }
1129
+ store.raw.setValue("schemaVersion", SYNC_SCHEMA_VERSION);
1130
+ store.setLastUserId({userId});
1131
+ currentUserId = userId;
1132
+ return {userChanged};
1133
+ };
1134
+
1135
+ const handleDelta = (delta: SyncDelta): void => {
1136
+ const {seqJump, applied} = applyDelta({delta, store});
1137
+ debugLog?.record({
1138
+ collection: delta.collection,
1139
+ detail: {applied, data: delta.data, deleted: delta.deleted === true, seqJump},
1140
+ direction: "inbound",
1141
+ entityId: delta.id,
1142
+ label: `delta ${delta.method} ${delta.collection}/${delta.id} @${delta.seq}`,
1143
+ operation: delta.method,
1144
+ seq: delta.seq,
1145
+ stream: delta.stream,
1146
+ type: "delta",
1147
+ });
1148
+ if (!seqJump) {
1149
+ return;
1150
+ }
1151
+ // Seq jumps are hints, not proofs (permission-filtered deltas legitimately
1152
+ // skip seqs) — rate-limit the reconcile per stream.
1153
+ const minInterval =
1154
+ config.seqJumpReconcileMinIntervalMs ?? DEFAULT_SEQ_JUMP_RECONCILE_MIN_INTERVAL_MS;
1155
+ const last = lastSeqJumpReconcileAt.get(delta.stream);
1156
+ if (last !== undefined && now() - last < minInterval) {
1157
+ return;
1158
+ }
1159
+ lastSeqJumpReconcileAt.set(delta.stream, now());
1160
+ void reconcile().catch(warn("seq-jump reconcile failed"));
1161
+ };
1162
+
1163
+ /**
1164
+ * (Re)bind the delta handler under the CURRENT connection epoch, dropping any
1165
+ * previous binding. The bound closure compares its captured epoch against the
1166
+ * live one, so a delta delivered through a transport whose listener set
1167
+ * survives reconnects (the socket transport keeps one set for the lifetime of
1168
+ * the client) is ignored once a user-switch bounce has moved the epoch on.
1169
+ */
1170
+ const bindDeltaHandler = (): void => {
1171
+ const myEpoch = connectionEpoch;
1172
+ const unbindPrevious = unbindDeltaHandler;
1173
+ unbindDeltaHandler = transport.onDelta((delta: SyncDelta): void => {
1174
+ if (myEpoch !== connectionEpoch) {
1175
+ // A stale connection's delta arriving after a bounce for a new user.
1176
+ return;
1177
+ }
1178
+ handleDelta(delta);
1179
+ });
1180
+ unbindPrevious?.();
1181
+ };
1182
+
1183
+ /**
1184
+ * Re-handshake the transport for the currently-resolved user: invalidate the
1185
+ * old connection's deltas, disconnect, reconnect, and resubscribe. Called only
1186
+ * on a confirmed identity change (never on a same-user re-auth, which must
1187
+ * keep the live socket). Resolves even when the reconnect fails — local-first:
1188
+ * the transport's own background reconnection surfaces a later success.
1189
+ */
1190
+ const bounceTransport = async (): Promise<void> => {
1191
+ connectionEpoch += 1;
1192
+ transport.disconnect();
1193
+ setConnected(false);
1194
+ if (simulatedOffline) {
1195
+ // A simulated outage owns connectivity; rebind so deltas land again after
1196
+ // goOnline() without reconnecting behind the caller's back here.
1197
+ bindDeltaHandler();
1198
+ return;
1199
+ }
1200
+ try {
1201
+ await transport.connect();
1202
+ } catch (error) {
1203
+ warn("transport reconnect after user change failed; continuing offline")(error);
1204
+ }
1205
+ bindDeltaHandler();
1206
+ transport.subscribe(config.collections);
1207
+ };
1208
+
1209
+ const handleStatusChange = ({
1210
+ connected: isConnected,
1211
+ authExpired,
1212
+ }: {
1213
+ connected: boolean;
1214
+ authExpired?: boolean;
1215
+ }): void => {
1216
+ setConnected(isConnected);
1217
+ if (!isConnected) {
1218
+ // D1: the server's session re-validation sweep disconnected this socket
1219
+ // (sync:auth-expired). Map straight into the existing A4 auth-pause path —
1220
+ // INV-2: no wipe, outbox untouched, zero retry budget consumed. The
1221
+ // reconnect attempt Socket.io makes on its own will keep failing the
1222
+ // handshake with the same expired/invalid credentials until the host app
1223
+ // re-authenticates (handleAuthChange clears the pause on same-user re-auth).
1224
+ if (authExpired) {
1225
+ setAuthPaused(true);
1226
+ }
1227
+ return;
1228
+ }
1229
+ // B3: re-probe batch support on every reconnect — a previous
1230
+ // `batchUnsupported` determination may have been against an old server
1231
+ // that has since been upgraded, or the reconnect landed on a different
1232
+ // instance behind a load balancer.
1233
+ coordinator.notifyReconnect();
1234
+ void reconcile().catch(warn("reconnect reconcile failed"));
1235
+ void replayOutbox().catch(warn("reconnect replay failed"));
1236
+ };
1237
+
1238
+ /**
1239
+ * E1: `handleAuthChange` goes through the SAME lifecycle mutex as
1240
+ * `start`/`stop` — it mutates the same shared state (`currentUserId`,
1241
+ * `persister` via `runUserCheck`) that a concurrent stop()/start() would.
1242
+ * Queuing it here means a rapid stop()-then-start() for a new user can
1243
+ * never interleave with an in-flight auth-change handler from the OLD
1244
+ * user's session; whichever queued first fully completes before the next
1245
+ * runs. The generation check additionally covers the case where THIS
1246
+ * handler itself is stale — e.g. it was queued behind a stop() while
1247
+ * `getUserId()` resolves, and by the time it runs a fresh generation has
1248
+ * already started up for a different user.
1249
+ */
1250
+ const handleAuthChange = (): void => {
1251
+ void withLifecycle(async (): Promise<void> => {
1252
+ const myGeneration = generation;
1253
+ const userId = await config.authProvider.getUserId();
1254
+ if (generation !== myGeneration) {
1255
+ // Superseded by a stop()/start() while awaiting the auth provider —
1256
+ // that operation now owns currentUserId/persister; do nothing.
1257
+ return;
1258
+ }
1259
+ if (!userId) {
1260
+ // Logged out: NEVER wipe (INV-2). Keep all local data, clear the
1261
+ // current-user pointer (mutate() requires start() again), and remain
1262
+ // paused — reconcile/replay stand down until the same user (or a
1263
+ // different one, via the wipe path below) re-authenticates.
1264
+ currentUserId = undefined;
1265
+ // 9.4: drop the socket — its handshake credentials belong to a session
1266
+ // that no longer exists, and anything it still pushes must not be
1267
+ // applied. No reconnect: the next authenticated auth change owns that.
1268
+ connectionEpoch += 1;
1269
+ transport.disconnect();
1270
+ setConnected(false);
1271
+ setAuthPaused(true);
1272
+ return;
1273
+ }
1274
+ if (userId === currentUserId) {
1275
+ // Same-user re-auth: the pause (if any) clears fully and replay
1276
+ // resumes with the outbox completely intact. The live socket already
1277
+ // authenticated as this same identity, so it is deliberately NOT
1278
+ // bounced — a reconnect here would drop deltas for no reason.
1279
+ setAuthPaused(false);
1280
+ void replayOutbox().catch(warn("post-auth replay failed"));
1281
+ return;
1282
+ }
1283
+ // Different userId: existing wipe-on-user-change behavior, or a first
1284
+ // login after a logout (currentUserId undefined) — either way this is a
1285
+ // confirmed identity change, never inferred from a bare 401.
1286
+ await runUserCheck(userId);
1287
+ if (generation !== myGeneration) {
1288
+ return;
1289
+ }
1290
+ // 9.4: the connection (and its per-connection server-side subscriptions)
1291
+ // was authenticated as the PREVIOUS identity — or was dropped by the
1292
+ // logout branch above — so re-handshake before any sync work resumes.
1293
+ await bounceTransport();
1294
+ if (generation !== myGeneration) {
1295
+ return;
1296
+ }
1297
+ setAuthPaused(false);
1298
+ void reconcile().catch(warn("post-auth reconcile failed"));
1299
+ void replayOutbox().catch(warn("post-auth replay failed"));
1300
+ }).catch(warn("auth change handling failed"));
1301
+ };
1302
+
1303
+ const startReconcileTimer = (): void => {
1304
+ const interval = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
1305
+ if (interval <= 0) {
1306
+ return;
1307
+ }
1308
+ reconcileTimer = setInterval(() => {
1309
+ void reconcile().catch(warn("periodic reconcile failed"));
1310
+ void replayOutbox().catch(warn("periodic replay failed"));
1311
+ }, interval);
1312
+ };
1313
+
1314
+ const stopReconcileTimer = (): void => {
1315
+ if (reconcileTimer !== undefined) {
1316
+ clearInterval(reconcileTimer);
1317
+ reconcileTimer = undefined;
1318
+ }
1319
+ };
1320
+
1321
+ /**
1322
+ * E1: lifecycle serialization. `start`/`stop` both queue through the same
1323
+ * `lifecycle` mutex as `handleAuthChange`, so at most one of these ever
1324
+ * runs at a time, in call order — the bug this fixes was a `stop()`
1325
+ * re-reading the module-level `persister` after awaiting a debounced
1326
+ * `save()`, by which point an interleaved `start()` for a new user had
1327
+ * already replaced it, destroying the NEW user's persister instead of the
1328
+ * old one. On top of mutual exclusion, every operation captures its own
1329
+ * `myGeneration` and re-checks `generation === myGeneration` after each
1330
+ * `await` — belt-and-suspenders against any future call site that manages
1331
+ * to bypass the mutex (e.g. a direct call from a test), and cheap enough to
1332
+ * always do.
1333
+ */
1334
+ const start = async (): Promise<void> =>
1335
+ withLifecycle(async (): Promise<void> => {
1336
+ if (isStarted) {
1337
+ // E1: double-start() is a no-op rather than a second full
1338
+ // initialization — calling start() again would double-register the
1339
+ // transport/auth-change listeners and leak a second reconcile timer.
1340
+ // A caller that wants a hard restart should stop() first.
1341
+ return;
1342
+ }
1343
+ generation += 1;
1344
+ const myGeneration = generation;
1345
+ const authRetryAttempts = Math.max(
1346
+ 1,
1347
+ config.startAuthRetryAttempts ?? DEFAULT_START_AUTH_RETRY_ATTEMPTS
1348
+ );
1349
+ const authRetryDelayMs = config.startAuthRetryDelayMs ?? DEFAULT_START_AUTH_RETRY_DELAY_MS;
1350
+ let userId: string | null = null;
1351
+ for (let attempt = 1; attempt <= authRetryAttempts; attempt += 1) {
1352
+ userId = await config.authProvider.getUserId();
1353
+ if (userId || attempt === authRetryAttempts) {
1354
+ break;
1355
+ }
1356
+ await sleep(authRetryDelayMs);
1357
+ if (generation !== myGeneration) {
1358
+ // A stop() (or another start()) ran while we were retrying auth
1359
+ // resolution — abandon this attempt, see the generation check below.
1360
+ return;
1361
+ }
1362
+ }
1363
+ if (!userId) {
1364
+ throw new Error("createSyncDb.start() requires an authenticated user");
1365
+ }
1366
+ if (generation !== myGeneration) {
1367
+ // A stop() (or another start()) ran while awaiting the auth
1368
+ // provider — that operation now owns the lifecycle; abandon this one
1369
+ // rather than initializing state a newer generation doesn't expect.
1370
+ return;
1371
+ }
1372
+ simulatedOffline = false;
1373
+ setAuthPaused(false);
1374
+ // Re-open the cross-window debug bridge a previous stop()/signOut() closed.
1375
+ attachDebugBridge();
1376
+ await createAndStartPersister(userId);
1377
+ if (generation !== myGeneration) {
1378
+ return;
1379
+ }
1380
+ const {userChanged} = await runUserCheck(userId);
1381
+ if (generation !== myGeneration) {
1382
+ return;
1383
+ }
1384
+ if (userChanged) {
1385
+ // 9.4: a different user's data was just wiped — invalidate any live
1386
+ // connection authenticated as that user (and its deltas) before the
1387
+ // connect below re-handshakes as the new one.
1388
+ connectionEpoch += 1;
1389
+ transport.disconnect();
1390
+ setConnected(false);
1391
+ }
1392
+
1393
+ // C2: migrate any legacy snapshot:{collection} cursors before the first discovery
1394
+ // so the per-stream bootstrap path starts from a clean cursor set. This is a cheap,
1395
+ // idempotent fast-path — Phase E's schema-version wipe (runUserCheck ->
1396
+ // wipeAndRebootstrap) already re-bootstraps any store still on v1, so in practice no
1397
+ // v2 store carries legacy `snapshot:` cursors. Kept because it costs one table scan
1398
+ // and lets a v2-with-legacy-cursors store (which should not exist) recover without a
1399
+ // full wipe; after the first run there are no `snapshot:` keys left, so it no-ops.
1400
+ migrateLegacySnapshotCursors();
1401
+
1402
+ // A1: startup crash recovery, before the first replayOutbox() — repair
1403
+ // any outbox rows stranded mid-lifecycle by a prior crash/reload (inFlight
1404
+ // never resolved, acked-with-still-pending entity, conflicted with no
1405
+ // conflict row written).
1406
+ const recovery = outbox.recoverStartupState({userId});
1407
+ // Clear husk conflict rows a pre-fix build left behind (see
1408
+ // pruneGhostConflicts) before recovery's counts are reported, so a store
1409
+ // carrying them recovers without a wipe.
1410
+ const prunedConflicts = pruneGhostConflicts({store});
1411
+ debugLog?.record({
1412
+ detail: {...recovery, prunedConflicts},
1413
+ direction: "system",
1414
+ label: `startup recovery (${recovery.recoveredInFlight.length} inFlight, ${recovery.releasedEntities.length} released, ${recovery.clearedOrphanPendings.length} orphan pendings cleared, ${recovery.repairedConflicts.length} conflicts repaired, ${prunedConflicts.length} husk conflicts pruned)`,
1415
+ type: "reconcile",
1416
+ });
1417
+
1418
+ bindDeltaHandler();
1419
+ unsubscribers.push((): void => {
1420
+ unbindDeltaHandler?.();
1421
+ unbindDeltaHandler = undefined;
1422
+ });
1423
+ unsubscribers.push(transport.onStatusChange(handleStatusChange));
1424
+ unsubscribers.push(config.authProvider.onAuthChange(handleAuthChange));
1425
+
1426
+ try {
1427
+ await transport.connect();
1428
+ } catch (error) {
1429
+ // Local-first: start succeeds offline; reconnection/status events pick
1430
+ // up syncing when connectivity returns.
1431
+ warn("transport connect failed; starting offline")(error);
1432
+ }
1433
+ if (generation !== myGeneration) {
1434
+ return;
1435
+ }
1436
+ transport.subscribe(config.collections);
1437
+ // C2: run an initial stream discovery + per-stream bootstrap on start (not only via
1438
+ // the reconnect status event) so a client that starts offline-then-online, or with a
1439
+ // warm socket, still backfills newly-joined streams and drains legacy cursors.
1440
+ void reconcile().catch(warn("startup reconcile failed"));
1441
+ startReconcileTimer();
1442
+ isStarted = true;
1443
+ void replayOutbox().catch(warn("startup replay failed"));
1444
+ });
1445
+
1446
+ const stop = async (): Promise<void> =>
1447
+ withLifecycle(async (): Promise<void> => {
1448
+ generation += 1;
1449
+ isStarted = false;
1450
+ closeDebugBridge();
1451
+ stopReconcileTimer();
1452
+ simulatedOffline = false;
1453
+ for (const unsubscribe of unsubscribers) {
1454
+ unsubscribe();
1455
+ }
1456
+ unsubscribers = [];
1457
+ transport.disconnect();
1458
+ setConnected(false);
1459
+ coordinator.dispose(currentUserId ? {userId: currentUserId} : undefined);
1460
+ // Capture the persister into a local BEFORE the awaits below: this is
1461
+ // the exact fix for the original bug (a later start() calling
1462
+ // createAndStartPersister() reassigns the module-level `persister`
1463
+ // binding, so re-reading it after the await would destroy the NEW
1464
+ // user's persister instead of this stop()'s). The mutex already
1465
+ // prevents that interleaving, but capturing the local costs nothing and
1466
+ // remains correct even if that invariant is ever relaxed.
1467
+ const persisterToStop = persister;
1468
+ persister = undefined;
1469
+ currentUserId = undefined;
1470
+ if (persisterToStop) {
1471
+ // Flush any pending autosave so a clean stop never loses local writes.
1472
+ await persisterToStop.save();
1473
+ await persisterToStop.destroy();
1474
+ }
1475
+ });
1476
+
1477
+ const goOffline = (): void => {
1478
+ if (simulatedOffline) {
1479
+ return;
1480
+ }
1481
+ simulatedOffline = true;
1482
+ stopReconcileTimer();
1483
+ transport.disconnect();
1484
+ // The transport's own status event may arrive asynchronously; report the
1485
+ // disconnect now so status consumers (and the debug log) see it immediately.
1486
+ setConnected(false);
1487
+ };
1488
+
1489
+ const goOnline = async (): Promise<void> => {
1490
+ if (!simulatedOffline) {
1491
+ return;
1492
+ }
1493
+ simulatedOffline = false;
1494
+ try {
1495
+ await transport.connect();
1496
+ } catch (error) {
1497
+ // Local-first: goOnline never throws; the transport's background
1498
+ // reconnection surfaces a later success through onStatusChange.
1499
+ warn("transport reconnect failed; still offline")(error);
1500
+ }
1501
+ // The (re)connect status event triggers reconcile + outbox replay via
1502
+ // handleStatusChange, and the transport re-subscribes its collections.
1503
+ startReconcileTimer();
1504
+ };
1505
+
1506
+ const mutate = ({
1507
+ collection,
1508
+ operation,
1509
+ id,
1510
+ data,
1511
+ }: MutateArgs): {
1512
+ mutationId: string;
1513
+ id: string;
1514
+ } => {
1515
+ if (!currentUserId) {
1516
+ throw new Error("mutate() requires start() to have resolved an authenticated user");
1517
+ }
1518
+ if (operation !== "create" && !id) {
1519
+ throw new Error(`mutate() requires an id for ${operation}`);
1520
+ }
1521
+ const mutationId = generateMutationId();
1522
+ const entityId = id ?? generateMutationId();
1523
+ const existing = store.getEntity<Record<string, unknown> | null>({collection, id: entityId});
1524
+
1525
+ if (operation === "delete") {
1526
+ // Deleting an id the local store has never seen would write a tombstone for a
1527
+ // row that never existed and queue a mutation the server is certain to reject
1528
+ // (404 → terminal validation nack), leaving a phantom behind. Nothing the UI
1529
+ // renders can be in that state, so this is a caller bug worth surfacing.
1530
+ if (!existing) {
1531
+ throw new Error(
1532
+ `mutate() cannot delete ${collection}/${entityId}: no such entity in the local store`
1533
+ );
1534
+ }
1535
+ // One write, not two: upsertEntity flips `deleted` and stamps `deletedAt` on the
1536
+ // transition exactly like softDeleteEntity, and also records the pending
1537
+ // mutation id that protects the row from inbound deltas.
1538
+ store.upsertEntity({
1539
+ collection,
1540
+ data: existing.data ?? null,
1541
+ deleted: true,
1542
+ id: entityId,
1543
+ pendingMutationId: mutationId,
1544
+ });
1545
+ } else {
1546
+ const mergedData =
1547
+ operation === "update" && existing && typeof existing.data === "object" && existing.data
1548
+ ? {...existing.data, ...data}
1549
+ : (data ?? {});
1550
+ store.upsertEntity({
1551
+ collection,
1552
+ data: mergedData,
1553
+ id: entityId,
1554
+ pendingMutationId: mutationId,
1555
+ });
1556
+ }
1557
+
1558
+ outbox.enqueue({
1559
+ args: data ?? {},
1560
+ baseVersion: existing?.seq,
1561
+ collection,
1562
+ entityId,
1563
+ mutationId,
1564
+ operation,
1565
+ userId: currentUserId,
1566
+ });
1567
+ debugLog?.record({
1568
+ collection,
1569
+ detail: {baseVersion: existing?.seq, data},
1570
+ direction: "local",
1571
+ entityId,
1572
+ label: `${operation} ${collection}/${entityId}`,
1573
+ mutationId,
1574
+ operation,
1575
+ type: "mutate",
1576
+ });
1577
+ void replayOutbox().catch(warn("post-mutate replay failed"));
1578
+ return {id: entityId, mutationId};
1579
+ };
1580
+
1581
+ const resolveConflict = ({
1582
+ mutationId,
1583
+ strategy,
1584
+ }: {
1585
+ mutationId: string;
1586
+ strategy: ConflictResolutionStrategy;
1587
+ }): void => {
1588
+ applyConflictResolution({mutationId, outbox, store, strategy});
1589
+ debugLog?.record({
1590
+ detail: {strategy},
1591
+ direction: "local",
1592
+ label: `resolve conflict (${strategy})`,
1593
+ mutationId,
1594
+ type: "resolve",
1595
+ });
1596
+ // keepMine re-enqueues the mutation with a fresh baseVersion — drain it now
1597
+ // rather than waiting for the next mutate/reconnect/periodic trigger.
1598
+ void replayOutbox().catch(warn("post-resolve replay failed"));
1599
+ };
1600
+
1601
+ const retryFailed = ({entityId}: {entityId: string}): void => {
1602
+ coordinator.retryFailed({entityId});
1603
+ debugLog?.record({
1604
+ detail: {entityId},
1605
+ direction: "local",
1606
+ label: `retry failed (${entityId})`,
1607
+ type: "resolve",
1608
+ });
1609
+ void replayOutbox().catch(warn("post-retryFailed replay failed"));
1610
+ };
1611
+
1612
+ /**
1613
+ * Attribute the queued/failed/conflict totals to the collections they came
1614
+ * from so apps can surface one notification per collection. Collections with
1615
+ * nothing outstanding are omitted.
1616
+ */
1617
+ const buildCollectionStatuses = ({
1618
+ conflicts,
1619
+ }: {
1620
+ conflicts: SyncConflict[];
1621
+ }): Record<string, SyncCollectionStatus> => {
1622
+ const outboxCounts = currentUserId
1623
+ ? outbox.countsByCollection({statuses: ["queued", "failed"], userId: currentUserId})
1624
+ : {};
1625
+ const statuses: Record<string, SyncCollectionStatus> = {};
1626
+ const forCollection = (collection: string): SyncCollectionStatus => {
1627
+ const existing = statuses[collection];
1628
+ if (existing) {
1629
+ return existing;
1630
+ }
1631
+ const created: SyncCollectionStatus = {conflictCount: 0, failedCount: 0, queuedCount: 0};
1632
+ statuses[collection] = created;
1633
+ return created;
1634
+ };
1635
+ for (const [collection, counts] of Object.entries(outboxCounts)) {
1636
+ const entry = forCollection(collection);
1637
+ entry.queuedCount = counts.queued ?? 0;
1638
+ entry.failedCount = counts.failed ?? 0;
1639
+ }
1640
+ for (const conflict of conflicts) {
1641
+ forCollection(conflict.collection).conflictCount += 1;
1642
+ }
1643
+ return statuses;
1644
+ };
1645
+
1646
+ const getSyncStatus = (): SyncStatus => {
1647
+ const drainProgress = currentUserId
1648
+ ? coordinator.getDrainProgress({userId: currentUserId})
1649
+ : {draining: false, sentThisDrain: 0, totalThisDrain: 0};
1650
+ const conflicts = listConflicts({store});
1651
+ return {
1652
+ blockedEntities: currentUserId
1653
+ ? coordinator.getBlockedEntities({userId: currentUserId}).length
1654
+ : 0,
1655
+ collections: buildCollectionStatuses({conflicts}),
1656
+ conflictCount: conflicts.length,
1657
+ draining: drainProgress.draining,
1658
+ failedCount: currentUserId
1659
+ ? outbox.countByStatus({status: "failed", userId: currentUserId})
1660
+ : 0,
1661
+ isOnline: connected,
1662
+ isSyncing: syncingCount > 0,
1663
+ ...(authPaused ? {paused: "auth" as const} : {}),
1664
+ persistence: persistenceMode,
1665
+ queuedCount: currentUserId ? outbox.listQueued({userId: currentUserId}).length : 0,
1666
+ sentThisDrain: drainProgress.sentThisDrain,
1667
+ streams: getAllCursors({store}),
1668
+ totalThisDrain: drainProgress.totalThisDrain,
1669
+ };
1670
+ };
1671
+
1672
+ const onStatusChange = (callback: () => void): (() => void) => {
1673
+ statusListeners.add(callback);
1674
+ return () => {
1675
+ statusListeners.delete(callback);
1676
+ };
1677
+ };
1678
+
1679
+ /**
1680
+ * E1: a sign-out mutates the same shared state as start()/stop()/
1681
+ * handleAuthChange (`currentUserId`, the persister, coordinator state), so it
1682
+ * queues on the same lifecycle mutex and bumps the generation — an in-flight
1683
+ * reconcile/replay from the signed-out session sees itself superseded and
1684
+ * stands down instead of writing into a store that no longer has an owner.
1685
+ */
1686
+ const signOut = async (): Promise<void> =>
1687
+ withLifecycle(async (): Promise<void> => {
1688
+ generation += 1;
1689
+ isStarted = false;
1690
+ closeDebugBridge();
1691
+ const userId = currentUserId;
1692
+ stopReconcileTimer();
1693
+ simulatedOffline = false;
1694
+ for (const unsubscribe of unsubscribers) {
1695
+ unsubscribe();
1696
+ }
1697
+ unsubscribers = [];
1698
+ connectionEpoch += 1;
1699
+ transport.disconnect();
1700
+ setConnected(false);
1701
+ setAuthPaused(false);
1702
+ currentUserId = undefined;
1703
+ // Capture and clear the persister before awaiting, exactly as stop() does:
1704
+ // it is destroyed below (or by the wipe), so leaving the module-level
1705
+ // binding pointing at it would hand a later start() a dead persister.
1706
+ const persisterToStop = persister;
1707
+ persister = undefined;
1708
+ if (userId && config.wipeOnSignOut) {
1709
+ coordinator.dispose({userId});
1710
+ // E3(f): the strongest wipe case must also drop the cached derived
1711
+ // encryption key — the same rationale as the different-user wipe.
1712
+ await wipeLocalData({
1713
+ databaseNames: [config.name],
1714
+ keyCacheDbNames: [DEFAULT_KEY_CACHE_DB_NAME],
1715
+ persister: persisterToStop,
1716
+ store,
1717
+ });
1718
+ lastSeqJumpReconcileAt.clear();
1719
+ return;
1720
+ }
1721
+ coordinator.dispose(userId ? {userId} : undefined);
1722
+ if (persisterToStop) {
1723
+ // Flush any pending autosave so a sign-out without a wipe never loses
1724
+ // local writes (they belong to the user who may sign back in).
1725
+ await persisterToStop.save();
1726
+ await persisterToStop.destroy();
1727
+ }
1728
+ });
1729
+
1730
+ return {
1731
+ debug: debugLog,
1732
+ forceResync,
1733
+ getSyncStatus,
1734
+ goOffline,
1735
+ goOnline,
1736
+ mutate,
1737
+ onStatusChange,
1738
+ outbox,
1739
+ reconcile,
1740
+ replayOutbox,
1741
+ resolveConflict,
1742
+ retryFailed,
1743
+ signOut,
1744
+ start,
1745
+ stop,
1746
+ store,
1747
+ };
1748
+ };