@abloatai/ablo 0.34.1 → 0.36.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 (536) hide show
  1. package/AGENTS.md +2 -1
  2. package/CHANGELOG.md +758 -5
  3. package/README.md +56 -502
  4. package/bin/ablo.cjs +39 -0
  5. package/dist/BaseSyncedStore.d.ts +176 -48
  6. package/dist/BaseSyncedStore.js +346 -214
  7. package/dist/Database.d.ts +17 -44
  8. package/dist/Database.js +96 -79
  9. package/dist/InstanceCache.d.ts +31 -6
  10. package/dist/InstanceCache.js +65 -30
  11. package/dist/LazyReferenceCollection.d.ts +3 -3
  12. package/dist/LazyReferenceCollection.js +4 -4
  13. package/dist/Model.d.ts +23 -13
  14. package/dist/Model.js +27 -17
  15. package/dist/ModelRegistry.d.ts +8 -4
  16. package/dist/ModelRegistry.js +20 -18
  17. package/dist/NetworkMonitor.d.ts +3 -1
  18. package/dist/NetworkMonitor.js +7 -5
  19. package/dist/{SyncEngineContext.d.ts → RuntimeContext.d.ts} +20 -13
  20. package/dist/{SyncEngineContext.js → RuntimeContext.js} +11 -12
  21. package/dist/SyncClient.d.ts +47 -47
  22. package/dist/SyncClient.js +215 -156
  23. package/dist/ai-sdk/coordinatedTool.d.ts +2 -2
  24. package/dist/ai-sdk/coordinatedTool.js +1 -1
  25. package/dist/ai-sdk/coordinationContext.d.ts +2 -2
  26. package/dist/ai-sdk/coordinationContext.js +1 -1
  27. package/dist/ai-sdk/wrap.d.ts +3 -3
  28. package/dist/ai-sdk/wrap.js +2 -2
  29. package/dist/auth/index.d.ts +1 -156
  30. package/dist/auth/index.js +8 -301
  31. package/dist/client/Ablo.d.ts +42 -287
  32. package/dist/client/Ablo.js +129 -963
  33. package/dist/client/abloClient.d.ts +309 -0
  34. package/dist/client/abloClient.js +13 -0
  35. package/dist/client/clientPrelude.d.ts +52 -0
  36. package/dist/client/clientPrelude.js +60 -0
  37. package/dist/client/consoleLogger.d.ts +2 -2
  38. package/dist/client/coreClient.d.ts +60 -0
  39. package/dist/client/coreClient.js +118 -0
  40. package/dist/client/createInternalComponents.d.ts +8 -4
  41. package/dist/client/createInternalComponents.js +17 -10
  42. package/dist/client/createModelProxy.d.ts +98 -373
  43. package/dist/client/createModelProxy.js +233 -139
  44. package/dist/client/humans.d.ts +69 -0
  45. package/dist/client/humans.js +78 -0
  46. package/dist/client/modelRegistration.d.ts +1 -1
  47. package/dist/client/modelRegistration.js +9 -9
  48. package/dist/client/options.d.ts +73 -17
  49. package/dist/client/reactiveEngine.d.ts +53 -0
  50. package/dist/client/reactiveEngine.js +688 -0
  51. package/dist/client/resourceTypes.d.ts +9 -250
  52. package/dist/client/resourceTypes.js +8 -5
  53. package/dist/client/schemaConfig.d.ts +4 -4
  54. package/dist/client/schemaConfig.js +6 -2
  55. package/dist/client/storeCluster.d.ts +47 -0
  56. package/dist/client/storeCluster.js +118 -0
  57. package/dist/client/storeLifecycle.d.ts +61 -0
  58. package/dist/client/storeLifecycle.js +231 -0
  59. package/dist/client/validateAbloOptions.d.ts +3 -2
  60. package/dist/client/validateAbloOptions.js +1 -1
  61. package/dist/client/wsMutationExecutor.d.ts +3 -3
  62. package/dist/client/wsMutationExecutor.js +3 -3
  63. package/dist/context.d.ts +22 -9
  64. package/dist/context.js +33 -9
  65. package/dist/coordination/ClaimLog.d.ts +26 -0
  66. package/dist/coordination/ClaimLog.js +32 -0
  67. package/dist/coordination/index.d.ts +1 -15
  68. package/dist/coordination/index.js +8 -31
  69. package/dist/core/index.d.ts +3 -3
  70. package/dist/core/index.js +2 -2
  71. package/dist/docs/catalog.d.ts +72 -0
  72. package/dist/docs/catalog.js +230 -0
  73. package/dist/docs/index.d.ts +10 -0
  74. package/dist/docs/index.js +10 -0
  75. package/dist/environment.d.ts +1 -40
  76. package/dist/environment.js +8 -37
  77. package/dist/index.d.ts +44 -36
  78. package/dist/index.js +30 -22
  79. package/dist/interfaces/index.d.ts +44 -134
  80. package/dist/keys/index.d.ts +1 -77
  81. package/dist/keys/index.js +8 -190
  82. package/dist/mutators/{RecordingTransaction.d.ts → RecordingMutation.d.ts} +4 -4
  83. package/dist/mutators/{RecordingTransaction.js → RecordingMutation.js} +2 -2
  84. package/dist/mutators/Transaction.d.ts +1 -1
  85. package/dist/mutators/Transaction.js +1 -1
  86. package/dist/mutators/UndoManager.d.ts +6 -6
  87. package/dist/mutators/UndoManager.js +5 -5
  88. package/dist/mutators/defineMutators.d.ts +3 -3
  89. package/dist/mutators/defineMutators.js +1 -1
  90. package/dist/mutators/inverseOp.js +2 -2
  91. package/dist/mutators/mutateActions.d.ts +3 -3
  92. package/dist/mutators/mutateActions.js +1 -1
  93. package/dist/mutators/readerActions.d.ts +1 -1
  94. package/dist/mutators/undoApply.d.ts +1 -1
  95. package/dist/mutators/undoApply.js +1 -1
  96. package/dist/policy/index.d.ts +2 -2
  97. package/dist/policy/index.js +1 -1
  98. package/dist/query/client.d.ts +5 -2
  99. package/dist/query/client.js +10 -9
  100. package/dist/query/types.d.ts +6 -41
  101. package/dist/query/types.js +2 -2
  102. package/dist/react/AbloProvider.d.ts +18 -8
  103. package/dist/react/AbloProvider.js +10 -9
  104. package/dist/react/context.d.ts +3 -3
  105. package/dist/react/context.js +1 -1
  106. package/dist/react/createAbloReact.d.ts +56 -0
  107. package/dist/react/createAbloReact.js +51 -0
  108. package/dist/react/index.d.ts +6 -5
  109. package/dist/react/index.js +6 -3
  110. package/dist/react/internalContext.d.ts +1 -1
  111. package/dist/react/useAblo.d.ts +12 -5
  112. package/dist/react/useAblo.js +26 -8
  113. package/dist/react/useCurrentUserId.js +1 -1
  114. package/dist/react/useErrorListener.js +1 -1
  115. package/dist/react/useMutationFailureListener.d.ts +2 -2
  116. package/dist/react/useMutationFailureListener.js +1 -1
  117. package/dist/react/useMutators.d.ts +3 -3
  118. package/dist/react/useMutators.js +3 -3
  119. package/dist/react/useUndoScope.d.ts +5 -5
  120. package/dist/react/useUndoScope.js +1 -1
  121. package/dist/schema/coordination.d.ts +69 -10
  122. package/dist/schema/coordination.js +90 -9
  123. package/dist/schema/ddl.js +2 -2
  124. package/dist/schema/diff.d.ts +1 -1
  125. package/dist/schema/generate.js +1 -1
  126. package/dist/schema/index.d.ts +11 -10
  127. package/dist/schema/index.js +22 -18
  128. package/dist/schema/queries.d.ts +27 -27
  129. package/dist/schema/queries.js +23 -23
  130. package/dist/schema/select.d.ts +3 -3
  131. package/dist/schema/select.js +6 -3
  132. package/dist/schema/serialize.d.ts +15 -6
  133. package/dist/schema/serialize.js +20 -3
  134. package/dist/schema/sugar.d.ts +6 -7
  135. package/dist/schema/sugar.js +9 -12
  136. package/dist/schema/syncDeltaRow.d.ts +4 -152
  137. package/dist/schema/syncDeltaRow.js +4 -105
  138. package/dist/server/adapter.d.ts +18 -1
  139. package/dist/server/commit.d.ts +10 -16
  140. package/dist/server/index.d.ts +1 -1
  141. package/dist/server/index.js +1 -1
  142. package/dist/server/readConfig.d.ts +1 -1
  143. package/dist/source/adapter.d.ts +7 -5
  144. package/dist/source/adapter.js +7 -5
  145. package/dist/source/adapters/drizzle.d.ts +1 -1
  146. package/dist/source/adapters/drizzle.js +2 -2
  147. package/dist/source/adapters/kysely.d.ts +1 -1
  148. package/dist/source/adapters/kysely.js +1 -1
  149. package/dist/source/adapters/kyselyMutationCore.d.ts +1 -1
  150. package/dist/source/adapters/kyselyMutationCore.js +2 -2
  151. package/dist/source/adapters/memory.js +1 -1
  152. package/dist/source/adapters/prisma.d.ts +8 -3
  153. package/dist/source/adapters/prisma.js +1 -1
  154. package/dist/source/connector.js +1 -1
  155. package/dist/source/connectorProtocol.d.ts +2 -8
  156. package/dist/source/connectorProtocol.js +3 -2
  157. package/dist/source/contract.d.ts +29 -17
  158. package/dist/source/contract.js +27 -22
  159. package/dist/source/factory.d.ts +1 -1
  160. package/dist/source/idempotency.js +2 -2
  161. package/dist/source/index.d.ts +1 -0
  162. package/dist/source/index.js +3 -0
  163. package/dist/source/next.d.ts +1 -1
  164. package/dist/source/signing.d.ts +9 -2
  165. package/dist/source/signing.js +4 -1
  166. package/dist/source/types.d.ts +6 -4
  167. package/dist/source/types.js +1 -1
  168. package/dist/{core/storeContract.d.ts → storeContract.d.ts} +6 -6
  169. package/dist/{core → stores}/DatabaseManager.d.ts +3 -1
  170. package/dist/{core → stores}/DatabaseManager.js +14 -13
  171. package/dist/stores/ObjectStore.d.ts +1 -1
  172. package/dist/{core → stores}/StoreManager.d.ts +9 -26
  173. package/dist/{core → stores}/StoreManager.js +29 -77
  174. package/dist/stores/SyncActionStore.d.ts +4 -2
  175. package/dist/stores/SyncActionStore.js +11 -17
  176. package/dist/stores/syncAction.d.ts +26 -0
  177. package/dist/stores/syncAction.js +16 -0
  178. package/dist/surface.d.ts +3 -3
  179. package/dist/surface.js +6 -4
  180. package/dist/sync/BootstrapFetcher.d.ts +127 -6
  181. package/dist/sync/BootstrapFetcher.js +511 -83
  182. package/dist/sync/ConnectionManager.d.ts +6 -198
  183. package/dist/sync/ConnectionManager.js +6 -677
  184. package/dist/sync/OnDemandLoader.d.ts +5 -2
  185. package/dist/sync/OnDemandLoader.js +61 -21
  186. package/dist/sync/SubscriptionManager.d.ts +13 -2
  187. package/dist/sync/SubscriptionManager.js +23 -5
  188. package/dist/sync/SyncWebSocket.d.ts +27 -510
  189. package/dist/sync/SyncWebSocket.js +76 -954
  190. package/dist/sync/awaitClaimGrant.d.ts +4 -44
  191. package/dist/sync/awaitClaimGrant.js +4 -109
  192. package/dist/sync/bootstrapApply.d.ts +3 -0
  193. package/dist/sync/bootstrapApply.js +2 -2
  194. package/dist/sync/commitFrames.d.ts +6 -40
  195. package/dist/sync/commitFrames.js +6 -97
  196. package/dist/sync/contextPorts.d.ts +18 -0
  197. package/dist/sync/contextPorts.js +31 -0
  198. package/dist/sync/createClaimStream.d.ts +5 -49
  199. package/dist/sync/createClaimStream.js +5 -469
  200. package/dist/sync/createPresenceStream.d.ts +26 -4
  201. package/dist/sync/createPresenceStream.js +28 -20
  202. package/dist/sync/createSnapshot.d.ts +2 -2
  203. package/dist/sync/createSnapshot.js +1 -1
  204. package/dist/sync/credentialLifecycle.d.ts +5 -173
  205. package/dist/sync/credentialLifecycle.js +5 -320
  206. package/dist/sync/deltaPipeline.d.ts +13 -12
  207. package/dist/sync/deltaPipeline.js +21 -4
  208. package/dist/sync/groupChange.d.ts +3 -0
  209. package/dist/sync/groupChange.js +16 -14
  210. package/dist/sync/participants.d.ts +24 -6
  211. package/dist/sync/participants.js +32 -23
  212. package/dist/sync/schemaDrift.d.ts +55 -0
  213. package/dist/sync/schemaDrift.js +53 -0
  214. package/dist/sync/schemas.d.ts +23 -33
  215. package/dist/sync/schemas.js +29 -20
  216. package/dist/sync/syncPlan.d.ts +3 -3
  217. package/dist/sync/wsFrameHandlers.d.ts +6 -114
  218. package/dist/sync/wsFrameHandlers.js +6 -392
  219. package/dist/syncLog/contract.d.ts +20 -0
  220. package/dist/syncLog/contract.js +19 -0
  221. package/dist/syncLog/index.d.ts +1 -0
  222. package/dist/syncLog/index.js +1 -0
  223. package/dist/transaction/ablo.d.ts +88 -0
  224. package/dist/transaction/ablo.js +33 -0
  225. package/dist/{client/auth.d.ts → transaction/auth/apiKey.d.ts} +43 -8
  226. package/dist/{client/auth.js → transaction/auth/apiKey.js} +19 -0
  227. package/dist/transaction/auth/bootstrapScope.d.ts +15 -0
  228. package/dist/transaction/auth/bootstrapScope.js +1 -0
  229. package/dist/transaction/auth/capability.d.ts +212 -0
  230. package/dist/transaction/auth/capability.js +224 -0
  231. package/dist/{auth → transaction/auth}/credentialSource.d.ts +8 -1
  232. package/dist/{client → transaction/auth}/identity.d.ts +8 -7
  233. package/dist/{client → transaction/auth}/identity.js +1 -1
  234. package/dist/transaction/auth/index.d.ts +162 -0
  235. package/dist/transaction/auth/index.js +304 -0
  236. package/dist/{auth → transaction/auth}/schemas.d.ts +1 -1
  237. package/dist/{auth → transaction/auth}/schemas.js +13 -13
  238. package/dist/{client → transaction/auth}/sessionMint.d.ts +8 -8
  239. package/dist/{client → transaction/auth}/sessionMint.js +4 -7
  240. package/dist/transaction/coordination/awaitClaimGrant.d.ts +56 -0
  241. package/dist/transaction/coordination/awaitClaimGrant.js +124 -0
  242. package/dist/{client → transaction/coordination}/claimHeartbeatLoop.d.ts +34 -0
  243. package/dist/{client → transaction/coordination}/claimHeartbeatLoop.js +20 -0
  244. package/dist/transaction/coordination/claimMeta.d.ts +49 -0
  245. package/dist/transaction/coordination/claimMeta.js +52 -0
  246. package/dist/transaction/coordination/createClaimStream.d.ts +64 -0
  247. package/dist/transaction/coordination/createClaimStream.js +475 -0
  248. package/dist/transaction/coordination/events.d.ts +74 -0
  249. package/dist/transaction/coordination/events.js +7 -0
  250. package/dist/transaction/coordination/index.d.ts +19 -0
  251. package/dist/transaction/coordination/index.js +45 -0
  252. package/dist/transaction/coordination/locator.d.ts +104 -0
  253. package/dist/transaction/coordination/locator.js +102 -0
  254. package/dist/transaction/coordination/schema.d.ts +1536 -0
  255. package/dist/transaction/coordination/schema.js +1177 -0
  256. package/dist/transaction/coordination/targetConflict.d.ts +2 -0
  257. package/dist/transaction/coordination/targetConflict.js +107 -0
  258. package/dist/{coordination → transaction/coordination}/trace.d.ts +7 -18
  259. package/dist/{coordination → transaction/coordination}/trace.js +18 -25
  260. package/dist/transaction/durableWrites.d.ts +62 -0
  261. package/dist/{client → transaction}/durableWrites.js +28 -3
  262. package/dist/transaction/environment.d.ts +105 -0
  263. package/dist/transaction/environment.js +108 -0
  264. package/dist/{errorCodes.d.ts → transaction/errorCodes.d.ts} +12 -12
  265. package/dist/{errorCodes.js → transaction/errorCodes.js} +45 -18
  266. package/dist/{errors.d.ts → transaction/errors.d.ts} +37 -13
  267. package/dist/{errors.js → transaction/errors.js} +85 -16
  268. package/dist/transaction/footprint.d.ts +111 -0
  269. package/dist/transaction/footprint.js +0 -0
  270. package/dist/transaction/index.d.ts +20 -0
  271. package/dist/transaction/index.js +20 -0
  272. package/dist/transaction/keys/index.d.ts +87 -0
  273. package/dist/transaction/keys/index.js +207 -0
  274. package/dist/transaction/log/syncDeltaRow.d.ts +158 -0
  275. package/dist/transaction/log/syncDeltaRow.js +95 -0
  276. package/dist/{sync/syncPosition.d.ts → transaction/logPosition.d.ts} +22 -8
  277. package/dist/{sync/syncPosition.js → transaction/logPosition.js} +15 -6
  278. package/dist/transaction/logger.d.ts +16 -0
  279. package/dist/transaction/logger.js +7 -0
  280. package/dist/transaction/observability.d.ts +53 -0
  281. package/dist/transaction/observability.js +19 -0
  282. package/dist/transaction/plugin.d.ts +285 -0
  283. package/dist/transaction/plugin.js +106 -0
  284. package/dist/{policy → transaction/policy}/types.d.ts +3 -3
  285. package/dist/{policy → transaction/policy}/types.js +2 -0
  286. package/dist/transaction/resources/httpResources.d.ts +321 -0
  287. package/dist/transaction/resources/httpResources.js +7 -0
  288. package/dist/transaction/resources/modelOperations.d.ts +427 -0
  289. package/dist/transaction/resources/modelOperations.js +12 -0
  290. package/dist/transaction/resources/mutationOptions.d.ts +66 -0
  291. package/dist/transaction/resources/mutationOptions.js +9 -0
  292. package/dist/transaction/resources/where.d.ts +101 -0
  293. package/dist/transaction/resources/where.js +115 -0
  294. package/dist/{client → transaction/resources}/writeOptionsSchema.d.ts +2 -6
  295. package/dist/{client → transaction/resources}/writeOptionsSchema.js +9 -5
  296. package/dist/{schema → transaction/schema}/field.d.ts +17 -23
  297. package/dist/{schema → transaction/schema}/field.js +5 -5
  298. package/dist/transaction/schema/fieldRef.d.ts +38 -0
  299. package/dist/transaction/schema/fieldRef.js +11 -0
  300. package/dist/transaction/schema/loadStrategy.d.ts +45 -0
  301. package/dist/transaction/schema/loadStrategy.js +46 -0
  302. package/dist/{schema → transaction/schema}/model.d.ts +50 -35
  303. package/dist/{schema → transaction/schema}/model.js +30 -20
  304. package/dist/transaction/schema/openapi.d.ts +58 -0
  305. package/dist/transaction/schema/openapi.js +501 -0
  306. package/dist/{schema → transaction/schema}/relation.d.ts +21 -16
  307. package/dist/{schema → transaction/schema}/relation.js +7 -7
  308. package/dist/{schema → transaction/schema}/residency.d.ts +0 -9
  309. package/dist/{schema → transaction/schema}/residency.js +0 -5
  310. package/dist/{schema → transaction/schema}/roles.d.ts +5 -5
  311. package/dist/{schema → transaction/schema}/roles.js +5 -5
  312. package/dist/{schema → transaction/schema}/schema.d.ts +39 -10
  313. package/dist/{schema → transaction/schema}/schema.js +24 -3
  314. package/dist/{schema → transaction/schema}/tenancy.d.ts +1 -1
  315. package/dist/{schema → transaction/schema}/tenancy.js +7 -4
  316. package/dist/transaction/transactionLayer.d.ts +82 -0
  317. package/dist/transaction/transactionLayer.js +24 -0
  318. package/dist/{transactions → transaction/transactions/settlement}/commitEnvelope.d.ts +5 -6
  319. package/dist/{transactions → transaction/transactions/settlement}/commitEnvelope.js +9 -13
  320. package/dist/{transactions → transaction/transactions/settlement}/httpCommitEnvelope.d.ts +9 -2
  321. package/dist/{transactions → transaction/transactions/settlement}/httpCommitEnvelope.js +5 -9
  322. package/dist/{transactions/durableWriteStore.d.ts → transaction/transactions/settlement/pendingWrite.d.ts} +11 -37
  323. package/dist/transaction/transactions/settlement/pendingWrite.js +20 -0
  324. package/dist/transaction/transport/commitFrames.d.ts +90 -0
  325. package/dist/transaction/transport/commitFrames.js +134 -0
  326. package/dist/transaction/transport/connectionManager.d.ts +215 -0
  327. package/dist/transaction/transport/connectionManager.js +673 -0
  328. package/dist/transaction/transport/credentialLifecycle.d.ts +177 -0
  329. package/dist/transaction/transport/credentialLifecycle.js +324 -0
  330. package/dist/{sync → transaction/transport}/heartbeat.d.ts +3 -1
  331. package/dist/{sync → transaction/transport}/heartbeat.js +6 -4
  332. package/dist/transaction/transport/httpClient.d.ts +131 -0
  333. package/dist/{client → transaction/transport}/httpClient.js +6 -5
  334. package/dist/transaction/transport/httpOptions.d.ts +33 -0
  335. package/dist/transaction/transport/httpOptions.js +12 -0
  336. package/dist/{client → transaction/transport}/httpTransport.js +295 -97
  337. package/dist/{sync/NetworkProbe.d.ts → transaction/transport/networkProbe.d.ts} +7 -4
  338. package/dist/{sync/NetworkProbe.js → transaction/transport/networkProbe.js} +14 -13
  339. package/dist/transaction/transport/wsFrameHandlers.d.ts +128 -0
  340. package/dist/transaction/transport/wsFrameHandlers.js +429 -0
  341. package/dist/transaction/transport/wsTransport.d.ts +574 -0
  342. package/dist/transaction/transport/wsTransport.js +1023 -0
  343. package/dist/transaction/types/assertExact.d.ts +17 -0
  344. package/dist/transaction/types/assertExact.js +1 -0
  345. package/dist/{types → transaction/types}/global.d.ts +17 -2
  346. package/dist/{types → transaction/types}/global.js +2 -1
  347. package/dist/{types → transaction/types}/index.d.ts +14 -46
  348. package/dist/{types → transaction/types}/index.js +7 -16
  349. package/dist/{types → transaction/types}/streams.d.ts +73 -45
  350. package/dist/transaction/utils/duration.d.ts +50 -0
  351. package/dist/{utils → transaction/utils}/duration.js +32 -0
  352. package/dist/{utils → transaction/utils}/json.d.ts +18 -0
  353. package/dist/transaction/utils/json.js +276 -0
  354. package/dist/transaction/wire/accountResponses.d.ts +420 -0
  355. package/dist/transaction/wire/accountResponses.js +290 -0
  356. package/dist/transaction/wire/auth.d.ts +56 -0
  357. package/dist/transaction/wire/auth.js +63 -0
  358. package/dist/transaction/wire/claimEvent.d.ts +76 -0
  359. package/dist/transaction/wire/claimEvent.js +73 -0
  360. package/dist/transaction/wire/claims.d.ts +530 -0
  361. package/dist/transaction/wire/claims.js +327 -0
  362. package/dist/{wire → transaction/wire}/commit.d.ts +125 -193
  363. package/dist/{wire → transaction/wire}/commit.js +68 -47
  364. package/dist/{wire → transaction/wire}/delta.d.ts +66 -17
  365. package/dist/{wire → transaction/wire}/delta.js +37 -13
  366. package/dist/transaction/wire/errorEnvelope.d.ts +72 -0
  367. package/dist/{wire → transaction/wire}/errorEnvelope.js +36 -5
  368. package/dist/transaction/wire/feedCursor.d.ts +60 -0
  369. package/dist/transaction/wire/feedCursor.js +82 -0
  370. package/dist/transaction/wire/feedEvent.d.ts +204 -0
  371. package/dist/transaction/wire/feedEvent.js +65 -0
  372. package/dist/transaction/wire/frames.d.ts +194 -0
  373. package/dist/transaction/wire/frames.js +50 -0
  374. package/dist/transaction/wire/inboundFrames.d.ts +562 -0
  375. package/dist/transaction/wire/inboundFrames.js +116 -0
  376. package/dist/transaction/wire/index.d.ts +54 -0
  377. package/dist/transaction/wire/index.js +83 -0
  378. package/dist/{wire → transaction/wire}/listEnvelope.d.ts +13 -14
  379. package/dist/transaction/wire/listEnvelope.js +42 -0
  380. package/dist/transaction/wire/modelMutations.d.ts +31 -0
  381. package/dist/transaction/wire/modelMutations.js +52 -0
  382. package/dist/transaction/wire/modelResponses.d.ts +85 -0
  383. package/dist/transaction/wire/modelResponses.js +43 -0
  384. package/dist/transaction/wire/modelShape.d.ts +78 -0
  385. package/dist/transaction/wire/modelShape.js +74 -0
  386. package/dist/transactions/{TransactionQueue.d.ts → mutations/MutationQueue.d.ts} +85 -38
  387. package/dist/transactions/{TransactionQueue.js → mutations/MutationQueue.js} +141 -80
  388. package/dist/transactions/{TransactionStore.d.ts → mutations/MutationStore.d.ts} +8 -8
  389. package/dist/transactions/{TransactionStore.js → mutations/MutationStore.js} +2 -2
  390. package/dist/transactions/{coalesceRules.d.ts → mutations/coalesceRules.d.ts} +10 -10
  391. package/dist/transactions/{coalesceRules.js → mutations/coalesceRules.js} +1 -1
  392. package/dist/transactions/mutations/commitLatency.d.ts +52 -0
  393. package/dist/transactions/mutations/commitLatency.js +130 -0
  394. package/dist/transactions/{commitOutboxStore.d.ts → mutations/commitOutboxStore.d.ts} +1 -5
  395. package/dist/transactions/{commitOutboxStore.js → mutations/commitOutboxStore.js} +1 -1
  396. package/dist/transactions/{commitPayload.d.ts → mutations/commitPayload.d.ts} +18 -16
  397. package/dist/transactions/{commitPayload.js → mutations/commitPayload.js} +15 -15
  398. package/dist/transactions/{deltaConfirmation.d.ts → mutations/deltaConfirmation.d.ts} +15 -11
  399. package/dist/transactions/{deltaConfirmation.js → mutations/deltaConfirmation.js} +14 -12
  400. package/dist/transactions/mutations/durableWriteStore.d.ts +14 -0
  401. package/dist/transactions/mutations/durableWriteStore.js +12 -0
  402. package/dist/transactions/{optimisticApply.d.ts → mutations/optimisticApply.d.ts} +7 -7
  403. package/dist/transactions/{replayValidation.d.ts → mutations/replayValidation.d.ts} +4 -3
  404. package/dist/transactions/{replayValidation.js → mutations/replayValidation.js} +7 -5
  405. package/dist/utils/mobxSetup.d.ts +1 -1
  406. package/dist/utils/mobxSetup.js +5 -2
  407. package/dist/{core → views}/QueryView.d.ts +2 -2
  408. package/dist/{core → views}/QueryView.js +2 -2
  409. package/dist/{core → views}/ViewRegistry.d.ts +1 -1
  410. package/dist/{core/queryUtils.d.ts → views/incrementalView.d.ts} +6 -6
  411. package/dist/{core/queryUtils.js → views/incrementalView.js} +6 -6
  412. package/dist/webhooks/events.d.ts +2 -2
  413. package/dist/wire/index.d.ts +1 -34
  414. package/dist/wire/index.js +8 -49
  415. package/docs/agent-messaging.md +3 -3
  416. package/docs/agents.md +20 -13
  417. package/docs/api-keys.md +14 -10
  418. package/docs/api.md +27 -61
  419. package/docs/audit.md +6 -3
  420. package/docs/cli.md +41 -13
  421. package/docs/client-behavior.md +11 -9
  422. package/docs/concurrency-convention.md +49 -57
  423. package/docs/coordination.md +283 -121
  424. package/docs/data-sources.md +7 -5
  425. package/docs/debugging.md +39 -15
  426. package/docs/deployment.md +267 -0
  427. package/docs/examples/agent-human.md +49 -42
  428. package/docs/examples/ai-sdk-tool.md +69 -44
  429. package/docs/examples/existing-python-backend.md +8 -6
  430. package/docs/examples/nextjs.md +129 -47
  431. package/docs/examples/scoped-agent.md +46 -45
  432. package/docs/examples/server-agent.md +46 -26
  433. package/docs/groups.md +87 -30
  434. package/docs/guarantees.md +41 -12
  435. package/docs/how-it-works.md +38 -12
  436. package/docs/idempotency.md +126 -0
  437. package/docs/identity.md +77 -74
  438. package/docs/index.md +172 -86
  439. package/docs/integration-guide.md +31 -19
  440. package/docs/mcp.md +46 -21
  441. package/docs/migration.md +95 -18
  442. package/docs/operating-on-your-database.md +3 -1
  443. package/docs/projects.md +3 -1
  444. package/docs/quickstart.md +22 -5
  445. package/docs/react.md +31 -18
  446. package/docs/schema-contract.md +5 -3
  447. package/docs/session-settings.md +108 -0
  448. package/docs/sessions.md +4 -2
  449. package/docs/webhooks.md +12 -10
  450. package/llms.txt +48 -18
  451. package/package.json +21 -26
  452. package/dist/agent/Agent.d.ts +0 -366
  453. package/dist/agent/Agent.js +0 -514
  454. package/dist/agent/index.d.ts +0 -115
  455. package/dist/agent/index.js +0 -128
  456. package/dist/agent/session.d.ts +0 -93
  457. package/dist/agent/session.js +0 -149
  458. package/dist/agent/types.d.ts +0 -68
  459. package/dist/agent/types.js +0 -9
  460. package/dist/cli.cjs +0 -286329
  461. package/dist/client/durableWrites.d.ts +0 -21
  462. package/dist/client/httpClient.d.ts +0 -80
  463. package/dist/coordination/schema.d.ts +0 -722
  464. package/dist/coordination/schema.js +0 -578
  465. package/dist/schema/openapi.d.ts +0 -29
  466. package/dist/schema/openapi.js +0 -124
  467. package/dist/testing/fixtures/bootstrap.d.ts +0 -49
  468. package/dist/testing/fixtures/bootstrap.js +0 -59
  469. package/dist/testing/fixtures/deltas.d.ts +0 -83
  470. package/dist/testing/fixtures/deltas.js +0 -136
  471. package/dist/testing/fixtures/models.d.ts +0 -83
  472. package/dist/testing/fixtures/models.js +0 -272
  473. package/dist/testing/helpers/reactWrapper.d.ts +0 -69
  474. package/dist/testing/helpers/reactWrapper.js +0 -67
  475. package/dist/testing/helpers/syncEngineHarness.d.ts +0 -54
  476. package/dist/testing/helpers/syncEngineHarness.js +0 -73
  477. package/dist/testing/helpers/wait.d.ts +0 -30
  478. package/dist/testing/helpers/wait.js +0 -49
  479. package/dist/testing/index.d.ts +0 -23
  480. package/dist/testing/index.js +0 -33
  481. package/dist/testing/mocks/FakeDatabase.d.ts +0 -18
  482. package/dist/testing/mocks/FakeDatabase.js +0 -10
  483. package/dist/testing/mocks/MockMutationExecutor.d.ts +0 -87
  484. package/dist/testing/mocks/MockMutationExecutor.js +0 -192
  485. package/dist/testing/mocks/MockNetworkMonitor.d.ts +0 -20
  486. package/dist/testing/mocks/MockNetworkMonitor.js +0 -46
  487. package/dist/testing/mocks/MockSyncContext.d.ts +0 -51
  488. package/dist/testing/mocks/MockSyncContext.js +0 -71
  489. package/dist/testing/mocks/MockSyncStore.d.ts +0 -88
  490. package/dist/testing/mocks/MockSyncStore.js +0 -171
  491. package/dist/testing/mocks/MockWebSocket.d.ts +0 -71
  492. package/dist/testing/mocks/MockWebSocket.js +0 -118
  493. package/dist/transactions/durableWriteStore.js +0 -30
  494. package/dist/utils/duration.d.ts +0 -25
  495. package/dist/utils/json.js +0 -88
  496. package/dist/wire/errorEnvelope.d.ts +0 -55
  497. package/dist/wire/frames.d.ts +0 -197
  498. package/dist/wire/frames.js +0 -49
  499. package/dist/wire/listEnvelope.js +0 -18
  500. package/docs/interaction-model.md +0 -97
  501. /package/dist/{core → query}/QueryProcessor.d.ts +0 -0
  502. /package/dist/{core → query}/QueryProcessor.js +0 -0
  503. /package/dist/{core/storeContract.js → storeContract.js} +0 -0
  504. /package/dist/{core → stores}/openIDBWithTimeout.d.ts +0 -0
  505. /package/dist/{core → stores}/openIDBWithTimeout.js +0 -0
  506. /package/dist/{client → transaction/auth}/credentialEndpoint.d.ts +0 -0
  507. /package/dist/{client → transaction/auth}/credentialEndpoint.js +0 -0
  508. /package/dist/{auth → transaction/auth}/credentialPolicy.d.ts +0 -0
  509. /package/dist/{auth → transaction/auth}/credentialPolicy.js +0 -0
  510. /package/dist/{auth → transaction/auth}/credentialSource.js +0 -0
  511. /package/dist/{client → transaction/auth}/hostedEndpoints.d.ts +0 -0
  512. /package/dist/{client → transaction/auth}/hostedEndpoints.js +0 -0
  513. /package/dist/{client → transaction}/persistence.d.ts +0 -0
  514. /package/dist/{client → transaction}/persistence.js +0 -0
  515. /package/dist/{client → transaction/resources}/functionalUpdate.d.ts +0 -0
  516. /package/dist/{client → transaction/resources}/functionalUpdate.js +0 -0
  517. /package/dist/{transactions → transaction/transactions/settlement}/idempotencyKey.d.ts +0 -0
  518. /package/dist/{transactions → transaction/transactions/settlement}/idempotencyKey.js +0 -0
  519. /package/dist/{client → transaction/transport}/httpTransport.d.ts +0 -0
  520. /package/dist/{types → transaction/types}/modelData.d.ts +0 -0
  521. /package/dist/{types → transaction/types}/modelData.js +0 -0
  522. /package/dist/{types → transaction/types}/participant.d.ts +0 -0
  523. /package/dist/{types → transaction/types}/participant.js +0 -0
  524. /package/dist/{types → transaction/types}/streams.js +0 -0
  525. /package/dist/{utils → transaction/utils}/asyncIterator.d.ts +0 -0
  526. /package/dist/{utils → transaction/utils}/asyncIterator.js +0 -0
  527. /package/dist/{wire → transaction/wire}/bootstrapReason.d.ts +0 -0
  528. /package/dist/{wire → transaction/wire}/bootstrapReason.js +0 -0
  529. /package/dist/{wire → transaction/wire}/protocol.d.ts +0 -0
  530. /package/dist/{wire → transaction/wire}/protocol.js +0 -0
  531. /package/dist/{wire → transaction/wire}/protocolVersion.d.ts +0 -0
  532. /package/dist/{wire → transaction/wire}/protocolVersion.js +0 -0
  533. /package/dist/transactions/{UnconfirmedWrites.d.ts → mutations/UnconfirmedWrites.d.ts} +0 -0
  534. /package/dist/transactions/{UnconfirmedWrites.js → mutations/UnconfirmedWrites.js} +0 -0
  535. /package/dist/transactions/{optimisticApply.js → mutations/optimisticApply.js} +0 -0
  536. /package/dist/{core → views}/ViewRegistry.js +0 -0
