@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,880 @@
1
+ /**
2
+ * Builds the typed client for a single schema model — the object reached as
3
+ * `ablo.<model>`.
4
+ *
5
+ * Each schema model gets one {@link ModelOperations}: the async server reads
6
+ * `get` and `list`, with the same point lookup restricted to the local graph under
7
+ * `local`, the writes `create`, `update`, and `delete`, the coordination
8
+ * namespace `claim` (callable as `claim({ id })`, plus `claim.state`,
9
+ * `claim.queue`, `claim.release`, and `claim.reorder`), `join`, and `onChange`.
10
+ * The factory returns a plain object; the client assembles the `ablo.<model>`
11
+ * lookup table from one of these per model.
12
+ */
13
+ import { autorun } from 'mobx';
14
+ import { AbloClaimedError, AbloValidationError, toAbloError, } from '@abloatai/transaction/errors';
15
+ import { reconcileFunctionalUpdate, } from '@abloatai/transaction/resources/functionalUpdate';
16
+ import { claimDescription, } from '@abloatai/transaction/coordination/schema';
17
+ import { Model, modelAsRow } from '../Model.js';
18
+ import { toMs } from '@abloatai/transaction/utils/duration';
19
+ import { LEASE_TTL_MS } from '@abloatai/transaction/wire/protocol';
20
+ import { heartbeatCadenceMs, resolveHeartbeatOptions, resolveHeartbeatPlan, startClaimHeartbeatLoop, } from '@abloatai/transaction/coordination/claimHeartbeatLoop';
21
+ import { assertWriteOptions } from '@abloatai/transaction/resources/writeOptionsSchema';
22
+ import { subTarget } from '@abloatai/transaction/coordination';
23
+ // A named claim-meta crossing (see `claim-meta-crossings-are-enumerated` in
24
+ // .dependency-cruiser.cjs): the reactive proxy's self-claim targets are
25
+ // decodes that build a public claim, so their `meta` converts wire→declared
26
+ // here like the other enumerated crossings.
27
+ import { declaredMeta } from '@abloatai/transaction/coordination/claimMeta';
28
+ import { ModelScope } from '@abloatai/transaction/types';
29
+ const modelClientMeta = new WeakMap();
30
+ export function getModelClientMeta(modelClient) {
31
+ if (typeof modelClient !== 'object' || modelClient === null)
32
+ return undefined;
33
+ return modelClientMeta.get(modelClient);
34
+ }
35
+ export function createModelProxy(schemaKey, registeredModelName, objectPool, syncClient, registry,
36
+ /**
37
+ * The one thing this factory asks of the loader: fetch rows for a model.
38
+ *
39
+ * Declared as the slice rather than the whole `OnDemandLoader` because the
40
+ * whole is a class, and a parameter typed as a class can only ever be
41
+ * satisfied by an instance of it — so every caller that has a narrower
42
+ * collaborator, a test most of all, is pushed into a cast through `unknown`
43
+ * to supply the one method that is actually read.
44
+ */
45
+ hydration, collaboration,
46
+ /** The client-wide `wait` default; a per-call `wait` still wins over it. */
47
+ defaultWait) {
48
+ /**
49
+ * Resolve a row **this** resource owns.
50
+ *
51
+ * The pool is one id space, so `objectPool.get(id)` happily returns another
52
+ * model's row. Every write path below addresses rows by bare id, so without
53
+ * this an id from a sibling model resolves and gets written — silently
54
+ * corrupting a row the caller never named.
55
+ *
56
+ * `undefined` means genuinely absent. A row belonging to another model throws:
57
+ * unlike a read, a cross-model *write* is never a legitimate outcome, and
58
+ * naming both models turns a silent corruption into a one-line diagnosis.
59
+ */
60
+ const ownRowOrThrow = (id) => {
61
+ const own = objectPool.getOfType(id, registeredModelName);
62
+ if (own)
63
+ return own;
64
+ const foreign = objectPool.get(id);
65
+ if (!foreign)
66
+ return undefined;
67
+ const owner = foreign.getModelName();
68
+ throw new AbloValidationError(`No ${registeredModelName} with id ${id} — that id belongs to a ${owner}. ` +
69
+ `Read or write it through ${owner}.`, { code: 'entity_not_found' });
70
+ };
71
+ const ModelClass = registry.getModelByName(registeredModelName);
72
+ if (!ModelClass) {
73
+ throw new AbloValidationError(`Ablo: schema model "${schemaKey}" resolved to "${registeredModelName}", ` +
74
+ 'but no matching constructor was registered.', { code: 'model_not_registered' });
75
+ }
76
+ // The coordination plane must speak the same wire dialect as the commit
77
+ // plane: the lowercased typename (`task`), not the schema key (`tasks`). The
78
+ // server's commit-time claim guard probes the lease store with the commit
79
+ // operation's model name, so a lease recorded under the schema key never
80
+ // matches — which would silently disarm the guard for every model whose
81
+ // schema key differs from its typename (a plural key against a singular
82
+ // typename, i.e. nearly all of them). Public surfaces such as
83
+ // `Claim.target.model` keep the schema key; only the wire and coordination
84
+ // targets use this.
85
+ const wireModel = registeredModelName.toLowerCase();
86
+ // Last-line guarantee for the public surface: any rejection from a lower
87
+ // layer (transport timeout, IndexedDB failure, a third-party throw) is
88
+ // coerced to an AbloError before it reaches the consumer. The SDK's
89
+ // contract is that callers only ever catch tagged errors — `instanceof
90
+ // AbloError` / `e.type` always hold. Internal helpers stay unwrapped; only
91
+ // the methods exposed on `operations` are guarded.
92
+ const guard = (fn) => {
93
+ return async (...args) => {
94
+ try {
95
+ return await fn(...args);
96
+ }
97
+ catch (err) {
98
+ throw toAbloError(err);
99
+ }
100
+ };
101
+ };
102
+ const load = async (options) => {
103
+ const rows = await hydration.fetch(schemaKey, options);
104
+ return rows.map((row) => modelAsRow(row));
105
+ };
106
+ const waitForMutation = async (model, options) => {
107
+ // A per-call `wait` wins; otherwise the client-wide default decides. This
108
+ // is the single point that turns "confirmed" into actually waiting, so a
109
+ // client configured that way rejects on a refused write everywhere rather
110
+ // than in the one place a caller remembered to ask.
111
+ if ((options?.wait ?? defaultWait) !== 'confirmed')
112
+ return;
113
+ // Let sibling writes from the same synchronous burst enter the mutation
114
+ // queue before forcing a drain. Without this yield, every confirmed
115
+ // create/update calls syncNow() alone, defeating the queue's microtask
116
+ // coalescer and producing one SQL transaction per delta.
117
+ await Promise.resolve();
118
+ await syncClient.syncNow();
119
+ await syncClient.waitForConfirmation(model.getModelName(), model.id);
120
+ };
121
+ // Claims this proxy currently holds, keyed by entity id. Lets the flat
122
+ // `release({ id })` and `update({ id, data })` find the lease and snapshot a
123
+ // `claim({ id })` took, without a per-call handle. Released on dispose,
124
+ // explicit release, or TTL expiry.
125
+ //
126
+ // `target`, `description`, and `expiresAt` are kept alongside the lease so
127
+ // `claim.state` can synthesize a self-claim: the server excludes a holder's
128
+ // own presence frames, so this proxy is the only place that knows the client
129
+ // holds the row. `expiresAt` is the client's best estimate from the requested
130
+ // TTL (a real epoch-millisecond expiry, not a fabricated watermark), defaulting
131
+ // to the server's keepalive lease window when no TTL was requested.
132
+ const activeClaims = new Map();
133
+ // Server keepalive lease window — the same `LEASE_TTL_MS` the wire protocol
134
+ // declares, so the client's estimate and the server's lease cannot drift.
135
+ // This is the fallback expiry estimate when a claim is taken without an
136
+ // explicit TTL.
137
+ const DEFAULT_LEASE_TTL_MS = LEASE_TTL_MS;
138
+ const isClaimHandle = (value) => typeof value === 'object' &&
139
+ value !== null &&
140
+ value.object === 'claim' &&
141
+ typeof value.id === 'string' &&
142
+ typeof value.release === 'function';
143
+ const mutationOptions = (params) => {
144
+ const rest = {
145
+ idempotencyKey: params.idempotencyKey,
146
+ label: params.label,
147
+ wait: params.wait,
148
+ readAt: params.readAt,
149
+ onStale: params.onStale,
150
+ fenceToken: params.fenceToken,
151
+ claimRef: params.claimRef,
152
+ reads: params.reads,
153
+ track: params.track,
154
+ };
155
+ // The write-options schema — the runtime twin of the compile-time params.
156
+ // Catches plain-JavaScript callers (for example `onStale: 'rejct'`) at the
157
+ // call site with a typed error instead of a silent no-op or a server 400.
158
+ assertWriteOptions(rest, `${schemaKey} write`);
159
+ return rest;
160
+ };
161
+ const releaseClaim = async (id) => {
162
+ const held = activeClaims.get(id);
163
+ if (!held)
164
+ return;
165
+ activeClaims.delete(id);
166
+ await held.lease.release?.();
167
+ };
168
+ const takeClaim = async (params) => {
169
+ if (!collaboration) {
170
+ throw new AbloValidationError(`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`, { code: 'model_claim_not_configured' });
171
+ }
172
+ const { id, ...options } = params;
173
+ // Is someone else already on this target? Read the local coordination
174
+ // snapshot up front — it decides whether a re-read is needed after the
175
+ // claim (a free or already-held target cannot have changed underneath us).
176
+ const held = collaboration.state({ model: wireModel, id });
177
+ const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
178
+ const failFast = options.queue === false;
179
+ // The try-claim (`queue: false`): a held target is an expected outcome,
180
+ // not an error, so it resolves `null` — the caller reads `if (!claim)`
181
+ // and moves on; who holds it stays readable via `claim.state`. Best-effort
182
+ // at the client (a racing claim not yet synced into our snapshot slips
183
+ // through here) — the commit-time claim guard is the authoritative
184
+ // backstop that rejects the loser's first write. For work-distribution
185
+ // dedup that's exactly right: don't wait (that would double-process), skip.
186
+ if (failFast && contended) {
187
+ return null;
188
+ }
189
+ // Ensure the row exists locally before claiming.
190
+ let model = ownRowOrThrow(id);
191
+ if (!model) {
192
+ await load({ where: [['id', id]] });
193
+ model = ownRowOrThrow(id);
194
+ }
195
+ if (!model) {
196
+ throw new AbloValidationError(`Entity not found: ${registeredModelName}/${id}`, { code: 'entity_not_found' });
197
+ }
198
+ // Write intent: enter the entity scope before acquiring the lease so the
199
+ // holder's claim presence broadcasts to everyone in this entity group,
200
+ // including a peer that subscribed just before us. Pinning before the lease
201
+ // rather than after closes the subscribe-versus-broadcast race: the server
202
+ // fans presence out at claim time, so this client must be in the group when
203
+ // the claim lands. Awaited because the broadcast ordering depends on it;
204
+ // still best-effort (the store swallows reconcile errors).
205
+ await collaboration.pinScope?.({ [schemaKey]: id });
206
+ // Acquire the lease. By default (`queue` is not false) this goes through the
207
+ // server's fair FIFO queue: `queue: true` resolves only once the lease is
208
+ // genuinely ours, blocking behind any current holder, with no check-then-act
209
+ // gap because the server orders contenders. Fail-fast skips the queue: an
210
+ // observed conflict was already rejected above, so this just records the lease.
211
+ const lease = await collaboration.createClaim({
212
+ target: {
213
+ model: wireModel,
214
+ id,
215
+ // The whole sub-entity locator in one move — listing its members here
216
+ // is what let `fields` die between the caller and the lease, so the
217
+ // claim covered the whole row while the caller believed it named parts.
218
+ ...subTarget(options, schemaKey),
219
+ },
220
+ description: claimDescription(options),
221
+ ttl: options.ttl,
222
+ queue: !failFast,
223
+ maxQueueDepth: options.maxQueueDepth,
224
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
225
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
226
+ waitTimeoutMs: options.waitTimeoutMs,
227
+ signal: options.signal,
228
+ });
229
+ // Only when the claim actually waited behind another holder can the row have
230
+ // changed underneath us — re-read so the claimed snapshot reflects what that
231
+ // holder committed before releasing. Either of two signals suffices:
232
+ // - `lease.waited` — the server granted the claim after the client
233
+ // provably queued behind a holder. Authoritative; it works even when the
234
+ // local snapshot is blind, since claim fan-out is entity-scoped and a
235
+ // broadly-subscribed client never observes peers' claims.
236
+ // - `contended` — the local snapshot saw a holder up front. Kept for the
237
+ // no-queue paths, where no grant frame exists.
238
+ if ((contended || lease.waited === true) && !failFast) {
239
+ // `type: 'complete'` forces the round-trip: the hydration ledger would
240
+ // otherwise serve the local row for an already-hydrated id, and the
241
+ // holder's final write may not have fanned out yet — the exact
242
+ // stale-snapshot race this re-read closes.
243
+ await load({ where: [['id', id]], type: 'complete' });
244
+ model = ownRowOrThrow(id) ?? model;
245
+ }
246
+ const snapshot = collaboration.createSnapshot(schemaKey, id);
247
+ const description = claimDescription(options);
248
+ // The self-claim's `ClaimTarget` mirrors what a peer's `claim.state` would
249
+ // report (`state` maps `held.target.model` to `type`), so a holder and a
250
+ // peer see the same `target.type` for one row — the wire model token.
251
+ // Its `meta` is the DECLARED shape (the handle is a public claim), so the
252
+ // wire-shaped projection converts back through `declaredMeta` — the same
253
+ // crossing the HTTP handle assembly makes.
254
+ const { meta: selfMeta, ...selfNarrowed } = subTarget(options, schemaKey);
255
+ const selfTarget = {
256
+ type: wireModel,
257
+ id,
258
+ ...selfNarrowed,
259
+ ...(selfMeta !== undefined ? { meta: declaredMeta(selfMeta) } : {}),
260
+ };
261
+ const ttlMs = options.ttl !== undefined ? toMs(options.ttl) : DEFAULT_LEASE_TTL_MS;
262
+ const expiresAt = Date.now() + ttlMs;
263
+ activeClaims.set(id, {
264
+ lease,
265
+ snapshot,
266
+ target: selfTarget,
267
+ description,
268
+ expiresAt,
269
+ });
270
+ const { meta: targetMeta, ...targetNarrowed } = subTarget(options, schemaKey);
271
+ const target = {
272
+ type: schemaKey,
273
+ id,
274
+ ...targetNarrowed,
275
+ ...(targetMeta !== undefined ? { meta: declaredMeta(targetMeta) } : {}),
276
+ };
277
+ // One reading of the heartbeat options — cadence and callbacks from
278
+ // whichever spelling the caller used (plan object, shorthand, or the
279
+ // deprecated flat callbacks).
280
+ const plan = resolveHeartbeatPlan(options);
281
+ // A beat resolves with the server's extended expiry; keep the local
282
+ // self-claim estimate in step so `claim.state` renders the real window,
283
+ // and surface every answer through the plan's `onBeat` (pressure signal).
284
+ const heartbeat = async (beatOptions) => {
285
+ if (!lease.heartbeat) {
286
+ throw new AbloValidationError('This claim handle has no heartbeat wiring, which the standard Ablo({ schema, apiKey }) client provides on every claim. This appears only when a claim is minted through an internal path that predates heartbeats.', { code: 'claim_not_wired' });
287
+ }
288
+ const resolved = resolveHeartbeatOptions(beatOptions);
289
+ const beat = await lease.heartbeat({
290
+ ttl: resolved.ttl ?? options.ttl,
291
+ ...(resolved.details !== undefined ? { details: resolved.details } : {}),
292
+ });
293
+ const held = activeClaims.get(id);
294
+ if (held)
295
+ held.expiresAt = beat.expiresAt;
296
+ plan.onBeat?.(beat);
297
+ return beat;
298
+ };
299
+ // Opt-in auto-heartbeat: the loop beats until release, and a definitive
300
+ // loss stops it and surfaces through the plan's `onLost`.
301
+ const stopHeartbeatLoop = plan.loop
302
+ ? startClaimHeartbeatLoop({
303
+ beat: () => heartbeat(),
304
+ intervalMs: heartbeatCadenceMs(ttlMs, plan.cadence),
305
+ ...(plan.onLost ? { onLost: plan.onLost } : {}),
306
+ })
307
+ : undefined;
308
+ const release = () => {
309
+ stopHeartbeatLoop?.();
310
+ return releaseClaim(id);
311
+ };
312
+ return {
313
+ object: 'claim',
314
+ id: lease.id,
315
+ readAt: snapshot.stamp,
316
+ // The fencing token the server minted for this grant, forwarded from the
317
+ // lease so writes taken under this handle carry it (Option B).
318
+ ...(lease.fenceToken !== undefined ? { fenceToken: lease.fenceToken } : {}),
319
+ target,
320
+ description,
321
+ data: modelAsRow(model),
322
+ release,
323
+ revoke: () => {
324
+ void release();
325
+ },
326
+ heartbeat,
327
+ [Symbol.asyncDispose]: release,
328
+ };
329
+ };
330
+ // The row-free sibling of `takeClaim`: locks a key by id alone, for a row that
331
+ // lives only in the customer's own database and was never synced into Ablo.
332
+ // Everything about the lease — the fail-fast contention check, the scope pin,
333
+ // the `createClaim` grant, the heartbeat wiring, and the `activeClaims`
334
+ // bookkeeping — is identical; what's dropped is the object-pool `load` (and its
335
+ // `entity_not_found` throw), the post-grant re-read, and the `.data` field,
336
+ // since there is no local row to hydrate or return.
337
+ const takeRowFreeClaim = async (id, options) => {
338
+ if (!collaboration) {
339
+ throw new AbloValidationError(`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`, { code: 'model_claim_not_configured' });
340
+ }
341
+ // Is someone else already on this target? Read the local coordination
342
+ // snapshot up front so a `queue: false` caller can reject before announcing
343
+ // a claim the server would refuse.
344
+ const held = collaboration.state({ model: wireModel, id });
345
+ const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
346
+ const failFast = options.queue === false;
347
+ // The try-claim (`queue: false`): resolve `null` if a holder is already
348
+ // visible — an expected outcome, not an error. Best-effort at the client —
349
+ // a row this participant never synced usually carries no local claim state
350
+ // either, so a peer gets the deterministic `null` only once it has
351
+ // observed the holder (entered the row's entity scope). The server's
352
+ // queue is the backstop for the queuing path.
353
+ if (failFast && contended) {
354
+ return null;
355
+ }
356
+ // Enter the entity scope before acquiring the lease so the holder's claim
357
+ // presence broadcasts to everyone in this entity group — the same ordering
358
+ // the row-bearing path relies on. No pool `load` and no `entity_not_found`
359
+ // throw: the row lives only in the customer's database, so there is nothing
360
+ // to hydrate here and nothing to re-read after the grant.
361
+ await collaboration.pinScope?.({ [schemaKey]: id });
362
+ const lease = await collaboration.createClaim({
363
+ target: {
364
+ model: wireModel,
365
+ id,
366
+ // The whole sub-entity locator in one move — listing its members here
367
+ // is what let `fields` die between the caller and the lease, so the
368
+ // claim covered the whole row while the caller believed it named parts.
369
+ ...subTarget(options, schemaKey),
370
+ },
371
+ description: claimDescription(options),
372
+ ttl: options.ttl,
373
+ queue: !failFast,
374
+ maxQueueDepth: options.maxQueueDepth,
375
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
376
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
377
+ waitTimeoutMs: options.waitTimeoutMs,
378
+ signal: options.signal,
379
+ });
380
+ // A watermark-only snapshot: `createSnapshot` still reads the engine's
381
+ // current `lastSyncId` even though the pool holds no row (the bucket is
382
+ // empty). It costs nothing extra and gives a write taken under this lease a
383
+ // real `readAt` to guard against changes since the lease was acquired.
384
+ const snapshot = collaboration.createSnapshot(schemaKey, id);
385
+ const description = claimDescription(options);
386
+ const selfTarget = {
387
+ type: wireModel,
388
+ id,
389
+ ...subTarget(options, schemaKey),
390
+ };
391
+ const ttlMs = options.ttl !== undefined ? toMs(options.ttl) : DEFAULT_LEASE_TTL_MS;
392
+ const expiresAt = Date.now() + ttlMs;
393
+ activeClaims.set(id, {
394
+ lease,
395
+ snapshot,
396
+ target: selfTarget,
397
+ description,
398
+ expiresAt,
399
+ });
400
+ const target = {
401
+ type: schemaKey,
402
+ id,
403
+ ...subTarget(options, schemaKey),
404
+ };
405
+ // One reading of the heartbeat options — cadence and callbacks from
406
+ // whichever spelling the caller used.
407
+ const plan = resolveHeartbeatPlan(options);
408
+ // A beat resolves with the server's extended expiry; keep the local
409
+ // self-claim estimate in step so `claim.state` renders the real window.
410
+ const heartbeat = async (beatOptions) => {
411
+ if (!lease.heartbeat) {
412
+ throw new AbloValidationError('This claim handle has no heartbeat wiring, which the standard Ablo({ schema, apiKey }) client provides on every claim. This appears only when a claim is minted through an internal path that predates heartbeats.', { code: 'claim_not_wired' });
413
+ }
414
+ const resolved = resolveHeartbeatOptions(beatOptions);
415
+ const beat = await lease.heartbeat({
416
+ ttl: resolved.ttl ?? options.ttl,
417
+ ...(resolved.details !== undefined ? { details: resolved.details } : {}),
418
+ });
419
+ const held = activeClaims.get(id);
420
+ if (held)
421
+ held.expiresAt = beat.expiresAt;
422
+ plan.onBeat?.(beat);
423
+ return beat;
424
+ };
425
+ const stopHeartbeatLoop = plan.loop
426
+ ? startClaimHeartbeatLoop({
427
+ beat: () => heartbeat(),
428
+ intervalMs: heartbeatCadenceMs(ttlMs, plan.cadence),
429
+ ...(plan.onLost ? { onLost: plan.onLost } : {}),
430
+ })
431
+ : undefined;
432
+ const release = () => {
433
+ stopHeartbeatLoop?.();
434
+ return releaseClaim(id);
435
+ };
436
+ return {
437
+ object: 'claim',
438
+ id: lease.id,
439
+ readAt: snapshot.stamp,
440
+ // Forward the grant's fencing token so writes under this row-free lease
441
+ // carry it (Option B), exactly as the row-bearing claim does.
442
+ ...(lease.fenceToken !== undefined ? { fenceToken: lease.fenceToken } : {}),
443
+ target,
444
+ description,
445
+ release,
446
+ revoke: () => {
447
+ void release();
448
+ },
449
+ heartbeat,
450
+ [Symbol.asyncDispose]: release,
451
+ };
452
+ };
453
+ // `claim` overloads on its first argument: an options object claims a synced
454
+ // row and resolves to a HeldClaim (carrying `.data`); a bare id claims a key
455
+ // whose row Ablo doesn't hold and resolves to a HeldLease (no `.data`). Both
456
+ // route their throws through `toAbloError` via the guarded takers, so the
457
+ // two-signature shape survives — wrapping the dispatcher itself in `guard`
458
+ // would collapse the overloads to one.
459
+ const guardedTakeClaim = guard(takeClaim);
460
+ const guardedTakeRowFreeClaim = guard(takeRowFreeClaim);
461
+ function claim(arg, opts) {
462
+ return typeof arg === 'string'
463
+ ? guardedTakeRowFreeClaim(arg, opts ?? {})
464
+ : guardedTakeClaim(arg);
465
+ }
466
+ // `claim` is a callable namespace: invoke it to take a claim, reach its
467
+ // members to read/steer the coordination plane. Attach the readers to the
468
+ // callable so `ablo.<model>.claim(...)` and `ablo.<model>.claim.state(...)`
469
+ // are the same object.
470
+ // `state` and `queue` take a caller-named `meta` shape. The runtime cannot
471
+ // check it and is not meant to: `target.meta` is application data the
472
+ // protocol carries verbatim and never interprets, so naming its type is the
473
+ // caller asserting what it put there — the same bargain as parsing your own
474
+ // JSON into an interface. These read as `Claim` here, and the one assertion
475
+ // that applies the caller's parameter is on the assignment below, in one
476
+ // place rather than at every call site.
477
+ /**
478
+ * This client's own claim on a row, as a claim-state object.
479
+ *
480
+ * The server excludes a holder's own presence frames and the client skips
481
+ * them, so a row this client holds is absent from every peer-derived read.
482
+ * Both `state` and `list` therefore synthesize it from the stored lease, and
483
+ * they do it through here so the two answers cannot describe the same
484
+ * holding differently.
485
+ */
486
+ const ownClaimState = (id) => {
487
+ const own = activeClaims.get(id);
488
+ if (!own)
489
+ return null;
490
+ return {
491
+ object: 'claim',
492
+ id: own.lease.id,
493
+ status: 'active',
494
+ target: own.target,
495
+ description: own.description,
496
+ heldBy: collaboration?.selfParticipantId ?? '',
497
+ participantKind: collaboration?.selfParticipantKind ?? 'user',
498
+ expiresAt: own.expiresAt,
499
+ // Symmetric with the peer projection: a holder reading its own claim
500
+ // sees the same `meta` an observer does.
501
+ ...(own.target.meta !== undefined ? { meta: own.target.meta } : {}),
502
+ };
503
+ };
504
+ const claimReaders = {
505
+ state(params) {
506
+ // Read interest: a passive observer of a row's claim state must enter that
507
+ // row's entity scope, or it sits only on broader `org:`/`user:` groups and
508
+ // never receives the holder's entity-scoped claim presence. Best-effort
509
+ // and fire-and-forget — it never blocks or rejects the read.
510
+ void collaboration?.enterScope?.({ [schemaKey]: params.id });
511
+ // Self-awareness: the server excludes a holder's own presence frames and
512
+ // the client skips them, so `state` would return null for a row this client
513
+ // holds. Synthesize the active claim from the stored lease so the holder
514
+ // sees its own claim, honoring the documented contract on `claim.state`.
515
+ return (ownClaimState(params.id) ??
516
+ collaboration?.state({ model: wireModel, id: params.id }) ??
517
+ null);
518
+ },
519
+ /**
520
+ * Every claim on the row, holders first. Sub-row claims on disjoint parts
521
+ * are all granted, so a row can have several holders at once and
522
+ * {@link state} answers with one of them — this is the read that renders
523
+ * all of them. Same list envelope as {@link queue}, reactive on the same
524
+ * snapshot, so a render reads it inline.
525
+ */
526
+ list(params) {
527
+ void collaboration?.enterScope?.({ [schemaKey]: params.id });
528
+ const own = ownClaimState(params.id);
529
+ const peers = collaboration?.holders({ model: wireModel, id: params.id }) ?? [];
530
+ return {
531
+ object: 'list',
532
+ // Own claim first: the server excludes a holder's own presence frames,
533
+ // so it is never among `peers` and the two never duplicate.
534
+ data: own ? [own, ...peers] : [...peers],
535
+ };
536
+ },
537
+ queue(params) {
538
+ return {
539
+ object: 'list',
540
+ data: collaboration?.queue({ model: wireModel, id: params.id }) ?? [],
541
+ };
542
+ },
543
+ reorder(params) {
544
+ collaboration?.reorder({ model: wireModel, id: params.id }, params.order);
545
+ },
546
+ release: guard((params) => releaseClaim(isClaimHandle(params) ? params.target.id : params.id)),
547
+ };
548
+ // The one place the caller's `meta` parameter is applied — see the note on
549
+ // `claimReaders`. Everything else about this object is checked structurally.
550
+ const claimApi = Object.assign(claim, claimReaders);
551
+ const local = {
552
+ get(id) {
553
+ // Scoped to this model: an id belonging to a sibling model reads as
554
+ // absent rather than being handed back as if it were a `T`.
555
+ return objectPool.getOfType(id, registeredModelName);
556
+ },
557
+ list(options) {
558
+ const all = objectPool.getByType(ModelClass, (options?.state ?? ModelScope.live));
559
+ let result = all;
560
+ if (options?.where) {
561
+ const where = options.where;
562
+ result = result.filter((item) => {
563
+ for (const [key, value] of Object.entries(where)) {
564
+ if (item[key] !== value)
565
+ return false;
566
+ }
567
+ return true;
568
+ });
569
+ }
570
+ if (options?.filter) {
571
+ result = result.filter(options.filter);
572
+ }
573
+ const orderEntry = options?.orderBy ? Object.entries(options.orderBy)[0] : undefined;
574
+ if (orderEntry) {
575
+ const [field, dir] = orderEntry;
576
+ result = [...result].sort((a, b) => {
577
+ const av = a[field];
578
+ const bv = b[field];
579
+ if (av == null || bv == null)
580
+ return 0;
581
+ const cmp = av < bv ? -1 : av > bv ? 1 : 0;
582
+ return dir === 'desc' ? -cmp : cmp;
583
+ });
584
+ }
585
+ if (options?.offset)
586
+ result = result.slice(options.offset);
587
+ if (options?.limit)
588
+ result = result.slice(0, options.limit);
589
+ return result;
590
+ },
591
+ count(options) {
592
+ return local.list(options).length;
593
+ },
594
+ };
595
+ const get = guard(async (params) => {
596
+ // Read-interest enrolment: authoritative point reads enter the same
597
+ // entity scope as the claim stream, while remaining settled reads.
598
+ void collaboration?.enterScope?.({ [schemaKey]: params.id });
599
+ const rows = await load({
600
+ ...params,
601
+ where: [['id', params.id]],
602
+ limit: 1,
603
+ });
604
+ return rows[0];
605
+ });
606
+ const operations = {
607
+ local,
608
+ get,
609
+ retrieve: get,
610
+ // No automatic scope enrolment on bulk `list`: that would subscribe to an
611
+ // unbounded set of rows' entity groups.
612
+ list: guard(load),
613
+ create: guard(async (params) => {
614
+ const id = params.id ?? Model.generateId();
615
+ const opts = mutationOptions(params);
616
+ const claim = params.claim;
617
+ let autoLease;
618
+ if (claim && !isClaimHandle(claim)) {
619
+ if (!collaboration) {
620
+ throw new AbloValidationError(`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`, { code: 'model_claim_not_configured' });
621
+ }
622
+ // Write intent: enter the new row's entity scope before acquiring the
623
+ // create-claim so the holder's claim presence broadcasts to everyone
624
+ // already in this entity group (closing the subscribe-versus-broadcast
625
+ // race — see `takeClaim`). Released with the lease in the `finally`
626
+ // below. Awaited for broadcast ordering; still best-effort.
627
+ await collaboration.pinScope?.({ [schemaKey]: id });
628
+ autoLease = await collaboration.createClaim({
629
+ target: {
630
+ model: wireModel,
631
+ id,
632
+ ...subTarget(claim, schemaKey),
633
+ },
634
+ description: claimDescription(claim, 'creating'),
635
+ ttl: claim.ttl,
636
+ queue: claim.queue !== false,
637
+ maxQueueDepth: claim.maxQueueDepth,
638
+ });
639
+ }
640
+ // Default `organizationId` from the client's identity, matching the other
641
+ // write path — without this, a caller that omits it would create an
642
+ // org-unscoped row on one write path but not the other. An explicit value
643
+ // in `data` still wins via the spread.
644
+ const orgDefault = params.data.organizationId ??
645
+ syncClient.getOrganizationId();
646
+ const model = new ModelClass({
647
+ id,
648
+ ...(orgDefault != null ? { organizationId: orgDefault } : {}),
649
+ ...params.data,
650
+ createdAt: new Date(),
651
+ updatedAt: new Date(),
652
+ });
653
+ const effective = {
654
+ ...opts,
655
+ ...(autoLease ? { claim: autoLease } : {}),
656
+ ...(isClaimHandle(claim) ? { claim: { id: claim.id } } : {}),
657
+ };
658
+ try {
659
+ syncClient.add(model, effective);
660
+ await waitForMutation(model, effective);
661
+ return modelAsRow(model);
662
+ }
663
+ finally {
664
+ await autoLease?.release?.().catch(() => { });
665
+ }
666
+ }),
667
+ // `update` is overloaded — classic `update({ id, data })` + functional
668
+ // `update(id, current => next)`. The IIFE keeps the shared error-guard
669
+ // wrapping while exposing the two public signatures (a plain `guard(...)`
670
+ // would collapse them to one).
671
+ update: (() => {
672
+ const updateImpl = guard(async (arg, updater, contention) => {
673
+ // Functional form: update(id, current => next). Same guarantee as the
674
+ // HTTP client (shared reconcile loop), implemented with this transport's
675
+ // own read-fresh + confirmed compare-and-swap. A forced server round-trip
676
+ // gets the latest row + watermark; the write is stale-guarded by it, so
677
+ // concurrent writers reconcile instead of clobbering — no claim needed.
678
+ if (typeof arg === 'string') {
679
+ const id = arg;
680
+ if (typeof updater !== 'function') {
681
+ throw new AbloValidationError(`${registeredModelName}.update('${id}', updater): the second argument must ` +
682
+ `be an updater function (current) => next. To write a fixed value, use ` +
683
+ `update({ id, data }).`, { code: 'write_options_invalid' });
684
+ }
685
+ if (!collaboration) {
686
+ throw new AbloValidationError(`${registeredModelName}.update(id, updater) needs the collaboration runtime ` +
687
+ `(a live WebSocket) to read the row's watermark for its compare-and-swap. ` +
688
+ `Use the standard Ablo({ schema, apiKey }) client.`, { code: 'model_claim_not_configured' });
689
+ }
690
+ return reconcileFunctionalUpdate(updater, contention, {
691
+ model: registeredModelName,
692
+ id,
693
+ readFresh: async () => {
694
+ // `type: 'complete'` forces the round-trip — the hydration ledger
695
+ // would otherwise serve a possibly-stale local row for a hydrated id.
696
+ await load({ where: [['id', id]], type: 'complete' });
697
+ const fresh = ownRowOrThrow(id);
698
+ const snapshot = collaboration.createSnapshot(schemaKey, id);
699
+ return {
700
+ data: fresh ? modelAsRow(fresh) : undefined,
701
+ stamp: snapshot.stamp,
702
+ };
703
+ },
704
+ writeNext: async (patch, readAt) => {
705
+ const model = ownRowOrThrow(id);
706
+ if (!model) {
707
+ throw new AbloValidationError(`Entity not found: ${registeredModelName}/${id}`, { code: 'entity_not_found' });
708
+ }
709
+ const effective = {
710
+ wait: 'confirmed',
711
+ readAt,
712
+ onStale: 'reject',
713
+ };
714
+ model.applyChanges(patch);
715
+ syncClient.update(model, effective);
716
+ await waitForMutation(model, effective);
717
+ return modelAsRow(model);
718
+ },
719
+ });
720
+ }
721
+ const params = arg;
722
+ const autoClaim = params.claim && !isClaimHandle(params.claim) ? params.claim : null;
723
+ if (autoClaim) {
724
+ const handle = await takeClaim({ ...autoClaim, id: params.id });
725
+ // A declined try-claim is `null` only on the standalone verb; a
726
+ // write that could not take its claim is a failed write.
727
+ if (!handle) {
728
+ throw new AbloClaimedError(`${registeredModelName}/${params.id} is held by another participant, so this update's claim could not be taken.`, { code: 'entity_claimed' });
729
+ }
730
+ try {
731
+ return await operations.update({ ...params, claim: handle });
732
+ }
733
+ finally {
734
+ await handle.release();
735
+ }
736
+ }
737
+ const { id } = params;
738
+ const model = ownRowOrThrow(id);
739
+ if (!model)
740
+ throw new AbloValidationError(`Entity not found: ${registeredModelName}/${id}`, { code: 'entity_not_found' });
741
+ // If we hold a claim on this row, guard the write with its snapshot
742
+ // watermark + lease so it's stale-rejected and attributed to the claim.
743
+ const claimed = activeClaims.get(id);
744
+ const opts = mutationOptions(params);
745
+ const handle = isClaimHandle(params.claim) ? params.claim : undefined;
746
+ const effective = claimed
747
+ ? {
748
+ wait: 'confirmed',
749
+ readAt: claimed.snapshot.stamp,
750
+ onStale: 'reject',
751
+ claimRef: { id: claimed.lease.id },
752
+ ...opts,
753
+ }
754
+ : {
755
+ // A carried handle engages the same stale guard as a claim this
756
+ // proxy took itself — the watermark rides on the handle, so it
757
+ // works across clients (HTTP-minted handles included).
758
+ ...(handle?.readAt !== undefined
759
+ ? {
760
+ wait: 'confirmed',
761
+ readAt: handle.readAt,
762
+ onStale: 'reject',
763
+ ...(handle.fenceToken !== undefined
764
+ ? { fenceToken: handle.fenceToken }
765
+ : {}),
766
+ }
767
+ : {}),
768
+ ...opts,
769
+ ...(handle ? { claim: { id: handle.id } } : {}),
770
+ };
771
+ // Local user update: `applyChanges` keeps change tracking on so the
772
+ // edited fields land in `modifiedProperties` and are actually sent to
773
+ // the server. (`updateFromData` is the hydration path and would discard
774
+ // the tracking, producing an empty `input: {}` no-op mutation.)
775
+ model.applyChanges(params.data);
776
+ syncClient.update(model, effective);
777
+ await waitForMutation(model, effective);
778
+ return modelAsRow(model);
779
+ });
780
+ function update(arg, updater, contention) {
781
+ return updateImpl(arg, updater, contention);
782
+ }
783
+ return update;
784
+ })(),
785
+ delete: guard(async (params) => {
786
+ const autoClaim = params.claim && !isClaimHandle(params.claim) ? params.claim : null;
787
+ if (autoClaim) {
788
+ const handle = await takeClaim({ ...autoClaim, id: params.id });
789
+ // Same rule as update: a write that could not take its claim fails.
790
+ if (!handle) {
791
+ throw new AbloClaimedError(`${registeredModelName}/${params.id} is held by another participant, so this delete's claim could not be taken.`, { code: 'entity_claimed' });
792
+ }
793
+ try {
794
+ await operations.delete({ ...params, claim: handle });
795
+ }
796
+ finally {
797
+ await handle.release();
798
+ }
799
+ return;
800
+ }
801
+ const { id } = params;
802
+ // Scoped: "ensure absent" stays idempotent for an id this model simply
803
+ // doesn't hold, but an id owned by a sibling model throws rather than
804
+ // deleting a row the caller never addressed.
805
+ const model = ownRowOrThrow(id);
806
+ // Idempotent delete: "ensure absent". A row that isn't in this client's
807
+ // replicated view is already gone from its perspective, so a delete is a
808
+ // no-op success rather than an `entity_not_found` error. This matches the
809
+ // HTTP client and makes delete safe to retry or race (two actors deleting
810
+ // the same row).
811
+ if (!model)
812
+ return;
813
+ const claimed = activeClaims.get(id);
814
+ const opts = mutationOptions(params);
815
+ const handle = isClaimHandle(params.claim) ? params.claim : undefined;
816
+ const effective = claimed
817
+ ? {
818
+ wait: 'confirmed',
819
+ readAt: claimed.snapshot.stamp,
820
+ onStale: 'reject',
821
+ claimRef: { id: claimed.lease.id },
822
+ ...(claimed.lease.fenceToken !== undefined
823
+ ? { fenceToken: claimed.lease.fenceToken }
824
+ : {}),
825
+ ...opts,
826
+ }
827
+ : {
828
+ ...(handle?.readAt !== undefined
829
+ ? {
830
+ wait: 'confirmed',
831
+ readAt: handle.readAt,
832
+ onStale: 'reject',
833
+ }
834
+ : {}),
835
+ ...opts,
836
+ ...(handle ? { claim: { id: handle.id } } : {}),
837
+ };
838
+ syncClient.delete(model, effective);
839
+ await waitForMutation(model, effective);
840
+ }),
841
+ // `claim` is a callable namespace (take a claim) carrying the coordination
842
+ // readers (`claim.state` / `claim.queue` / `claim.release` / `claim.reorder`).
843
+ claim: claimApi,
844
+ track: guard(async (params) => {
845
+ const dep = {
846
+ model: wireModel,
847
+ id: params.id,
848
+ ...(params.readAt !== undefined ? { readAt: params.readAt } : {}),
849
+ };
850
+ // A track carries no write, so it rides the commit lane as a zero-operation
851
+ // commit: the queue tolerates disconnects and de-dupes replays, and the
852
+ // server's track-only path registers the premise and reports anything
853
+ // that already fired. Reuse the same lane the batch `commits.create` door
854
+ // uses rather than opening a bespoke transport.
855
+ const clientTxId = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
856
+ ? crypto.randomUUID()
857
+ : `tx_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
858
+ const queue = syncClient.getMutationQueue();
859
+ await queue.enqueueCommit(clientTxId, [], { track: [dep] });
860
+ const { notifications } = await queue.waitForCommitReceipt(clientTxId);
861
+ return notifications && notifications.length > 0 ? { notifications } : {};
862
+ }),
863
+ join: guard((ids, options) => {
864
+ if (!collaboration?.createJoin) {
865
+ throw new AbloValidationError(`Model "${schemaKey}" was built without a WebSocket runtime, so join() is unavailable here. Presence needs a live socket — use the standard Ablo({ schema, apiKey }) client (not the HTTP transport).`, { code: 'model_join_not_configured' });
866
+ }
867
+ return collaboration.createJoin(schemaKey, ids, options);
868
+ }),
869
+ onChange(callback, options) {
870
+ return autorun(() => {
871
+ callback(local.list(options));
872
+ });
873
+ },
874
+ };
875
+ modelClientMeta.set(operations, {
876
+ key: schemaKey,
877
+ typename: registeredModelName,
878
+ });
879
+ return operations;
880
+ }