@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,668 @@
1
+ /**
2
+ * Creates a {@link ClaimStream} over a live sync connection. A claim is a
3
+ * short-lived, advisory lease a participant takes on an entity (or a field of
4
+ * one) to signal "I'm working on this"; the stream lets you take claims, see
5
+ * everyone else's, and watch the wait queue when a claim is contended.
6
+ *
7
+ * The stream is built directly on the sync WebSocket and shares that one
8
+ * connection. It learns about other participants' claims from the same
9
+ * `presence_update` frames the {@link createPresenceStream} presence stream
10
+ * consumes — the server piggybacks each participant's `activeClaims` on every
11
+ * presence frame — and sends its own claims as `claim_begin` and
12
+ * `claim_abandon` frames.
13
+ *
14
+ * Wire frames:
15
+ * • Outbound `claim_begin` — announce a claim: `{ claimId, entityType,
16
+ * entityId, description, field?, estimatedMs? }`.
17
+ * • Outbound `claim_abandon` — release it: `{ claimId, entityType?,
18
+ * entityId? }`.
19
+ * • Inbound, via presence — `event.activeClaims`, each stamped with
20
+ * `declaredAt` and `expiresAt`.
21
+ * • Inbound `claim_rejected` — the server refused the claim, with conflict
22
+ * metadata.
23
+ */
24
+
25
+ import type {
26
+ WsTransport,
27
+ PresenceUpdate,
28
+ } from '@abloatai/transaction/transport/wsTransport';
29
+ import type {
30
+ ClaimOptions,
31
+ ClaimTarget,
32
+ Claim,
33
+ ClaimHeartbeat,
34
+ ClaimHeartbeatOptions,
35
+ ClaimLeaseOptions,
36
+ ClaimRejection,
37
+ ClaimLost,
38
+ ClaimStream,
39
+ PresenceTarget,
40
+ } from '@abloatai/transaction/types/streams';
41
+ import { asyncIteratorFrom } from '@abloatai/transaction/utils/asyncIterator';
42
+ import { toMs } from '@abloatai/transaction/utils/duration';
43
+ import {
44
+ claimDescription,
45
+ descriptionFromMeta,
46
+ participantKindFromWire,
47
+ } from '@abloatai/transaction/coordination/schema';
48
+ import {
49
+ isTargetTuple,
50
+ subTarget,
51
+ streamTarget,
52
+ wireTarget,
53
+ type ClaimTargetDetails,
54
+ } from '@abloatai/transaction/coordination/locator';
55
+ import { declaredMeta } from '@abloatai/transaction/coordination/claimMeta';
56
+ import { AbloClaimedError, AbloConnectionError } from '@abloatai/transaction/errors';
57
+ import { resolveHeartbeatOptions } from '@abloatai/transaction/coordination/claimHeartbeatLoop';
58
+ import { noopLogger, type Logger } from '@abloatai/transaction/logger';
59
+
60
+ /**
61
+ * The wire capability the claim stream actually uses: subscribe to typed
62
+ * inbound frames, check liveness, and send outbound frames. The duplex
63
+ * `WsTransport` satisfies it, so production wiring is unchanged — but depending on the port
64
+ * rather than the whole socket class lets a test drive it with a plain object,
65
+ * no cast. `Pick` carries the exact (generic, typed-payload) `subscribe`
66
+ * signature, so every handler stays fully typed.
67
+ */
68
+ export type ClaimTransport = Pick<WsTransport, 'subscribe' | 'isConnected' | 'send'>;
69
+
70
+ /** Readable target for the coordination trace: `documents:abc` / `documents:abc.title`. */
71
+ function claimLabel(type: string, id: string, field?: string): string {
72
+ return field ? `${type}:${id}.${field}` : `${type}:${id}`;
73
+ }
74
+
75
+ export interface ClaimStreamConfig {
76
+ /** Identity used to filter our own active claims out of `others`. */
77
+ participantId: string;
78
+ /** Where the coordination trace is logged. Defaults to silent. */
79
+ logger?: Logger;
80
+ }
81
+
82
+ /**
83
+ * How long a heartbeat waits for its `claim_heartbeat_ack` before giving up
84
+ * as transient (the auto-heartbeat loop's next tick retries). Comfortably
85
+ * above a round trip, comfortably below the ttl/3 beat cadence.
86
+ */
87
+ const HEARTBEAT_ACK_TIMEOUT_MS = 10_000;
88
+
89
+ export interface AttachableClaimStream extends ClaimStream {
90
+ /**
91
+ * Mints a lease directly: sends the `claim_begin` frame and returns a held
92
+ * {@link Claim} that carries no row `data` (the resource layer reads the row
93
+ * and stamps it). This is an internal entry point, not part of the public
94
+ * {@link ClaimStream}; application code takes a claim through
95
+ * `ablo.<model>.claim({ id })`, which is built on this.
96
+ */
97
+ claim(target: PresenceTarget, opts?: ClaimOptions): Claim;
98
+ attach(transport: ClaimTransport): void;
99
+ /**
100
+ * Seeds the participant identity once the host resolves it. The stream can
101
+ * be built before identity is known — a hosted client learns who it is
102
+ * from its credential's scope during connect — and until then the
103
+ * construction-time id (possibly empty) would let the participant's own
104
+ * claims into `others`. Idempotent; later frames filter on the new id.
105
+ */
106
+ setParticipant(participant: { id: string }): void;
107
+ dispose(): void;
108
+ }
109
+
110
+ /**
111
+ * What this participant needs to remember about a claim it holds, so it can
112
+ * re-announce it after a reconnect.
113
+ *
114
+ * The sub-entity locator is taken from {@link ClaimTargetDetails} rather than
115
+ * listed again: a member this record forgot would be a member the re-announced
116
+ * claim silently lost, which is a narrower claim than the one the holder
117
+ * believes it has.
118
+ */
119
+ type OwnClaim = ClaimTargetDetails & {
120
+ readonly entityType: string;
121
+ readonly entityId: string;
122
+ /** Peer-visible description of the work, shown to other participants. */
123
+ readonly description: string;
124
+ readonly estimatedMs: number | undefined;
125
+ /** When set, wait in the server's fair first-come-first-served queue if the
126
+ * entity is already claimed, instead of being rejected. */
127
+ readonly queue?: boolean;
128
+ };
129
+
130
+ export function createClaimStream(
131
+ config: ClaimStreamConfig,
132
+ transport: ClaimTransport | null = null,
133
+ ): AttachableClaimStream {
134
+ // Mutable: the host seeds the resolved identity via `setParticipant` once
135
+ // it is known; the own-claim filter always reads the current value.
136
+ let participantId = config.participantId;
137
+ const logger = config.logger ?? noopLogger;
138
+
139
+ // ── State: others' open claims, keyed by claimId ───────────────
140
+ const activeByClaimId = new Map<string, Claim>();
141
+ let claimsSnapshot: readonly Claim[] = Object.freeze([]);
142
+
143
+ // ── State: our own open claims (for re-announce on reconnect) ───
144
+ const ownClaims = new Map<string, OwnClaim>();
145
+
146
+ // ── State: per-entity wait queues, from `claim_queue` frames ────
147
+ // Keyed `type:id`; the value is the FIFO line of queued claims. Powers
148
+ // the reactive `queue(target)` read — who's waiting and what they intend.
149
+ const queueByEntity = new Map<string, readonly Claim[]>();
150
+ const entityKey = (type: string, id: string): string => `${type}:${id}`;
151
+ const EMPTY_QUEUE: readonly Claim[] = Object.freeze([]);
152
+ // Last queue position we logged per own-claim, so advancing in line is traced
153
+ // once per change (not re-logged on every server re-fan of the same line).
154
+ const lastLoggedQueuePos = new Map<string, number>();
155
+
156
+ // ── Subscribers ──────────────────────────────────────────────────
157
+ const listeners = new Set<() => void>();
158
+ const rejectionListeners = new Set<(r: ClaimRejection) => void>();
159
+ const lostListeners = new Set<(l: ClaimLost) => void>();
160
+
161
+ // ── State: in-flight heartbeats awaiting their ack, keyed by claimId ──
162
+ const pendingHeartbeats = new Map<
163
+ string,
164
+ {
165
+ resolve: (value: ClaimHeartbeat) => void;
166
+ reject: (error: Error) => void;
167
+ timer: ReturnType<typeof setTimeout>;
168
+ }
169
+ >();
170
+
171
+ const settleHeartbeat = (
172
+ claimId: string,
173
+ settle: (pending: {
174
+ resolve: (value: ClaimHeartbeat) => void;
175
+ reject: (error: Error) => void;
176
+ }) => void,
177
+ ): void => {
178
+ const pending = pendingHeartbeats.get(claimId);
179
+ if (!pending) return;
180
+ pendingHeartbeats.delete(claimId);
181
+ clearTimeout(pending.timer);
182
+ settle(pending);
183
+ };
184
+
185
+ const notifyListeners = () => {
186
+ claimsSnapshot = Object.freeze(Array.from(activeByClaimId.values()));
187
+ for (const l of listeners) {
188
+ try {
189
+ l();
190
+ } catch {
191
+ /* listener errors don't break siblings */
192
+ }
193
+ }
194
+ };
195
+
196
+ // ── Wire wiring ──────────────────────────────────────────────────
197
+ let attached: ClaimTransport | null = null;
198
+ const unsubs: (() => void)[] = [];
199
+
200
+ function attach(t: ClaimTransport): void {
201
+ if (attached) return;
202
+ attached = t;
203
+
204
+ // (1) Inbound presence frames carry every participant's full
205
+ // active-claim set. Prune previous claims by holder, then
206
+ // re-add from the frame — the frame is authoritative for that
207
+ // participant's open claims at that moment.
208
+ unsubs.push(
209
+ t.subscribe('presence_update', (event: PresenceUpdate) => {
210
+ if (!event.userId) return;
211
+ if (event.userId === participantId) return;
212
+
213
+ let mutated = false;
214
+
215
+ if (event.kind === 'leave') {
216
+ for (const [id, claim] of activeByClaimId) {
217
+ if (claim.heldBy === event.userId) {
218
+ activeByClaimId.delete(id);
219
+ mutated = true;
220
+ }
221
+ }
222
+ if (mutated) notifyListeners();
223
+ return;
224
+ }
225
+
226
+ for (const [id, claim] of activeByClaimId) {
227
+ if (claim.heldBy === event.userId) {
228
+ activeByClaimId.delete(id);
229
+ mutated = true;
230
+ }
231
+ }
232
+ for (const claim of event.activeClaims ?? []) {
233
+ // Terminal-status entries (committed / expired / canceled) are
234
+ // one-shot "this claim ended" signals. The holder sweep above
235
+ // already removed the prior active entry; skipping the re-add
236
+ // drops it from `others`, which is what resolves a contender's
237
+ // `settled()`. Absent status means active (wire back-compat).
238
+ if (claim.status && claim.status !== 'active') continue;
239
+ // Resolve the always-present public field, tolerating a frame that
240
+ // carries the value in `meta` rather than as an explicit description.
241
+ const description =
242
+ claim.description ??
243
+ descriptionFromMeta(claim.meta) ??
244
+ 'editing';
245
+ // The frame is parsed permissively, on purpose; `declaredMeta` is where
246
+ // that wire value becomes the shape the program declared.
247
+ const { meta, ...details } = subTarget(claim);
248
+ activeByClaimId.set(claim.claimId, {
249
+ object: 'claim',
250
+ id: claim.claimId,
251
+ status: 'active',
252
+ heldBy: event.userId,
253
+ participantKind: participantKindFromWire(
254
+ event.participantKind,
255
+ event.isAgent,
256
+ ),
257
+ target: {
258
+ ...streamTarget(claim),
259
+ ...details,
260
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
261
+ },
262
+ description,
263
+ ttlSeconds: Math.max(
264
+ 0,
265
+ Math.floor((claim.expiresAt - Date.now()) / 1000),
266
+ ),
267
+ createdAt: claim.declaredAt,
268
+ expiresAt: claim.expiresAt,
269
+ });
270
+ mutated = true;
271
+ }
272
+ if (mutated) notifyListeners();
273
+ }),
274
+ );
275
+
276
+ // (2) Server-side rejection frames.
277
+ unsubs.push(
278
+ t.subscribe('claim_rejected', (rejection) => {
279
+ if (!rejection.claimId) return;
280
+ if (ownClaims.has(rejection.claimId)) {
281
+ const tgt = rejection.target
282
+ ? claimLabel(rejection.target.entityType, rejection.target.entityId, rejection.target.field)
283
+ : rejection.claimId;
284
+ logger.info(
285
+ `claim: rejected ${tgt}${rejection.heldBy ? ` — held by ${rejection.heldBy}` : ''}`,
286
+ { claimId: rejection.claimId, reason: rejection.reason },
287
+ );
288
+ }
289
+ // Drop the rejected own-claim so reconnect doesn't re-announce
290
+ // a claim the server already rejected (would just spam both
291
+ // sides with conflicts).
292
+ ownClaims.delete(rejection.claimId);
293
+ for (const l of rejectionListeners) {
294
+ try {
295
+ l(rejection);
296
+ } catch {
297
+ /* isolate */
298
+ }
299
+ }
300
+ }),
301
+ );
302
+
303
+ // (2a) Server-side loss frames — you held the claim, then lost it
304
+ // (preempted or expired). Distinct from a rejection, which is a claim
305
+ // the server refused.
306
+ unsubs.push(
307
+ // The frame is validated by the transport's dispatcher against the same
308
+ // schema this parameter's type comes from, so it arrives proven.
309
+ t.subscribe('claim_lost', (lost) => {
310
+ if (ownClaims.has(lost.claimId)) {
311
+ const c = ownClaims.get(lost.claimId);
312
+ logger.info(
313
+ `claim: lost ${c ? claimLabel(c.entityType, c.entityId, c.field) : lost.claimId} (preempted or expired)`,
314
+ { claimId: lost.claimId },
315
+ );
316
+ }
317
+ // Drop the lost own-claim so reconnect doesn't re-announce a lease we
318
+ // no longer hold.
319
+ ownClaims.delete(lost.claimId);
320
+ for (const l of lostListeners) {
321
+ try {
322
+ l(lost);
323
+ } catch {
324
+ /* isolate */
325
+ }
326
+ }
327
+ }),
328
+ );
329
+
330
+ // (2b) Per-entity wait-queue snapshots. The server fans the full line
331
+ // out on every queue mutation; we replace our cached line for that
332
+ // entity and notify so `queue(target)` reads reactively.
333
+ unsubs.push(
334
+ t.subscribe('claim_queue', (p) => {
335
+ const key = entityKey(p.target.type, p.target.id);
336
+ const line = p.queue;
337
+ if (line.length === 0) queueByEntity.delete(key);
338
+ else
339
+ // The wait line crosses from the wire into the public `Claim` shape
340
+ // like every other read does, so its meta goes through `declaredMeta`
341
+ // rather than arriving as the open record the frame was parsed as.
342
+ queueByEntity.set(
343
+ key,
344
+ Object.freeze(
345
+ line.map((entry) => {
346
+ const { meta, ...target } = entry.target;
347
+ return {
348
+ ...entry,
349
+ target: {
350
+ ...target,
351
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
352
+ },
353
+ };
354
+ }),
355
+ ),
356
+ );
357
+ // If we are in this line, trace our position (the "agent queued behind a
358
+ // claim" moment) — once per position change, so advancing is visible.
359
+ const ourIndex = line.findIndex((c) => ownClaims.has(c.id));
360
+ const ourClaim = ourIndex >= 0 ? line[ourIndex] : undefined;
361
+ if (ourClaim) {
362
+ const ourId = ourClaim.id;
363
+ if (lastLoggedQueuePos.get(ourId) !== ourIndex) {
364
+ lastLoggedQueuePos.set(ourId, ourIndex);
365
+ logger.info(
366
+ `claim: queued for ${claimLabel(p.target.type, p.target.id)} — position ${ourIndex + 1} of ${line.length}, waiting`,
367
+ { claimId: ourId },
368
+ );
369
+ }
370
+ }
371
+ notifyListeners();
372
+ }),
373
+ );
374
+
375
+ // (2c) Heartbeat replies — correlate back to the awaiting beat by
376
+ // claimId. `held` resolves with the extended expiry; `queued` and
377
+ // `lost` reject with a typed claimed error, because a heartbeat on
378
+ // a handle we thought we held coming back as anything but `held`
379
+ // means the lease is no longer ours.
380
+ unsubs.push(
381
+ t.subscribe('claim_heartbeat_ack', (ack) => {
382
+ settleHeartbeat(ack.claimId, ({ resolve, reject }) => {
383
+ if (ack.status === 'held' && ack.expiresAt !== undefined) {
384
+ resolve({
385
+ expiresAt: ack.expiresAt,
386
+ ...(ack.queueDepth !== undefined
387
+ ? { queueDepth: ack.queueDepth }
388
+ : {}),
389
+ });
390
+ return;
391
+ }
392
+ const c = ownClaims.get(ack.claimId);
393
+ reject(
394
+ new AbloClaimedError(
395
+ `The lease behind ${c ? claimLabel(c.entityType, c.entityId, c.field) : `claim ${ack.claimId}`} is no longer held — it expired or was granted onward while this participant was working. Re-acquire the claim and retry; a write attempted under the old lease is rejected by its \`readAt\` guard.`,
396
+ { code: 'claim_lost' },
397
+ ),
398
+ );
399
+ });
400
+ }),
401
+ );
402
+
403
+ // (3) On reconnect, re-announce every open self-claim — the
404
+ // server's claim state is in-memory and is lost across
405
+ // restarts. Without this, peers would see our claims vanish
406
+ // whenever the connection blipped.
407
+ unsubs.push(
408
+ t.subscribe('connected', () => {
409
+ for (const [claimId, claim] of ownClaims) {
410
+ sendBegin(claimId, claim);
411
+ }
412
+ }),
413
+ );
414
+ }
415
+
416
+ if (transport) attach(transport);
417
+
418
+ // ── Outbound ────────────────────────────────────────────────────
419
+ function sendBegin(claimId: string, claim: OwnClaim): void {
420
+ if (!attached?.isConnected()) return;
421
+ attached.send({
422
+ type: 'claim_begin',
423
+ payload: {
424
+ claimId,
425
+ ...wireTarget(claim),
426
+ description: claim.description,
427
+ ...subTarget(claim),
428
+ estimatedMs: claim.estimatedMs,
429
+ queue: claim.queue,
430
+ },
431
+ });
432
+ }
433
+
434
+ function sendReorder(
435
+ entityType: string,
436
+ entityId: string,
437
+ order: readonly Claim[],
438
+ ): void {
439
+ if (!attached?.isConnected()) return;
440
+ attached.send({
441
+ type: 'claim_reorder',
442
+ payload: {
443
+ entityType,
444
+ entityId,
445
+ // The wire shape identifies a waiter by heldBy + claimId; map the
446
+ // ergonomic `Claim[]` (what `queueFor` returns) down to that.
447
+ order: order.map((i) => ({ heldBy: i.heldBy, claimId: i.id })),
448
+ },
449
+ });
450
+ }
451
+
452
+ /**
453
+ * Send one heartbeat and await its ack. Rejects with
454
+ * {@link AbloConnectionError} (transient — the auto-heartbeat loop retries
455
+ * on its next tick) when the socket is down or the ack times out, and with
456
+ * {@link AbloClaimedError} (definitive) when the server answers that the
457
+ * lease is no longer ours.
458
+ */
459
+ function sendHeartbeat(
460
+ claimId: string,
461
+ claim: OwnClaim,
462
+ options: ClaimHeartbeatOptions,
463
+ ): Promise<ClaimHeartbeat> {
464
+ if (!attached?.isConnected()) {
465
+ return Promise.reject(
466
+ new AbloConnectionError(
467
+ `The heartbeat for ${claimLabel(claim.entityType, claim.entityId, claim.field)} was skipped because the connection is down. The keepalive renews held leases automatically on reconnect; the next beat retries.`,
468
+ ),
469
+ );
470
+ }
471
+ return new Promise<ClaimHeartbeat>((resolve, reject) => {
472
+ settleHeartbeat(claimId, ({ reject: rejectPrior }) => {
473
+ rejectPrior(
474
+ new AbloConnectionError(
475
+ 'A newer heartbeat for this claim superseded the one still awaiting its reply.',
476
+ ),
477
+ );
478
+ });
479
+ const timer = setTimeout(() => {
480
+ settleHeartbeat(claimId, ({ reject: rejectTimeout }) => {
481
+ rejectTimeout(
482
+ new AbloConnectionError(
483
+ `No reply to the heartbeat for ${claimLabel(claim.entityType, claim.entityId, claim.field)} arrived within ${HEARTBEAT_ACK_TIMEOUT_MS / 1000}s. The next beat retries.`,
484
+ ),
485
+ );
486
+ });
487
+ }, HEARTBEAT_ACK_TIMEOUT_MS);
488
+ pendingHeartbeats.set(claimId, { resolve, reject, timer });
489
+ attached?.send({
490
+ type: 'claim_heartbeat',
491
+ payload: {
492
+ claimId,
493
+ entityType: claim.entityType,
494
+ entityId: claim.entityId,
495
+ ...(options.ttl !== undefined ? { ttlMs: toMs(options.ttl) } : {}),
496
+ ...(options.details !== undefined ? { details: options.details } : {}),
497
+ },
498
+ });
499
+ });
500
+ }
501
+
502
+ function sendAbandon(claimId: string, claim?: OwnClaim): void {
503
+ if (!attached?.isConnected()) return;
504
+ // Carry the target so the server can dequeue us if we were only *waiting*
505
+ // (a queued claim isn't in the holder set it would otherwise scan). Held
506
+ // claims are found by claimId regardless; the target is harmless there.
507
+ attached.send({
508
+ type: 'claim_abandon',
509
+ payload: {
510
+ claimId,
511
+ entityType: claim?.entityType,
512
+ entityId: claim?.entityId,
513
+ },
514
+ });
515
+ }
516
+
517
+ // The locator half derives from `OwnClaim` rather than being restated: a
518
+ // member spelled out here is a member that dies before `sendBegin`, which is
519
+ // how `fields` used to be lost between `claim()` and the socket.
520
+ function mintHandle(
521
+ args: Omit<OwnClaim, 'description' | 'estimatedMs' | 'queue'> & {
522
+ description: string;
523
+ ttl?: ClaimLeaseOptions['ttl'];
524
+ queue?: boolean;
525
+ },
526
+ ): Claim {
527
+ const claimId = crypto.randomUUID();
528
+ const estimatedMs = args.ttl !== undefined ? toMs(args.ttl) : undefined;
529
+ // The handle the caller reads back is a public claim, so its `meta` is the
530
+ // declared shape; the `OwnClaim` below stays wire-typed, because that is
531
+ // what goes on the socket.
532
+ const { meta, ...details } = subTarget(args);
533
+ const claim: OwnClaim = {
534
+ ...wireTarget(args),
535
+ ...subTarget(args),
536
+ description: args.description,
537
+ estimatedMs,
538
+ queue: args.queue,
539
+ };
540
+ ownClaims.set(claimId, claim);
541
+ sendBegin(claimId, claim);
542
+ // Coordination trace (info): the creator can see their human/agent claims.
543
+ logger.info(
544
+ `claim: requesting ${claimLabel(claim.entityType, claim.entityId, claim.field)} for "${claim.description}"` +
545
+ (claim.queue ? ' (will queue if contended)' : ''),
546
+ { claimId },
547
+ );
548
+
549
+ let revoked = false;
550
+ const revoke = () => {
551
+ if (revoked) return;
552
+ revoked = true;
553
+ ownClaims.delete(claimId);
554
+ sendAbandon(claimId, claim);
555
+ logger.info(
556
+ `claim: released ${claimLabel(claim.entityType, claim.entityId, claim.field)}`,
557
+ { claimId },
558
+ );
559
+ };
560
+
561
+ return {
562
+ object: 'claim',
563
+ id: claimId,
564
+ status: 'active',
565
+ description: args.description,
566
+ target: {
567
+ ...streamTarget(args),
568
+ ...details,
569
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
570
+ },
571
+ release: async () => {
572
+ revoke();
573
+ },
574
+ revoke,
575
+ heartbeat: (options?: ClaimLeaseOptions['ttl'] | ClaimHeartbeatOptions) =>
576
+ sendHeartbeat(claimId, claim, resolveHeartbeatOptions(options)),
577
+ [Symbol.asyncDispose]: async () => {
578
+ revoke();
579
+ },
580
+ };
581
+ }
582
+
583
+ function resolveTarget(target: PresenceTarget): ClaimTarget {
584
+ if (isTargetTuple(target)) return { type: target[0], id: target[1] };
585
+ return target;
586
+ }
587
+
588
+ return {
589
+ claim(
590
+ target: PresenceTarget,
591
+ opts?: ClaimOptions,
592
+ ): Claim {
593
+ const resolved = resolveTarget(target);
594
+ return mintHandle({
595
+ ...wireTarget(resolved),
596
+ ...subTarget(resolved),
597
+ description: claimDescription({ ...opts, meta: resolved.meta }),
598
+ ttl: opts?.ttl,
599
+ queue: opts?.queue,
600
+ });
601
+ },
602
+ get others() {
603
+ return claimsSnapshot;
604
+ },
605
+ queueFor(target: PresenceTarget): readonly Claim[] {
606
+ const ref = resolveTarget(target);
607
+ return queueByEntity.get(entityKey(ref.type, ref.id)) ?? EMPTY_QUEUE;
608
+ },
609
+ reorder(target: PresenceTarget, order: readonly Claim[]): void {
610
+ const ref = resolveTarget(target);
611
+ sendReorder(ref.type, ref.id, order);
612
+ },
613
+ onChange: (listener: () => void) => {
614
+ listeners.add(listener);
615
+ return () => {
616
+ listeners.delete(listener);
617
+ };
618
+ },
619
+ onRejected: (listener: (rejection: ClaimRejection) => void) => {
620
+ rejectionListeners.add(listener);
621
+ return () => {
622
+ rejectionListeners.delete(listener);
623
+ };
624
+ },
625
+ onLost: (listener: (lost: ClaimLost) => void) => {
626
+ lostListeners.add(listener);
627
+ return () => {
628
+ lostListeners.delete(listener);
629
+ };
630
+ },
631
+ [Symbol.asyncIterator]() {
632
+ return asyncIteratorFrom<readonly Claim[]>(
633
+ (onChange) => {
634
+ listeners.add(onChange);
635
+ return () => {
636
+ listeners.delete(onChange);
637
+ };
638
+ },
639
+ () => claimsSnapshot,
640
+ );
641
+ },
642
+ attach,
643
+ setParticipant(participant: { id: string }): void {
644
+ participantId = participant.id;
645
+ },
646
+ dispose(): void {
647
+ for (const off of unsubs) off();
648
+ unsubs.length = 0;
649
+ for (const claimId of [...pendingHeartbeats.keys()]) {
650
+ settleHeartbeat(claimId, ({ reject }) => {
651
+ reject(
652
+ new AbloConnectionError(
653
+ 'The claim stream was disposed while this heartbeat was awaiting its reply.',
654
+ ),
655
+ );
656
+ });
657
+ }
658
+ listeners.clear();
659
+ rejectionListeners.clear();
660
+ lostListeners.clear();
661
+ activeByClaimId.clear();
662
+ ownClaims.clear();
663
+ queueByEntity.clear();
664
+ claimsSnapshot = Object.freeze([]);
665
+ attached = null;
666
+ },
667
+ };
668
+ }