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