@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,475 @@
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
+ import { asyncIteratorFrom } from '@abloatai/transaction/utils/asyncIterator';
25
+ import { toMs } from '@abloatai/transaction/utils/duration';
26
+ import { claimDescription, descriptionFromMeta, participantKindFromWire, } from '@abloatai/transaction/coordination/schema';
27
+ import { isTargetTuple, subTarget, streamTarget, wireTarget, } from '@abloatai/transaction/coordination/locator';
28
+ import { declaredMeta } from '@abloatai/transaction/coordination/claimMeta';
29
+ import { AbloClaimedError, AbloConnectionError } from '@abloatai/transaction/errors';
30
+ import { resolveHeartbeatOptions } from '@abloatai/transaction/coordination/claimHeartbeatLoop';
31
+ import { noopLogger } from '@abloatai/transaction/logger';
32
+ /** Readable target for the coordination trace: `documents:abc` / `documents:abc.title`. */
33
+ function claimLabel(type, id, field) {
34
+ return field ? `${type}:${id}.${field}` : `${type}:${id}`;
35
+ }
36
+ /**
37
+ * How long a heartbeat waits for its `claim_heartbeat_ack` before giving up
38
+ * as transient (the auto-heartbeat loop's next tick retries). Comfortably
39
+ * above a round trip, comfortably below the ttl/3 beat cadence.
40
+ */
41
+ const HEARTBEAT_ACK_TIMEOUT_MS = 10_000;
42
+ export function createClaimStream(config, transport = null) {
43
+ // Mutable: the host seeds the resolved identity via `setParticipant` once
44
+ // it is known; the own-claim filter always reads the current value.
45
+ let participantId = config.participantId;
46
+ const logger = config.logger ?? noopLogger;
47
+ // ── State: others' open claims, keyed by claimId ───────────────
48
+ const activeByClaimId = new Map();
49
+ let claimsSnapshot = Object.freeze([]);
50
+ // ── State: our own open claims (for re-announce on reconnect) ───
51
+ const ownClaims = new Map();
52
+ // ── State: per-entity wait queues, from `claim_queue` frames ────
53
+ // Keyed `type:id`; the value is the FIFO line of queued claims. Powers
54
+ // the reactive `queue(target)` read — who's waiting and what they intend.
55
+ const queueByEntity = new Map();
56
+ const entityKey = (type, id) => `${type}:${id}`;
57
+ const EMPTY_QUEUE = Object.freeze([]);
58
+ // Last queue position we logged per own-claim, so advancing in line is traced
59
+ // once per change (not re-logged on every server re-fan of the same line).
60
+ const lastLoggedQueuePos = new Map();
61
+ // ── Subscribers ──────────────────────────────────────────────────
62
+ const listeners = new Set();
63
+ const rejectionListeners = new Set();
64
+ const lostListeners = new Set();
65
+ // ── State: in-flight heartbeats awaiting their ack, keyed by claimId ──
66
+ const pendingHeartbeats = new Map();
67
+ const settleHeartbeat = (claimId, settle) => {
68
+ const pending = pendingHeartbeats.get(claimId);
69
+ if (!pending)
70
+ return;
71
+ pendingHeartbeats.delete(claimId);
72
+ clearTimeout(pending.timer);
73
+ settle(pending);
74
+ };
75
+ const notifyListeners = () => {
76
+ claimsSnapshot = Object.freeze(Array.from(activeByClaimId.values()));
77
+ for (const l of listeners) {
78
+ try {
79
+ l();
80
+ }
81
+ catch {
82
+ /* listener errors don't break siblings */
83
+ }
84
+ }
85
+ };
86
+ // ── Wire wiring ──────────────────────────────────────────────────
87
+ let attached = null;
88
+ const unsubs = [];
89
+ function attach(t) {
90
+ if (attached)
91
+ return;
92
+ attached = t;
93
+ // (1) Inbound presence frames carry every participant's full
94
+ // active-claim set. Prune previous claims by holder, then
95
+ // re-add from the frame — the frame is authoritative for that
96
+ // participant's open claims at that moment.
97
+ unsubs.push(t.subscribe('presence_update', (event) => {
98
+ if (!event.userId)
99
+ return;
100
+ if (event.userId === participantId)
101
+ return;
102
+ let mutated = false;
103
+ if (event.kind === 'leave') {
104
+ for (const [id, claim] of activeByClaimId) {
105
+ if (claim.heldBy === event.userId) {
106
+ activeByClaimId.delete(id);
107
+ mutated = true;
108
+ }
109
+ }
110
+ if (mutated)
111
+ notifyListeners();
112
+ return;
113
+ }
114
+ for (const [id, claim] of activeByClaimId) {
115
+ if (claim.heldBy === event.userId) {
116
+ activeByClaimId.delete(id);
117
+ mutated = true;
118
+ }
119
+ }
120
+ for (const claim of event.activeClaims ?? []) {
121
+ // Terminal-status entries (committed / expired / canceled) are
122
+ // one-shot "this claim ended" signals. The holder sweep above
123
+ // already removed the prior active entry; skipping the re-add
124
+ // drops it from `others`, which is what resolves a contender's
125
+ // `settled()`. Absent status means active (wire back-compat).
126
+ if (claim.status && claim.status !== 'active')
127
+ continue;
128
+ // Resolve the always-present public field, tolerating a frame that
129
+ // carries the value in `meta` rather than as an explicit description.
130
+ const description = claim.description ??
131
+ descriptionFromMeta(claim.meta) ??
132
+ 'editing';
133
+ // The frame is parsed permissively, on purpose; `declaredMeta` is where
134
+ // that wire value becomes the shape the program declared.
135
+ const { meta, ...details } = subTarget(claim);
136
+ activeByClaimId.set(claim.claimId, {
137
+ object: 'claim',
138
+ id: claim.claimId,
139
+ status: 'active',
140
+ heldBy: event.userId,
141
+ participantKind: participantKindFromWire(event.participantKind, event.isAgent),
142
+ target: {
143
+ ...streamTarget(claim),
144
+ ...details,
145
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
146
+ },
147
+ description,
148
+ ttlSeconds: Math.max(0, Math.floor((claim.expiresAt - Date.now()) / 1000)),
149
+ createdAt: claim.declaredAt,
150
+ expiresAt: claim.expiresAt,
151
+ });
152
+ mutated = true;
153
+ }
154
+ if (mutated)
155
+ notifyListeners();
156
+ }));
157
+ // (2) Server-side rejection frames.
158
+ unsubs.push(t.subscribe('claim_rejected', (rejection) => {
159
+ if (!rejection.claimId)
160
+ return;
161
+ if (ownClaims.has(rejection.claimId)) {
162
+ const tgt = rejection.target
163
+ ? claimLabel(rejection.target.entityType, rejection.target.entityId, rejection.target.field)
164
+ : rejection.claimId;
165
+ logger.info(`claim: rejected ${tgt}${rejection.heldBy ? ` — held by ${rejection.heldBy}` : ''}`, { claimId: rejection.claimId, reason: rejection.reason });
166
+ }
167
+ // Drop the rejected own-claim so reconnect doesn't re-announce
168
+ // a claim the server already rejected (would just spam both
169
+ // sides with conflicts).
170
+ ownClaims.delete(rejection.claimId);
171
+ for (const l of rejectionListeners) {
172
+ try {
173
+ l(rejection);
174
+ }
175
+ catch {
176
+ /* isolate */
177
+ }
178
+ }
179
+ }));
180
+ // (2a) Server-side loss frames — you held the claim, then lost it
181
+ // (preempted or expired). Distinct from a rejection, which is a claim
182
+ // the server refused.
183
+ unsubs.push(
184
+ // The frame is validated by the transport's dispatcher against the same
185
+ // schema this parameter's type comes from, so it arrives proven.
186
+ t.subscribe('claim_lost', (lost) => {
187
+ if (ownClaims.has(lost.claimId)) {
188
+ const c = ownClaims.get(lost.claimId);
189
+ logger.info(`claim: lost ${c ? claimLabel(c.entityType, c.entityId, c.field) : lost.claimId} (preempted or expired)`, { claimId: lost.claimId });
190
+ }
191
+ // Drop the lost own-claim so reconnect doesn't re-announce a lease we
192
+ // no longer hold.
193
+ ownClaims.delete(lost.claimId);
194
+ for (const l of lostListeners) {
195
+ try {
196
+ l(lost);
197
+ }
198
+ catch {
199
+ /* isolate */
200
+ }
201
+ }
202
+ }));
203
+ // (2b) Per-entity wait-queue snapshots. The server fans the full line
204
+ // out on every queue mutation; we replace our cached line for that
205
+ // entity and notify so `queue(target)` reads reactively.
206
+ unsubs.push(t.subscribe('claim_queue', (p) => {
207
+ const key = entityKey(p.target.type, p.target.id);
208
+ const line = p.queue;
209
+ if (line.length === 0)
210
+ queueByEntity.delete(key);
211
+ else
212
+ // The wait line crosses from the wire into the public `Claim` shape
213
+ // like every other read does, so its meta goes through `declaredMeta`
214
+ // rather than arriving as the open record the frame was parsed as.
215
+ queueByEntity.set(key, Object.freeze(line.map((entry) => {
216
+ const { meta, ...target } = entry.target;
217
+ return {
218
+ ...entry,
219
+ target: {
220
+ ...target,
221
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
222
+ },
223
+ };
224
+ })));
225
+ // If we are in this line, trace our position (the "agent queued behind a
226
+ // claim" moment) — once per position change, so advancing is visible.
227
+ const ourIndex = line.findIndex((c) => ownClaims.has(c.id));
228
+ const ourClaim = ourIndex >= 0 ? line[ourIndex] : undefined;
229
+ if (ourClaim) {
230
+ const ourId = ourClaim.id;
231
+ if (lastLoggedQueuePos.get(ourId) !== ourIndex) {
232
+ lastLoggedQueuePos.set(ourId, ourIndex);
233
+ logger.info(`claim: queued for ${claimLabel(p.target.type, p.target.id)} — position ${ourIndex + 1} of ${line.length}, waiting`, { claimId: ourId });
234
+ }
235
+ }
236
+ notifyListeners();
237
+ }));
238
+ // (2c) Heartbeat replies — correlate back to the awaiting beat by
239
+ // claimId. `held` resolves with the extended expiry; `queued` and
240
+ // `lost` reject with a typed claimed error, because a heartbeat on
241
+ // a handle we thought we held coming back as anything but `held`
242
+ // means the lease is no longer ours.
243
+ unsubs.push(t.subscribe('claim_heartbeat_ack', (ack) => {
244
+ settleHeartbeat(ack.claimId, ({ resolve, reject }) => {
245
+ if (ack.status === 'held' && ack.expiresAt !== undefined) {
246
+ resolve({
247
+ expiresAt: ack.expiresAt,
248
+ ...(ack.queueDepth !== undefined
249
+ ? { queueDepth: ack.queueDepth }
250
+ : {}),
251
+ });
252
+ return;
253
+ }
254
+ const c = ownClaims.get(ack.claimId);
255
+ reject(new AbloClaimedError(`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.`, { code: 'claim_lost' }));
256
+ });
257
+ }));
258
+ // (3) On reconnect, re-announce every open self-claim — the
259
+ // server's claim state is in-memory and is lost across
260
+ // restarts. Without this, peers would see our claims vanish
261
+ // whenever the connection blipped.
262
+ unsubs.push(t.subscribe('connected', () => {
263
+ for (const [claimId, claim] of ownClaims) {
264
+ sendBegin(claimId, claim);
265
+ }
266
+ }));
267
+ }
268
+ if (transport)
269
+ attach(transport);
270
+ // ── Outbound ────────────────────────────────────────────────────
271
+ function sendBegin(claimId, claim) {
272
+ if (!attached?.isConnected())
273
+ return;
274
+ attached.send({
275
+ type: 'claim_begin',
276
+ payload: {
277
+ claimId,
278
+ ...wireTarget(claim),
279
+ description: claim.description,
280
+ ...subTarget(claim),
281
+ estimatedMs: claim.estimatedMs,
282
+ queue: claim.queue,
283
+ },
284
+ });
285
+ }
286
+ function sendReorder(entityType, entityId, order) {
287
+ if (!attached?.isConnected())
288
+ return;
289
+ attached.send({
290
+ type: 'claim_reorder',
291
+ payload: {
292
+ entityType,
293
+ entityId,
294
+ // The wire shape identifies a waiter by heldBy + claimId; map the
295
+ // ergonomic `Claim[]` (what `queueFor` returns) down to that.
296
+ order: order.map((i) => ({ heldBy: i.heldBy, claimId: i.id })),
297
+ },
298
+ });
299
+ }
300
+ /**
301
+ * Send one heartbeat and await its ack. Rejects with
302
+ * {@link AbloConnectionError} (transient — the auto-heartbeat loop retries
303
+ * on its next tick) when the socket is down or the ack times out, and with
304
+ * {@link AbloClaimedError} (definitive) when the server answers that the
305
+ * lease is no longer ours.
306
+ */
307
+ function sendHeartbeat(claimId, claim, options) {
308
+ if (!attached?.isConnected()) {
309
+ return Promise.reject(new AbloConnectionError(`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.`));
310
+ }
311
+ return new Promise((resolve, reject) => {
312
+ settleHeartbeat(claimId, ({ reject: rejectPrior }) => {
313
+ rejectPrior(new AbloConnectionError('A newer heartbeat for this claim superseded the one still awaiting its reply.'));
314
+ });
315
+ const timer = setTimeout(() => {
316
+ settleHeartbeat(claimId, ({ reject: rejectTimeout }) => {
317
+ rejectTimeout(new AbloConnectionError(`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.`));
318
+ });
319
+ }, HEARTBEAT_ACK_TIMEOUT_MS);
320
+ pendingHeartbeats.set(claimId, { resolve, reject, timer });
321
+ attached?.send({
322
+ type: 'claim_heartbeat',
323
+ payload: {
324
+ claimId,
325
+ entityType: claim.entityType,
326
+ entityId: claim.entityId,
327
+ ...(options.ttl !== undefined ? { ttlMs: toMs(options.ttl) } : {}),
328
+ ...(options.details !== undefined ? { details: options.details } : {}),
329
+ },
330
+ });
331
+ });
332
+ }
333
+ function sendAbandon(claimId, claim) {
334
+ if (!attached?.isConnected())
335
+ return;
336
+ // Carry the target so the server can dequeue us if we were only *waiting*
337
+ // (a queued claim isn't in the holder set it would otherwise scan). Held
338
+ // claims are found by claimId regardless; the target is harmless there.
339
+ attached.send({
340
+ type: 'claim_abandon',
341
+ payload: {
342
+ claimId,
343
+ entityType: claim?.entityType,
344
+ entityId: claim?.entityId,
345
+ },
346
+ });
347
+ }
348
+ // The locator half derives from `OwnClaim` rather than being restated: a
349
+ // member spelled out here is a member that dies before `sendBegin`, which is
350
+ // how `fields` used to be lost between `claim()` and the socket.
351
+ function mintHandle(args) {
352
+ const claimId = crypto.randomUUID();
353
+ const estimatedMs = args.ttl !== undefined ? toMs(args.ttl) : undefined;
354
+ // The handle the caller reads back is a public claim, so its `meta` is the
355
+ // declared shape; the `OwnClaim` below stays wire-typed, because that is
356
+ // what goes on the socket.
357
+ const { meta, ...details } = subTarget(args);
358
+ const claim = {
359
+ ...wireTarget(args),
360
+ ...subTarget(args),
361
+ description: args.description,
362
+ estimatedMs,
363
+ queue: args.queue,
364
+ };
365
+ ownClaims.set(claimId, claim);
366
+ sendBegin(claimId, claim);
367
+ // Coordination trace (info): the creator can see their human/agent claims.
368
+ logger.info(`claim: requesting ${claimLabel(claim.entityType, claim.entityId, claim.field)} for "${claim.description}"` +
369
+ (claim.queue ? ' (will queue if contended)' : ''), { claimId });
370
+ let revoked = false;
371
+ const revoke = () => {
372
+ if (revoked)
373
+ return;
374
+ revoked = true;
375
+ ownClaims.delete(claimId);
376
+ sendAbandon(claimId, claim);
377
+ logger.info(`claim: released ${claimLabel(claim.entityType, claim.entityId, claim.field)}`, { claimId });
378
+ };
379
+ return {
380
+ object: 'claim',
381
+ id: claimId,
382
+ status: 'active',
383
+ description: args.description,
384
+ target: {
385
+ ...streamTarget(args),
386
+ ...details,
387
+ ...(meta !== undefined ? { meta: declaredMeta(meta) } : {}),
388
+ },
389
+ release: async () => {
390
+ revoke();
391
+ },
392
+ revoke,
393
+ heartbeat: (options) => sendHeartbeat(claimId, claim, resolveHeartbeatOptions(options)),
394
+ [Symbol.asyncDispose]: async () => {
395
+ revoke();
396
+ },
397
+ };
398
+ }
399
+ function resolveTarget(target) {
400
+ if (isTargetTuple(target))
401
+ return { type: target[0], id: target[1] };
402
+ return target;
403
+ }
404
+ return {
405
+ claim(target, opts) {
406
+ const resolved = resolveTarget(target);
407
+ return mintHandle({
408
+ ...wireTarget(resolved),
409
+ ...subTarget(resolved),
410
+ description: claimDescription({ ...opts, meta: resolved.meta }),
411
+ ttl: opts?.ttl,
412
+ queue: opts?.queue,
413
+ });
414
+ },
415
+ get others() {
416
+ return claimsSnapshot;
417
+ },
418
+ queueFor(target) {
419
+ const ref = resolveTarget(target);
420
+ return queueByEntity.get(entityKey(ref.type, ref.id)) ?? EMPTY_QUEUE;
421
+ },
422
+ reorder(target, order) {
423
+ const ref = resolveTarget(target);
424
+ sendReorder(ref.type, ref.id, order);
425
+ },
426
+ onChange: (listener) => {
427
+ listeners.add(listener);
428
+ return () => {
429
+ listeners.delete(listener);
430
+ };
431
+ },
432
+ onRejected: (listener) => {
433
+ rejectionListeners.add(listener);
434
+ return () => {
435
+ rejectionListeners.delete(listener);
436
+ };
437
+ },
438
+ onLost: (listener) => {
439
+ lostListeners.add(listener);
440
+ return () => {
441
+ lostListeners.delete(listener);
442
+ };
443
+ },
444
+ [Symbol.asyncIterator]() {
445
+ return asyncIteratorFrom((onChange) => {
446
+ listeners.add(onChange);
447
+ return () => {
448
+ listeners.delete(onChange);
449
+ };
450
+ }, () => claimsSnapshot);
451
+ },
452
+ attach,
453
+ setParticipant(participant) {
454
+ participantId = participant.id;
455
+ },
456
+ dispose() {
457
+ for (const off of unsubs)
458
+ off();
459
+ unsubs.length = 0;
460
+ for (const claimId of [...pendingHeartbeats.keys()]) {
461
+ settleHeartbeat(claimId, ({ reject }) => {
462
+ reject(new AbloConnectionError('The claim stream was disposed while this heartbeat was awaiting its reply.'));
463
+ });
464
+ }
465
+ listeners.clear();
466
+ rejectionListeners.clear();
467
+ lostListeners.clear();
468
+ activeByClaimId.clear();
469
+ ownClaims.clear();
470
+ queueByEntity.clear();
471
+ claimsSnapshot = Object.freeze([]);
472
+ attached = null;
473
+ },
474
+ };
475
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Captures a local {@link Snapshot} of a chosen set of entities, along with a
3
+ * watermark, so a caller can detect when that state has gone stale. This is
4
+ * what an LLM caller threads into a prompt: `stamp` flows into later writes as
5
+ * `readAt`, so the server rejects a mutation premised on data that has since
6
+ * changed; `signal` is an `AbortSignal` that fires as soon as any captured
7
+ * entity receives a delta, so a mid-generation invalidation can abort the token
8
+ * stream instead of producing output against stale context.
9
+ *
10
+ * It reads the current entity state from the in-memory pool, reads the engine's
11
+ * current `lastSyncId` as the watermark, and subscribes to delta frames on the
12
+ * existing sync connection — no second connection.
13
+ */
14
+ import type { InstanceCache } from '../InstanceCache.js';
15
+ import type { Schema } from '@abloatai/transaction/schema/schema';
16
+ import type { SyncWebSocket } from './SyncWebSocket.js';
17
+ import type { Snapshot } from '@abloatai/transaction/types/streams';
18
+ export interface CreateSnapshotArgs<TSchema extends Schema = Schema, K extends keyof TSchema['models'] & string = keyof TSchema['models'] & string> {
19
+ pool: InstanceCache;
20
+ /** Live transport for delta subscriptions. May be null if the engine
21
+ * hasn't connected yet — the snapshot still resolves with current
22
+ * pool state, but `signal` won't fire until reconnect. */
23
+ transport: SyncWebSocket | null;
24
+ /** Returns the engine's current `lastSyncId`. Read at snapshot time
25
+ * to stamp the watermark; not re-read after. */
26
+ getLastSyncId: () => number;
27
+ entities: Readonly<Record<K, string | readonly string[]>>;
28
+ }
29
+ export declare function createSnapshot<TSchema extends Schema, K extends keyof TSchema['models'] & string>(args: CreateSnapshotArgs<TSchema, K>): Snapshot<TSchema, K>;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Captures a local {@link Snapshot} of a chosen set of entities, along with a
3
+ * watermark, so a caller can detect when that state has gone stale. This is
4
+ * what an LLM caller threads into a prompt: `stamp` flows into later writes as
5
+ * `readAt`, so the server rejects a mutation premised on data that has since
6
+ * changed; `signal` is an `AbortSignal` that fires as soon as any captured
7
+ * entity receives a delta, so a mid-generation invalidation can abort the token
8
+ * stream instead of producing output against stale context.
9
+ *
10
+ * It reads the current entity state from the in-memory pool, reads the engine's
11
+ * current `lastSyncId` as the watermark, and subscribes to delta frames on the
12
+ * existing sync connection — no second connection.
13
+ */
14
+ import { AbloValidationError } from '@abloatai/transaction/errors';
15
+ import { modelAsRow } from '../Model.js';
16
+ /**
17
+ * The snapshot result exposes `stamp`, `signal`, and `onChange` at its top
18
+ * level, alongside one bucket per model. If a schema declares a model with one
19
+ * of these names, the two would collide, so snapshot creation throws instead.
20
+ */
21
+ const RESERVED_SNAPSHOT_KEYS = new Set([
22
+ 'stamp',
23
+ 'signal',
24
+ 'onChange',
25
+ ]);
26
+ export function createSnapshot(args) {
27
+ const { pool, transport, getLastSyncId, entities } = args;
28
+ // ── Validate keys ────────────────────────────────────────────────
29
+ for (const key of Object.keys(entities)) {
30
+ if (RESERVED_SNAPSHOT_KEYS.has(key)) {
31
+ throw new AbloValidationError(`engine.snapshot: model key "${key}" collides with a reserved ` +
32
+ `snapshot field (stamp / signal / onChange). Rename the model ` +
33
+ 'in your schema.', { code: 'snapshot_reserved_key' });
34
+ }
35
+ }
36
+ // ── Watermark ────────────────────────────────────────────────────
37
+ const stamp = getLastSyncId();
38
+ // ── Capture data + watched set ───────────────────────────────────
39
+ const watched = new Set(); // `${type}:${id}`
40
+ const data = {};
41
+ for (const [type, idOrIds] of Object.entries(entities)) {
42
+ const ids = Array.isArray(idOrIds)
43
+ ? idOrIds
44
+ : [idOrIds];
45
+ const bucket = {};
46
+ for (const id of ids) {
47
+ const m = pool.get(id);
48
+ // Only include if the model actually has the requested type —
49
+ // pool keys models globally by id, so `pool.get(id)` could
50
+ // return a different model that happens to share the id (rare,
51
+ // but type guards keep the surface honest).
52
+ if (m &&
53
+ typeof m.getModelName === 'function' &&
54
+ m.getModelName() === type) {
55
+ bucket[id] = modelAsRow(m);
56
+ }
57
+ watched.add(`${type}:${id}`);
58
+ }
59
+ data[type] = bucket;
60
+ }
61
+ // ── Invalidation wiring ──────────────────────────────────────────
62
+ const listeners = new Set();
63
+ const controller = new AbortController();
64
+ const fireChange = (change) => {
65
+ if (!controller.signal.aborted) {
66
+ controller.abort(new Error('snapshot invalidated — underlying entity received a delta'));
67
+ }
68
+ for (const l of listeners) {
69
+ try {
70
+ l(change);
71
+ }
72
+ catch {
73
+ /* listener errors don't break siblings */
74
+ }
75
+ }
76
+ };
77
+ let unsubDelta = null;
78
+ if (transport) {
79
+ unsubDelta = transport.subscribe('delta', (delta) => {
80
+ const key = `${delta.modelName}:${delta.modelId}`;
81
+ if (!watched.has(key))
82
+ return;
83
+ // Every delta to a captured entity is reported as 'semantic' severity.
84
+ fireChange({
85
+ model: delta.modelName,
86
+ id: delta.modelId,
87
+ severity: 'semantic',
88
+ });
89
+ });
90
+ }
91
+ // ── Build the flat result ────────────────────────────────────────
92
+ const result = {
93
+ stamp,
94
+ signal: controller.signal,
95
+ onChange: (listener) => {
96
+ listeners.add(listener);
97
+ // The caller unsubscribes its own listener via the returned function.
98
+ // The underlying delta subscription lives for the snapshot's lifetime;
99
+ // there is no explicit dispose because a snapshot is short-lived (one
100
+ // LLM call's worth) and the subscription is cheap.
101
+ return () => {
102
+ listeners.delete(listener);
103
+ // Once the last listener is gone and the abort has fired, drop the
104
+ // delta subscription too — nothing is listening anymore.
105
+ if (listeners.size === 0 && controller.signal.aborted && unsubDelta) {
106
+ unsubDelta();
107
+ unsubDelta = null;
108
+ }
109
+ };
110
+ },
111
+ };
112
+ for (const [modelName, bucket] of Object.entries(data)) {
113
+ result[modelName] = bucket;
114
+ }
115
+ return result;
116
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Moved to the settlement core with the duplex transport (ADR 0016): keeping
3
+ * a long-lived socket's credential fresh is connection plumbing an agent needs
4
+ * as much as a browser does. This path re-exports it so existing importers
5
+ * stay unchanged.
6
+ */
7
+ export { DEFAULT_PREROLL_INTERVAL_MS, MIN_PREROLL_DELAY_MS, computePrerollDelayMs, CredentialLifecycle, type CredentialRefreshOutcome, type CredentialRecoveryOutcome, type CredentialRefreshResult, type CredentialRefresher, type CredentialLifecycleContext, } from '@abloatai/transaction/transport/credentialLifecycle';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Moved to the settlement core with the duplex transport (ADR 0016): keeping
3
+ * a long-lived socket's credential fresh is connection plumbing an agent needs
4
+ * as much as a browser does. This path re-exports it so existing importers
5
+ * stay unchanged.
6
+ */
7
+ export { DEFAULT_PREROLL_INTERVAL_MS, MIN_PREROLL_DELAY_MS, computePrerollDelayMs, CredentialLifecycle, } from '@abloatai/transaction/transport/credentialLifecycle';