@@ -0,0 +1,673 @@
1
+ /**
2
+ * Owns the sync engine's connection lifecycle: the state machine that carries a
3
+ * client from a healthy connection, through a dropout, and back to live. It
4
+ * watches the browser's online/offline and visibility events, probes real
5
+ * connectivity and session validity with {@link probeNetwork}, applies retry
6
+ * backoff with a ceiling and jitter, and runs a watchdog for the cases where
7
+ * the browser never fires an event (VPN flips, captive portals). When it
8
+ * decides to recover, it drives the reconnect sequence — bootstrap, then
9
+ * WebSocket connect — through the {@link ConnectionCallbacks.onReconnect}
10
+ * callback and reacts to the outcome.
11
+ *
12
+ * It deliberately does not perform the bootstrap, local-storage, or object-pool
13
+ * work itself; that lives in the embedding store, which the manager reaches
14
+ * only through its callbacks. One manager is created per store, started on the
15
+ * first successful connect and disposed on teardown.
16
+ *
17
+ * This is a plain state machine, not a reactive object: it lives in the
18
+ * settlement core, which carries no reactivity runtime (ADR 0016). A consumer
19
+ * that wants to render recovery progress mirrors the transitions through
20
+ * {@link ConnectionCallbacks.onStateChange} into its own observable state —
21
+ * which is what the reactive engine's store does.
22
+ *
23
+ * CONNECTED ──(socket drop)──► PROBING_NETWORK ──► RECONNECTING ──► CONNECTED
24
+ * │ │ │
25
+ * (network lost) ▼ ▼
26
+ * ▼ SESSION_EXPIRED BACKOFF ──► PROBING_NETWORK
27
+ * OFFLINE ──(online)──► PROBING_NETWORK
28
+ * │
29
+ * ▼
30
+ * WAITING_FOR_NETWORK
31
+ *
32
+ * Three behaviors are worth calling out. A network return or tab focus during a
33
+ * backoff delay jumps straight to probing instead of waiting out the full
34
+ * interval. Reaching the retry ceiling while the browser reports offline parks
35
+ * in `waiting_for_network` rather than hard-reloading a browser that has no
36
+ * network. And a socket drop (close code 1006) goes straight to probing rather
37
+ * than the passive `offline` state — 1006 is generated locally and carries no
38
+ * connectivity signal, so on a healthy machine no online/offline event ever
39
+ * fires; only a genuine operating-system network loss parks in `offline` to
40
+ * wait for the `online` event.
41
+ */
42
+ import { probeNetwork } from './networkProbe.js';
43
+ import { noopLogger } from '../logger.js';
44
+ import { noopSocketObservability, } from '../observability.js';
45
+ // ─── Tunables ─────────────────────────────────────────────────────────────
46
+ const DEFAULT_BACKOFF = {
47
+ BASE_MS: 2_000,
48
+ MAX_MS: 30_000,
49
+ MAX_ATTEMPTS: 8,
50
+ JITTER: 0.15,
51
+ };
52
+ const ONLINE_DEBOUNCE_MS = 500;
53
+ const WATCHDOG_INTERVAL_MS = 30_000;
54
+ const MAX_STUCK_CYCLES_BEFORE_RELOAD = 6;
55
+ /** Cap on consecutive access-key re-mints before giving up to `auth_blocked`.
56
+ * Stops a hot loop if the server keeps reporting the key stale even after a
57
+ * "successful" re-mint (clock skew, a mint returning an already-rejected key). */
58
+ const MAX_CREDENTIAL_REFRESH_ATTEMPTS = 3;
59
+ // ─── ConnectionManager ────────────────────────────────────────────────────
60
+ export class ConnectionManager {
61
+ // Connection state, mirrored to the consumer via `onStateChange`.
62
+ state = 'connected';
63
+ offlineSince = null;
64
+ attempt = 0;
65
+ lastProbeResult = null;
66
+ // Private
67
+ callbacks = null;
68
+ backoffTimer = null;
69
+ debounceTimer = null;
70
+ watchdogTimer = null;
71
+ stuckCycles = 0;
72
+ /** Consecutive access-key re-mints in the current recovery cycle; reset on
73
+ * reaching `connected`. See {@link MAX_CREDENTIAL_REFRESH_ATTEMPTS}. */
74
+ credentialRefreshAttempts = 0;
75
+ disposed = false;
76
+ baseUrl;
77
+ getAuthToken;
78
+ backoff;
79
+ logger;
80
+ observability;
81
+ handleBrowserOnline = null;
82
+ handleBrowserOffline = null;
83
+ handleVisibilityChange = null;
84
+ constructor(options = {}) {
85
+ this.baseUrl = options.baseUrl;
86
+ this.getAuthToken = options.getAuthToken;
87
+ this.backoff = { ...DEFAULT_BACKOFF, ...(options.backoff ?? {}) };
88
+ this.logger = options.logger ?? noopLogger;
89
+ this.observability = options.observability ?? noopSocketObservability;
90
+ }
91
+ // ── Lifecycle ────────────────────────────────────────────────────────
92
+ start(callbacks) {
93
+ this.callbacks = callbacks;
94
+ this.setupBrowserListeners();
95
+ this.startWatchdog();
96
+ this.logger.info('[ConnectionManager] Started');
97
+ }
98
+ dispose() {
99
+ this.disposed = true;
100
+ this.clearBackoffTimer();
101
+ this.clearDebounceTimer();
102
+ if (this.watchdogTimer) {
103
+ clearInterval(this.watchdogTimer);
104
+ this.watchdogTimer = null;
105
+ }
106
+ this.removeBrowserListeners();
107
+ this.callbacks = null;
108
+ this.logger.info('[ConnectionManager] Disposed');
109
+ }
110
+ // ── Send events ──────────────────────────────────────────────────────
111
+ send(event) {
112
+ if (this.disposed)
113
+ return;
114
+ const prevState = this.state;
115
+ const nextState = this.transition(prevState, event);
116
+ if (nextState === null)
117
+ return;
118
+ this.logger.info('[ConnectionManager] Transition', {
119
+ from: prevState,
120
+ to: nextState,
121
+ event: event.type,
122
+ });
123
+ this.state = nextState;
124
+ if (prevState === 'connected' && nextState !== 'connected') {
125
+ this.offlineSince = new Date();
126
+ }
127
+ if (nextState === 'connected') {
128
+ this.offlineSince = null;
129
+ this.attempt = 0;
130
+ this.stuckCycles = 0;
131
+ }
132
+ // Notify the embedding store BEFORE running side effects, so the
133
+ // UI flips to the new label (e.g. "Reconnecting…") at the same
134
+ // tick the probe / backoff actually starts. Errors in the consumer
135
+ // must not break the FSM — wrap defensively.
136
+ try {
137
+ this.callbacks?.onStateChange?.(nextState, prevState);
138
+ }
139
+ catch (err) {
140
+ this.logger.debug('[ConnectionManager] onStateChange threw', {
141
+ error: err instanceof Error ? err.message : String(err),
142
+ });
143
+ }
144
+ this.onEnterState(nextState, event);
145
+ }
146
+ // ── Pure transition ──────────────────────────────────────────────────
147
+ transition(state, event) {
148
+ switch (state) {
149
+ case 'connected':
150
+ switch (event.type) {
151
+ case 'NETWORK_LOST':
152
+ // The OS reported the NIC down — park passively in `offline` and
153
+ // wait for the `online` event. Probing a downed adapter is wasted
154
+ // work.
155
+ return 'offline';
156
+ case 'WS_DISCONNECTED':
157
+ // The socket died (typically code 1006) but the operating-system
158
+ // network is almost certainly fine — 1006 is generated locally when
159
+ // the TCP connection vanishes and carries no connectivity signal, so
160
+ // the browser fires no online/offline event. Probe immediately rather
161
+ // than landing in the passive `offline` dead-end (which only escaped
162
+ // via the 30s watchdog, long after queued commits rolled back). The
163
+ // probe fast-fails if we genuinely are offline → waiting_for_network.
164
+ return 'probing_network';
165
+ case 'WS_SESSION_ERROR':
166
+ case 'BOOTSTRAP_FAILED_SESSION':
167
+ return 'session_expired';
168
+ case 'WS_HANDSHAKE_FAILED':
169
+ return 'probing_network';
170
+ case 'TAB_VISIBLE':
171
+ return 'probing_network';
172
+ default:
173
+ return null;
174
+ }
175
+ case 'offline':
176
+ switch (event.type) {
177
+ case 'NETWORK_ONLINE':
178
+ case 'MANUAL_RETRY':
179
+ case 'TAB_VISIBLE':
180
+ case 'WS_HANDSHAKE_FAILED':
181
+ case 'CREDENTIAL_REFRESHED':
182
+ return 'probing_network';
183
+ case 'WS_SESSION_ERROR':
184
+ case 'BOOTSTRAP_FAILED_SESSION':
185
+ return 'session_expired';
186
+ default:
187
+ return null;
188
+ }
189
+ case 'probing_network':
190
+ switch (event.type) {
191
+ case 'PROBE_SUCCESS':
192
+ return event.sessionValid ? 'reconnecting' : 'session_expired';
193
+ case 'PROBE_CREDENTIAL_STALE':
194
+ // Access key expired but the login is fine — re-mint, don't sign out.
195
+ return 'refreshing_credential';
196
+ case 'PROBE_AUTH_BLOCKED':
197
+ return 'auth_blocked';
198
+ case 'PROBE_FAILED':
199
+ return 'waiting_for_network';
200
+ case 'NETWORK_LOST':
201
+ return 'offline';
202
+ default:
203
+ return null;
204
+ }
205
+ case 'waiting_for_network':
206
+ switch (event.type) {
207
+ case 'NETWORK_ONLINE':
208
+ case 'TAB_VISIBLE':
209
+ case 'MANUAL_RETRY':
210
+ case 'BACKOFF_ELAPSED':
211
+ case 'CREDENTIAL_REFRESHED':
212
+ return 'probing_network';
213
+ case 'NETWORK_LOST':
214
+ return 'offline';
215
+ default:
216
+ return null;
217
+ }
218
+ case 'validating_session':
219
+ switch (event.type) {
220
+ case 'PROBE_SUCCESS':
221
+ return event.sessionValid ? 'reconnecting' : 'session_expired';
222
+ case 'PROBE_CREDENTIAL_STALE':
223
+ return 'refreshing_credential';
224
+ case 'PROBE_AUTH_BLOCKED':
225
+ return 'auth_blocked';
226
+ case 'NETWORK_LOST':
227
+ return 'offline';
228
+ default:
229
+ return null;
230
+ }
231
+ case 'refreshing_credential':
232
+ // Re-minting the short-lived access key (the `ek_`/`rk_`). The login is
233
+ // presumed valid; this is not a sign-out state.
234
+ switch (event.type) {
235
+ case 'CREDENTIAL_REFRESHED':
236
+ // Fresh key in hand — re-probe so we reconnect with it.
237
+ return 'probing_network';
238
+ case 'BOOTSTRAP_FAILED_SESSION':
239
+ // The re-mint hit a genuine 401/403: the long-lived login itself is
240
+ // gone. This is the only path from here to sign-out.
241
+ return 'session_expired';
242
+ case 'RECONNECT_FAILED':
243
+ // Couldn't reach the mint endpoint (offline/5xx/throw) — transient.
244
+ // Back off and retry; never sign out for a network failure.
245
+ return 'backoff';
246
+ case 'PROBE_AUTH_BLOCKED':
247
+ // Bounded-attempt fallback: the key keeps coming back stale even
248
+ // after re-mint (see runRefreshCredential's attempt guard). Stop
249
+ // looping without signing out.
250
+ return 'auth_blocked';
251
+ case 'NETWORK_LOST':
252
+ return 'offline';
253
+ default:
254
+ return null;
255
+ }
256
+ case 'reconnecting':
257
+ switch (event.type) {
258
+ case 'RECONNECT_SUCCESS':
259
+ case 'WS_CONNECTED':
260
+ return 'connected';
261
+ case 'RECONNECT_FAILED':
262
+ case 'WS_HANDSHAKE_FAILED':
263
+ return 'backoff';
264
+ case 'BOOTSTRAP_FAILED_SESSION':
265
+ case 'WS_SESSION_ERROR':
266
+ return 'session_expired';
267
+ case 'NETWORK_LOST':
268
+ return 'offline';
269
+ default:
270
+ return null;
271
+ }
272
+ case 'backoff':
273
+ switch (event.type) {
274
+ case 'BACKOFF_ELAPSED':
275
+ case 'MANUAL_RETRY':
276
+ case 'WS_HANDSHAKE_FAILED':
277
+ return 'probing_network';
278
+ case 'NETWORK_ONLINE':
279
+ case 'TAB_VISIBLE':
280
+ case 'CREDENTIAL_REFRESHED':
281
+ // Network came back (or a fresh credential arrived) while we were
282
+ // waiting out a backoff delay — jump straight to probing instead of
283
+ // waiting the full exponential interval. Fixes the "doesn't
284
+ // retrigger when internet comes back" bug.
285
+ return 'probing_network';
286
+ case 'NETWORK_LOST':
287
+ return 'offline';
288
+ case 'WS_SESSION_ERROR':
289
+ case 'BOOTSTRAP_FAILED_SESSION':
290
+ return 'session_expired';
291
+ default:
292
+ return null;
293
+ }
294
+ case 'auth_blocked':
295
+ // Reachable, but the data-plane rejected the credential (non-retryable,
296
+ // non-expiry — e.g. api_key_required, jwt_issuer_untrusted). Don't
297
+ // auto-reconnect and don't sign out. Allow a manual retry or a
298
+ // tab-focus / network-return / fresh-credential re-probe (e.g. after a
299
+ // server deploy or an out-of-band re-mint); a network drop parks
300
+ // offline; a genuine session error still expires.
301
+ switch (event.type) {
302
+ case 'MANUAL_RETRY':
303
+ case 'TAB_VISIBLE':
304
+ case 'NETWORK_ONLINE':
305
+ case 'CREDENTIAL_REFRESHED':
306
+ return 'probing_network';
307
+ case 'NETWORK_LOST':
308
+ return 'offline';
309
+ case 'WS_SESSION_ERROR':
310
+ case 'BOOTSTRAP_FAILED_SESSION':
311
+ return 'session_expired';
312
+ default:
313
+ return null;
314
+ }
315
+ case 'session_expired':
316
+ return null; // terminal
317
+ default:
318
+ return null;
319
+ }
320
+ }
321
+ // ── Side effects per state ───────────────────────────────────────────
322
+ onEnterState(state, event) {
323
+ switch (state) {
324
+ case 'connected':
325
+ this.clearBackoffTimer();
326
+ this.credentialRefreshAttempts = 0;
327
+ break;
328
+ case 'offline':
329
+ this.clearBackoffTimer();
330
+ this.callbacks?.onDisconnectWebSocket();
331
+ break;
332
+ case 'probing_network':
333
+ // A socket drop (`WS_DISCONNECTED`) lands here directly so recovery
334
+ // starts immediately. Tear the dead socket down first — that is what
335
+ // sets the socket's `isManualClose=true` and suppresses its own
336
+ // reconnect, keeping this machine the single reconnect authority on the
337
+ // human path. The teardown runs synchronously inside the `disconnected`
338
+ // emit, before the socket's onclose checks the flag, so the timing
339
+ // matches the previous `offline`-entry teardown. We gate on the drop
340
+ // event specifically: the other paths into `probing_network`
341
+ // (tab-focus re-validation, handshake retry, backoff elapse) must not
342
+ // tear down a socket that may still be live.
343
+ if (event.type === 'WS_DISCONNECTED') {
344
+ this.callbacks?.onDisconnectWebSocket();
345
+ }
346
+ void this.runProbe().catch(this.captureEffectFailure('probe'));
347
+ break;
348
+ case 'waiting_for_network':
349
+ this.scheduleBackoff();
350
+ break;
351
+ case 'reconnecting':
352
+ void this.runReconnect().catch(this.captureEffectFailure('reconnect'));
353
+ break;
354
+ case 'refreshing_credential':
355
+ void this.runRefreshCredential().catch(this.captureEffectFailure('refresh-credential'));
356
+ break;
357
+ case 'backoff':
358
+ this.scheduleBackoff();
359
+ break;
360
+ case 'auth_blocked':
361
+ // Stop here — the server is reachable but rejected the credential (for
362
+ // example api_key_required or jwt_issuer_untrusted from the data plane).
363
+ // Neither reconnecting nor re-authenticating fixes it. Drop the socket
364
+ // and wait for a manual retry or a re-probe. This deliberately does not
365
+ // call onSessionExpired (no sign-out) and does not reconnect — that is
366
+ // the whole point of the state.
367
+ this.clearBackoffTimer();
368
+ this.callbacks?.onDisconnectWebSocket();
369
+ this.observability.breadcrumb('Auth blocked — reachable but credential rejected; not reconnecting or signing out', 'sync.offline', 'error');
370
+ break;
371
+ case 'session_expired':
372
+ this.clearBackoffTimer();
373
+ this.callbacks?.onDisconnectWebSocket();
374
+ this.callbacks?.onSessionExpired();
375
+ this.observability.breadcrumb('Session expired — redirecting to signin', 'sync.offline', 'warning');
376
+ break;
377
+ }
378
+ }
379
+ // ── Async operations ─────────────────────────────────────────────────
380
+ /**
381
+ * FSM effects are fire-and-forget by design (`onEnterState` is sync). Each
382
+ * effect catches its own operational failures and maps them onto an FSM
383
+ * event, so a rejection here means the machine wedged mid-transition
384
+ * (`send()` or a transition listener threw) with no retry timer armed past
385
+ * it — capture it instead of losing the reconnect loop silently.
386
+ */
387
+ captureEffectFailure(effect) {
388
+ return (error) => {
389
+ this.observability.captureWebSocketError({
390
+ context: `connection-fsm-${effect}`,
391
+ error: error instanceof Error ? error.message : String(error),
392
+ });
393
+ };
394
+ }
395
+ async runProbe() {
396
+ try {
397
+ const result = await probeNetwork({
398
+ baseUrl: this.baseUrl,
399
+ getAuthToken: this.getAuthToken,
400
+ logger: this.logger,
401
+ });
402
+ this.lastProbeResult = result;
403
+ // One probe outcome → one event. Exhaustive over ProbeOutcome so a new
404
+ // outcome can't be silently dropped.
405
+ switch (result.outcome) {
406
+ case 'reachable':
407
+ this.send({ type: 'PROBE_SUCCESS', sessionValid: true });
408
+ break;
409
+ case 'session_expired':
410
+ // Genuine login expiry — terminal. (PROBE_SUCCESS with
411
+ // sessionValid:false routes to session_expired in the FSM.)
412
+ this.send({ type: 'PROBE_SUCCESS', sessionValid: false });
413
+ break;
414
+ case 'credential_stale':
415
+ // Access key expired but the login is fine — re-mint, don't sign out.
416
+ this.send({ type: 'PROBE_CREDENTIAL_STALE' });
417
+ break;
418
+ case 'auth_blocked':
419
+ this.send({ type: 'PROBE_AUTH_BLOCKED' });
420
+ break;
421
+ case 'unreachable':
422
+ this.send({ type: 'PROBE_FAILED' });
423
+ break;
424
+ default: {
425
+ const _exhaustive = result.outcome;
426
+ void _exhaustive;
427
+ this.send({ type: 'PROBE_FAILED' });
428
+ }
429
+ }
430
+ }
431
+ catch {
432
+ this.send({ type: 'PROBE_FAILED' });
433
+ }
434
+ }
435
+ /**
436
+ * Re-mint the short-lived access key on `refreshing_credential`. Delegates to
437
+ * the `onRefreshCredential` callback (which mints a fresh `ek_`/`rk_` from the
438
+ * still-valid login and pushes it into the credential source) and maps its
439
+ * tri-state outcome onto the FSM:
440
+ * - `refreshed` → `CREDENTIAL_REFRESHED` → re-probe & reconnect.
441
+ * - `session_error` → `BOOTSTRAP_FAILED_SESSION` → sign out (login is gone).
442
+ * - `network_error` → `RECONNECT_FAILED` → back off & retry (never sign out).
443
+ *
444
+ * A bounded attempt counter guards against a hot loop where the server keeps
445
+ * reporting the key stale even after a "successful" re-mint (e.g. a clock skew
446
+ * or a mint that returns an already-rejected key): after
447
+ * `MAX_CREDENTIAL_REFRESH_ATTEMPTS` we fall through to `auth_blocked` (stop,
448
+ * no sign-out) rather than spin. The counter resets once we reach `connected`.
449
+ *
450
+ * When no refresher is wired (e.g. a static `apiKey` deployment), we re-probe
451
+ * directly — the credential source's own scheduler owns refresh there.
452
+ */
453
+ async runRefreshCredential() {
454
+ if (this.credentialRefreshAttempts >= MAX_CREDENTIAL_REFRESH_ATTEMPTS) {
455
+ this.logger.debug('[ConnectionManager] Access key still stale after repeated re-mints — stopping', { attempts: this.credentialRefreshAttempts });
456
+ this.credentialRefreshAttempts = 0;
457
+ this.send({ type: 'PROBE_AUTH_BLOCKED' });
458
+ return;
459
+ }
460
+ this.credentialRefreshAttempts += 1;
461
+ const refresher = this.callbacks?.onRefreshCredential;
462
+ if (!refresher) {
463
+ // No re-mint path wired — re-probe with whatever the credential source
464
+ // holds (a static-key deployment refreshes out-of-band, if at all).
465
+ this.send({ type: 'CREDENTIAL_REFRESHED' });
466
+ return;
467
+ }
468
+ try {
469
+ const result = await refresher();
470
+ switch (result) {
471
+ case 'refreshed':
472
+ this.send({ type: 'CREDENTIAL_REFRESHED' });
473
+ break;
474
+ case 'session_error':
475
+ this.send({ type: 'BOOTSTRAP_FAILED_SESSION' });
476
+ break;
477
+ case 'network_error':
478
+ this.send({ type: 'RECONNECT_FAILED' });
479
+ break;
480
+ default: {
481
+ const _exhaustive = result;
482
+ void _exhaustive;
483
+ this.send({ type: 'RECONNECT_FAILED' });
484
+ }
485
+ }
486
+ }
487
+ catch (error) {
488
+ // A thrown refresher is transient by contract (offline / mint endpoint
489
+ // unreachable) — back off and retry, never sign out.
490
+ this.logger.debug('[ConnectionManager] Credential re-mint threw (transient)', { error });
491
+ this.send({ type: 'RECONNECT_FAILED' });
492
+ }
493
+ }
494
+ async runReconnect() {
495
+ if (!this.callbacks)
496
+ return;
497
+ try {
498
+ const result = await this.callbacks.onReconnect();
499
+ switch (result) {
500
+ case 'success':
501
+ this.send({ type: 'RECONNECT_SUCCESS' });
502
+ break;
503
+ case 'session_error':
504
+ this.send({ type: 'BOOTSTRAP_FAILED_SESSION' });
505
+ break;
506
+ case 'network_error':
507
+ this.send({ type: 'RECONNECT_FAILED' });
508
+ break;
509
+ }
510
+ }
511
+ catch (error) {
512
+ this.logger.debug('[ConnectionManager] Reconnect threw', { error });
513
+ this.send({ type: 'RECONNECT_FAILED' });
514
+ }
515
+ }
516
+ // ── Backoff ──────────────────────────────────────────────────────────
517
+ scheduleBackoff() {
518
+ this.clearBackoffTimer();
519
+ if (this.attempt >= this.backoff.MAX_ATTEMPTS) {
520
+ // If still offline, a hard reload will fail or serve cached and
521
+ // we'll loop. Park in waiting_for_network and let the `online`
522
+ // event (or watchdog) restart the cycle when the network comes
523
+ // back.
524
+ if (typeof navigator !== 'undefined' && navigator.onLine === false) {
525
+ this.logger.debug('[ConnectionManager] Max retries while offline — parking until network restored');
526
+ this.observability.breadcrumb('Max retries — parking offline', 'sync.offline', 'warning');
527
+ this.attempt = 0;
528
+ return;
529
+ }
530
+ this.logger.debug('[ConnectionManager] Max retries — hard reload');
531
+ this.observability.breadcrumb('Max retries — hard reload', 'sync.offline', 'error');
532
+ if (typeof window !== 'undefined') {
533
+ window.location.reload();
534
+ }
535
+ return;
536
+ }
537
+ const baseDelay = Math.min(this.backoff.BASE_MS * Math.pow(2, this.attempt), this.backoff.MAX_MS);
538
+ const jitter = baseDelay * this.backoff.JITTER * (2 * Math.random() - 1);
539
+ const delay = Math.round(baseDelay + jitter);
540
+ this.attempt++;
541
+ this.backoffTimer = setTimeout(() => {
542
+ this.backoffTimer = null;
543
+ this.send({ type: 'BACKOFF_ELAPSED' });
544
+ }, delay);
545
+ }
546
+ // ── Browser listeners ────────────────────────────────────────────────
547
+ setupBrowserListeners() {
548
+ if (typeof window === 'undefined')
549
+ return;
550
+ this.handleBrowserOnline = () => {
551
+ this.clearDebounceTimer();
552
+ this.debounceTimer = setTimeout(() => {
553
+ this.send({ type: 'NETWORK_ONLINE' });
554
+ }, ONLINE_DEBOUNCE_MS);
555
+ };
556
+ this.handleBrowserOffline = () => {
557
+ this.clearDebounceTimer();
558
+ this.send({ type: 'NETWORK_LOST' });
559
+ };
560
+ this.handleVisibilityChange = () => {
561
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
562
+ this.send({ type: 'TAB_VISIBLE' });
563
+ }
564
+ };
565
+ window.addEventListener('online', this.handleBrowserOnline);
566
+ window.addEventListener('offline', this.handleBrowserOffline);
567
+ if (typeof document !== 'undefined') {
568
+ document.addEventListener('visibilitychange', this.handleVisibilityChange);
569
+ }
570
+ }
571
+ removeBrowserListeners() {
572
+ if (typeof window === 'undefined')
573
+ return;
574
+ if (this.handleBrowserOnline) {
575
+ window.removeEventListener('online', this.handleBrowserOnline);
576
+ }
577
+ if (this.handleBrowserOffline) {
578
+ window.removeEventListener('offline', this.handleBrowserOffline);
579
+ }
580
+ if (this.handleVisibilityChange && typeof document !== 'undefined') {
581
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
582
+ }
583
+ }
584
+ // ── Watchdog ─────────────────────────────────────────────────────────
585
+ startWatchdog() {
586
+ if (typeof window === 'undefined')
587
+ return;
588
+ this.watchdogTimer = setInterval(() => {
589
+ if (this.disposed)
590
+ return;
591
+ // "Stuck" means parked in a non-active recovery state (offline,
592
+ // waiting_for_network, backoff). This deliberately does not gate on
593
+ // `navigator.onLine === true`: per MDN, `navigator.onLine` is only
594
+ // reliable when it returns false ("definitely offline"), and even that
595
+ // lies after laptop wake or VPN flips. Gating the watchdog on `onLine`
596
+ // was what stranded the machine in `offline` forever — when the browser
597
+ // briefly reported offline and never re-fired the `online` event, there
598
+ // was no escape. The probe itself fast-fails when truly offline, so an
599
+ // unconditional retry costs nothing in the genuine case.
600
+ const isStuck = this.state !== 'connected' &&
601
+ this.state !== 'session_expired' &&
602
+ this.state !== 'probing_network' &&
603
+ this.state !== 'refreshing_credential' &&
604
+ this.state !== 'reconnecting';
605
+ if (isStuck) {
606
+ this.stuckCycles++;
607
+ // Hard-reload gate: only reload when `navigator.onLine` is true.
608
+ // `onLine === false` is the one direction we trust (MDN: "false
609
+ // means definitely offline"), and reloading while truly offline
610
+ // would either serve cached content forever or fail and leave
611
+ // the user with a broken page.
612
+ const browserOnline = typeof navigator === 'undefined' || navigator.onLine;
613
+ if (this.stuckCycles >= MAX_STUCK_CYCLES_BEFORE_RELOAD && browserOnline) {
614
+ this.logger.debug('[ConnectionManager] Watchdog: sustained stuck — hard reload');
615
+ this.observability.breadcrumb('Watchdog hard reload', 'sync.offline', 'error');
616
+ if (typeof window !== 'undefined') {
617
+ window.location.reload();
618
+ }
619
+ return;
620
+ }
621
+ this.logger.info('[ConnectionManager] Watchdog: stuck — retry', {
622
+ state: this.state,
623
+ stuckCycles: this.stuckCycles,
624
+ browserOnline,
625
+ });
626
+ this.attempt = 0;
627
+ this.send({ type: 'MANUAL_RETRY' });
628
+ }
629
+ else {
630
+ this.stuckCycles = 0;
631
+ }
632
+ }, WATCHDOG_INTERVAL_MS);
633
+ }
634
+ // ── UI-friendly views ─────────────────────────────────────────────────
635
+ get isConnected() { return this.state === 'connected'; }
636
+ get isOffline() { return this.state === 'offline' || this.state === 'waiting_for_network'; }
637
+ get isReconnecting() {
638
+ return (this.state === 'probing_network' ||
639
+ this.state === 'validating_session' ||
640
+ this.state === 'refreshing_credential' ||
641
+ this.state === 'reconnecting' ||
642
+ this.state === 'backoff');
643
+ }
644
+ get isSessionExpired() { return this.state === 'session_expired'; }
645
+ get offlineDuration() {
646
+ if (!this.offlineSince)
647
+ return null;
648
+ const ms = Date.now() - this.offlineSince.getTime();
649
+ const seconds = Math.floor(ms / 1000);
650
+ const minutes = Math.floor(seconds / 60);
651
+ const hours = Math.floor(minutes / 60);
652
+ if (seconds < 60)
653
+ return 'Just now';
654
+ if (minutes < 60)
655
+ return `${minutes}m ago`;
656
+ if (hours < 24)
657
+ return `${hours}h ago`;
658
+ return `${Math.floor(hours / 24)}d ago`;
659
+ }
660
+ // ── Timer helpers ─────────────────────────────────────────────────────
661
+ clearBackoffTimer() {
662
+ if (this.backoffTimer) {
663
+ clearTimeout(this.backoffTimer);
664
+ this.backoffTimer = null;
665
+ }
666
+ }
667
+ clearDebounceTimer() {
668
+ if (this.debounceTimer) {
669
+ clearTimeout(this.debounceTimer);
670
+ this.debounceTimer = null;
671
+ }
672
+ }
673
+ }