@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,744 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useCallback,
5
+ useContext,
6
+ useEffect,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ createContext,
11
+ type ReactNode,
12
+ } from 'react';
13
+ import type { Schema, SchemaRecord } from '@abloatai/transaction/schema/schema';
14
+ import type { AbloClient as Ablo } from '../client.js';
15
+ import type {
16
+ Claim,
17
+ Duration,
18
+ Peer,
19
+ } from '@abloatai/transaction/types/streams';
20
+ import type {
21
+ EngineParticipant,
22
+ ParticipantScope,
23
+ ParticipantStatus,
24
+ } from '../local/sync/participants.js';
25
+ import {
26
+ createParticipantClaimId,
27
+ parseParticipantTtlSeconds,
28
+ resolveParticipantSyncGroups,
29
+ } from '../local/sync/participants.js';
30
+ import { SyncContext, type SyncStoreContract } from './context.js';
31
+ import { AbloInternalContext, type AbloInternalContextValue } from './internalContext.js';
32
+ import { AbloValidationError } from '@abloatai/transaction/errors';
33
+ import { useSyncStatus } from './useSyncStatus.js';
34
+ import { DefaultFallback } from './DefaultFallback.js';
35
+
36
+ /**
37
+ * Ablo umbrella provider — owns the sync engine, multiplayer, and
38
+ * the full lifecycle (Strict-Mode-safe singleton, `beforeunload`,
39
+ * session-expiry handling, post-bootstrap hooks).
40
+ *
41
+ * Design goals:
42
+ *
43
+ * - **One component, one import.** Consumers write the provider
44
+ * once at the root; nothing else needs to plumb the engine.
45
+ * - **Multiplayer is default.** React consumers are always browsers doing
46
+ * multiplayer UI, so `useJoin()` / `useAblo()` are always
47
+ * available. No opt-in prop.
48
+ * - **Declarative props for app glue.** `preventUnsavedChanges`,
49
+ * `onSessionExpired`, `postBootstrap`, `resolveUsers` — each
50
+ * absorbs a class of integration code that previously lived in
51
+ * userland.
52
+ * - **Singleton safety.** The engine lives in a ref and rotates
53
+ * only when `userId` / account scope / `url` change. React
54
+ * Strict Mode double-mount does not leak a second WebSocket.
55
+ */
56
+
57
+ // ── Props ────────────────────────────────────────────────────────────
58
+
59
+ /**
60
+ * Props for `<AbloProvider>`.
61
+ *
62
+ * The one required prop is a prebuilt {@link Ablo} client — the client
63
+ * owns auth and the credential lifecycle; this provider is the reactive
64
+ * binding over it:
65
+ *
66
+ * ```tsx
67
+ * // Build once at module scope — a new instance per render tears down the socket.
68
+ * // The endpoint string points at your session-mint route (`ablo init`
69
+ * // scaffolds it); the SDK fetches it and keeps the token fresh.
70
+ * const ablo = Ablo({ schema, authEndpoint: '/api/ablo-session' });
71
+ *
72
+ * <AbloProvider client={ablo}>
73
+ * <App />
74
+ * </AbloProvider>
75
+ * ```
76
+ *
77
+ * That's it for most apps. `userId` is informational; the `fallback`,
78
+ * `preventUnsavedChanges`, and `on*` props are opt-in app glue; and the
79
+ * block tagged "Optional DI (advanced)" below is escape-hatch wiring for
80
+ * tests and platform builders — if you don't recognize a prop there, you
81
+ * don't need it.
82
+ */
83
+ export interface AbloProviderProps<R extends SchemaRecord = SchemaRecord> {
84
+ /**
85
+ * A prebuilt {@link Ablo} client — **the only way to configure the engine.**
86
+ * Construct it yourself with `Ablo({ schema, apiKey, ... })` and pass the
87
+ * instance: the CLIENT owns auth, the credential lifecycle, transport, and
88
+ * connection; this provider is the thin REACTIVE binding over it (context,
89
+ * the bootstrap gate, error/​session forwarding).
90
+ *
91
+ * Memoize it (build it once, e.g. with `useMemo` or module scope) — a new
92
+ * instance each render re-keys the bootstrap gate and tears down the socket.
93
+ */
94
+ client: Ablo<R>;
95
+
96
+ /**
97
+ * The app user id, surfaced via `useCurrentUserId()` for app-owned fields.
98
+ * Purely informational for the React tree — sync identity is resolved by the
99
+ * client from its auth, not from this. Optional.
100
+ */
101
+ userId?: string;
102
+
103
+ /**
104
+ * Block tab close while there are unsynced local writes (the standard
105
+ * `beforeunload` prompt). Browsers ignore custom messages — don't pass one.
106
+ */
107
+ preventUnsavedChanges?: boolean;
108
+
109
+ /**
110
+ * Fired after the client has completed its terminal authentication cleanup
111
+ * (or surfaced a cleanup failure). Use it for app side effects such as a
112
+ * redirect to sign-in or clearing analytics identity.
113
+ */
114
+ onSessionExpired?: () => void | Promise<void>;
115
+
116
+ /**
117
+ * Fired on any error the provider surfaces (engine/WebSocket/bootstrap). For
118
+ * Sentry/Datadog. React-only consumers can use `useErrorListener()` instead.
119
+ */
120
+ onError?: (error: Error) => void;
121
+
122
+ /** @internal placeholder so the old WS-URL prop shape doesn't silently leak in. */
123
+ url?: never;
124
+
125
+ /**
126
+ * Rendered in place of `children` during the *first* bootstrap pass —
127
+ * while the engine is actively transitioning from `initial` →
128
+ * `connected` and has never successfully connected before. Once the
129
+ * engine reaches `connected` the gate latches open for the lifetime
130
+ * of this provider instance; transient `reconnecting` / `needs-auth`
131
+ * states do NOT re-show the fallback (the app's own UI handles those
132
+ * by then).
133
+ *
134
+ * Defaults to `<DefaultFallback />` — a neutral theme-adaptive
135
+ * spinner that uses `currentColor`, ships with zero design-system
136
+ * dependencies, and self-centers in a full-parent container. Pass
137
+ * your own `<Skeleton />` for a branded loading UX. Pass `null` to
138
+ * render nothing during bootstrap. Pass the string literal
139
+ * `"passthrough"` to opt out of the gate entirely — children render
140
+ * immediately and consumers are responsible for their own gating
141
+ * (`<ClientSideSuspense>` or manual `useSyncStatus()` checks).
142
+ * Useful for pages that mount debug helpers, error boundaries, or
143
+ * analytics that must run pre-ready.
144
+ */
145
+ fallback?: ReactNode | 'passthrough';
146
+
147
+ children: ReactNode;
148
+ }
149
+
150
+ // ── Implementation ───────────────────────────────────────────────────
151
+
152
+ /**
153
+ * Lightweight event emitter for provider-level errors. Lives on the
154
+ * provider instance (ref-based) so `useErrorListener` subscriptions
155
+ * survive re-renders without thrashing.
156
+ */
157
+ function createErrorEmitter() {
158
+ const listeners = new Set<(err: Error) => void>();
159
+ return {
160
+ subscribe(fn: (err: Error) => void): () => void {
161
+ listeners.add(fn);
162
+ return () => { listeners.delete(fn); };
163
+ },
164
+ emit(err: Error): void {
165
+ for (const fn of listeners) {
166
+ try { fn(err); } catch {}
167
+ }
168
+ },
169
+ };
170
+ }
171
+
172
+ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
173
+ props: AbloProviderProps<R>,
174
+ ): React.ReactElement {
175
+ const {
176
+ client,
177
+ userId,
178
+ preventUnsavedChanges,
179
+ onSessionExpired,
180
+ onError,
181
+ fallback = <DefaultFallback />,
182
+ children,
183
+ } = props;
184
+
185
+ // The client IS the engine — synchronous, never null. This provider is a
186
+ // REACTIVE binding over it (context + bootstrap gate + error/session
187
+ // forwarding); it does NOT construct, configure, or own the connection. The
188
+ // client owns auth, the credential lifecycle (first mint, refresh, and
189
+ // wake/online/focus re-mint — see `Ablo({ apiKey })`), transport, and
190
+ // `dispose()`. The CONSUMER built the client, so the consumer owns teardown;
191
+ // the provider never disposes it.
192
+ const engine = client;
193
+ const schema = engine.schema;
194
+
195
+ // Account scope isn't a prop — read it from `_store.orgId` once `ready()`
196
+ // resolves the identity from the client's auth.
197
+ const [resolvedAccountScope, setResolvedAccountScope] = useState<string | null>(null);
198
+
199
+ // ── Error emitter (provider-instance scoped) ─────────────────────
200
+ const errorEmitterRef = useRef<ReturnType<typeof createErrorEmitter> | null>(null);
201
+ if (!errorEmitterRef.current) {
202
+ errorEmitterRef.current = createErrorEmitter();
203
+ }
204
+ const errorEmitter = errorEmitterRef.current;
205
+
206
+ // Stash callbacks in refs so a new identity each render doesn't re-run the
207
+ // start effect (the `useEventCallback` idiom).
208
+ const onErrorRef = useRef(onError);
209
+ onErrorRef.current = onError;
210
+ useEffect(() => {
211
+ return errorEmitter.subscribe((err) => onErrorRef.current?.(err));
212
+ }, [errorEmitter]);
213
+ const onSessionExpiredRef = useRef(onSessionExpired);
214
+ onSessionExpiredRef.current = onSessionExpired;
215
+
216
+ // Re-key the bootstrap gate when the client INSTANCE changes — a genuinely new
217
+ // engine is a fresh "first bootstrap". Stable for the common single-client app.
218
+ const clientGenRef = useRef<{ client: Ablo<R>; gen: number }>({ client, gen: 0 });
219
+ if (clientGenRef.current.client !== client) {
220
+ clientGenRef.current = { client, gen: clientGenRef.current.gen + 1 };
221
+ }
222
+ const engineKey = String(clientGenRef.current.gen);
223
+
224
+ // ── Start + session-error wiring ─────────────────────────────────
225
+ //
226
+ // Two reactive jobs only:
227
+ // 1. Forward the client's completed terminal-session transition to
228
+ // onSessionExpired. Credential cleanup lives in the CLIENT, so direct
229
+ // consumers and React consumers have the same security boundary.
230
+ // 2. Drive `ready()` (idempotent) so bootstrap starts on mount, then read the
231
+ // resolved org scope for SyncContext.
232
+ // It does NOT dispose the client (consumer-owned) and does NOT touch auth.
233
+ useEffect(() => {
234
+ let stale = false;
235
+
236
+ const unsubscribeSession = engine.onSessionError((err) => {
237
+ errorEmitter.emit(err);
238
+ void (async () => {
239
+ try {
240
+ await onSessionExpiredRef.current?.();
241
+ } catch (hookErr) {
242
+ errorEmitter.emit(hookErr as Error);
243
+ }
244
+ })().catch(() => {
245
+ // Only a throwing errorEmitter subscriber can land here — it was
246
+ // already the error-reporting path, so swallow rather than surface
247
+ // an unhandled rejection loop.
248
+ });
249
+ });
250
+
251
+ engine
252
+ .ready()
253
+ .then(() => {
254
+ if (stale) return;
255
+ setResolvedAccountScope(
256
+ (engine._store as SyncStoreContract & { orgId?: string }).orgId ?? null,
257
+ );
258
+ })
259
+ .catch((err) => {
260
+ if (stale) return;
261
+ errorEmitter.emit(err as Error);
262
+ });
263
+
264
+ return () => {
265
+ stale = true;
266
+ unsubscribeSession();
267
+ };
268
+ }, [engine, errorEmitter]);
269
+
270
+ // ── beforeunload + preventUnsavedChanges ─────────────────────────
271
+
272
+ useEffect(() => {
273
+ if (typeof window === 'undefined') return;
274
+ const handler = (event: BeforeUnloadEvent) => {
275
+ // Best-effort IDB flush on TAB CLOSE — the client is going away with the
276
+ // page regardless. This is NOT an unmount teardown: the consumer owns the
277
+ // client's lifecycle and the provider never disposes it on unmount.
278
+ void engine.dispose();
279
+ if (preventUnsavedChanges && engine._store.hasUnsyncedChanges) {
280
+ event.preventDefault();
281
+ event.returnValue = '';
282
+ }
283
+ };
284
+ window.addEventListener('beforeunload', handler);
285
+ return () => { window.removeEventListener('beforeunload', handler); };
286
+ }, [engine, preventUnsavedChanges]);
287
+
288
+ // ── SyncContext value (for useQuery/useOne/useMutate hooks) ──────
289
+ //
290
+ // The engine is always present (it's the `client` prop), but its org scope is
291
+ // unknown until `ready()` resolves identity — so `syncValue` is null until
292
+ // then, which drives the initial fallback below.
293
+ const syncValue = useMemo(() => {
294
+ const currentAccountScope =
295
+ resolvedAccountScope ??
296
+ (engine._store as SyncStoreContract & { orgId?: string }).orgId;
297
+ if (!currentAccountScope) return null;
298
+ return {
299
+ store: engine._store,
300
+ organizationId: currentAccountScope,
301
+ schema,
302
+ };
303
+ }, [engine, resolvedAccountScope, schema]);
304
+
305
+ // ── Internal context (currentUserId + error subscription) ────────
306
+
307
+ const internalValue = useMemo<AbloInternalContextValue>(() => ({
308
+ currentUserId: userId ?? null,
309
+ subscribeError: errorEmitter.subscribe,
310
+ emitError: errorEmitter.emit,
311
+ engine: engine as Ablo<SchemaRecord>,
312
+ }), [userId, errorEmitter, engine]);
313
+
314
+ // ── Render ───────────────────────────────────────────────────────
315
+ //
316
+ // Two-phase gate (see `BootstrapGate` below for the latch logic):
317
+ //
318
+ // 1. Engine is null on first render (constructed in the effect
319
+ // above, not in render). We render `fallback` directly — there
320
+ // is no SyncContext to read status from, and by definition the
321
+ // engine hasn't started bootstrapping.
322
+ // 2. Engine exists. Mount SyncContext. `BootstrapGate` then reads
323
+ // `useSyncStatus()` and shows `fallback` only during the very
324
+ // first `connecting` transition; children render on every
325
+ // subsequent state change, including reconnects and auth
326
+ // failures (the app's own UI handles those).
327
+ //
328
+ // `fallback === 'passthrough'` short-circuits both branches — children
329
+ // render immediately without any gate, restoring pre-gate behavior
330
+ // for consumers who need debug helpers / error boundaries / analytics
331
+ // to mount before the engine is ready.
332
+
333
+ const passthrough = fallback === 'passthrough';
334
+ const initialFallback = passthrough ? children : fallback;
335
+
336
+ if (!syncValue) {
337
+ return (
338
+ <AbloInternalContext.Provider value={internalValue}>
339
+ {initialFallback}
340
+ </AbloInternalContext.Provider>
341
+ );
342
+ }
343
+
344
+ return (
345
+ <AbloInternalContext.Provider value={internalValue}>
346
+ <SyncContext.Provider value={syncValue}>
347
+ {passthrough ? (
348
+ children
349
+ ) : (
350
+ <BootstrapGate key={engineKey} fallback={fallback}>
351
+ {children}
352
+ </BootstrapGate>
353
+ )}
354
+ </SyncContext.Provider>
355
+ </AbloInternalContext.Provider>
356
+ );
357
+ }
358
+
359
+ /**
360
+ * Internal gate that renders `fallback` only during the very first
361
+ * bootstrap pass. Latches open on the first `connected` / `reconnecting`
362
+ * / `disconnected` transition and stays open — subsequent transient
363
+ * `connecting` states (hard reconnect after an offline stretch) do NOT
364
+ * re-show the fallback, because by then the app has already rendered
365
+ * once and its own reconnect UI should take over.
366
+ *
367
+ * Re-keyed on `engineState.key` in the parent so engine rotations
368
+ * (userId/org/url change) reset the latch — a new engine genuinely IS
369
+ * a new "first bootstrap" cycle.
370
+ */
371
+ function BootstrapGate({
372
+ fallback,
373
+ children,
374
+ }: {
375
+ readonly fallback: ReactNode;
376
+ readonly children: ReactNode;
377
+ }): ReactNode {
378
+ const status = useSyncStatus();
379
+ const [everConnected, setEverConnected] = useState(false);
380
+
381
+ useEffect(() => {
382
+ if (
383
+ status.name === 'connected' ||
384
+ status.name === 'reconnecting' ||
385
+ status.name === 'disconnected'
386
+ ) {
387
+ setEverConnected(true);
388
+ }
389
+ }, [status.name]);
390
+
391
+ const showFallback = !everConnected && status.name === 'connecting';
392
+ return <>{showFallback ? fallback : children}</>;
393
+ }
394
+
395
+
396
+ export type { EngineParticipant, ParticipantScope, ParticipantStatus };
397
+
398
+ /**
399
+ * Options for `useJoin`. The hook reuses the engine's single
400
+ * WebSocket and opens a scoped claim on it when `scope` is provided:
401
+ * one TCP connection, N logical sub-syncgroup participants.
402
+ */
403
+ export interface UseJoinOptions {
404
+ readonly scope?: ParticipantScope;
405
+ /**
406
+ * Lease TTL for the participant claim, as a compact duration (`'5m'`) or a
407
+ * number of seconds. The same dial and the same spelling as
408
+ * `ablo.<model>.join(ids, { ttl })` and every other lease in the SDK.
409
+ */
410
+ readonly ttl?: Duration;
411
+ /**
412
+ * @deprecated Use `ttl`. Removed in 0.37.0.
413
+ *
414
+ * The same rename as on `ParticipantJoinOptions`: one lease, and the seconds
415
+ * spelling was the one that misled, because it accepted duration strings too.
416
+ */
417
+ readonly ttlSeconds?: number | string | null;
418
+ /** Tear down + don't re-join while true. */
419
+ readonly paused?: boolean;
420
+ /**
421
+ * Acquire a write-claim CLAIM on the scope, in addition to read interest.
422
+ *
423
+ * Default `false`: opening a scope subscribes the connection to its deltas
424
+ * (read interest, via `update_subscription`) but does NOT claim it — a
425
+ * viewer is not a claimant. Set `true` when the participant intends to
426
+ * WRITE (editing a report, an agent staking work): the claim is sent so peers
427
+ * observe it, and the scope is pinned so it stays subscribed (never warms)
428
+ * for as long as the claim is held.
429
+ */
430
+ readonly claim?: boolean;
431
+ /**
432
+ * Backfill the scope's CURRENT state into the pool on enter, in addition to
433
+ * tailing live changes.
434
+ *
435
+ * Default `false`: entering a scope subscribes to its FUTURE deltas only — if
436
+ * the scope's rows aren't already loaded, the view is empty until something
437
+ * changes. Set `true` when opening an entity that may not be loaded yet (a
438
+ * deep-linked report, a never-opened ledger) so its current rows are fetched and
439
+ * injected once, then kept fresh by the live tail. The fetch is single-flight
440
+ * and runs once per group; a failure soft-fails (the live tail still flows).
441
+ */
442
+ readonly hydrate?: boolean;
443
+ }
444
+
445
+ export interface UseJoinReturn {
446
+ readonly participant: EngineParticipant | null;
447
+ /** Everyone else on the engine's sync groups (`participant.presence.others`), bridged to React. */
448
+ readonly peers: readonly Peer[];
449
+ /** Active claim claims by peers (`participant.claims.others`), bridged to React. */
450
+ readonly claims: readonly Claim[];
451
+ readonly status: ParticipantStatus;
452
+ readonly error: Error | null;
453
+ }
454
+
455
+ const EMPTY_PRESENCE: readonly Peer[] = Object.freeze([]);
456
+ const EMPTY_INTENTS: readonly Claim[] = Object.freeze([]);
457
+
458
+ /**
459
+ * Join multiplayer for a given scope. Returns the participant and its
460
+ * lifecycle status. Auto-cleans up on unmount or when `paused`
461
+ * flips to true.
462
+ *
463
+ * `useJoin` is the React form of `ablo.<model>.join` — scope-level
464
+ * read-interest + presence; returns the reactive participant facade
465
+ * (peers/claims/status).
466
+ *
467
+ * The returned `participant` is an `EngineParticipant` — `.presence`
468
+ * + `.claims` only — backed by the engine's existing socket. For
469
+ * headless-bot patterns (a separate identity in the same browser
470
+ * tab), construct a second `Ablo({ kind: 'agent', ... })` directly.
471
+ */
472
+ export function useJoin(opts: UseJoinOptions): UseJoinReturn {
473
+ const ctx = useContext(AbloInternalContext);
474
+ const engine = ctx?.engine ?? null;
475
+ const { paused = false } = opts;
476
+ // Resolve the model-form scope ({ reports: id } / refs) THROUGH the schema, so a
477
+ // model's declared `scope` kind is honored (typename `Report` → `report:<id>`,
478
+ // not the `type:id` string fallback). Schema appears once the engine is ready;
479
+ // until then refs resolve by convention, then re-resolve when it arrives.
480
+ const scopeKey = JSON.stringify(
481
+ resolveParticipantSyncGroups(opts.scope, engine?.schema).sort(),
482
+ );
483
+ const scopedSyncGroups = useMemo(
484
+ () => JSON.parse(scopeKey) as string[],
485
+ [scopeKey],
486
+ );
487
+ const [claimError, setClaimError] = useState<Error | null>(null);
488
+ const [claimConnected, setClaimConnected] = useState(false);
489
+
490
+ // Reference-stable participant facade — same socket as entity sync,
491
+ // so there is no `connect()` / `disconnect()` lifecycle here. The
492
+ // engine manages the connection; the hook is a thin window onto its
493
+ // already-attached presence + claim streams.
494
+ const participant: EngineParticipant | null = useMemo(() => {
495
+ if (!engine) return null;
496
+ return { presence: engine.presence, claims: engine.claims };
497
+ }, [engine]);
498
+
499
+ // Status maps to the engine's sync state. `connecting` while the
500
+ // engine bootstraps; `connected` once `engine.ready()` resolves and
501
+ // any scoped participant claim has acked; `error` if the claim
502
+ // fails; `disconnected` while paused or before the engine exists.
503
+ const syncStatus = useSyncStatus();
504
+ // Only a write-claim participant waits on a claim ack. A pure reader
505
+ // (the default) is `connected` as soon as the engine is — its read
506
+ // interest is fire-and-forget `update_subscription`, not a claim.
507
+ const needsClaim = !!opts.claim && scopedSyncGroups.length > 0;
508
+ const status: ParticipantStatus = paused || !engine
509
+ ? 'disconnected'
510
+ : claimError
511
+ ? 'error'
512
+ : syncStatus.name === 'connected'
513
+ ? needsClaim && !claimConnected
514
+ ? 'connecting'
515
+ : 'connected'
516
+ : syncStatus.name === 'disconnected' || syncStatus.name === 'needs-auth'
517
+ ? 'disconnected'
518
+ : 'connecting';
519
+ const error: Error | null = claimError;
520
+
521
+ // ── Read interest (always) ───────────────────────────────────────
522
+ // Subscribe the connection to the scope's sync groups while mounted +
523
+ // connected — the area-of-interest navigation primitive. No claim, no
524
+ // TTL: a viewer just receives the scope's deltas. Hysteresis (warm TTL)
525
+ // lives in the store's SubscriptionManager, so a quick unmount/remount
526
+ // (tab flip) doesn't re-bootstrap.
527
+ useEffect(() => {
528
+ const scope = opts.scope;
529
+ if (paused || !engine || !scope || scopedSyncGroups.length === 0) return;
530
+ if (syncStatus.name !== 'connected') return;
531
+ const store = engine._store;
532
+ // `hydrate` backfills the scope's current state after subscribing
533
+ // (store handles subscribe-first ordering + single-flight). leaveScope
534
+ // only moves read interest; the hydrated rows stay in the pool.
535
+ void store.enterScope?.(scope, { hydrate: opts.hydrate });
536
+ return () => {
537
+ void store.leaveScope?.(scope);
538
+ };
539
+ // scopeKey is the stable proxy for the resolved groups; same idiom as
540
+ // the claim effect below.
541
+ }, [engine, paused, scopeKey, syncStatus.name, opts.hydrate]);
542
+
543
+ // ── Write claim (opt-in: `claim: true`) ─────────────────────────
544
+ // A claim is the write-claim primitive — distinct from read interest
545
+ // above. Only sent when the caller opts in; it makes peers observe the
546
+ // claim and pins the scope so it never warms while held.
547
+ useEffect(() => {
548
+ setClaimError(null);
549
+ setClaimConnected(false);
550
+ const scope = opts.scope;
551
+ if (paused || !engine || !opts.claim || !scope || scopedSyncGroups.length === 0)
552
+ return;
553
+ if (syncStatus.name !== 'connected') return;
554
+ const ws = engine._ws;
555
+ const store = engine._store;
556
+
557
+ let cancelled = false;
558
+ const claimId = createParticipantClaimId();
559
+ ws.sendClaim(claimId, scopedSyncGroups, {
560
+ // Reading the retired spelling IS the compatibility path; it goes at 0.37.0.
561
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
562
+ ttlSeconds: parseParticipantTtlSeconds(opts.ttl ?? opts.ttlSeconds),
563
+ })
564
+ .then(() => {
565
+ if (!cancelled) setClaimConnected(true);
566
+ })
567
+ .catch((err) => {
568
+ if (!cancelled) {
569
+ setClaimError(err instanceof Error ? err : new Error(String(err)));
570
+ }
571
+ });
572
+ // Prominence: hold the scope subscribed for as long as the claim lives.
573
+ void store.pinScope?.(scope);
574
+
575
+ return () => {
576
+ cancelled = true;
577
+ ws.sendRelease(claimId);
578
+ void store.unpinScope?.(scope);
579
+ };
580
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- same compatibility read as above.
581
+ }, [engine, paused, scopeKey, syncStatus.name, opts.ttl, opts.ttlSeconds, opts.claim]);
582
+
583
+ // Bridge the engine's presence + claims streams into React state.
584
+ // Plain useState + useEffect is sufficient — mid-frame tearing on a
585
+ // peer list is harmless (users won't notice one frame of stale
586
+ // presence). Queries and sync status use useSyncExternalStore
587
+ // because transactions CAN tear visibly; presence can't.
588
+ const [peers, setPeers] = useState<readonly Peer[]>(EMPTY_PRESENCE);
589
+ const [claims, setClaims] = useState<readonly Claim[]>(EMPTY_INTENTS);
590
+
591
+ useEffect(() => {
592
+ if (!participant || paused) {
593
+ setPeers(EMPTY_PRESENCE);
594
+ setClaims(EMPTY_INTENTS);
595
+ return;
596
+ }
597
+ setPeers(participant.presence.others);
598
+ setClaims(participant.claims.others);
599
+ const unsubPresence = participant.presence.onChange(() => {
600
+ setPeers(participant.presence.others);
601
+ });
602
+ const unsubClaims = participant.claims.onChange(() => {
603
+ setClaims(participant.claims.others);
604
+ });
605
+ return () => {
606
+ unsubPresence();
607
+ unsubClaims();
608
+ };
609
+ }, [participant, paused]);
610
+
611
+ return { participant, peers, claims, status, error };
612
+ }
613
+
614
+ /**
615
+ * Read-only presence: the OTHER participants currently visible to this
616
+ * connection, bridged to React. Unlike {@link useJoin}, this does
617
+ * NOT enter/leave a scope (no `update_subscription`, no warm-TTL churn) —
618
+ * it is a pure reader of the engine's already-flowing presence stream.
619
+ *
620
+ * Pass `scope` to narrow to the peers on that scope's sync group(s); omit
621
+ * it to get everyone on the engine's groups. Membership is driven entirely
622
+ * by the presence channel (set server-side on connect, independent of any
623
+ * cursor/collaboration traffic), so reading it never affects what the
624
+ * connection is subscribed to and can't deadlock against a gated channel.
625
+ *
626
+ * Use this to answer "is anyone else here?" — e.g. suppressing live-cursor
627
+ * broadcasts while alone — when some OTHER mount already owns the scope's
628
+ * read interest (scope `leave` is not reference-counted, so a second
629
+ * `useJoin` on the same scope would warm-drop the owner's
630
+ * subscription on unmount).
631
+ *
632
+ * ```ts
633
+ * const peers = usePeers({ reports: reportId });
634
+ * const alone = !peers.some((p) => p.participantKind === 'user');
635
+ * ```
636
+ */
637
+ export function usePeers(scope?: ParticipantScope): readonly Peer[] {
638
+ const ctx = useContext(AbloInternalContext);
639
+ const engine = ctx?.engine ?? null;
640
+
641
+ // Resolve scope → groups through the schema (same idiom as useJoin).
642
+ // The stringified, sorted key is the stable effect dependency.
643
+ const scopeKey = JSON.stringify(
644
+ resolveParticipantSyncGroups(scope, engine?.schema).sort(),
645
+ );
646
+ const groups = useMemo(() => JSON.parse(scopeKey) as string[], [scopeKey]);
647
+
648
+ const [peers, setPeers] = useState<readonly Peer[]>(EMPTY_PRESENCE);
649
+
650
+ useEffect(() => {
651
+ if (!engine) {
652
+ setPeers(EMPTY_PRESENCE);
653
+ return;
654
+ }
655
+ const presence = engine.presence;
656
+ const compute = (): readonly Peer[] =>
657
+ groups.length === 0
658
+ ? presence.others
659
+ : presence.others.filter((p) =>
660
+ p.syncGroups.some((g) => groups.includes(g)),
661
+ );
662
+ // Plain useState + onChange — presence changes on join/leave/activity
663
+ // only (never on cursor traffic, a separate channel), so this fires
664
+ // rarely; a frame of stale presence is harmless (same rationale as
665
+ // useJoin's peers bridge).
666
+ setPeers(compute());
667
+ return presence.onChange(() => { setPeers(compute()); });
668
+ }, [engine, scopeKey]);
669
+
670
+ return peers;
671
+ }
672
+
673
+ // ── Escape-hatches: raw engine/store access ──────────────────────────
674
+
675
+ /**
676
+ * Returns the raw `SyncEngine` proxy. Typically you want the typed
677
+ * hooks (`useQuery`, `useOne`, `useMutate`) — this is for rare cases
678
+ * where you need direct access (e.g., `sync.tasks.onChange(cb)`).
679
+ *
680
+ * The generic parameter narrows the return type to your schema's
681
+ * model record so call sites get typed `sync.tasks.findMany()` /
682
+ * `sync.sections.create(...)` without a cast at the call site:
683
+ *
684
+ * ```ts
685
+ * const sync = useSync<(typeof schema)['models']>();
686
+ * ```
687
+ *
688
+ * The runtime value is the exact engine the provider constructed;
689
+ * the generic just widens the compile-time type.
690
+ */
691
+ export function useSync<R extends SchemaRecord = SchemaRecord>(): Ablo<R> {
692
+ const ctx = useContext(AbloInternalContext);
693
+ if (!ctx) {
694
+ throw new AbloValidationError(
695
+ 'useSync: no <AbloProvider> mounted above this component.',
696
+ { code: 'no_ablo_provider' },
697
+ );
698
+ }
699
+ if (!ctx.engine) {
700
+ throw new AbloValidationError(
701
+ 'useSync: the sync engine has not yet initialized. Wrap your ' +
702
+ 'consumer in <ClientSideSuspense> or guard on useSyncStatus().',
703
+ { code: 'sync_not_ready' },
704
+ );
705
+ }
706
+ return rebindProviderEngine(ctx.engine);
707
+ }
708
+
709
+ function rebindProviderEngine<R extends SchemaRecord>(
710
+ engine: Ablo<SchemaRecord>,
711
+ ): Ablo<R> {
712
+ return engine as Ablo<R>;
713
+ }
714
+
715
+ /**
716
+ * Returns the underlying `SyncStoreContract` (the BaseSyncedStore).
717
+ * Most consumers should prefer the typed hooks (`useQuery` etc.); this
718
+ * is for advanced cases like direct InstanceCache access or custom
719
+ * reactive bridges. Throws if the provider hasn't mounted the store
720
+ * yet — wrap consumers in `<ClientSideSuspense>` to gate correctly.
721
+ *
722
+ * The generic parameter lets consumers widen the return type to a
723
+ * concrete `BaseSyncedStore<...>` subclass if they track one:
724
+ *
725
+ * ```ts
726
+ * type AppStore = BaseSyncedStore<AppEvents, typeof schema>;
727
+ * const store = useSyncStore<AppStore>(); // no cast needed at call site
728
+ * ```
729
+ *
730
+ * The runtime value is always the concrete store the SDK constructed,
731
+ * so widening the type is safe. The bounded generic (`T extends
732
+ * SyncStoreContract`) keeps the widening honest.
733
+ */
734
+ export function useSyncStore<T extends SyncStoreContract = SyncStoreContract>(): T {
735
+ const sync = useContext(SyncContext);
736
+ if (!sync?.store) {
737
+ throw new AbloValidationError(
738
+ 'useSyncStore: the sync engine has not yet initialized. Wrap ' +
739
+ 'consumers in <ClientSideSuspense> or guard on useSyncStatus().',
740
+ { code: 'sync_not_ready' },
741
+ );
742
+ }
743
+ return sync.store as T;
744
+ }