@abloatai/humans 0.37.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 (404) hide show
  1. package/README.md +52 -0
  2. package/dist/Ablo.d.ts +208 -0
  3. package/dist/Ablo.js +120 -0
  4. package/dist/client.d.ts +317 -0
  5. package/dist/client.js +13 -0
  6. package/dist/core.d.ts +35 -0
  7. package/dist/core.js +48 -0
  8. package/dist/humans.d.ts +28 -0
  9. package/dist/humans.js +34 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +6 -0
  12. package/dist/local/BaseSyncedStore.d.ts +807 -0
  13. package/dist/local/BaseSyncedStore.js +1516 -0
  14. package/dist/local/Database.d.ts +322 -0
  15. package/dist/local/Database.js +1589 -0
  16. package/dist/local/InstanceCache.d.ts +255 -0
  17. package/dist/local/InstanceCache.js +1263 -0
  18. package/dist/local/LazyReferenceCollection.d.ts +177 -0
  19. package/dist/local/LazyReferenceCollection.js +461 -0
  20. package/dist/local/Model.d.ts +475 -0
  21. package/dist/local/Model.js +950 -0
  22. package/dist/local/ModelRegistry.d.ts +225 -0
  23. package/dist/local/ModelRegistry.js +539 -0
  24. package/dist/local/NetworkMonitor.d.ts +28 -0
  25. package/dist/local/NetworkMonitor.js +79 -0
  26. package/dist/local/RuntimeContext.d.ts +52 -0
  27. package/dist/local/RuntimeContext.js +80 -0
  28. package/dist/local/SyncClient.d.ts +516 -0
  29. package/dist/local/SyncClient.js +1754 -0
  30. package/dist/local/adapters/alwaysOnline.d.ts +14 -0
  31. package/dist/local/adapters/alwaysOnline.js +17 -0
  32. package/dist/local/adapters/inMemoryStorage.d.ts +37 -0
  33. package/dist/local/adapters/inMemoryStorage.js +122 -0
  34. package/dist/local/client/clientPrelude.d.ts +52 -0
  35. package/dist/local/client/clientPrelude.js +60 -0
  36. package/dist/local/client/consoleLogger.d.ts +35 -0
  37. package/dist/local/client/consoleLogger.js +44 -0
  38. package/dist/local/client/createInternalComponents.d.ts +50 -0
  39. package/dist/local/client/createInternalComponents.js +98 -0
  40. package/dist/local/client/createModelProxy.d.ts +248 -0
  41. package/dist/local/client/createModelProxy.js +880 -0
  42. package/dist/local/client/modelRegistration.d.ts +10 -0
  43. package/dist/local/client/modelRegistration.js +316 -0
  44. package/dist/local/client/options.d.ts +440 -0
  45. package/dist/local/client/options.js +7 -0
  46. package/dist/local/client/reactiveEngine.d.ts +53 -0
  47. package/dist/local/client/reactiveEngine.js +705 -0
  48. package/dist/local/client/resourceTypes.d.ts +12 -0
  49. package/dist/local/client/resourceTypes.js +10 -0
  50. package/dist/local/client/schemaConfig.d.ts +44 -0
  51. package/dist/local/client/schemaConfig.js +185 -0
  52. package/dist/local/client/storeCluster.d.ts +46 -0
  53. package/dist/local/client/storeCluster.js +133 -0
  54. package/dist/local/client/storeLifecycle.d.ts +61 -0
  55. package/dist/local/client/storeLifecycle.js +236 -0
  56. package/dist/local/client/validateAbloOptions.d.ts +42 -0
  57. package/dist/local/client/validateAbloOptions.js +43 -0
  58. package/dist/local/client/wsMutationExecutor.d.ts +27 -0
  59. package/dist/local/client/wsMutationExecutor.js +72 -0
  60. package/dist/local/context.d.ts +42 -0
  61. package/dist/local/context.js +81 -0
  62. package/dist/local/coordination/ClaimLog.d.ts +26 -0
  63. package/dist/local/coordination/ClaimLog.js +32 -0
  64. package/dist/local/interfaces/index.d.ts +311 -0
  65. package/dist/local/interfaces/index.js +9 -0
  66. package/dist/local/localModelContract.d.ts +14 -0
  67. package/dist/local/localModelContract.js +1 -0
  68. package/dist/local/logPosition.d.ts +31 -0
  69. package/dist/local/logPosition.js +53 -0
  70. package/dist/local/mutationPersistence.d.ts +6 -0
  71. package/dist/local/mutationPersistence.js +1 -0
  72. package/dist/local/mutators/RecordingMutation.d.ts +36 -0
  73. package/dist/local/mutators/RecordingMutation.js +182 -0
  74. package/dist/local/mutators/Transaction.d.ts +40 -0
  75. package/dist/local/mutators/Transaction.js +58 -0
  76. package/dist/local/mutators/UndoManager.d.ts +258 -0
  77. package/dist/local/mutators/UndoManager.js +665 -0
  78. package/dist/local/mutators/defineMutators.d.ts +60 -0
  79. package/dist/local/mutators/defineMutators.js +18 -0
  80. package/dist/local/mutators/inverseOp.d.ts +126 -0
  81. package/dist/local/mutators/inverseOp.js +71 -0
  82. package/dist/local/mutators/mutateActions.d.ts +45 -0
  83. package/dist/local/mutators/mutateActions.js +105 -0
  84. package/dist/local/mutators/readerActions.d.ts +33 -0
  85. package/dist/local/mutators/readerActions.js +57 -0
  86. package/dist/local/mutators/undoApply.d.ts +51 -0
  87. package/dist/local/mutators/undoApply.js +117 -0
  88. package/dist/local/persistence.d.ts +7 -0
  89. package/dist/local/persistence.js +9 -0
  90. package/dist/local/query/QueryProcessor.d.ts +75 -0
  91. package/dist/local/query/QueryProcessor.js +255 -0
  92. package/dist/local/query/client.d.ts +64 -0
  93. package/dist/local/query/client.js +138 -0
  94. package/dist/local/query/types.d.ts +85 -0
  95. package/dist/local/query/types.js +16 -0
  96. package/dist/local/schema/serialize.d.ts +1 -0
  97. package/dist/local/schema/serialize.js +1 -0
  98. package/dist/local/store/queryApi.d.ts +13 -0
  99. package/dist/local/store/queryApi.js +35 -0
  100. package/dist/local/storeContract.d.ts +145 -0
  101. package/dist/local/storeContract.js +12 -0
  102. package/dist/local/stores/DatabaseManager.d.ts +112 -0
  103. package/dist/local/stores/DatabaseManager.js +400 -0
  104. package/dist/local/stores/ObjectStore.d.ts +115 -0
  105. package/dist/local/stores/ObjectStore.js +393 -0
  106. package/dist/local/stores/ObjectStoreContract.d.ts +38 -0
  107. package/dist/local/stores/ObjectStoreContract.js +1 -0
  108. package/dist/local/stores/StoreManager.d.ts +114 -0
  109. package/dist/local/stores/StoreManager.js +304 -0
  110. package/dist/local/stores/SyncActionStore.d.ts +99 -0
  111. package/dist/local/stores/SyncActionStore.js +506 -0
  112. package/dist/local/stores/openIDBWithTimeout.d.ts +65 -0
  113. package/dist/local/stores/openIDBWithTimeout.js +153 -0
  114. package/dist/local/stores/persistenceCleanup.d.ts +7 -0
  115. package/dist/local/stores/persistenceCleanup.js +26 -0
  116. package/dist/local/stores/persistenceIdentity.d.ts +27 -0
  117. package/dist/local/stores/persistenceIdentity.js +38 -0
  118. package/dist/local/stores/syncAction.d.ts +26 -0
  119. package/dist/local/stores/syncAction.js +16 -0
  120. package/dist/local/stores/v1PersistenceDeletion.d.ts +8 -0
  121. package/dist/local/stores/v1PersistenceDeletion.js +16 -0
  122. package/dist/local/sync/BootstrapFetcher.d.ts +284 -0
  123. package/dist/local/sync/BootstrapFetcher.js +964 -0
  124. package/dist/local/sync/ConnectionManager.d.ts +8 -0
  125. package/dist/local/sync/ConnectionManager.js +8 -0
  126. package/dist/local/sync/OnDemandLoader.d.ts +231 -0
  127. package/dist/local/sync/OnDemandLoader.js +743 -0
  128. package/dist/local/sync/SubscriptionManager.d.ts +159 -0
  129. package/dist/local/sync/SubscriptionManager.js +243 -0
  130. package/dist/local/sync/SyncWebSocket.d.ts +173 -0
  131. package/dist/local/sync/SyncWebSocket.js +438 -0
  132. package/dist/local/sync/bootstrapApply.d.ts +73 -0
  133. package/dist/local/sync/bootstrapApply.js +73 -0
  134. package/dist/local/sync/commitFrames.d.ts +8 -0
  135. package/dist/local/sync/commitFrames.js +8 -0
  136. package/dist/local/sync/connectionManagerLifecycle.d.ts +23 -0
  137. package/dist/local/sync/connectionManagerLifecycle.js +126 -0
  138. package/dist/local/sync/contextPorts.d.ts +18 -0
  139. package/dist/local/sync/contextPorts.js +31 -0
  140. package/dist/local/sync/createClaimStream.d.ts +64 -0
  141. package/dist/local/sync/createClaimStream.js +475 -0
  142. package/dist/local/sync/createSnapshot.d.ts +29 -0
  143. package/dist/local/sync/createSnapshot.js +116 -0
  144. package/dist/local/sync/credentialLifecycle.d.ts +7 -0
  145. package/dist/local/sync/credentialLifecycle.js +7 -0
  146. package/dist/local/sync/deltaPipeline.d.ts +116 -0
  147. package/dist/local/sync/deltaPipeline.js +357 -0
  148. package/dist/local/sync/groupChange.d.ts +116 -0
  149. package/dist/local/sync/groupChange.js +244 -0
  150. package/dist/local/sync/initialize.d.ts +27 -0
  151. package/dist/local/sync/initialize.js +137 -0
  152. package/dist/local/sync/participants.d.ts +132 -0
  153. package/dist/local/sync/participants.js +342 -0
  154. package/dist/local/sync/persistedPrefix.d.ts +12 -0
  155. package/dist/local/sync/persistedPrefix.js +22 -0
  156. package/dist/local/sync/reconnect.d.ts +23 -0
  157. package/dist/local/sync/reconnect.js +55 -0
  158. package/dist/local/sync/schemaDrift.d.ts +55 -0
  159. package/dist/local/sync/schemaDrift.js +53 -0
  160. package/dist/local/sync/schemas.d.ts +71 -0
  161. package/dist/local/sync/schemas.js +94 -0
  162. package/dist/local/sync/socketEventWiring.d.ts +31 -0
  163. package/dist/local/sync/socketEventWiring.js +130 -0
  164. package/dist/local/sync/syncCursor.d.ts +40 -0
  165. package/dist/local/sync/syncCursor.js +55 -0
  166. package/dist/local/sync/syncPlan.d.ts +54 -0
  167. package/dist/local/sync/syncPlan.js +50 -0
  168. package/dist/local/sync/terminalSessionLifecycle.d.ts +20 -0
  169. package/dist/local/sync/terminalSessionLifecycle.js +50 -0
  170. package/dist/local/sync/wsFrameHandlers.d.ts +8 -0
  171. package/dist/local/sync/wsFrameHandlers.js +8 -0
  172. package/dist/local/transactions/databaseCommitOutbox.d.ts +15 -0
  173. package/dist/local/transactions/databaseCommitOutbox.js +16 -0
  174. package/dist/local/transactions/localMutation.d.ts +10 -0
  175. package/dist/local/transactions/localMutation.js +37 -0
  176. package/dist/local/transactions/mutations/MutationQueue.d.ts +511 -0
  177. package/dist/local/transactions/mutations/MutationQueue.js +1498 -0
  178. package/dist/local/transactions/mutations/MutationStore.d.ts +20 -0
  179. package/dist/local/transactions/mutations/MutationStore.js +53 -0
  180. package/dist/local/transactions/mutations/UnconfirmedWrites.d.ts +82 -0
  181. package/dist/local/transactions/mutations/UnconfirmedWrites.js +104 -0
  182. package/dist/local/transactions/mutations/batchProcessing.d.ts +64 -0
  183. package/dist/local/transactions/mutations/batchProcessing.js +349 -0
  184. package/dist/local/transactions/mutations/coalesceRules.d.ts +58 -0
  185. package/dist/local/transactions/mutations/coalesceRules.js +140 -0
  186. package/dist/local/transactions/mutations/commitApi.d.ts +19 -0
  187. package/dist/local/transactions/mutations/commitApi.js +74 -0
  188. package/dist/local/transactions/mutations/commitLane.d.ts +70 -0
  189. package/dist/local/transactions/mutations/commitLane.js +140 -0
  190. package/dist/local/transactions/mutations/commitLatency.d.ts +52 -0
  191. package/dist/local/transactions/mutations/commitLatency.js +130 -0
  192. package/dist/local/transactions/mutations/commitPayload.d.ts +165 -0
  193. package/dist/local/transactions/mutations/commitPayload.js +152 -0
  194. package/dist/local/transactions/mutations/commitTransport.d.ts +36 -0
  195. package/dist/local/transactions/mutations/commitTransport.js +104 -0
  196. package/dist/local/transactions/mutations/deltaConfirmation.d.ts +63 -0
  197. package/dist/local/transactions/mutations/deltaConfirmation.js +235 -0
  198. package/dist/local/transactions/mutations/durableCommitRestore.d.ts +17 -0
  199. package/dist/local/transactions/mutations/durableCommitRestore.js +95 -0
  200. package/dist/local/transactions/mutations/durableWriteStore.d.ts +14 -0
  201. package/dist/local/transactions/mutations/durableWriteStore.js +12 -0
  202. package/dist/local/transactions/mutations/executionSelection.d.ts +6 -0
  203. package/dist/local/transactions/mutations/executionSelection.js +42 -0
  204. package/dist/local/transactions/mutations/failureHandling.d.ts +16 -0
  205. package/dist/local/transactions/mutations/failureHandling.js +130 -0
  206. package/dist/local/transactions/mutations/failurePolicy.d.ts +13 -0
  207. package/dist/local/transactions/mutations/failurePolicy.js +48 -0
  208. package/dist/local/transactions/mutations/localMutation.d.ts +58 -0
  209. package/dist/local/transactions/mutations/localMutation.js +75 -0
  210. package/dist/local/transactions/mutations/modelOperations.d.ts +44 -0
  211. package/dist/local/transactions/mutations/modelOperations.js +144 -0
  212. package/dist/local/transactions/mutations/mutationPersistence.d.ts +25 -0
  213. package/dist/local/transactions/mutations/mutationPersistence.js +188 -0
  214. package/dist/local/transactions/mutations/pendingDrain.d.ts +33 -0
  215. package/dist/local/transactions/mutations/pendingDrain.js +112 -0
  216. package/dist/local/transactions/mutations/processingScheduler.d.ts +14 -0
  217. package/dist/local/transactions/mutations/processingScheduler.js +24 -0
  218. package/dist/local/transactions/mutations/queueCoalescing.d.ts +13 -0
  219. package/dist/local/transactions/mutations/queueCoalescing.js +35 -0
  220. package/dist/local/transactions/mutations/replayValidation.d.ts +187 -0
  221. package/dist/local/transactions/mutations/replayValidation.js +164 -0
  222. package/dist/local/transactions/reconnectDrain.d.ts +11 -0
  223. package/dist/local/transactions/reconnectDrain.js +13 -0
  224. package/dist/local/utils/mobxSetup.d.ts +53 -0
  225. package/dist/local/utils/mobxSetup.js +330 -0
  226. package/dist/local/views/QueryView.d.ts +79 -0
  227. package/dist/local/views/QueryView.js +218 -0
  228. package/dist/local/views/ViewRegistry.d.ts +20 -0
  229. package/dist/local/views/ViewRegistry.js +57 -0
  230. package/dist/local/views/incrementalView.d.ts +45 -0
  231. package/dist/local/views/incrementalView.js +69 -0
  232. package/dist/plugin.d.ts +285 -0
  233. package/dist/plugin.js +106 -0
  234. package/dist/presenceStream.d.ts +69 -0
  235. package/dist/presenceStream.js +200 -0
  236. package/dist/react/AbloProvider.d.ts +242 -0
  237. package/dist/react/AbloProvider.js +456 -0
  238. package/dist/react/ClientSideSuspense.d.ts +36 -0
  239. package/dist/react/ClientSideSuspense.js +17 -0
  240. package/dist/react/DefaultFallback.d.ts +24 -0
  241. package/dist/react/DefaultFallback.js +43 -0
  242. package/dist/react/context.d.ts +55 -0
  243. package/dist/react/context.js +29 -0
  244. package/dist/react/createAbloReact.d.ts +50 -0
  245. package/dist/react/createAbloReact.js +48 -0
  246. package/dist/react/internalContext.d.ts +33 -0
  247. package/dist/react/internalContext.js +3 -0
  248. package/dist/react/useAblo.d.ts +96 -0
  249. package/dist/react/useAblo.js +120 -0
  250. package/dist/react/useCurrentUserId.d.ts +2 -0
  251. package/dist/react/useCurrentUserId.js +12 -0
  252. package/dist/react/useErrorListener.d.ts +2 -0
  253. package/dist/react/useErrorListener.js +14 -0
  254. package/dist/react/useMutationFailureListener.d.ts +8 -0
  255. package/dist/react/useMutationFailureListener.js +19 -0
  256. package/dist/react/useMutators.d.ts +56 -0
  257. package/dist/react/useMutators.js +84 -0
  258. package/dist/react/useSyncStatus.d.ts +19 -0
  259. package/dist/react/useSyncStatus.js +37 -0
  260. package/dist/react/useUndoScope.d.ts +34 -0
  261. package/dist/react/useUndoScope.js +73 -0
  262. package/dist/react.d.ts +18 -0
  263. package/dist/react.js +14 -0
  264. package/dist/reactRuntime.d.ts +4 -0
  265. package/dist/reactRuntime.js +2 -0
  266. package/dist/surface.d.ts +36 -0
  267. package/dist/surface.js +77 -0
  268. package/dist/useReactive.d.ts +6 -0
  269. package/dist/useReactive.js +43 -0
  270. package/package.json +119 -0
  271. package/src/Ablo.ts +456 -0
  272. package/src/client.ts +374 -0
  273. package/src/core.ts +104 -0
  274. package/src/humans.ts +61 -0
  275. package/src/index.ts +40 -0
  276. package/src/local/BaseSyncedStore.ts +1991 -0
  277. package/src/local/Database.ts +2052 -0
  278. package/src/local/InstanceCache.ts +1503 -0
  279. package/src/local/LazyReferenceCollection.ts +563 -0
  280. package/src/local/Model.ts +1124 -0
  281. package/src/local/ModelRegistry.ts +762 -0
  282. package/src/local/NetworkMonitor.ts +88 -0
  283. package/src/local/RuntimeContext.ts +141 -0
  284. package/src/local/SyncClient.ts +2131 -0
  285. package/src/local/adapters/alwaysOnline.ts +20 -0
  286. package/src/local/adapters/inMemoryStorage.ts +141 -0
  287. package/src/local/client/clientPrelude.ts +112 -0
  288. package/src/local/client/consoleLogger.ts +60 -0
  289. package/src/local/client/createInternalComponents.ts +163 -0
  290. package/src/local/client/createModelProxy.ts +1390 -0
  291. package/src/local/client/modelRegistration.ts +350 -0
  292. package/src/local/client/options.ts +526 -0
  293. package/src/local/client/reactiveEngine.ts +935 -0
  294. package/src/local/client/resourceTypes.ts +37 -0
  295. package/src/local/client/schemaConfig.ts +194 -0
  296. package/src/local/client/storeCluster.ts +172 -0
  297. package/src/local/client/storeLifecycle.ts +343 -0
  298. package/src/local/client/validateAbloOptions.ts +95 -0
  299. package/src/local/client/wsMutationExecutor.ts +110 -0
  300. package/src/local/context.ts +96 -0
  301. package/src/local/coordination/ClaimLog.ts +39 -0
  302. package/src/local/interfaces/index.ts +468 -0
  303. package/src/local/localModelContract.ts +15 -0
  304. package/src/local/logPosition.ts +84 -0
  305. package/src/local/mutationPersistence.ts +7 -0
  306. package/src/local/mutators/RecordingMutation.ts +222 -0
  307. package/src/local/mutators/Transaction.ts +97 -0
  308. package/src/local/mutators/UndoManager.ts +741 -0
  309. package/src/local/mutators/defineMutators.ts +76 -0
  310. package/src/local/mutators/inverseOp.ts +83 -0
  311. package/src/local/mutators/mutateActions.ts +167 -0
  312. package/src/local/mutators/readerActions.ts +99 -0
  313. package/src/local/mutators/undoApply.ts +141 -0
  314. package/src/local/persistence.ts +16 -0
  315. package/src/local/query/QueryProcessor.ts +347 -0
  316. package/src/local/query/client.ts +197 -0
  317. package/src/local/query/types.ts +102 -0
  318. package/src/local/schema/serialize.ts +1 -0
  319. package/src/local/store/queryApi.ts +56 -0
  320. package/src/local/storeContract.ts +146 -0
  321. package/src/local/stores/DatabaseManager.ts +507 -0
  322. package/src/local/stores/ObjectStore.ts +449 -0
  323. package/src/local/stores/ObjectStoreContract.ts +48 -0
  324. package/src/local/stores/StoreManager.ts +388 -0
  325. package/src/local/stores/SyncActionStore.ts +579 -0
  326. package/src/local/stores/openIDBWithTimeout.ts +195 -0
  327. package/src/local/stores/persistenceCleanup.ts +43 -0
  328. package/src/local/stores/persistenceIdentity.ts +83 -0
  329. package/src/local/stores/syncAction.ts +21 -0
  330. package/src/local/stores/v1PersistenceDeletion.ts +21 -0
  331. package/src/local/sync/BootstrapFetcher.ts +1224 -0
  332. package/src/local/sync/ConnectionManager.ts +15 -0
  333. package/src/local/sync/OnDemandLoader.ts +927 -0
  334. package/src/local/sync/SubscriptionManager.ts +300 -0
  335. package/src/local/sync/SyncWebSocket.ts +584 -0
  336. package/src/local/sync/bootstrapApply.ts +130 -0
  337. package/src/local/sync/commitFrames.ts +16 -0
  338. package/src/local/sync/connectionManagerLifecycle.ts +158 -0
  339. package/src/local/sync/contextPorts.ts +37 -0
  340. package/src/local/sync/createClaimStream.ts +668 -0
  341. package/src/local/sync/createSnapshot.ts +160 -0
  342. package/src/local/sync/credentialLifecycle.ts +18 -0
  343. package/src/local/sync/deltaPipeline.ts +473 -0
  344. package/src/local/sync/groupChange.ts +343 -0
  345. package/src/local/sync/initialize.ts +205 -0
  346. package/src/local/sync/participants.ts +564 -0
  347. package/src/local/sync/persistedPrefix.ts +27 -0
  348. package/src/local/sync/reconnect.ts +88 -0
  349. package/src/local/sync/schemaDrift.ts +86 -0
  350. package/src/local/sync/schemas.ts +118 -0
  351. package/src/local/sync/socketEventWiring.ts +196 -0
  352. package/src/local/sync/syncCursor.ts +62 -0
  353. package/src/local/sync/syncPlan.ts +89 -0
  354. package/src/local/sync/terminalSessionLifecycle.ts +66 -0
  355. package/src/local/sync/wsFrameHandlers.ts +20 -0
  356. package/src/local/transactions/databaseCommitOutbox.ts +33 -0
  357. package/src/local/transactions/localMutation.ts +58 -0
  358. package/src/local/transactions/mutations/MutationQueue.ts +1998 -0
  359. package/src/local/transactions/mutations/MutationStore.ts +65 -0
  360. package/src/local/transactions/mutations/UnconfirmedWrites.ts +133 -0
  361. package/src/local/transactions/mutations/batchProcessing.ts +469 -0
  362. package/src/local/transactions/mutations/coalesceRules.ts +192 -0
  363. package/src/local/transactions/mutations/commitApi.ts +97 -0
  364. package/src/local/transactions/mutations/commitLane.ts +191 -0
  365. package/src/local/transactions/mutations/commitLatency.ts +164 -0
  366. package/src/local/transactions/mutations/commitPayload.ts +281 -0
  367. package/src/local/transactions/mutations/commitTransport.ts +174 -0
  368. package/src/local/transactions/mutations/deltaConfirmation.ts +298 -0
  369. package/src/local/transactions/mutations/durableCommitRestore.ts +128 -0
  370. package/src/local/transactions/mutations/durableWriteStore.ts +21 -0
  371. package/src/local/transactions/mutations/executionSelection.ts +42 -0
  372. package/src/local/transactions/mutations/failureHandling.ts +154 -0
  373. package/src/local/transactions/mutations/failurePolicy.ts +61 -0
  374. package/src/local/transactions/mutations/localMutation.ts +135 -0
  375. package/src/local/transactions/mutations/modelOperations.ts +210 -0
  376. package/src/local/transactions/mutations/mutationPersistence.ts +231 -0
  377. package/src/local/transactions/mutations/pendingDrain.ts +160 -0
  378. package/src/local/transactions/mutations/processingScheduler.ts +35 -0
  379. package/src/local/transactions/mutations/queueCoalescing.ts +45 -0
  380. package/src/local/transactions/mutations/replayValidation.ts +192 -0
  381. package/src/local/transactions/reconnectDrain.ts +24 -0
  382. package/src/local/utils/mobxSetup.ts +388 -0
  383. package/src/local/views/QueryView.ts +311 -0
  384. package/src/local/views/ViewRegistry.ts +61 -0
  385. package/src/local/views/incrementalView.ts +92 -0
  386. package/src/plugin.ts +396 -0
  387. package/src/presenceStream.ts +279 -0
  388. package/src/react/AbloProvider.tsx +744 -0
  389. package/src/react/ClientSideSuspense.tsx +57 -0
  390. package/src/react/DefaultFallback.tsx +60 -0
  391. package/src/react/context.ts +89 -0
  392. package/src/react/createAbloReact.ts +116 -0
  393. package/src/react/internalContext.ts +38 -0
  394. package/src/react/useAblo.ts +280 -0
  395. package/src/react/useCurrentUserId.ts +17 -0
  396. package/src/react/useErrorListener.ts +22 -0
  397. package/src/react/useMutationFailureListener.ts +34 -0
  398. package/src/react/useMutators.ts +184 -0
  399. package/src/react/useSyncStatus.ts +42 -0
  400. package/src/react/useUndoScope.ts +143 -0
  401. package/src/react.ts +69 -0
  402. package/src/reactRuntime.ts +10 -0
  403. package/src/surface.ts +106 -0
  404. package/src/useReactive.ts +51 -0
