@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,950 @@
1
+ /**
2
+ * Model is the base class for the sync engine's domain models. A model is a
3
+ * plain domain object: it holds data and business logic, tracks its own
4
+ * property changes, and validates itself, and it returns the changes to apply
5
+ * rather than applying them. It does not reach into stores or singletons and
6
+ * does not perform side effects such as saving or sending notifications;
7
+ * persistence and sync are driven by the store that owns the model.
8
+ */
9
+ import { runInAction, isComputedProp } from 'mobx';
10
+ import { v4 as uuid } from 'uuid';
11
+ import { M1 } from './utils/mobxSetup.js';
12
+ import { getActiveRegistry, hasActiveRegistry } from './ModelRegistry.js';
13
+ import { getContext } from './context.js';
14
+ import { AbloValidationError } from '@abloatai/transaction/errors';
15
+ /**
16
+ * Internal wire-hydration hint. Symbol-keyed and non-enumerable at the call
17
+ * site, so it can never enter persistence, JSON, a mutation payload, or a
18
+ * consumer's model fields.
19
+ */
20
+ export const DEFER_MODEL_OBSERVABILITY = Symbol('ablo.deferModelObservability');
21
+ /**
22
+ * Validation error for model validation failures
23
+ */
24
+ export class ValidationError extends Error {
25
+ errors;
26
+ constructor(errors) {
27
+ super(`Validation failed: ${errors.join(', ')}`);
28
+ this.errors = errors;
29
+ this.name = 'ValidationError';
30
+ }
31
+ }
32
+ /** Shared frozen default for {@link Model.getDerivedGetterNames}. */
33
+ const EMPTY_DERIVED_GETTERS = Object.freeze([]);
34
+ /**
35
+ * The abstract base class every domain model extends. It holds the model's id
36
+ * and timestamps, tracks in-place property changes for change detection and
37
+ * undo, and serializes itself, while leaving persistence and sync to the store
38
+ * that owns it.
39
+ */
40
+ export class Model {
41
+ /** Static reference to active SyncedStore for reactive queries */
42
+ static store = null;
43
+ /** Unique identifier - always permanent UUID */
44
+ id;
45
+ /** Client ID - always equals id, kept for compatibility */
46
+ clientId;
47
+ /** MobX observable properties storage */
48
+ _mobxProperties = {};
49
+ /** Referenced models cache */
50
+ _referencedModels = {};
51
+ /** Track property changes */
52
+ modifiedProperties = new Map();
53
+ /** Track if this is a new model */
54
+ _isNew = true;
55
+ /** Original data snapshot */
56
+ _originalData;
57
+ /** Sync status */
58
+ syncStatus = 'pending';
59
+ /** Timestamps */
60
+ createdAt;
61
+ updatedAt;
62
+ archivedAt;
63
+ /** Validation rules */
64
+ validationRules = {};
65
+ /** Lifecycle state */
66
+ isDisposed = false;
67
+ disposers = [];
68
+ /**
69
+ * Whether MobX field instrumentation has been installed. Wire hydration can
70
+ * deliberately defer this work until the cache hands the model to a
71
+ * consumer; optimistic/local models still install it in their constructor.
72
+ */
73
+ _observabilityReady = false;
74
+ _observabilityDeferred = false;
75
+ /**
76
+ * Track observed LazyReferenceCollections for GC prevention
77
+ * When any collection is being observed by React, the model should not be GC'd
78
+ * Following MobX best practice: https://mobx.js.org/lazy-observables.html
79
+ */
80
+ _observedCollections = new Set();
81
+ constructor(data = {}) {
82
+ // Always generate permanent UUID on client
83
+ this.id = data.id ?? Model.generateId();
84
+ this.clientId = this.id; // No more temp IDs!
85
+ // Ensure dates are Date objects, not strings
86
+ this.createdAt = data.createdAt
87
+ ? data.createdAt instanceof Date
88
+ ? data.createdAt
89
+ : new Date(data.createdAt)
90
+ : new Date();
91
+ // A record that arrives WITH `createdAt` but WITHOUT `updatedAt` is
92
+ // server/IDB data whose update timestamp didn't survive the wire —
93
+ // falling back to "now" here fabricated an edit time for every such
94
+ // record on every bootstrap (the reports gallery sorted everything to
95
+ // "edited just now"). Fall back to createdAt instead; only a genuinely
96
+ // new local model (no dates at all) stamps the current time.
97
+ this.updatedAt = data.updatedAt
98
+ ? data.updatedAt instanceof Date
99
+ ? data.updatedAt
100
+ : new Date(data.updatedAt)
101
+ : data.createdAt
102
+ ? new Date(this.createdAt)
103
+ : new Date();
104
+ this.syncStatus = data.syncStatus ?? 'pending';
105
+ }
106
+ /**
107
+ * Generate unique ID
108
+ */
109
+ static generateId() {
110
+ return uuid();
111
+ }
112
+ /**
113
+ * Set the active SyncedStore reference for reactive queries.
114
+ * Called once at engine initialization.
115
+ */
116
+ static setStore(store) {
117
+ Model.store = store;
118
+ }
119
+ /**
120
+ * Get the active SyncedStore reference for reactive queries.
121
+ *
122
+ * Returns `null` if no store has been registered yet (e.g. during
123
+ * bootstrap before the engine is ready). Subclasses should use this
124
+ * instead of reaching into the private static field via bracket
125
+ * notation — the generic parameter lets app-side Model subclasses
126
+ * narrow the return to their concrete store type.
127
+ *
128
+ * @example
129
+ * // In a Section model getter
130
+ * const store = Section.getStore();
131
+ * if (!store) return [];
132
+ * return store.getByForeignKey<Block>('Block', 'sectionId', this.id);
133
+ */
134
+ static getStore() {
135
+ return Model.store;
136
+ }
137
+ /**
138
+ * Initialize MobX observability
139
+ */
140
+ makeObservable() {
141
+ if (this._observabilityReady)
142
+ return;
143
+ const modelName = this.getModelName();
144
+ // Get metadata from static ModelRegistry
145
+ const propertyMetadata = getActiveRegistry().getProperties(modelName);
146
+ const referenceMetadata = getActiveRegistry().getReferences(modelName);
147
+ // Use M1 for observability setup
148
+ M1(this, propertyMetadata, referenceMetadata);
149
+ this._observabilityReady = true;
150
+ this._observabilityDeferred = false;
151
+ }
152
+ /** Mark a schema model as intentionally cold until cache exposure. */
153
+ deferObservability() {
154
+ if (!this._observabilityReady)
155
+ this._observabilityDeferred = true;
156
+ }
157
+ /**
158
+ * Activate a cold wire-hydrated model before it crosses a consumer-visible
159
+ * cache boundary. Idempotent, so ordinary eagerly observable models pay only
160
+ * the boolean check.
161
+ */
162
+ ensureObservable() {
163
+ if (this._observabilityDeferred)
164
+ this.makeObservable();
165
+ }
166
+ /**
167
+ * Track property changes
168
+ */
169
+ propertyChanged(propertyName, oldValue, newValue) {
170
+ if (oldValue === newValue)
171
+ return;
172
+ runInAction(() => {
173
+ // Preserve the earliest captured `old` for this field until the entry
174
+ // is cleared (by `clearChanges` on sync-ack or by a mutator consuming
175
+ // it). Consecutive in-place mutations between mutator invocations —
176
+ // e.g. a drag loop writing `block.position = ...` on every frame —
177
+ // would otherwise overwrite `.old` with each frame's predecessor,
178
+ // destroying the pre-session baseline that `RecordingMutation`
179
+ // relies on to record a correct undo inverse. `.new` always reflects
180
+ // the latest value so the transaction queue's `getChanges()` keeps
181
+ // sending the right payload to the server.
182
+ const existing = this.modifiedProperties.get(propertyName);
183
+ this.modifiedProperties.set(propertyName, {
184
+ old: existing ? existing.old : oldValue,
185
+ new: newValue,
186
+ });
187
+ this.updatedAt = new Date();
188
+ });
189
+ }
190
+ /**
191
+ * Get changes as object
192
+ */
193
+ getChanges() {
194
+ const changes = {};
195
+ for (const [propertyName, change] of this.modifiedProperties) {
196
+ changes[propertyName] = change.new;
197
+ }
198
+ return changes;
199
+ }
200
+ /**
201
+ * Check if model has changes
202
+ */
203
+ get hasChanges() {
204
+ return this.modifiedProperties.size > 0;
205
+ }
206
+ /**
207
+ * Mark model as persisted (not new)
208
+ */
209
+ markAsPersisted() {
210
+ this._isNew = false;
211
+ this._originalData = this.captureSnapshot();
212
+ }
213
+ /**
214
+ * Check if this is a new model
215
+ */
216
+ isNew() {
217
+ return this._isNew;
218
+ }
219
+ /**
220
+ * Return a read-only view of the snapshot taken at {@link markAsPersisted}
221
+ * or at load time. The undo machinery uses it to recover a field's pre-edit
222
+ * value when the field was written without first being tracked in
223
+ * `modifiedProperties`. The returned object is the live snapshot, so callers
224
+ * must not mutate it.
225
+ *
226
+ * This per-instance baseline is needed because application code can edit a
227
+ * model in two ways that coexist: a direct property write
228
+ * (`section.title = 'foo'`) and a recorded mutation. A design in which every
229
+ * write went through a single recorded path would not need it, since the
230
+ * last acknowledged state would already be the authoritative baseline.
231
+ */
232
+ getOriginalSnapshot() {
233
+ return this._originalData;
234
+ }
235
+ /**
236
+ * Clear tracked changes
237
+ */
238
+ clearChanges() {
239
+ runInAction(() => {
240
+ this.modifiedProperties.clear();
241
+ this._originalData = this.captureSnapshot();
242
+ });
243
+ }
244
+ /**
245
+ * Capture a before-image for `keys` — the single source of truth for the
246
+ * "previous value" that undo inverses are built from. Both undo paths call
247
+ * this so they can never drift: the stream path
248
+ * (`MutationQueue.extractPreviousData`) and the manual-record path
249
+ * (`RecordingMutation.snapshotFields`).
250
+ *
251
+ * Resolution order per key:
252
+ * 1. `modifiedProperties.get(key).old` — first-old-wins pre-session
253
+ * baseline, set whenever the field was mutated in place before commit.
254
+ * 2. `getOriginalSnapshot()[key]` — the last loaded/acked row, the correct
255
+ * before-image for a key written without a prior in-place mutation
256
+ * (e.g. a `precomputedChanges` write).
257
+ * 3. `fallbackToLive` only — the current live value. The manual-record path
258
+ * wants this last resort; the stream path deliberately omits unresolved
259
+ * keys so `buildUndoOps` drops an un-revertible inverse rather than
260
+ * inventing one. The flag is the one intentional difference between the
261
+ * two callers — do not collapse it.
262
+ *
263
+ * `id` is always skipped. Values are read out per-key, so the
264
+ * `getOriginalSnapshot()` "callers must not mutate" contract is preserved.
265
+ *
266
+ * Invariant this relies on: a given undo scope is either stream-recorded
267
+ * (`recordFromStream: true`) or manual (`useMutators({ undoScope })`), never
268
+ * both — otherwise a write would be captured twice. No surface sets both.
269
+ */
270
+ capturePreviousValues(keys, opts) {
271
+ const out = {};
272
+ const modified = this.modifiedProperties instanceof Map ? this.modifiedProperties : null;
273
+ const original = this.getOriginalSnapshot();
274
+ for (const key of keys) {
275
+ if (key === 'id')
276
+ continue;
277
+ const mod = modified?.get(key);
278
+ if (mod) {
279
+ out[key] = mod.old;
280
+ }
281
+ else if (original && key in original) {
282
+ out[key] = original[key];
283
+ }
284
+ else if (opts?.fallbackToLive) {
285
+ out[key] = Reflect.get(this, key);
286
+ }
287
+ }
288
+ return out;
289
+ }
290
+ /**
291
+ * Drop the `modifiedProperties` entries for `keys` — re-baselines a field
292
+ * after its `.old` has been frozen into a committed transaction, so the next
293
+ * write to the same field starts from this commit's result rather than the
294
+ * stale pre-session `.old` that {@link propertyChanged}'s first-old-wins
295
+ * policy preserves. Safe because the committed transaction owns its own
296
+ * frozen `data`/`previousData`; neither re-reads `modifiedProperties`. `id`
297
+ * is never consumed. With no `keys`, consumes every tracked field.
298
+ */
299
+ consumeModifiedFields(keys) {
300
+ if (!(this.modifiedProperties instanceof Map) || this.modifiedProperties.size === 0) {
301
+ return;
302
+ }
303
+ const only = keys ? new Set(keys) : null;
304
+ for (const key of [...this.modifiedProperties.keys()]) {
305
+ if (key === 'id')
306
+ continue;
307
+ if (only && !only.has(key))
308
+ continue;
309
+ this.modifiedProperties.delete(key);
310
+ }
311
+ }
312
+ /**
313
+ * Validate model
314
+ */
315
+ validate() {
316
+ if (this.isDisposed) {
317
+ throw new AbloValidationError('Cannot validate disposed model', {
318
+ code: 'model_disposed',
319
+ });
320
+ }
321
+ const errors = [];
322
+ const modelName = this.getModelName();
323
+ const properties = getActiveRegistry().getProperties(modelName);
324
+ if (properties) {
325
+ const json = this.toJSON();
326
+ for (const [propName, metadata] of properties) {
327
+ // Check required fields
328
+ if (!metadata.nullable && !metadata.optional) {
329
+ const value = json[propName];
330
+ if (value == null || value === '') {
331
+ errors.push(`${propName} is required`);
332
+ }
333
+ }
334
+ // Run custom validation rules
335
+ const rules = this.validationRules[propName];
336
+ if (rules) {
337
+ const value = json[propName];
338
+ for (const rule of rules) {
339
+ const error = rule(value);
340
+ if (error)
341
+ errors.push(error);
342
+ }
343
+ }
344
+ }
345
+ }
346
+ // Run model-specific validation
347
+ const customErrors = this.customValidate();
348
+ errors.push(...customErrors);
349
+ return errors;
350
+ }
351
+ /**
352
+ * Override for custom validation
353
+ */
354
+ customValidate() {
355
+ return [];
356
+ }
357
+ /**
358
+ * Add validation rule
359
+ */
360
+ addValidationRule(propName, rule) {
361
+ this.validationRules[propName] ??= [];
362
+ this.validationRules[propName].push(rule);
363
+ }
364
+ /**
365
+ * Prepare save operation
366
+ * Returns the changes to be saved without side effects
367
+ */
368
+ prepareSave() {
369
+ if (this.isDisposed) {
370
+ throw new AbloValidationError('Cannot prepare save for disposed model', {
371
+ code: 'model_disposed',
372
+ });
373
+ }
374
+ // Validate first
375
+ const errors = this.validate();
376
+ if (errors.length > 0) {
377
+ throw new ValidationError(errors);
378
+ }
379
+ if (this._isNew) {
380
+ // New model - return create operation
381
+ return {
382
+ type: 'create',
383
+ modelName: this.getModelName(), // the registered model name
384
+ modelId: this.id,
385
+ timestamp: new Date(),
386
+ };
387
+ }
388
+ else if (this.hasChanges) {
389
+ // Existing model with changes - return update operation
390
+ return {
391
+ type: 'update',
392
+ modelName: this.getModelName(), // the registered model name
393
+ modelId: this.id,
394
+ changes: new Map(this.modifiedProperties),
395
+ timestamp: new Date(),
396
+ };
397
+ }
398
+ // No changes
399
+ return null;
400
+ }
401
+ /**
402
+ * Prepare delete operation
403
+ */
404
+ prepareDelete() {
405
+ if (this.isDisposed) {
406
+ throw new AbloValidationError('Cannot prepare delete for disposed model', {
407
+ code: 'model_disposed',
408
+ });
409
+ }
410
+ this.willDelete();
411
+ return {
412
+ type: 'delete',
413
+ modelName: this.getModelName(), // the registered model name
414
+ modelId: this.id,
415
+ timestamp: new Date(),
416
+ };
417
+ }
418
+ /**
419
+ * Prepare archive operation
420
+ */
421
+ prepareArchive() {
422
+ if (this.isDisposed) {
423
+ throw new AbloValidationError('Cannot prepare archive for disposed model', {
424
+ code: 'model_disposed',
425
+ });
426
+ }
427
+ this.archivedAt = new Date();
428
+ return {
429
+ type: 'archive',
430
+ modelName: this.getModelName(), // the registered model name
431
+ modelId: this.id,
432
+ timestamp: new Date(),
433
+ };
434
+ }
435
+ /**
436
+ * Prepare unarchive operation
437
+ */
438
+ prepareUnarchive() {
439
+ if (this.isDisposed) {
440
+ throw new AbloValidationError('Cannot prepare unarchive for disposed model', {
441
+ code: 'model_disposed',
442
+ });
443
+ }
444
+ this.archivedAt = null;
445
+ return {
446
+ type: 'unarchive',
447
+ modelName: this.getModelName(), // the registered model name
448
+ modelId: this.id,
449
+ timestamp: new Date(),
450
+ };
451
+ }
452
+ /**
453
+ * Safely assign each field of `data` onto this instance, skipping `id`,
454
+ * unknown keys, MobX computed accessors, and getter-only (read-only)
455
+ * properties, and coercing date fields. Shared by `updateFromData`
456
+ * (hydration) and `applyChanges` (local user update).
457
+ *
458
+ * Change tracking is explicit: for every field actually
459
+ * written, `onWrite(key, oldValue, newValue)` is invoked with the value
460
+ * captured immediately before assignment. `applyChanges` passes a hook
461
+ * that records the change in `modifiedProperties`; `updateFromData`
462
+ * passes none (hydration must not generate outbound mutations).
463
+ *
464
+ * This is not the ONLY tracking path. `mobxSetup`'s `observe()` bridge is
465
+ * live and forwards a DIRECT assignment (`layer.position = next`) to
466
+ * `propertyChanged` as well — product code writes model fields directly in
467
+ * plenty of places (keyboard nudge, formatting, AI tools), and those writes
468
+ * have to reach the server and the undo stream too. The two paths compose:
469
+ * a direct write establishes the first-old-wins baseline, and a later
470
+ * `applyChanges` carrying the value the model already holds is a no-op that
471
+ * leaves that baseline intact.
472
+ */
473
+ assignFieldsFromData(data, onWrite) {
474
+ // Update properties with safety checks for read-only/computed accessors
475
+ for (const [key, raw] of Object.entries(data)) {
476
+ if (key === 'id')
477
+ continue;
478
+ // Only attempt to set if the property exists on instance or prototype
479
+ if (!(this.hasOwnProperty(key) || key in this))
480
+ continue;
481
+ // Never assign to MobX computed properties (they may expose a setter that throws)
482
+ try {
483
+ if (isComputedProp(this, key)) {
484
+ continue;
485
+ }
486
+ }
487
+ catch {
488
+ // If MobX internals are unavailable for some reason, fall back to descriptor checks below
489
+ }
490
+ // Resolve property descriptor from own or prototype chain
491
+ const ownDesc = Object.getOwnPropertyDescriptor(this, key);
492
+ let desc = ownDesc;
493
+ if (!desc) {
494
+ let proto = Object.getPrototypeOf(this);
495
+ while (proto && proto !== Object.prototype && !desc) {
496
+ desc = Object.getOwnPropertyDescriptor(proto, key);
497
+ proto = Object.getPrototypeOf(proto);
498
+ }
499
+ }
500
+ // Determine writability: allow if data descriptor writable, or accessor with setter
501
+ const writable = desc
502
+ ? ('writable' in desc && !!desc.writable) ||
503
+ ('set' in desc && typeof desc.set === 'function')
504
+ : true;
505
+ if (!writable) {
506
+ // Skip read-only accessor properties (getter-only)
507
+ continue;
508
+ }
509
+ // Handle date conversions
510
+ const value = (key === 'createdAt' || key === 'updatedAt' || key === 'archivedAt') && raw
511
+ ? new Date(raw)
512
+ : raw;
513
+ // Capture the pre-write value BEFORE assignment so trackers
514
+ // (undo inverse, getChanges) see the true previous value.
515
+ const oldValue = onWrite ? this[key] : undefined;
516
+ // Dynamic property assignment - use indexed access
517
+ this[key] = value;
518
+ onWrite?.(key, oldValue, value);
519
+ }
520
+ }
521
+ /**
522
+ * Update from raw data (hydration)
523
+ *
524
+ * Used for inbound server deltas and pool upserts. Change tracking is
525
+ * deliberately suppressed: hydration writes must not land in
526
+ * `modifiedProperties`, otherwise applying a server delta would queue a
527
+ * brand-new outbound mutation and the record would echo forever. For a
528
+ * local user edit, use `applyChanges` instead.
529
+ *
530
+ * Suppression takes two forms and BOTH are load-bearing: we pass no
531
+ * `onWrite` hook, and we clear/restore `modifiedProperties` around the
532
+ * assignment. The second is what catches `mobxSetup`'s `observe()` bridge,
533
+ * which fires on the assignment itself and would otherwise record an
534
+ * inbound delta as a local edit — queueing an outbound mutation that echoes
535
+ * forever, and putting a collaborator's change on your undo stack. Do not
536
+ * remove it while that bridge exists (`mobxSetup.M1`).
537
+ */
538
+ updateFromData(data) {
539
+ if (this.isDisposed) {
540
+ throw new AbloValidationError('Cannot update disposed model', {
541
+ code: 'model_disposed',
542
+ });
543
+ }
544
+ runInAction(() => {
545
+ const originalTracking = this.modifiedProperties;
546
+ this.modifiedProperties = new Map();
547
+ // No `onWrite` → this call records nothing itself.
548
+ this.assignFieldsFromData(data);
549
+ this.modifiedProperties = originalTracking;
550
+ });
551
+ // Mark as persisted if updating existing model
552
+ if (!this._isNew) {
553
+ this._originalData = this.captureSnapshot();
554
+ }
555
+ this.didUpdate();
556
+ }
557
+ /**
558
+ * Apply a local, user-initiated update from a data object — the write
559
+ * path for `proxy.update({ id, data })`, which is the one and only way
560
+ * application code mutates synced fields.
561
+ *
562
+ * Unlike `updateFromData` (hydration, untracked), this records every
563
+ * written field in `modifiedProperties` via `propertyChanged`, so
564
+ * `getChanges()` and the transaction queue send the edited fields to the
565
+ * server and the undo system gets a correct pre-write baseline. Recording
566
+ * is explicit here, through the `onWrite` hook, and does not rely on any
567
+ * MobX `observe()` side channel.
568
+ *
569
+ * `_originalData` is intentionally not reset here: it stays as the
570
+ * last-persisted baseline until `clearChanges()` runs on sync-ack.
571
+ */
572
+ applyChanges(data) {
573
+ if (this.isDisposed) {
574
+ throw new AbloValidationError('Cannot update disposed model', {
575
+ code: 'model_disposed',
576
+ });
577
+ }
578
+ runInAction(() => {
579
+ this.assignFieldsFromData(data, (key, oldValue, newValue) => {
580
+ this.propertyChanged(key, oldValue, newValue);
581
+ });
582
+ });
583
+ this.didUpdate();
584
+ }
585
+ /**
586
+ * Serialize to JSON
587
+ * This method should not trigger MobX reactions since it's used for serialization
588
+ * Returns Record<string, any> to allow subclass specialization with more specific return types
589
+ */
590
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
591
+ toJSON() {
592
+ const modelName = this.getModelName();
593
+ const properties = getActiveRegistry().getProperties(modelName);
594
+ const result = {
595
+ __class: this.getModelName(), // the registered model name for consistency
596
+ __typename: this.getModelName(), // __typename mirrors __class as the wire type discriminator
597
+ id: this.id,
598
+ createdAt: this.createdAt?.toISOString(),
599
+ updatedAt: this.updatedAt?.toISOString(),
600
+ clientId: this.clientId,
601
+ syncStatus: this.syncStatus,
602
+ };
603
+ if (this.archivedAt !== undefined) {
604
+ result.archivedAt = this.archivedAt?.toISOString() ?? null;
605
+ }
606
+ if (properties) {
607
+ const self = this;
608
+ for (const [propName, metadata] of properties) {
609
+ // Skip certain types
610
+ if (metadata.type === 'ephemeralProperty')
611
+ continue;
612
+ if (metadata.type === 'referenceModel')
613
+ continue;
614
+ if (metadata.type === 'referenceCollection')
615
+ continue;
616
+ const value = self[propName];
617
+ if (value !== undefined) {
618
+ result[propName] = value;
619
+ }
620
+ }
621
+ }
622
+ return result;
623
+ }
624
+ /**
625
+ * Clone this model
626
+ */
627
+ clone() {
628
+ const Constructor = this.constructor;
629
+ const clone = new Constructor();
630
+ const data = this.toJSON();
631
+ delete data.id; // New ID for clone
632
+ delete data.createdAt;
633
+ delete data.updatedAt;
634
+ clone.updateFromData(data);
635
+ return clone;
636
+ }
637
+ getModelName() {
638
+ const registeredName = getActiveRegistry().getModelNameFromConstructor(this.constructor);
639
+ if (registeredName) {
640
+ return registeredName;
641
+ }
642
+ const className = this.constructor.name;
643
+ // Use consumer-provided fallback map from config (replaces hardcoded Prisma name map)
644
+ const fallbackMap = getContext().config.classNameFallbackMap;
645
+ return fallbackMap[className] ?? className.replace(/Model$/, '');
646
+ }
647
+ /**
648
+ * Read a field value by name. Runtime-safe dynamic field access —
649
+ * schema-generated models store all declared fields as instance properties.
650
+ * Use this for generic code (sort comparators, filter predicates that work
651
+ * across model types) that reads fields by name string.
652
+ */
653
+ getField(name) {
654
+ return Reflect.get(this, name);
655
+ }
656
+ /**
657
+ * Check equality
658
+ */
659
+ equals(other) {
660
+ return this.id === other.id && this.constructor === other.constructor;
661
+ }
662
+ /**
663
+ * String representation
664
+ */
665
+ toString() {
666
+ return `${this.constructor.name}[${this.id}]`;
667
+ }
668
+ // ==========================================
669
+ // MobX Observation Tracking (for GC prevention)
670
+ // ==========================================
671
+ /**
672
+ * Register a LazyReferenceCollection as being observed
673
+ * Called by LazyReferenceCollection when onBecomeObserved fires
674
+ */
675
+ _registerObservedCollection(collection) {
676
+ this._observedCollections.add(collection);
677
+ }
678
+ /**
679
+ * Unregister a LazyReferenceCollection that's no longer observed
680
+ * Called by LazyReferenceCollection when onBecomeUnobserved fires
681
+ */
682
+ _unregisterObservedCollection(collection) {
683
+ this._observedCollections.delete(collection);
684
+ }
685
+ /**
686
+ * Check if any collection on this model is currently being observed by React
687
+ * Used by InstanceCache GC to prevent disposing models in active use
688
+ */
689
+ hasObservedCollections() {
690
+ return this._observedCollections.size > 0;
691
+ }
692
+ /**
693
+ * Get count of observed collections (for debugging)
694
+ */
695
+ get observedCollectionCount() {
696
+ return this._observedCollections.size;
697
+ }
698
+ /**
699
+ * Dispose model
700
+ */
701
+ dispose() {
702
+ if (this.isDisposed)
703
+ return;
704
+ // Clean up
705
+ for (const disposer of this.disposers) {
706
+ disposer();
707
+ }
708
+ this.disposers = [];
709
+ this._referencedModels = {};
710
+ this.modifiedProperties.clear();
711
+ this._observedCollections.clear();
712
+ // Dispose collections. Gracefully skip when no active registry
713
+ // exists — `dispose()` is a cleanup path and must not crash when a
714
+ // test (or a teardown during engine shutdown) calls it after the
715
+ // registry is gone. Production flows always have one set, so the
716
+ // collection-disposal branch still runs there.
717
+ if (hasActiveRegistry()) {
718
+ const modelName = this.getModelName();
719
+ const properties = getActiveRegistry().getProperties(modelName);
720
+ if (properties) {
721
+ const self = this;
722
+ for (const [propName, metadata] of properties) {
723
+ if (metadata.type === 'referenceCollection') {
724
+ const collection = self[propName];
725
+ if (collection?.dispose) {
726
+ collection.dispose();
727
+ }
728
+ }
729
+ }
730
+ }
731
+ }
732
+ this.isDisposed = true;
733
+ }
734
+ /**
735
+ * Check if disposed
736
+ */
737
+ get disposed() {
738
+ return this.isDisposed;
739
+ }
740
+ /**
741
+ * Lifecycle hooks - override in subclasses
742
+ */
743
+ didUpdate() { }
744
+ willDelete() { }
745
+ /**
746
+ * Capture snapshot for change detection
747
+ */
748
+ captureSnapshot() {
749
+ const snapshot = {};
750
+ const modelName = this.getModelName();
751
+ const properties = getActiveRegistry().getProperties(modelName);
752
+ if (properties) {
753
+ const json = this.toJSON();
754
+ for (const [propName] of properties) {
755
+ snapshot[propName] = json[propName];
756
+ }
757
+ }
758
+ return snapshot;
759
+ }
760
+ /**
761
+ * A fresh, plain row snapshot that READS every declared field through its
762
+ * MobX observable getter. This is the reactive read surface for
763
+ * `useReactive`/`useAblo`, and it relies on two MobX facts:
764
+ *
765
+ * 1. MobX tracks property *access*, not values — so reading each field here,
766
+ * inside the caller's tracked function, SUBSCRIBES the reaction to that
767
+ * field. A bare `return model` (the previous `modelAsRow`) dereferences
768
+ * nothing, so an in-place delta update fires no reaction and the UI never
769
+ * re-renders. (https://mobx.js.org/understanding-reactivity.html)
770
+ * 2. The returned object is a NEW identity each call, so the hook's equality
771
+ * check detects the change — the same mutated instance would compare equal
772
+ * and suppress the re-render even after tracking fired.
773
+ *
774
+ * Unlike `toJSON()`, values keep their runtime types (a `Date` stays a `Date`,
775
+ * a json field stays its parsed object) and wire-noise keys
776
+ * (`__class`/`clientId`/`syncStatus`) are omitted — this is exactly the row
777
+ * the schema's `T` describes. Computed relations (`referenceModel`/
778
+ * `referenceCollection`) and ephemeral fields are skipped, matching `toJSON`'s
779
+ * row projection; they're lazy/recursive and not part of the row's data.
780
+ *
781
+ * Schema-derived getters (`computed:` entries and `${field}Json` getters) ARE
782
+ * materialized, as non-enumerable own values. The schema's inferred row type
783
+ * includes them, so omitting them would make every snapshot read of a computed
784
+ * silently `undefined` — a type-level lie. They're evaluated here, inside the
785
+ * caller's tracked function, so the reaction subscribes to whatever fields the
786
+ * getter reads. Non-enumerable keeps write-path parity with model instances:
787
+ * an instance's getters sit on the prototype and never enter `{...model}`
788
+ * spreads or `JSON.stringify`, and materialized values must not either — a
789
+ * spread-into-update would otherwise send computed keys to the server.
790
+ */
791
+ toReactiveSnapshot() {
792
+ const snapshot = {
793
+ id: this.id,
794
+ createdAt: this.createdAt,
795
+ updatedAt: this.updatedAt,
796
+ };
797
+ if (this.archivedAt !== undefined)
798
+ snapshot.archivedAt = this.archivedAt;
799
+ const properties = getActiveRegistry().getProperties(this.getModelName());
800
+ const self = this;
801
+ if (properties) {
802
+ for (const [propName, metadata] of properties) {
803
+ if (metadata.type === 'ephemeralProperty' ||
804
+ metadata.type === 'referenceModel' ||
805
+ metadata.type === 'referenceCollection') {
806
+ continue;
807
+ }
808
+ // Reading through the observable getter is the point: it subscribes the
809
+ // enclosing MobX reaction to this field.
810
+ snapshot[propName] = self[propName];
811
+ }
812
+ }
813
+ for (const name of this.getDerivedGetterNames()) {
814
+ Object.defineProperty(snapshot, name, {
815
+ // Evaluated on the model instance so `${field}Json` caches stay on it
816
+ // and the enclosing reaction tracks the fields the getter reads.
817
+ value: self[name],
818
+ enumerable: false,
819
+ configurable: true,
820
+ writable: false,
821
+ });
822
+ }
823
+ return snapshot;
824
+ }
825
+ /**
826
+ * Names of schema-derived getters — `computed:` entries and `${field}Json`
827
+ * getters — that {@link toReactiveSnapshot} materializes onto snapshots.
828
+ * The dynamic model class built by `registerModelsFromSchema` overrides this;
829
+ * hand-written Model subclasses default to none.
830
+ */
831
+ getDerivedGetterNames() {
832
+ return EMPTY_DERIVED_GETTERS;
833
+ }
834
+ /**
835
+ * Get field changes for activity tracking
836
+ */
837
+ getFieldChanges() {
838
+ const changes = [];
839
+ for (const [field, change] of this.modifiedProperties) {
840
+ changes.push({
841
+ field,
842
+ oldValue: change.old,
843
+ newValue: change.new,
844
+ fieldType: this.getFieldType(change.new),
845
+ });
846
+ }
847
+ return changes;
848
+ }
849
+ getFieldType(value) {
850
+ if (value === null || value === undefined)
851
+ return 'string';
852
+ if (typeof value === 'number')
853
+ return 'number';
854
+ if (value instanceof Date)
855
+ return 'date';
856
+ if (Array.isArray(value))
857
+ return 'array';
858
+ if (typeof value === 'string' && /^[a-fA-F0-9-]{36}$/.test(value))
859
+ return 'reference';
860
+ return 'string';
861
+ }
862
+ /**
863
+ * Create model from JSON
864
+ */
865
+ static fromJSON(data) {
866
+ // Support both __class and __typename, and handle both old and new naming
867
+ const modelIdentifier = data.__typename ?? data.__class ?? data.modelName;
868
+ if (!modelIdentifier) {
869
+ throw new AbloValidationError('Model identifier (__typename, __class, or modelName) not found in data', { code: 'model_identifier_missing' });
870
+ }
871
+ // Try to get model class by identifier
872
+ let ModelClass = getActiveRegistry().getModelByName(modelIdentifier);
873
+ // If not found by registered name, try mapping to the class name
874
+ if (!ModelClass) {
875
+ const classNameMap = {
876
+ Task: 'TaskModel',
877
+ Project: 'Project',
878
+ Comment: 'CommentModel',
879
+ User: 'UserModel',
880
+ Organization: 'OrganizationModel',
881
+ StatusGroup: 'StatusGroupModel',
882
+ Team: 'TeamModel',
883
+ Member: 'MemberModel',
884
+ Role: 'RoleModel',
885
+ };
886
+ const className = classNameMap[modelIdentifier];
887
+ if (className) {
888
+ ModelClass = getActiveRegistry().getModelByName(className);
889
+ }
890
+ }
891
+ if (!ModelClass) {
892
+ throw new AbloValidationError(`Model class not found for: ${modelIdentifier}`, { code: 'model_class_not_registered' });
893
+ }
894
+ const instance = new ModelClass(data);
895
+ instance.markAsPersisted();
896
+ return instance;
897
+ }
898
+ /**
899
+ * Get sync status
900
+ */
901
+ getSyncStatus() {
902
+ return this.syncStatus;
903
+ }
904
+ /**
905
+ * Mark model as synced
906
+ */
907
+ markAsSynced() {
908
+ this.syncStatus = 'synced';
909
+ }
910
+ /**
911
+ * Mark model as pending sync
912
+ */
913
+ markAsPending() {
914
+ this.syncStatus = 'pending';
915
+ }
916
+ }
917
+ /**
918
+ * Project a dynamic-class `Model` instance to the schema row shape `T`.
919
+ *
920
+ * The runtime invariant: `createDynamicModelClass(...)` attaches every
921
+ * field of `T` directly onto the Model prototype/instance via
922
+ * `Object.defineProperty` and the M1 observable bridge, so a Model
923
+ * instance structurally satisfies `T` at runtime. The static type
924
+ * system can't see this because `T` is a free generic — there's no
925
+ * common ancestor between `Model` (base class) and the schema row
926
+ * interface produced by `defineSchema`.
927
+ *
928
+ * This is a typed boundary, not a bypass: every call site is the
929
+ * dynamic-class duality where Model-with-extras-and-T-fields is being
930
+ * returned to a consumer that only sees `T`. Concentrating the cast
931
+ * here means there's one place to look when the boundary changes.
932
+ */
933
+ export function modelAsRow(model) {
934
+ return model;
935
+ }
936
+ /**
937
+ * Inverse of `modelAsRow`: accept a row-shaped value (schema-derived
938
+ * `T` with at minimum an `id`) and surface it as a `Model`. Used by
939
+ * `BaseSyncedStore.save / delete / archive / unarchive` so consumers
940
+ * can pass either a typed schema row or a Model instance and the
941
+ * SDK's persistence path sees a uniform Model surface.
942
+ *
943
+ * Same runtime invariant as `modelAsRow`: dynamic-class instances
944
+ * carry both the row fields and the Model methods on the same object
945
+ * — one structural identity, two static views. The helper does no
946
+ * runtime conversion (no allocation, no copy) — it's a pure type cast.
947
+ */
948
+ export function rowAsModel(entity) {
949
+ return entity;
950
+ }