@@ -0,0 +1,1754 @@
1
+ /**
2
+ * Applies model mutations and manages the offline write queue. The
3
+ * SyncClient turns local create, update, delete, and archive calls into
4
+ * optimistic changes, holds them while the client is offline, sends them to
5
+ * the server when connectivity returns, and resolves conflicts when the
6
+ * server's version of a row disagrees with the local one. It sits between the
7
+ * reactive object pool and the {@link MutationQueue} that delivers writes
8
+ * over the network.
9
+ */
10
+ import { runInAction } from 'mobx';
11
+ import { InstanceCache, ModelScope } from './InstanceCache.js';
12
+ import { Model } from './Model.js';
13
+ import { snapshotJsonValue } from '@abloatai/transaction/utils/json';
14
+ // ModelRegistry instance accessed via this.objectPool.registry
15
+ import { LoadStrategy } from '@abloatai/transaction/types';
16
+ import { globalRuntime } from './context.js';
17
+ import { AbloAuthenticationError, AbloError, AbloValidationError } from '@abloatai/transaction/errors';
18
+ import { EventEmitter } from 'events';
19
+ import { NetworkMonitor } from './NetworkMonitor.js';
20
+ import { MutationQueue, } from './transactions/mutations/MutationQueue.js';
21
+ import { observeCommitLatency, } from './transactions/mutations/commitLatency.js';
22
+ import { UnconfirmedWrites, } from './transactions/mutations/UnconfirmedWrites.js';
23
+ import { LogPosition } from './logPosition.js';
24
+ import { createLocalMutationPort } from './transactions/localMutation.js';
25
+ import { createReconnectDrain } from './transactions/reconnectDrain.js';
26
+ import { DatabaseCommitOutboxStore } from './transactions/databaseCommitOutbox.js';
27
+ /**
28
+ * Reports whether an incoming snapshot record is strictly newer than the
29
+ * model already in the pool. The comparison uses the server-stamped
30
+ * `updatedAt` timestamp, since rows carry no numeric version and the delta
31
+ * pipeline resolves order by arrival (last write wins). An undefined incoming
32
+ * timestamp counts as not newer, so a known row is never clobbered; an
33
+ * undefined existing timestamp means the pooled row is unversioned, so the
34
+ * incoming record wins. The scoped hydrate-on-enter path uses this to drop
35
+ * snapshot rows that a live delta has already advanced past.
36
+ */
37
+ function rawRecordIsNewer(data, existing) {
38
+ const raw = data.updatedAt;
39
+ const inMs = raw instanceof Date
40
+ ? raw.getTime()
41
+ : typeof raw === 'string'
42
+ ? (Number.isNaN(Date.parse(raw)) ? undefined : Date.parse(raw))
43
+ : typeof raw === 'number'
44
+ ? raw
45
+ : undefined;
46
+ const exMs = existing.updatedAt instanceof Date ? existing.updatedAt.getTime() : undefined;
47
+ if (inMs === undefined)
48
+ return false;
49
+ if (exMs === undefined)
50
+ return true;
51
+ return inMs > exMs;
52
+ }
53
+ /**
54
+ * Converts an untyped server `updatedAt` value — an ISO string, epoch number,
55
+ * or Date read off an untyped row — into epoch milliseconds for
56
+ * last-write-wins comparison. Falsy or non-date values become 0, matching the
57
+ * conflict resolver's rule that a missing timestamp sorts as the epoch.
58
+ */
59
+ function toEpochMs(value) {
60
+ if (!value)
61
+ return 0;
62
+ if (value instanceof Date)
63
+ return value.getTime();
64
+ if (typeof value === 'string' || typeof value === 'number') {
65
+ return new Date(value).getTime();
66
+ }
67
+ return 0;
68
+ }
69
+ export class SyncClient extends EventEmitter {
70
+ runtime;
71
+ objectPool;
72
+ database;
73
+ mutationPersistence;
74
+ reconnectDrain = createReconnectDrain();
75
+ get mutationExecutor() { return this.runtime.mutationExecutor; }
76
+ networkMonitor;
77
+ /**
78
+ * @internal — test seam, stripped from the published declarations by
79
+ * `stripInternal`. Unit suites deliver queue lifecycle events directly.
80
+ */
81
+ mutationQueue;
82
+ observers = new Set();
83
+ // Authentication context
84
+ userId = null;
85
+ organizationId = null;
86
+ // The MutationQueue is the sole owner of queued transaction state.
87
+ pendingStages = new Set();
88
+ commitOutboxNamespace;
89
+ /** Compatibility view for diagnostics; transaction state lives in the queue. */
90
+ get pendingMutations() {
91
+ const transactions = [...this.mutationQueue.getOutstandingTransactions()];
92
+ const deferredCount = this.mutationQueue.getOutstandingTransactionCount() - transactions.length;
93
+ return deferredCount > 0
94
+ ? [...transactions, ...Array.from({ length: deferredCount })]
95
+ : transactions;
96
+ }
97
+ /**
98
+ * Tracks the ids of transactions the client has applied optimistically but
99
+ * the server has not yet confirmed. When a delta arrives, the receive path
100
+ * consults this set to recognize the echo of the client's own mutation and
101
+ * skip the now-redundant pool update; the IndexedDB write still runs,
102
+ * because the delta is the authoritative version of the row. Without this
103
+ * discriminator, an optimistically applied delete followed by a
104
+ * server-confirmed create echo would resurrect the row for the window
105
+ * between the two confirmations.
106
+ *
107
+ * The set is bounded with first-in-first-out eviction, and
108
+ * {@link SyncClient.getEchoMetrics} exposes its counters.
109
+ */
110
+ echoTracker = new UnconfirmedWrites();
111
+ // Connection state
112
+ connectionState = 'disconnected';
113
+ // Configuration
114
+ isDisposed = false;
115
+ /**
116
+ * The client's position in the global delta order, held as the single
117
+ * canonical {@link LogPosition} instance. The store advances `applied` and
118
+ * `persisted` as deltas land, the queue advances `acked` on commit
119
+ * responses, and snapshots and claims read `readFloor`.
120
+ */
121
+ position = new LogPosition();
122
+ constructor(objectPool, database, commitOutbox = new DatabaseCommitOutboxStore(database), commitOutboxNamespace = 'default', runtime = globalRuntime) {
123
+ super();
124
+ this.runtime = runtime;
125
+ this.objectPool = objectPool;
126
+ this.database = database;
127
+ this.mutationPersistence = {
128
+ saveTransaction: (transaction) => database.saveTransaction(snapshotJsonValue(transaction, '$.pendingMutation')),
129
+ removeTransaction: (id) => database.removeTransaction(id),
130
+ getPersistedTransactions: () => database.getPersistedTransactions(),
131
+ };
132
+ this.commitOutboxNamespace = commitOutboxNamespace;
133
+ this.networkMonitor = new NetworkMonitor(this.runtime);
134
+ // Initialize MutationQueue with proper configuration
135
+ const localMutationPort = createLocalMutationPort((event, payload) => {
136
+ this.mutationQueue.emit(event, payload);
137
+ });
138
+ this.mutationQueue = new MutationQueue({
139
+ position: this.position,
140
+ runtime: this.runtime,
141
+ localMutationPort,
142
+ maxBatchSize: 50, // Larger batches keep the batch count low for bulk operations
143
+ // A short delay keeps writes responsive; coalescing still groups them
144
+ batchDelay: 150,
145
+ maxRetries: 3,
146
+ enableOptimistic: true,
147
+ enablePersistence: true,
148
+ conflictResolution: {
149
+ strategy: 'last-write-wins',
150
+ },
151
+ });
152
+ this.mutationQueue.setPersistence(this.mutationPersistence);
153
+ this.mutationQueue.setCommitOutbox(commitOutbox);
154
+ // Provide connection state to MutationQueue - prevents rollbacks during disconnection
155
+ this.mutationQueue.setConnectionChecker(() => this.connectionState === 'connected');
156
+ // Restore object-pool state when a transaction is rolled back. If the
157
+ // server rejects a write or it times out, the model's previous state is
158
+ // put back. Because writes are no longer applied to IndexedDB
159
+ // optimistically, that store already holds the correct state.
160
+ this.setupTransactionRollbackHandling();
161
+ // Forward reconciliation requests from the transaction queue. When delta
162
+ // confirmation times out, the client cycles the WebSocket connection to
163
+ // trigger a catch-up from the server rather than rolling the write back.
164
+ this.setupReconciliationForwarding();
165
+ // Persist unconfirmed transactions to IndexedDB. When delta retries are
166
+ // exhausted, the write is cached so it survives a tab close.
167
+ this.setupAwaitingTransactionPersistence();
168
+ // Setup network monitoring
169
+ this.setupNetworkMonitoring();
170
+ }
171
+ /**
172
+ * Setup network monitoring handlers
173
+ */
174
+ setupNetworkMonitoring() {
175
+ // Both handlers emit to external listeners (which can throw) before/around
176
+ // their own try/catch — route rejections into observability rather than
177
+ // losing a failed reconnect flush silently.
178
+ this.networkMonitor.on('online', () => {
179
+ void this.handleReconnection().catch((error) => {
180
+ this.runtime.observability.captureMutationFailure({
181
+ context: 'network-online-reconnection',
182
+ error: error instanceof Error ? error : new Error(String(error)),
183
+ });
184
+ });
185
+ });
186
+ this.networkMonitor.on('offline', () => {
187
+ void this.handleDisconnection().catch((error) => {
188
+ this.runtime.observability.captureMutationFailure({
189
+ context: 'network-offline-handler',
190
+ error: error instanceof Error ? error : new Error(String(error)),
191
+ });
192
+ });
193
+ });
194
+ }
195
+ /**
196
+ * Handle transaction rollback. Two distinct shapes flow through this
197
+ * event:
198
+ *
199
+ * 1. **Server-rejected rollback** (`reason === 'permanent_error'`,
200
+ * `'max_retries_exhausted'`, `'conflict_server_wins'`) — the
201
+ * optimistic state is wrong, the row exists, restore previous
202
+ * state and notify the UI.
203
+ *
204
+ * 2. **Local-cancellation cleanup** (`reason === 'model_cancelled'`,
205
+ * `'cascade_parent_deleted'`) — the user deleted this model (or
206
+ * its parent), so a pending UPDATE on it gets cancelled. There's
207
+ * nothing to restore (the model is doomed) and no UI notification
208
+ * needed (the delete itself already triggered re-renders). Just
209
+ * discard the optimistic state silently.
210
+ *
211
+ * Treating both paths the same caused the deletion-flicker bug: every
212
+ * cancelled update on a multi-child record fired a per-model observer
213
+ * event and a `[SyncClient.rollback]` warn, producing N renders and N
214
+ * spam log lines for one user-initiated delete.
215
+ */
216
+ setupTransactionRollbackHandling() {
217
+ this.mutationQueue.on('optimistic:rollback', (event) => {
218
+ const { model, previousState, transaction, reason, error } = event;
219
+ // Local cleanup path — discard quietly. The optimistic state was
220
+ // applied to a model that's already disposed by the cascading
221
+ // delete, and emitting per-model observer events here would
222
+ // re-render N times for one user-initiated cascade.
223
+ if (reason === 'model_cancelled' || reason === 'cascade_parent_deleted') {
224
+ return;
225
+ }
226
+ // Surface the typed AbloError fields directly — `type`/`code`/
227
+ // `httpStatus`/`requestId` are what tell us the rollback cause
228
+ // (e.g. `AbloValidationError` with `code: 'schema_...'`,
229
+ // `AbloServerError` with `httpStatus: 500`). Falling back to
230
+ // generic message lets us still see unstructured errors.
231
+ // Mechanic-level breadcrumb only. The authoritative, user-facing
232
+ // reason is logged once at `warn` by `MutationQueue.handleFailure`
233
+ // (`Permanent error - rolling back`). Logging the same typed cause
234
+ // again here at `warn` is what produced three identical dumps per
235
+ // rejected write — keep it at `debug` so the rollback mechanics are
236
+ // available when debugging but don't double the console noise.
237
+ const abloErr = error instanceof AbloError ? error : undefined;
238
+ this.runtime.logger.debug('[SyncClient.rollback]', {
239
+ txType: transaction.type,
240
+ modelName: transaction.modelName,
241
+ modelId: transaction.modelId.slice(0, 12),
242
+ reason: reason ?? 'unknown',
243
+ errorType: abloErr?.type ?? error?.name,
244
+ errorCode: abloErr?.code,
245
+ httpStatus: abloErr?.httpStatus,
246
+ requestId: abloErr?.requestId,
247
+ message: error?.message,
248
+ });
249
+ this.runtime.observability.captureRollback({
250
+ transactionType: transaction.type,
251
+ modelName: transaction.modelName,
252
+ modelId: transaction.modelId,
253
+ reason: reason ?? 'unknown',
254
+ error: error?.message,
255
+ connectionState: this.connectionState,
256
+ });
257
+ try {
258
+ if (transaction.type === 'create') {
259
+ // CREATE rollback: remove the optimistically created entity
260
+ this.objectPool.remove(transaction.modelId);
261
+ }
262
+ else if (transaction.type === 'delete' &&
263
+ reason === 'permanent_error' &&
264
+ error?.message?.includes('not found')) {
265
+ // DELETE "not found" rollback: the entity doesn't exist on the server.
266
+ // Instead of restoring a ghost entity, remove it locally too.
267
+ // Both sides agree: this entity should not exist.
268
+ this.runtime.observability.breadcrumb('DELETE rolled back with "not found" - removing ghost entity', 'sync.conflict', 'info', {
269
+ modelId: transaction.modelId,
270
+ modelName: transaction.modelName,
271
+ });
272
+ this.objectPool.remove(transaction.modelId);
273
+ }
274
+ else if (model) {
275
+ // For update/delete/archive: restore model (with previousState if available)
276
+ // Guard: if the model was disposed (e.g. by a concurrent DELETE rollback or
277
+ // cascade), don't re-add it — Object.assign cannot restore the private
278
+ // isDisposed flag, so the model would be added in a broken state.
279
+ if (model.disposed) {
280
+ // Follow-on of an already-logged permanent error, not its own
281
+ // problem: the tx that failed has already surfaced the cause in
282
+ // MutationQueue. Restoring a disposed model is a no-op by
283
+ // design (can't revive the private isDisposed flag), so keep this
284
+ // at `debug` instead of emitting a second `warn` that reads as a
285
+ // distinct failure in the console.
286
+ this.runtime.logger.debug('[SyncClient] Rollback skipped restore (model already disposed)', {
287
+ modelId: transaction.modelId,
288
+ modelName: transaction.modelName,
289
+ reason,
290
+ });
291
+ }
292
+ else {
293
+ if (previousState)
294
+ Object.assign(model, previousState);
295
+ this.objectPool.add(model, ModelScope.live);
296
+ }
297
+ }
298
+ this.notifyObservers({
299
+ type: 'rollback',
300
+ modelType: transaction.modelName,
301
+ modelId: transaction.modelId,
302
+ transactionType: transaction.type,
303
+ });
304
+ // Emit event so SyncedStore can clear pendingDeletes on delete rollback
305
+ this.emit('sync:rollback', {
306
+ modelId: transaction.modelId,
307
+ modelName: transaction.modelName,
308
+ transactionType: transaction.type,
309
+ reason,
310
+ });
311
+ }
312
+ catch (error) {
313
+ this.runtime.observability.captureMutationFailure({
314
+ context: 'rollback-failed',
315
+ transactionId: transaction.id,
316
+ modelName: transaction.modelName,
317
+ modelId: transaction.modelId,
318
+ error: error instanceof Error ? error : new Error(String(error)),
319
+ });
320
+ }
321
+ });
322
+ }
323
+ /**
324
+ * Forward reconciliation requests from the {@link MutationQueue} to the
325
+ * sync layer. When delta confirmation times out, the queue emits
326
+ * `reconciliation:needed` instead of rolling back, so optimistic state the
327
+ * server may already have committed is never destroyed.
328
+ */
329
+ setupReconciliationForwarding() {
330
+ this.mutationQueue.on('reconciliation:needed', (event) => {
331
+ this.runtime.observability.captureReconciliation({
332
+ reason: event.reason,
333
+ model: event.model,
334
+ modelId: event.modelId,
335
+ syncIdNeeded: event.syncIdNeeded,
336
+ lastSeenSyncId: event.lastSeenSyncId,
337
+ retryCount: event.retryCount,
338
+ connectionState: this.connectionState,
339
+ });
340
+ // Forward to SyncedStore via event — it has access to the WebSocket
341
+ this.emit('reconciliation:needed', event);
342
+ });
343
+ }
344
+ /**
345
+ * Persist unconfirmed transactions to IndexedDB. When delta-confirmation
346
+ * retries are exhausted, the transaction is cached so it survives a tab
347
+ * close. On the next session, a WebSocket reconnect and delta catch-up
348
+ * deliver the missing deltas and confirm the transaction.
349
+ */
350
+ setupAwaitingTransactionPersistence() {
351
+ this.mutationQueue.on('transaction:persist_awaiting', (event) => {
352
+ // void is safe: the handler's body is fully try/catch'd.
353
+ void this.persistAwaitingTransaction(event);
354
+ });
355
+ // Clean up persisted awaiting transactions when they're finally confirmed
356
+ this.mutationQueue.on('transaction:completed', (tx) => {
357
+ // void is safe: the handler's body is fully try/catch'd.
358
+ void this.removeAwaitingTransaction(tx.id);
359
+ });
360
+ // Echo detection bridge. When the queue stages a transaction, the
361
+ // client has already optimistically applied the change to the
362
+ // pool — record the tx id so the matching server delta echo gets
363
+ // recognized in `applyDeltaBatchToPool`. The set is drained when
364
+ // the echo lands; if a transaction is rolled back before the
365
+ // server processes it, we drain on rollback too so a stale id
366
+ // doesn't permanently silence a foreign delta sharing the same id
367
+ // (vanishingly unlikely for UUIDs, but cheap insurance).
368
+ this.mutationQueue.on('transaction:created', (tx) => {
369
+ if (!tx.localOnly)
370
+ this.echoTracker.markPending(tx.id);
371
+ });
372
+ this.mutationQueue.on('optimistic:rollback', (event) => {
373
+ this.echoTracker.drainOnRollback(event.transaction.id);
374
+ });
375
+ }
376
+ /** Persist an unconfirmed transaction to IndexedDB (never rejects — failures are captured). */
377
+ async persistAwaitingTransaction(event) {
378
+ if (!this.database)
379
+ return;
380
+ try {
381
+ await this.database.saveTransaction({
382
+ id: `awaiting_${event.txId}`,
383
+ type: 'awaiting_delta',
384
+ timestamp: Date.now(),
385
+ awaitingDelta: {
386
+ syncIdNeeded: event.syncIdNeeded ?? 0,
387
+ modelName: event.model,
388
+ modelId: event.modelId,
389
+ operationType: event.operationType,
390
+ },
391
+ });
392
+ this.runtime.observability.breadcrumb('Persisted unconfirmed transaction to IDB', 'sync.transaction', 'info', {
393
+ txId: event.txId,
394
+ model: event.model,
395
+ modelId: event.modelId,
396
+ });
397
+ }
398
+ catch (error) {
399
+ this.runtime.observability.captureMutationFailure({
400
+ context: 'persist-awaiting-transaction',
401
+ modelName: event.model,
402
+ modelId: event.modelId,
403
+ error: error instanceof Error ? error : new Error(String(error)),
404
+ });
405
+ }
406
+ }
407
+ /** Drop the persisted awaiting-row once confirmed (never rejects). */
408
+ async removeAwaitingTransaction(txId) {
409
+ if (!this.database)
410
+ return;
411
+ try {
412
+ await this.database.removeTransaction(`awaiting_${txId}`);
413
+ }
414
+ catch {
415
+ // Ignore — might not have been persisted
416
+ }
417
+ }
418
+ /**
419
+ * Initialize sync client with authentication
420
+ */
421
+ async initialize(userId, organizationId) {
422
+ this.userId = userId;
423
+ this.organizationId = organizationId;
424
+ this.runtime.observability.setContext(userId, organizationId);
425
+ await this.mutationQueue.setCommitOutboxScope({
426
+ organizationId,
427
+ participantId: userId,
428
+ namespace: this.commitOutboxNamespace,
429
+ });
430
+ // Restore exact, already-sealed requests first. The returned source ids
431
+ // suppress any legacy queue entry left behind by an older non-atomic
432
+ // handoff.
433
+ const sealedMutationIds = await this.mutationQueue.restoreDurableCommits();
434
+ await this.mutationQueue.loadPersistedTransactions(this.mutationPersistence, sealedMutationIds);
435
+ // Read the initial network status from the injected OnlineStatusProvider.
436
+ // In the browser this reflects the host's connectivity signal; in Node it
437
+ // reports online by default. NetworkMonitor drives the ongoing
438
+ // online/offline transitions below — this read is only the initial
439
+ // snapshot taken when identity is set.
440
+ if (this.runtime.onlineStatus.isOnline()) {
441
+ this.setConnectionState('connected');
442
+ }
443
+ else {
444
+ // Offline - start in offline mode
445
+ this.setConnectionState('disconnected');
446
+ this.emit('sync:offline');
447
+ }
448
+ if (this.mutationQueue.getOutstandingTransactionCount() > 0) {
449
+ this.scheduleSync();
450
+ }
451
+ }
452
+ /**
453
+ * The organization this client writes under (set by `initialize`).
454
+ * Read by the model proxy so `create()` defaults `organizationId` the
455
+ * same way the mutator path does — `null` until identity is wired.
456
+ */
457
+ getOrganizationId() {
458
+ return this.organizationId;
459
+ }
460
+ /**
461
+ * Self-healing helper for individual model records.
462
+ *
463
+ * Two registry-driven repair passes run on every row hydrated from
464
+ * IndexedDB or merged from a delta:
465
+ *
466
+ * 1. **Auto-fill** — for each `autoFill` rule the consumer's schema
467
+ * declares on this model, copy the corresponding identity value
468
+ * (`organizationId` / `userId`) onto the row when it's missing.
469
+ * Repairs rows from a past version that didn't write the field.
470
+ *
471
+ * 2. **Required-field gate** — if the row is missing any field listed
472
+ * in the model's `requiredFields`, return `null` so the caller
473
+ * skips this record. Used for FK columns whose absence renders the
474
+ * row unrecoverable (e.g. a Block with no sectionId).
475
+ *
476
+ * The engine itself is product-neutral: model identity (which fields
477
+ * to back-fill, which absences are fatal) lives entirely in the
478
+ * consumer schema.
479
+ */
480
+ healModelRecord(modelType, data) {
481
+ const meta = this.objectPool.registry.getMetadata(modelType);
482
+ if (!meta)
483
+ return { data, healed: false };
484
+ const idPrefix = data.id?.slice(0, 8) ?? 'unknown';
485
+ let result = data;
486
+ let healed = false;
487
+ if (meta.autoFill) {
488
+ for (const rule of meta.autoFill) {
489
+ if (result[rule.field])
490
+ continue;
491
+ const replacement = rule.from === 'organizationId' ? this.organizationId : this.userId;
492
+ if (!replacement)
493
+ continue;
494
+ this.runtime.observability.captureSelfHealing({
495
+ modelName: modelType,
496
+ modelId: idPrefix,
497
+ field: rule.field,
498
+ action: `added missing ${rule.field}`,
499
+ });
500
+ result = { ...result, [rule.field]: replacement };
501
+ healed = true;
502
+ }
503
+ }
504
+ if (meta.requiredFields) {
505
+ for (const field of meta.requiredFields) {
506
+ if (result[field])
507
+ continue;
508
+ this.runtime.observability.captureSelfHealing({
509
+ modelName: modelType,
510
+ modelId: idPrefix,
511
+ field,
512
+ action: `skipped corrupted ${modelType} - missing ${field}`,
513
+ });
514
+ return null;
515
+ }
516
+ }
517
+ return { data: result, healed };
518
+ }
519
+ /**
520
+ * Hydrate InstanceCache with data from Database
521
+ * Called after bootstrap is complete
522
+ */
523
+ async hydrateFromDatabase() {
524
+ if (!this.database) {
525
+ throw new AbloValidationError('Database not available for hydration', {
526
+ code: 'sync_client_db_missing',
527
+ });
528
+ }
529
+ // Get model types that should be hydrated on startup (skip lazy per LSE)
530
+ const modelTypes = this.objectPool.registry.getRegisteredModelNames().filter((name) => {
531
+ const meta = this.objectPool.registry.getMetadata(name);
532
+ return meta?.loadStrategy === LoadStrategy.instant;
533
+ });
534
+ const totalStart = typeof performance !== 'undefined' ? performance.now() : Date.now();
535
+ // Phase 1: Fetch all data from IndexedDB and create model instances (async I/O).
536
+ // We collect all models across ALL types before touching MobX, so that Phase 2
537
+ // can add them in a single addBatch() call → ONE MobX action → ONE re-render.
538
+ const allModelsToAdd = [];
539
+ const perTypePerfLogs = [];
540
+ for (const modelType of modelTypes) {
541
+ const typeStart = typeof performance !== 'undefined' ? performance.now() : Date.now();
542
+ try {
543
+ // Get raw data from Database (via StoreManager)
544
+ const rawData = await this.database.hydrateModels(modelType);
545
+ const afterFetch = typeof performance !== 'undefined' ? performance.now() : Date.now();
546
+ // Create models in batch first, collect for deferred addBatch
547
+ const modelsForType = [];
548
+ const recordsToHeal = [];
549
+ for (const data of rawData) {
550
+ let withType = data && typeof data === 'object' && !data.__typename
551
+ ? { __typename: modelType, ...data }
552
+ : data;
553
+ // Self-healing: Fix corrupted IndexedDB records missing essential fields
554
+ const healResult = this.healModelRecord(modelType, withType);
555
+ if (healResult === null) {
556
+ continue; // Record is corrupted beyond repair — skip
557
+ }
558
+ withType = healResult.data;
559
+ if (healResult.healed) {
560
+ recordsToHeal.push({ id: healResult.data.id, data: healResult.data });
561
+ }
562
+ const model = this.objectPool.createFromData(withType);
563
+ if (model) {
564
+ modelsForType.push(model);
565
+ }
566
+ }
567
+ // Collect models for the single batched addBatch call in Phase 2
568
+ allModelsToAdd.push(...modelsForType);
569
+ // Persist healed records back to IndexedDB (fire-and-forget, non-blocking)
570
+ if (recordsToHeal.length > 0 && this.database) {
571
+ this.runtime.logger.info(`[SyncClient.hydrate] Persisting ${recordsToHeal.length} healed ${modelType} records to IndexedDB`);
572
+ // Use fire-and-forget to not block hydration.
573
+ // void is safe: the handler's body is fully try/catch'd.
574
+ void Promise.resolve().then(async () => {
575
+ try {
576
+ for (const { id, data } of recordsToHeal) {
577
+ await this.database.putRecord(modelType, id, data);
578
+ }
579
+ this.runtime.logger.info(`[SyncClient.hydrate] Successfully healed ${recordsToHeal.length} ${modelType} records`);
580
+ }
581
+ catch (err) {
582
+ this.runtime.observability.captureMutationFailure({
583
+ context: 'persist-healed-records',
584
+ modelName: modelType,
585
+ error: err instanceof Error ? err : new Error(String(err)),
586
+ });
587
+ }
588
+ });
589
+ }
590
+ const typeEnd = typeof performance !== 'undefined' ? performance.now() : Date.now();
591
+ perTypePerfLogs.push({
592
+ type: modelType,
593
+ fetched: rawData.length,
594
+ added: modelsForType.length,
595
+ fetchMs: (afterFetch - typeStart).toFixed(2),
596
+ createMs: (typeEnd - afterFetch).toFixed(2),
597
+ });
598
+ }
599
+ catch (error) {
600
+ this.runtime.observability.captureBootstrapFailure(error, { type: `hydrate-${modelType}` });
601
+ }
602
+ }
603
+ // Phase 2: Single MobX action — add ALL models across all types at once.
604
+ const addStart = typeof performance !== 'undefined' ? performance.now() : Date.now();
605
+ const totalAdded = this.objectPool.addBatch(allModelsToAdd, ModelScope.live);
606
+ const addEnd = typeof performance !== 'undefined' ? performance.now() : Date.now();
607
+ // Log per-type perf after the batched add (so logs still show per-type breakdown)
608
+ for (const entry of perTypePerfLogs) {
609
+ this.runtime.logger.debug('hydrate:type', parseFloat(entry.fetchMs) + parseFloat(entry.createMs), {
610
+ type: entry.type,
611
+ fetched: entry.fetched,
612
+ added: entry.added,
613
+ fetchMs: entry.fetchMs,
614
+ createMs: entry.createMs,
615
+ });
616
+ }
617
+ const totalEnd = typeof performance !== 'undefined' ? performance.now() : Date.now();
618
+ this.runtime.logger.debug('hydrate:total', totalEnd - totalStart, {
619
+ totalModels: totalAdded,
620
+ addBatchMs: (addEnd - addStart).toFixed(2),
621
+ });
622
+ // One-line startup summary: types pre-seeded and items per type
623
+ try {
624
+ const preseededTypes = this.objectPool.registry.getRegisteredModelNames();
625
+ const stats = this.objectPool.getStats();
626
+ this.runtime.logger.info('startup_summary', {
627
+ typesPreseeded: preseededTypes.length,
628
+ poolSize: stats.size,
629
+ typeCounts: stats.typeCounts,
630
+ });
631
+ }
632
+ catch { }
633
+ }
634
+ /**
635
+ * Re-hydrate InstanceCache from IndexedDB when the pool already has data.
636
+ *
637
+ * Unlike hydrateFromDatabase() (which uses addBatch and skips existing IDs),
638
+ * this method properly:
639
+ * 1. Upserts models — updates existing models in-place, adds new ones
640
+ * 2. Removes ghosts — deletes models from the pool that no longer exist in IndexedDB
641
+ *
642
+ * Used by background bootstrap, network recovery, and server-triggered re-bootstrap.
643
+ */
644
+ async rehydrateFromDatabase() {
645
+ if (!this.database) {
646
+ throw new AbloValidationError('Database not available for rehydration', {
647
+ code: 'sync_client_db_missing',
648
+ });
649
+ }
650
+ const totalStart = typeof performance !== 'undefined' ? performance.now() : Date.now();
651
+ // Model types to rehydrate (same filter as hydrateFromDatabase)
652
+ const modelTypes = this.objectPool.registry.getRegisteredModelNames().filter((name) => {
653
+ const meta = this.objectPool.registry.getMetadata(name);
654
+ return meta?.loadStrategy === LoadStrategy.instant;
655
+ });
656
+ // ── Phase 1: Read from IndexedDB & create model instances (async I/O) ──
657
+ const allModels = [];
658
+ const idbIdsByType = new Map();
659
+ let healedCount = 0;
660
+ let skippedCount = 0;
661
+ for (const modelType of modelTypes) {
662
+ try {
663
+ const rawData = await this.database.hydrateModels(modelType);
664
+ const idsForType = new Set();
665
+ idbIdsByType.set(modelType, idsForType);
666
+ for (const data of rawData) {
667
+ let withType = data && typeof data === 'object' && !data.__typename
668
+ ? { __typename: modelType, ...data }
669
+ : data;
670
+ // Self-healing
671
+ const healResult = this.healModelRecord(modelType, withType);
672
+ if (healResult === null) {
673
+ skippedCount++;
674
+ continue;
675
+ }
676
+ withType = healResult.data;
677
+ if (healResult.healed) {
678
+ healedCount++;
679
+ // Persist heal back to IndexedDB (fire-and-forget)
680
+ if (this.database) {
681
+ const id = healResult.data.id;
682
+ const healedData = healResult.data;
683
+ // void is safe: the handler's body is fully try/catch'd.
684
+ void Promise.resolve().then(async () => {
685
+ try {
686
+ await this.database.putRecord(modelType, id, healedData);
687
+ }
688
+ catch {
689
+ // Non-critical — will heal again next time
690
+ }
691
+ });
692
+ }
693
+ }
694
+ // Register ID before createFromData — prevents ghost removal
695
+ // if createFromData fails for a record that exists in IDB
696
+ const recordId = withType.id;
697
+ if (recordId) {
698
+ idsForType.add(recordId);
699
+ }
700
+ try {
701
+ const model = this.objectPool.createFromData(withType);
702
+ if (model) {
703
+ allModels.push(model);
704
+ }
705
+ }
706
+ catch (error) {
707
+ this.runtime.observability.breadcrumb('Model creation failed during rehydration', 'sync.bootstrap', 'warning', {
708
+ modelType,
709
+ modelId: recordId?.slice(0, 8) ?? 'unknown',
710
+ error: error instanceof Error ? error.message : String(error),
711
+ });
712
+ skippedCount++;
713
+ }
714
+ }
715
+ }
716
+ catch (error) {
717
+ this.runtime.observability.captureBootstrapFailure(error, { type: `rehydrate-${modelType}` });
718
+ }
719
+ }
720
+ // ── Phase 2: Upsert batch (single MobX action) ──
721
+ // createFromData already calls updateFromData() on existing models,
722
+ // so existing models are up-to-date. Upsert adds the new ones and
723
+ // updates scope for any that changed.
724
+ const beforeSize = this.objectPool.size;
725
+ this.objectPool.upsertBatch(allModels, ModelScope.live);
726
+ const addedCount = this.objectPool.size - beforeSize;
727
+ const updatedCount = allModels.length - addedCount;
728
+ // ── Phase 3: Reconcile ghost deletions (single MobX action) ──
729
+ // Only reconcile types that were rehydrated — never touch lazy-loaded types.
730
+ const ghostIds = [];
731
+ for (const modelType of modelTypes) {
732
+ const idbIds = idbIdsByType.get(modelType);
733
+ if (!idbIds)
734
+ continue; // Type had an error during fetch — don't reconcile
735
+ const poolIds = this.objectPool.getIdsByModelType(modelType);
736
+ if (!poolIds)
737
+ continue;
738
+ for (const poolId of poolIds) {
739
+ if (!idbIds.has(poolId)) {
740
+ ghostIds.push(poolId);
741
+ }
742
+ }
743
+ }
744
+ const removedCount = this.objectPool.removeBatch(ghostIds);
745
+ // ── Phase 4: Stats & logging ──
746
+ const totalEnd = typeof performance !== 'undefined' ? performance.now() : Date.now();
747
+ const elapsedMs = Math.round(totalEnd - totalStart);
748
+ const stats = {
749
+ added: addedCount,
750
+ updated: updatedCount,
751
+ removed: removedCount,
752
+ skipped: skippedCount,
753
+ healed: healedCount,
754
+ elapsedMs,
755
+ };
756
+ this.runtime.logger.info('[SyncClient.rehydrate] Complete', {
757
+ ...stats,
758
+ poolSize: this.objectPool.size,
759
+ ghostIds: ghostIds.length > 0 ? ghostIds.slice(0, 5).map((id) => id.slice(0, 8)) : [],
760
+ });
761
+ this.runtime.observability.breadcrumb('Rehydration complete', 'sync.bootstrap', 'info', {
762
+ added: stats.added,
763
+ updated: stats.updated,
764
+ removed: stats.removed,
765
+ elapsedMs: stats.elapsedMs,
766
+ });
767
+ return stats;
768
+ }
769
+ /**
770
+ * Apply a mutation to a model optimistically and queue it for server sync.
771
+ * IndexedDB is updated only once the server confirms the change with a delta
772
+ * packet.
773
+ *
774
+ * A model's changes are captured before the pool action runs, because a pool
775
+ * operation such as an upsert can clear the model's local change set;
776
+ * capturing first ensures those changes are never lost. The captured set is
777
+ * frozen and handed to {@link queueMutation}.
778
+ */
779
+ mutate(type, model, poolAction, writeOptions) {
780
+ // No-op UPDATE guard (O(1)). An update with no dirty fields would travel
781
+ // to the server, get dropped by `coalesceOperations` Rule 4 (empty input),
782
+ // and — if it was the only op — come back as `lastSyncId: 0`. That trips
783
+ // `captureCommitZeroSyncId` (false-positive Sentry anomaly) AND parks the
784
+ // tx in `awaiting_delta` for a 30s reconciliation timeout on a write that
785
+ // changed nothing. `Model.hasChanges` reads `modifiedProperties.size`, so
786
+ // this costs O(1) with no allocation (vs. O(N) materializing getChanges()).
787
+ //
788
+ // Strict `=== false` is deliberate: `rowAsModel` only casts, so a non-Model
789
+ // object can reach here with `hasChanges === undefined`. `undefined === false`
790
+ // is false → we fall through to the normal path rather than risk dropping a
791
+ // real write. Only a genuine Model with an empty dirty-set is skipped.
792
+ const hasChanges = model.hasChanges;
793
+ if (type === 'update' && hasChanges === false) {
794
+ return;
795
+ }
796
+ // Capture changes before the pool action runs. Pool operations —
797
+ // upsert in particular — can clear the model's local changes, so
798
+ // capturing first ensures they are never lost.
799
+ const capturedChanges = type === 'update' || type === 'create' ? this.captureModelChanges(model) : undefined;
800
+ poolAction();
801
+ this.stageMutation(type, model, capturedChanges, writeOptions);
802
+ this.notifyObservers({
803
+ type,
804
+ modelType: model.getModelName(),
805
+ model: type !== 'delete' ? model : undefined,
806
+ modelId: model.id,
807
+ });
808
+ // QueryProcessor uses `models:changed` to invalidate caches. Coalesce
809
+ // to one event per microtask: a paste of 100 rows should re-run
810
+ // affected queries ONCE, not 100×.
811
+ this.markModelChanged(model.getModelName());
812
+ }
813
+ pendingChangedTypes = null;
814
+ markModelChanged(modelType) {
815
+ if (!this.pendingChangedTypes) {
816
+ this.pendingChangedTypes = new Set();
817
+ const schedule = typeof queueMicrotask === 'function'
818
+ ? queueMicrotask
819
+ : (cb) => Promise.resolve().then(cb);
820
+ schedule(() => {
821
+ const types = this.pendingChangedTypes;
822
+ this.pendingChangedTypes = null;
823
+ if (types && types.size > 0)
824
+ this.emit('models:changed', types);
825
+ });
826
+ }
827
+ this.pendingChangedTypes.add(modelType);
828
+ }
829
+ /**
830
+ * Capture model changes immutably BEFORE any pool operations
831
+ * This prevents the fragile pattern of reading changes after state modification
832
+ */
833
+ captureModelChanges(model) {
834
+ if (typeof model.getChanges !== 'function')
835
+ return undefined;
836
+ const changes = model.getChanges();
837
+ // Return a frozen copy to prevent accidental modification
838
+ return Object.keys(changes).length > 0 ? Object.freeze({ ...changes }) : undefined;
839
+ }
840
+ /** Add new model (CREATE) - works offline */
841
+ add(model, options) {
842
+ this.mutate('create', model, () => { this.objectPool.add(model, ModelScope.live); }, options);
843
+ }
844
+ /** Update existing model (UPDATE) - works offline */
845
+ update(model, options) {
846
+ this.mutate('update', model, () => { this.objectPool.upsert(model, ModelScope.live); }, options);
847
+ }
848
+ /**
849
+ * Update existing model with pre-computed changes.
850
+ * Used by saveManyOptimized when incoming models have empty change-tracking
851
+ * (e.g. freshly constructed cell models from a bulk document decomposition).
852
+ */
853
+ updateWithChanges(model, changes) {
854
+ this.runtime.logger.debug(`SyncClient.updateWithChanges`, {
855
+ modelId: model.id,
856
+ modelType: model.getModelName(),
857
+ });
858
+ // Use pre-computed changes if provided, otherwise fall back to model.getChanges()
859
+ const capturedChanges = changes && Object.keys(changes).length > 0
860
+ ? Object.freeze({ ...changes })
861
+ : this.captureModelChanges(model);
862
+ // No-op UPDATE guard: neither an explicit change set nor model dirty-fields.
863
+ // `captureModelChanges` already returns undefined for an empty dirty-set, so
864
+ // an undefined here means there is genuinely nothing to send — skip rather
865
+ // than emit an empty-input update that the server coalesces to lastSyncId 0
866
+ // (see the same guard in `mutate`).
867
+ if (capturedChanges === undefined)
868
+ return;
869
+ this.objectPool.upsert(model, ModelScope.live);
870
+ this.stageMutation('update', model, capturedChanges);
871
+ this.notifyObservers({
872
+ type: 'update',
873
+ modelType: model.getModelName(),
874
+ model,
875
+ modelId: model.id,
876
+ });
877
+ }
878
+ /** Expose the GraphQL client for atomic mutations (e.g., createSectionWithBlocks).
879
+ * Used by SyncedStore for operations that bypass the transaction queue
880
+ * but still need optimistic pool updates at the sync layer. */
881
+ get gql() {
882
+ return this.mutationExecutor;
883
+ }
884
+ /** Delete model (DELETE) - works offline */
885
+ delete(model, options) {
886
+ // Clear pending mutations first to prevent "not found" errors on fast delete
887
+ this.mutationQueue.cancelTransactionsForModel(model.id);
888
+ this.mutate('delete', model, () => this.objectPool.remove(model.id), options);
889
+ }
890
+ /**
891
+ * Upload a file and create its attachment record. The upload runs through
892
+ * the {@link MutationQueue}, and a model is built from the server's
893
+ * response and added to the pool.
894
+ */
895
+ async uploadFile(file, options) {
896
+ if (!this.userId || !this.organizationId) {
897
+ throw new AbloAuthenticationError('Authentication required for file uploads', {
898
+ code: 'file_upload_auth_required',
899
+ });
900
+ }
901
+ try {
902
+ // Use MutationQueue to handle the upload mutation
903
+ const result = await this.mutationQueue.uploadAttachment(file, {
904
+ id: options.id,
905
+ attachableType: options.attachableType,
906
+ attachableId: options.attachableId,
907
+ metadata: options.metadata,
908
+ }, {
909
+ userId: this.userId,
910
+ organizationId: this.organizationId,
911
+ });
912
+ if (result) {
913
+ // Create model from response using ModelRegistry (generic — no concrete class import)
914
+ const model = this.objectPool.createFromData({
915
+ id: options.id,
916
+ ...result,
917
+ });
918
+ if (model) {
919
+ this.objectPool.add(model, ModelScope.live);
920
+ this.notifyObservers({
921
+ type: 'create',
922
+ modelType: model.getModelName(),
923
+ model,
924
+ });
925
+ return model;
926
+ }
927
+ }
928
+ return null;
929
+ }
930
+ catch (error) {
931
+ this.runtime.observability.captureMutationFailure({
932
+ context: 'file-upload',
933
+ error: error instanceof Error ? error : new Error(String(error)),
934
+ });
935
+ throw error;
936
+ }
937
+ }
938
+ /**
939
+ * Batch upload files — single GraphQL call + parallel S3 PUTs.
940
+ *
941
+ * Returns the raw `Model[]` built by the object pool (typename is
942
+ * determined by the payload the server returns — currently always
943
+ * `Attachment`). The SDK has no knowledge of app-specific model classes,
944
+ * so it cannot honestly claim a narrower return type; consumers that
945
+ * need an `Attachment[]` project through their own typed accessor
946
+ * (e.g. `store.query.attachments.findMany({ where: { id: IN ids } })`)
947
+ * after the upload resolves.
948
+ */
949
+ async batchUploadFiles(files, options) {
950
+ if (!this.userId || !this.organizationId) {
951
+ throw new AbloAuthenticationError('Authentication required for file uploads', {
952
+ code: 'file_upload_auth_required',
953
+ });
954
+ }
955
+ const items = options.ids.map((id) => ({
956
+ id,
957
+ attachableType: options.attachableType,
958
+ attachableId: options.attachableId,
959
+ metadata: options.metadata,
960
+ }));
961
+ const results = await this.mutationQueue.batchUploadAttachments(files, items, {
962
+ userId: this.userId,
963
+ organizationId: this.organizationId,
964
+ });
965
+ const models = [];
966
+ for (const result of results) {
967
+ const model = this.objectPool.createFromData({ ...result });
968
+ if (model) {
969
+ this.objectPool.add(model, ModelScope.live);
970
+ this.notifyObservers({
971
+ type: 'create',
972
+ modelType: model.getModelName(),
973
+ model,
974
+ });
975
+ models.push(model);
976
+ }
977
+ }
978
+ return models;
979
+ }
980
+ /** Archive model (ARCHIVE) - works offline */
981
+ archive(model) {
982
+ this.mutate('archive', model, () => { this.objectPool.updateScope(model.id, ModelScope.archived); });
983
+ }
984
+ /**
985
+ * Append a mutation to the pending queue and schedule its sync work.
986
+ *
987
+ * IndexedDB persistence and the server push are deferred to a microtask, so
988
+ * many pushes within the same tick collapse into a single serialization and
989
+ * a single process call. Without the deferral, queueing a hundred mutations
990
+ * at once — a large paste, a document import, bulk row creation — would
991
+ * reserialize the whole growing queue a hundred times, an O(N²) cost in
992
+ * `model.toJSON()`.
993
+ *
994
+ * @param mutation.capturedChanges - Pre-captured, frozen changes, used to
995
+ * avoid re-reading a model after pool operations that might clear them.
996
+ */
997
+ /** Stage one mutation through the queue, which owns durability and execution. */
998
+ stageMutation(type, model, capturedChanges, writeOptions) {
999
+ if (this.isDisposed)
1000
+ return;
1001
+ if (!this.userId || !this.organizationId) {
1002
+ this.mutationQueue.deferMutation(type, model, capturedChanges, writeOptions);
1003
+ return;
1004
+ }
1005
+ const context = { userId: this.userId, organizationId: this.organizationId };
1006
+ const staging = this.mutationQueue.enqueueModelMutation(type, model, context, capturedChanges, writeOptions);
1007
+ const pending = staging.then(() => undefined).catch((error) => {
1008
+ this.runtime.observability.captureMutationFailure({
1009
+ context: `stage-mutation-${type}`,
1010
+ modelName: model.getModelName(),
1011
+ modelId: model.id,
1012
+ error,
1013
+ });
1014
+ });
1015
+ this.pendingStages.add(pending);
1016
+ void pending.finally(() => this.pendingStages.delete(pending));
1017
+ }
1018
+ scheduleSync() {
1019
+ if (!this.runtime.onlineStatus.isOnline() || this.isDisposed)
1020
+ return;
1021
+ void this.processPendingMutations().catch((error) => {
1022
+ this.runtime.observability.captureMutationFailure({
1023
+ context: 'background-sync',
1024
+ error,
1025
+ });
1026
+ });
1027
+ }
1028
+ async processPendingMutations() {
1029
+ if (this.pendingStages.size > 0) {
1030
+ await Promise.all([...this.pendingStages]);
1031
+ }
1032
+ await this.drainPendingSettlements();
1033
+ }
1034
+ /**
1035
+ * Resolve a conflict between the local model and incoming server data,
1036
+ * called while processing deltas from the WebSocket. Certain server states,
1037
+ * such as deletions and deactivations, always take precedence even when the
1038
+ * local model has unsynced changes, so the two sides stay consistent.
1039
+ */
1040
+ resolveConflicts(localModel, serverData) {
1041
+ const hasLocalChanges = localModel.hasChanges;
1042
+ // Safely get timestamp, handling both Date objects and strings
1043
+ const localUpdatedAt = localModel.updatedAt
1044
+ ? localModel.updatedAt instanceof Date
1045
+ ? localModel.updatedAt.getTime()
1046
+ : new Date(localModel.updatedAt).getTime()
1047
+ : 0;
1048
+ const serverUpdatedAt = toEpochMs(serverData.updatedAt);
1049
+ this.runtime.logger.debug('Conflict resolution', {
1050
+ modelId: localModel.id,
1051
+ modelType: localModel.getModelName(),
1052
+ hasLocalChanges,
1053
+ localUpdatedAt: localModel.updatedAt?.toString(),
1054
+ serverUpdatedAt: serverData.updatedAt,
1055
+ localChanges: localModel.getChanges(),
1056
+ serverState: this.extractCriticalState(serverData),
1057
+ });
1058
+ // PRIORITY 1: Check for critical server states that must be respected
1059
+ // These states override any local changes to maintain data consistency
1060
+ const criticalServerStates = this.extractCriticalState(serverData);
1061
+ const shouldForceAcceptServer = this.hasCriticalStateChange(criticalServerStates);
1062
+ if (shouldForceAcceptServer) {
1063
+ this.runtime.logger.debug('Accepting server update - critical state change detected', {
1064
+ modelId: localModel.id,
1065
+ criticalStates: criticalServerStates,
1066
+ });
1067
+ // Force accept server state for critical changes
1068
+ localModel.updateFromData(serverData);
1069
+ localModel.clearChanges();
1070
+ localModel.markAsSynced();
1071
+ return localModel;
1072
+ }
1073
+ // Local-first: if we have local dirty fields, merge by field.
1074
+ // Keep locally changed fields; apply server for the rest.
1075
+ if (hasLocalChanges) {
1076
+ const localChanges = localModel.getChanges();
1077
+ this.runtime.logger.debug('Merging server update with local dirty fields', {
1078
+ modelId: localModel.id,
1079
+ keptFields: Object.keys(localChanges || {}),
1080
+ });
1081
+ // Merge: server baseline + local dirty fields win
1082
+ const merged = { ...serverData, ...(localChanges || {}) };
1083
+ // Preserve the most recent updatedAt without clearing dirty flags
1084
+ if (serverData.updatedAt || localModel.updatedAt) {
1085
+ const mergedUpdatedAt = new Date(Math.max(localUpdatedAt, serverUpdatedAt));
1086
+ // updateFromData accepts Date or ISO string for dates
1087
+ merged.updatedAt = mergedUpdatedAt;
1088
+ }
1089
+ localModel.updateFromData(merged);
1090
+ // Intentionally DO NOT clearChanges here; pending tx will confirm and clear
1091
+ return localModel;
1092
+ }
1093
+ // No local changes: fall back to LWW to converge
1094
+ // Accept server regardless of timestamp equality to stay in sync
1095
+ const acceptReason = serverUpdatedAt > localUpdatedAt ? 'server is newer' : 'no local changes';
1096
+ this.runtime.logger.debug(`Accepting server update - ${acceptReason}`);
1097
+ localModel.updateFromData(serverData);
1098
+ localModel.clearChanges();
1099
+ localModel.markAsSynced();
1100
+ return localModel;
1101
+ }
1102
+ /**
1103
+ * Extract the critical state fields from server data. These are the states
1104
+ * that must be honored even when the local model has unsynced changes. The
1105
+ * conflict resolver reads exactly these fields and no others.
1106
+ */
1107
+ extractCriticalState(serverData) {
1108
+ const critical = {};
1109
+ if (!serverData || typeof serverData !== 'object') {
1110
+ return critical;
1111
+ }
1112
+ // Deletion/archival states - always critical
1113
+ if (serverData.deletedAt !== undefined) {
1114
+ critical.deletedAt = serverData.deletedAt;
1115
+ }
1116
+ if (serverData.archivedAt !== undefined) {
1117
+ critical.archivedAt = serverData.archivedAt;
1118
+ }
1119
+ // Deactivation states - critical for assignments and similar entities
1120
+ if (serverData.isActive !== undefined && serverData.isActive === false) {
1121
+ critical.isActive = false;
1122
+ }
1123
+ if (serverData.unassignedAt !== undefined) {
1124
+ critical.unassignedAt = serverData.unassignedAt;
1125
+ }
1126
+ return critical;
1127
+ }
1128
+ /**
1129
+ * Check if critical state changes exist that require forcing server state
1130
+ */
1131
+ hasCriticalStateChange(criticalStates) {
1132
+ // Any critical state present means we should force accept server
1133
+ return (Object.keys(criticalStates).length > 0 &&
1134
+ Object.values(criticalStates).some((v) => v !== null && v !== undefined));
1135
+ }
1136
+ /**
1137
+ * Handle network reconnection
1138
+ */
1139
+ async handleReconnection() {
1140
+ this.runtime.observability.breadcrumb('Network reconnected', 'sync.offline');
1141
+ this.emit('sync:reconnecting');
1142
+ try {
1143
+ // MutationQueue owns the durable flush and commit lanes.
1144
+ await this.processPendingMutations();
1145
+ this.setConnectionState('connected');
1146
+ this.emit('sync:reconnected');
1147
+ }
1148
+ catch (error) {
1149
+ this.runtime.observability.captureMutationFailure({
1150
+ context: 'reconnection-sync',
1151
+ error: error instanceof Error ? error : new Error(String(error)),
1152
+ });
1153
+ this.emit('sync:error', error);
1154
+ }
1155
+ }
1156
+ /**
1157
+ * Handle network disconnection
1158
+ */
1159
+ async handleDisconnection() {
1160
+ this.runtime.observability.breadcrumb('Network disconnected', 'sync.offline');
1161
+ this.setConnectionState('disconnected');
1162
+ this.emit('sync:offline');
1163
+ }
1164
+ /**
1165
+ * Get current sync state
1166
+ */
1167
+ getState() {
1168
+ return {
1169
+ connectionState: this.connectionState,
1170
+ pendingMutations: this.mutationQueue.getOutstandingTransactionCount(),
1171
+ lastSyncAt: new Date(),
1172
+ error: undefined,
1173
+ };
1174
+ }
1175
+ /**
1176
+ * Set connection state
1177
+ */
1178
+ setConnectionState(state) {
1179
+ const oldState = this.connectionState;
1180
+ this.connectionState = state;
1181
+ if (oldState !== state) {
1182
+ this.runtime.observability.setConnectionState(state);
1183
+ this.runtime.observability.breadcrumb(`Connection: ${oldState} → ${state}`, 'sync.websocket');
1184
+ if (state === 'connected') {
1185
+ this.emit('connection:established');
1186
+ this.mutationQueue.setConnectionState('connected');
1187
+ }
1188
+ else if (state === 'disconnected') {
1189
+ this.emit('connection:disconnected');
1190
+ this.mutationQueue.setConnectionState('disconnected');
1191
+ }
1192
+ }
1193
+ }
1194
+ /**
1195
+ * Subscribe to events with disposer pattern
1196
+ */
1197
+ subscribe(event, handler) {
1198
+ super.on(event, handler);
1199
+ // Return disposer function
1200
+ return () => {
1201
+ this.off(event, handler);
1202
+ };
1203
+ }
1204
+ /**
1205
+ * Add observer for sync events
1206
+ */
1207
+ addObserver(observer) {
1208
+ this.observers.add(observer);
1209
+ }
1210
+ /**
1211
+ * Remove observer
1212
+ */
1213
+ removeObserver(observer) {
1214
+ this.observers.delete(observer);
1215
+ }
1216
+ /**
1217
+ * Notify all observers
1218
+ */
1219
+ notifyObservers(event) {
1220
+ for (const observer of this.observers) {
1221
+ if (observer.onSync) {
1222
+ try {
1223
+ observer.onSync(event);
1224
+ }
1225
+ catch (error) {
1226
+ this.runtime.observability.breadcrumb('Observer error', 'sync.transaction', 'error', {
1227
+ error: error instanceof Error ? error.message : String(error),
1228
+ });
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+ /**
1234
+ * Disconnect from sync
1235
+ */
1236
+ disconnect() {
1237
+ this.setConnectionState('disconnected');
1238
+ }
1239
+ /**
1240
+ * Mark the sync client as connected
1241
+ * Called when WebSocket successfully connects (can happen independently of browser online/offline)
1242
+ */
1243
+ markConnected() {
1244
+ this.setConnectionState('connected');
1245
+ // Browser online state may have marked the client connected before the
1246
+ // WebSocket itself was ready. Always kick both durable lanes on the real
1247
+ // socket event, even when the high-level state did not change.
1248
+ void this.drainPendingSettlements().catch((error) => {
1249
+ this.runtime.observability.captureMutationFailure({
1250
+ context: 'restore-commit-outbox',
1251
+ error: error instanceof Error ? error : new Error(String(error)),
1252
+ });
1253
+ });
1254
+ void this.processPendingMutations();
1255
+ }
1256
+ drainPendingSettlements() {
1257
+ return this.reconnectDrain.drain(() => this.mutationQueue.drainPending());
1258
+ }
1259
+ /**
1260
+ * Dispose and cleanup
1261
+ */
1262
+ dispose() {
1263
+ this.isDisposed = true;
1264
+ this.disconnect();
1265
+ this.networkMonitor.dispose();
1266
+ this.observers.clear();
1267
+ this.pendingStages.clear();
1268
+ this.removeAllListeners();
1269
+ }
1270
+ /**
1271
+ * Notify the {@link MutationQueue} of an incoming delta so it can confirm
1272
+ * hosted writes by sync-id threshold and queued forwards by their echoed
1273
+ * source-batch correlation id.
1274
+ * @param syncId - The sync id of the received delta.
1275
+ * @param transactionId - Optional server echo of the originating local write.
1276
+ * @param correlationId - Opaque batch identity decoded from a source WAL echo.
1277
+ */
1278
+ onDeltaReceived(syncId, transactionId, correlationId) {
1279
+ try {
1280
+ this.mutationQueue.onDeltaReceived(syncId, transactionId, correlationId);
1281
+ }
1282
+ catch (e) {
1283
+ this.runtime.observability.breadcrumb('Failed to notify delta received', 'sync.transaction', 'warning', {
1284
+ syncId,
1285
+ transactionId,
1286
+ correlationId,
1287
+ });
1288
+ }
1289
+ }
1290
+ /**
1291
+ * Cancel pending transactions for child entities orphaned by a parent's
1292
+ * deletion. The store calls this when a delete delta arrives for a parent,
1293
+ * cancelling any queued writes on children that reference it.
1294
+ *
1295
+ * @param childModelName - The child model type (for example, `Block`).
1296
+ * @param foreignKey - The foreign-key property name (for example, `sectionId`).
1297
+ * @param parentId - The id of the deleted parent.
1298
+ * @returns The number of transactions cancelled.
1299
+ */
1300
+ cancelTransactionsByForeignKey(childModelName, foreignKey, parentId) {
1301
+ return this.mutationQueue.cancelTransactionsByForeignKey(childModelName, foreignKey, parentId);
1302
+ }
1303
+ /**
1304
+ * Wait for a transaction to be confirmed by its delta echo. Delegates to the
1305
+ * {@link MutationQueue}, which handles the confirmation timeout.
1306
+ */
1307
+ waitForDeltaConfirmation(transactionId) {
1308
+ return this.mutationQueue.waitForConfirmation(transactionId);
1309
+ }
1310
+ /**
1311
+ * Force sync now - process pending mutations
1312
+ */
1313
+ async syncNow() {
1314
+ await this.processPendingMutations();
1315
+ }
1316
+ /**
1317
+ * Get sync statistics. Return type is inferred from the literal so
1318
+ * the call site sees the actual shape — `connectionState` narrowed
1319
+ * to its three states, `objectPoolStats` typed by `InstanceCache.getStats`.
1320
+ */
1321
+ getSyncStats() {
1322
+ return {
1323
+ connectionState: this.connectionState,
1324
+ pendingMutations: this.mutationQueue.getOutstandingTransactionCount(),
1325
+ objectPoolStats: this.objectPool.getStats(),
1326
+ };
1327
+ }
1328
+ /**
1329
+ * Get pending transaction count from MutationQueue
1330
+ * Used by SyncedStore to compute hasUnsyncedChanges
1331
+ */
1332
+ getPendingTransactionCount() {
1333
+ const stats = this.mutationQueue.getStats();
1334
+ // Include pending and executing as "unsynced"
1335
+ // awaiting_delta transactions are included in 'executing' until confirmed
1336
+ // Completed and failed are "synced" (either done or gave up)
1337
+ return stats.pending + stats.executing;
1338
+ }
1339
+ /**
1340
+ * Subscribe to transaction events for sync status tracking
1341
+ * Returns unsubscribe function
1342
+ */
1343
+ onTransactionEvent(event, callback) {
1344
+ const eventName = `transaction:${event}`;
1345
+ this.mutationQueue.on(eventName, callback);
1346
+ return () => this.mutationQueue.off(eventName, callback);
1347
+ }
1348
+ /**
1349
+ * Subscribe to mutation failures with the full payload. Mirrors the
1350
+ * underlying MutationQueue 'transaction:failed' shape so consumers
1351
+ * can render typed UI (toast keyed by `AbloError.type`, route-level
1352
+ * "this entity reverted" boundaries, telemetry).
1353
+ *
1354
+ * Distinct from `onTransactionEvent('failed', cb)`, which serves the
1355
+ * parameterless `pendingChanges` counter and intentionally drops the
1356
+ * payload. The two coexist: the counter callback stays lightweight, while
1357
+ * this typed listener drives user-visible surfaces.
1358
+ */
1359
+ onMutationFailure(listener) {
1360
+ this.mutationQueue.on('transaction:failed', listener);
1361
+ return () => this.mutationQueue.off('transaction:failed', listener);
1362
+ }
1363
+ /**
1364
+ * Subscribe to commit round-trip latency, split into the local seal and the
1365
+ * remote acknowledgement. Fires once per completed commit.
1366
+ *
1367
+ * Taps the {@link MutationQueue} emitter for the same reason
1368
+ * {@link onMutationFailure} does: the commit lifecycle events originate
1369
+ * there and the SyncClient's own emitter never rebroadcasts them.
1370
+ */
1371
+ onCommitLatency(listener) {
1372
+ return observeCommitLatency(this.mutationQueue, listener);
1373
+ }
1374
+ /**
1375
+ * Subscribe to local transaction creation with the full {@link QueuedMutation}
1376
+ * payload (`type`, `modelName`, `modelId`, `data`, `previousData`). This is
1377
+ * the feed the store's local-mutation subscription taps for undo recording.
1378
+ *
1379
+ * It subscribes to the {@link MutationQueue}'s emitter directly, since
1380
+ * that is the only emitter that fires `transaction:created`. The SyncClient's
1381
+ * own emitter (reached through {@link subscribe}) never rebroadcasts that
1382
+ * event, so routing undo through `subscribe('transaction:created')` would
1383
+ * record nothing. {@link onMutationFailure} taps the queue for the same
1384
+ * reason.
1385
+ */
1386
+ onLocalTransaction(listener) {
1387
+ this.mutationQueue.on('transaction:created', listener);
1388
+ const snapshotsByCommit = new Map();
1389
+ const onCommitStaging = (payload) => {
1390
+ snapshotsByCommit.set(payload.clientTxId, payload.operations.map((operation) => {
1391
+ if (operation.type === 'CREATE')
1392
+ return undefined;
1393
+ const resident = this.objectPool.get(operation.id);
1394
+ return resident?.toJSON();
1395
+ }));
1396
+ };
1397
+ const onCommitSealFailed = (payload) => {
1398
+ snapshotsByCommit.delete(payload.clientTxId);
1399
+ };
1400
+ // Commit-lane writes (`ablo.commits.create` — the agent/atomic door) ride
1401
+ // their own `commit:created` event: they have no optimistic pool apply,
1402
+ // so they must not feed the echo tracker's `transaction:created` path.
1403
+ // Enrich each operation with previous state captured from the pool HERE
1404
+ // (the queue is pool-free) and hand the synthesized transaction to the
1405
+ // same listener, so undo observes every write door — one stream.
1406
+ const onCommitCreated = (payload) => {
1407
+ const stagedSnapshots = snapshotsByCommit.get(payload.clientTxId);
1408
+ snapshotsByCommit.delete(payload.clientTxId);
1409
+ const TYPE_BY_WIRE = {
1410
+ CREATE: 'create',
1411
+ UPDATE: 'update',
1412
+ DELETE: 'delete',
1413
+ ARCHIVE: 'archive',
1414
+ UNARCHIVE: 'unarchive',
1415
+ };
1416
+ payload.operations.forEach((op, index) => {
1417
+ const type = TYPE_BY_WIRE[op.type];
1418
+ if (!type || !op.id)
1419
+ return;
1420
+ const snapshot = type === 'create'
1421
+ ? undefined
1422
+ : stagedSnapshots
1423
+ ? stagedSnapshots[index]
1424
+ : this.objectPool.get(op.id)?.toJSON();
1425
+ // A DELETE of a row the local graph never saw is not invertible —
1426
+ // recording it would make undo "restore" an empty husk. Skip it.
1427
+ if (type === 'delete' && !snapshot)
1428
+ return;
1429
+ // UPDATE inverse must only revert the fields this op actually wrote;
1430
+ // handing undo the FULL row would clobber concurrent edits to
1431
+ // unrelated fields on revert.
1432
+ const previousData = type === 'update' && snapshot && op.input
1433
+ ? Object.fromEntries(Object.keys(op.input).map((key) => [key, snapshot[key]]))
1434
+ : snapshot ?? null;
1435
+ listener({
1436
+ id: `${payload.clientTxId}_op${index}`,
1437
+ type,
1438
+ modelName: op.model,
1439
+ modelId: op.id,
1440
+ modelKey: op.model,
1441
+ data: op.input ?? undefined,
1442
+ previousData,
1443
+ context: {
1444
+ userId: this.userId ?? '',
1445
+ organizationId: this.organizationId ?? '',
1446
+ },
1447
+ status: 'pending',
1448
+ createdAt: Date.now(),
1449
+ attempts: 0,
1450
+ priority: 'normal',
1451
+ priorityScore: 0,
1452
+ });
1453
+ });
1454
+ };
1455
+ this.mutationQueue.on('commit:staging', onCommitStaging);
1456
+ this.mutationQueue.on('commit:seal_failed', onCommitSealFailed);
1457
+ this.mutationQueue.on('commit:created', onCommitCreated);
1458
+ return () => {
1459
+ this.mutationQueue.off('transaction:created', listener);
1460
+ this.mutationQueue.off('commit:staging', onCommitStaging);
1461
+ this.mutationQueue.off('commit:seal_failed', onCommitSealFailed);
1462
+ this.mutationQueue.off('commit:created', onCommitCreated);
1463
+ snapshotsByCommit.clear();
1464
+ };
1465
+ }
1466
+ /**
1467
+ * Wait for the latest in-flight transaction for (modelName, modelId)
1468
+ * to be confirmed by the server, or reject if it's rolled back.
1469
+ * Resolves immediately when no transaction is in flight — see
1470
+ * `MutationQueue.confirmationFor` for the lookup contract.
1471
+ *
1472
+ * Distinct from `waitForDeltaConfirmation(transactionId)` which keys
1473
+ * off a known tx id; this variant is for call sites that hold a
1474
+ * Model reference but never see the underlying transaction.
1475
+ */
1476
+ waitForConfirmation(modelName, modelId) {
1477
+ return this.mutationQueue.confirmationFor(modelName, modelId);
1478
+ }
1479
+ /**
1480
+ * Get detailed debug info for the sync debug page
1481
+ */
1482
+ getDebugInfo() {
1483
+ return {
1484
+ connectionState: this.connectionState,
1485
+ pendingMutationsCount: this.mutationQueue.getOutstandingTransactionCount(),
1486
+ mutationQueue: this.mutationQueue.getDebugInfo(),
1487
+ };
1488
+ }
1489
+ // --- Best-practice assignment ops ---
1490
+ async unassignEntity(entityType, entityId) {
1491
+ // Call server-side unassign to avoid per-id races
1492
+ await this.mutationExecutor.executeDelete('Assignment', entityId);
1493
+ }
1494
+ async reassignEntity(entityType, entityId, assigneeType, assigneeId, id) {
1495
+ await this.mutationExecutor.executeCreate('Assignment', id || '', {
1496
+ entityType,
1497
+ entityId,
1498
+ assigneeType,
1499
+ assigneeId,
1500
+ });
1501
+ }
1502
+ // ── Delta + Bootstrap application (owns InstanceCache writes) ──────────────
1503
+ /**
1504
+ * Apply a batch of delta results from Database to the InstanceCache.
1505
+ * Owns: model creation, upsert, remove, archive, conflict resolution.
1506
+ * Returns: nothing — InstanceCache is updated in place.
1507
+ */
1508
+ /**
1509
+ * Mark a local transaction as optimistically applied. The matching
1510
+ * server delta (when it arrives with the same `transactionId`) will
1511
+ * be recognized as an echo and skip the pool mutation. Called
1512
+ * automatically by `MutationQueue` when a transaction is staged;
1513
+ * exposed publicly so tests can drive the API directly.
1514
+ */
1515
+ markTransactionPending(transactionId) {
1516
+ this.echoTracker.markPending(transactionId);
1517
+ }
1518
+ /**
1519
+ * Read echo-detection counters: hits, rollbacks, evictions, and the
1520
+ * current pending-set size. Surfaced for production observability
1521
+ * — a sustained `evictions > 0` rate or `rollbacks` spike is a
1522
+ * health signal worth alerting on.
1523
+ */
1524
+ getEchoMetrics() {
1525
+ return this.echoTracker.getMetrics();
1526
+ }
1527
+ /**
1528
+ * Package-internal accessor for the {@link MutationQueue}. Used by
1529
+ * `Ablo.commits.create()` to route raw multi-operation envelopes through the
1530
+ * same retry-on-reconnect lane as the model proxy path, and by tests to
1531
+ * exercise the queue's interaction with {@link markTransactionPending} on the
1532
+ * real instance the SyncClient subscribes to. It is not re-exported to SDK
1533
+ * consumers; `Ablo` is the public surface.
1534
+ */
1535
+ getMutationQueue() {
1536
+ return this.mutationQueue;
1537
+ }
1538
+ applyDeltaBatchToPool(dbResults, enrichRelations) {
1539
+ const modelsToAdd = [];
1540
+ const modelsToUpsert = [];
1541
+ const idsToRemove = [];
1542
+ const idsToArchive = [];
1543
+ // Pre-pass: collect every id slated for `remove` in this batch. The
1544
+ // parent-delete flicker came from this exact pattern: a peer (or the
1545
+ // user themself) deletes a parent with N children; the commit produces
1546
+ // BOTH residual `update` deltas (from the optimistic edits that
1547
+ // happened just before the delete) AND `remove` deltas. The
1548
+ // `update` branch below would `createFromData` the row back into
1549
+ // the pool when `existing` was already gone (optimistic remove
1550
+ // happened), and the next loop iteration's `remove` would strip
1551
+ // it again — net effect: pool transitions live → gone → live →
1552
+ // gone in one tick, which the renderer catches mid-frame as a
1553
+ // flicker. Filter ops on doomed ids before they touch the pool.
1554
+ const idsBeingRemoved = new Set();
1555
+ for (const r of dbResults) {
1556
+ if (r.action === 'remove')
1557
+ idsBeingRemoved.add(r.modelId);
1558
+ }
1559
+ for (const result of dbResults) {
1560
+ const { modelName, modelId, action, transactionId } = result;
1561
+ // Echo detection: if this delta carries a transaction id that matches
1562
+ // one already applied optimistically, the pool already reflects the
1563
+ // mutation, so the pool operation is skipped. The IndexedDB write in
1564
+ // Database.processDeltaBatch still runs; only the in-memory pool update
1565
+ // is suppressed. This prevents a resurrection flicker: a server-confirmed
1566
+ // create arriving after the user has optimistically deleted the row would
1567
+ // otherwise re-add it for the brief window before the matching delete
1568
+ // confirmation lands.
1569
+ if (this.echoTracker.consumeEcho(transactionId)) {
1570
+ continue;
1571
+ }
1572
+ // If a later op in this batch will remove this id, skip earlier
1573
+ // add/update ops on it. Server FK ordering can produce
1574
+ // U(child)+D(child) when an optimistic edit and a delete both
1575
+ // commit in the same window; only the final state matters.
1576
+ if ((action === 'add' || action === 'update') && idsBeingRemoved.has(modelId)) {
1577
+ continue;
1578
+ }
1579
+ switch (action) {
1580
+ case 'add': {
1581
+ const existing = this.objectPool.get(modelId);
1582
+ if (existing) {
1583
+ existing.markAsSynced();
1584
+ }
1585
+ else if (result.data) {
1586
+ const data = enrichRelations(modelName, { ...result.data, __typename: modelName });
1587
+ const model = this.objectPool.createFromData(data, undefined, {
1588
+ deferObservability: true,
1589
+ });
1590
+ if (model)
1591
+ modelsToAdd.push(model);
1592
+ }
1593
+ break;
1594
+ }
1595
+ case 'update': {
1596
+ const existing = this.objectPool.get(modelId);
1597
+ if (existing && !existing.disposed && result.data) {
1598
+ enrichRelations(modelName, result.data);
1599
+ const resolved = this.resolveConflicts(existing, result.data);
1600
+ modelsToUpsert.push(resolved);
1601
+ }
1602
+ // Resurrection drop: if `existing` is gone (optimistic delete
1603
+ // discarded it; the matching D delta is in-flight) we used
1604
+ // to call `createFromData` here, which reintroduced the row
1605
+ // for a frame before the D delta stripped it again — the
1606
+ // chart-delete flicker. Trust the local state. If the server
1607
+ // still considers the row alive, a subsequent bootstrap or
1608
+ // resync will reconcile.
1609
+ break;
1610
+ }
1611
+ case 'remove':
1612
+ idsToRemove.push(modelId);
1613
+ break;
1614
+ case 'archive':
1615
+ idsToArchive.push(modelId);
1616
+ break;
1617
+ case 'verify':
1618
+ // `verify` is `Database.processDeltaBatch`'s signal for a delta
1619
+ // whose IDB store transaction FAILED. Pool isn't updated for
1620
+ // this delta — by design, since the persisted view doesn't
1621
+ // reflect it either — and the persistence-gated cursor in
1622
+ // `BaseSyncedStore.flushPendingDeltas` will NOT ack past it,
1623
+ // so the next 30s catch-up poll (or reconnect handshake) will
1624
+ // re-fetch and re-apply. Logged here so silent IDB failures
1625
+ // are observable instead of disappearing into a default switch
1626
+ // fall-through.
1627
+ // Self-healing: the next catch-up poll / reconnect re-fetches and
1628
+ // re-applies this delta, so it's forensic, not consumer-actionable → debug.
1629
+ this.runtime.logger.debug('[SyncClient.applyDeltaBatchToPool] skipping pool op for unpersisted delta', {
1630
+ modelName,
1631
+ modelId: modelId.slice(0, 12),
1632
+ });
1633
+ break;
1634
+ }
1635
+ }
1636
+ // Reveal the whole frame in a single MobX action. `addBatch`,
1637
+ // `upsertBatch`, `removeBatch`, and `updateScope` are each individually
1638
+ // wrapped in an action, so calling them in sequence flushes reactions at
1639
+ // every action boundary — a catch-up frame that adds, updates, and removes
1640
+ // would fire every dependent reaction several times in a row, re-rendering
1641
+ // and re-sorting on each. Wrapping them in one outer `runInAction` defers
1642
+ // all reaction flushes to a single boundary, so dependents recompute
1643
+ // exactly once regardless of how many models or operation kinds the frame
1644
+ // touched. The app therefore never observes a partially applied frame.
1645
+ runInAction(() => {
1646
+ if (modelsToAdd.length > 0)
1647
+ this.objectPool.addBatch(modelsToAdd, ModelScope.live);
1648
+ if (modelsToUpsert.length > 0)
1649
+ this.objectPool.upsertBatch(modelsToUpsert, ModelScope.live);
1650
+ if (idsToRemove.length > 0)
1651
+ this.objectPool.removeBatch(idsToRemove);
1652
+ for (const id of idsToArchive)
1653
+ this.objectPool.updateScope(id, ModelScope.archived);
1654
+ // Emit changed model types so QueryProcessor can auto-invalidate.
1655
+ // Kept inside the action so any observable query-cache state it
1656
+ // flips is part of the same atomic reveal.
1657
+ const changedTypes = new Set(dbResults.map(r => r.modelName));
1658
+ if (changedTypes.size > 0)
1659
+ this.emit('models:changed', changedTypes);
1660
+ });
1661
+ }
1662
+ /**
1663
+ * Apply bootstrap data to the InstanceCache with ghost removal.
1664
+ * Owns: model creation, batch upsert, ghost detection + removal.
1665
+ */
1666
+ applyBootstrapDataToPool(bootstrapData, protectedIds, options) {
1667
+ if (!bootstrapData.models) {
1668
+ return { added: 0, updated: 0, removed: 0, skipped: 0, healed: 0 };
1669
+ }
1670
+ const allModels = [];
1671
+ const serverIdsByType = new Map();
1672
+ let healedCount = 0;
1673
+ let skippedCount = 0;
1674
+ const failedTypes = new Set(bootstrapData.failedModels ?? []);
1675
+ for (const [modelType, records] of Object.entries(bootstrapData.models)) {
1676
+ if (failedTypes.has(modelType))
1677
+ continue;
1678
+ const idsForType = new Set();
1679
+ serverIdsByType.set(modelType, idsForType);
1680
+ if (!Array.isArray(records) || records.length === 0)
1681
+ continue;
1682
+ for (const rawRecord of records) {
1683
+ if (!rawRecord || typeof rawRecord !== 'object') {
1684
+ skippedCount++;
1685
+ continue;
1686
+ }
1687
+ let data = rawRecord;
1688
+ if (!data.__typename)
1689
+ data = { __typename: modelType, ...data };
1690
+ const healResult = this.healModelRecord(modelType, data);
1691
+ if (healResult === null) {
1692
+ skippedCount++;
1693
+ continue;
1694
+ }
1695
+ data = healResult.data;
1696
+ if (healResult.healed)
1697
+ healedCount++;
1698
+ const recordId = data.id;
1699
+ if (recordId)
1700
+ idsForType.add(recordId);
1701
+ // Scoped backfill for the hydrate-on-enter path: a subset snapshot is
1702
+ // taken at a server watermark. If a concurrent live delta already
1703
+ // advanced this row past the snapshot, skip it. `createFromData`
1704
+ // mutates the pooled model in place to keep instances alive, so this
1705
+ // version guard has to run before it; a guard at the upsert layer would
1706
+ // be too late, because the row would already be clobbered.
1707
+ if (options?.scoped && recordId) {
1708
+ const existing = this.objectPool.get(recordId);
1709
+ if (existing && !rawRecordIsNewer(data, existing)) {
1710
+ skippedCount++;
1711
+ continue;
1712
+ }
1713
+ }
1714
+ try {
1715
+ const model = this.objectPool.createFromData(data);
1716
+ if (model)
1717
+ allModels.push(model);
1718
+ }
1719
+ catch {
1720
+ skippedCount++;
1721
+ }
1722
+ }
1723
+ }
1724
+ // Upsert. The scoped stale-skip above already guarded the version, so a
1725
+ // plain upsert is correct here for both paths.
1726
+ const beforeSize = this.objectPool.size;
1727
+ this.objectPool.upsertBatch(allModels, ModelScope.live);
1728
+ const addedCount = this.objectPool.size - beforeSize;
1729
+ const updatedCount = allModels.length - addedCount;
1730
+ // Ghost removal: drop pool entities absent from the server snapshot. This
1731
+ // is valid only for a full bootstrap, where the snapshot is authoritative
1732
+ // for each returned type. A scoped subset snapshot must not remove rows of
1733
+ // the same type that belong to other, unhydrated groups.
1734
+ let removedCount = 0;
1735
+ if (!options?.scoped) {
1736
+ const ghostIds = [];
1737
+ for (const [modelType, serverIds] of serverIdsByType) {
1738
+ const poolIds = this.objectPool.getIdsByModelType(modelType);
1739
+ if (!poolIds)
1740
+ continue;
1741
+ for (const poolId of poolIds) {
1742
+ if (!serverIds.has(poolId) && !protectedIds?.has(poolId))
1743
+ ghostIds.push(poolId);
1744
+ }
1745
+ }
1746
+ removedCount = this.objectPool.removeBatch(ghostIds);
1747
+ }
1748
+ // Emit changed model types so QueryProcessor can auto-invalidate
1749
+ const changedTypes = new Set(Object.keys(bootstrapData.models));
1750
+ if (changedTypes.size > 0)
1751
+ this.emit('models:changed', changedTypes);
1752
+ return { added: addedCount, updated: updatedCount, removed: removedCount, skipped: skippedCount, healed: healedCount };
1753
+ }
1754
+ }