@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.
- package/README.md +52 -0
- package/dist/Ablo.d.ts +208 -0
- package/dist/Ablo.js +120 -0
- package/dist/client.d.ts +317 -0
- package/dist/client.js +13 -0
- package/dist/core.d.ts +35 -0
- package/dist/core.js +48 -0
- package/dist/humans.d.ts +28 -0
- package/dist/humans.js +34 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +6 -0
- package/dist/local/BaseSyncedStore.d.ts +807 -0
- package/dist/local/BaseSyncedStore.js +1516 -0
- package/dist/local/Database.d.ts +322 -0
- package/dist/local/Database.js +1589 -0
- package/dist/local/InstanceCache.d.ts +255 -0
- package/dist/local/InstanceCache.js +1263 -0
- package/dist/local/LazyReferenceCollection.d.ts +177 -0
- package/dist/local/LazyReferenceCollection.js +461 -0
- package/dist/local/Model.d.ts +475 -0
- package/dist/local/Model.js +950 -0
- package/dist/local/ModelRegistry.d.ts +225 -0
- package/dist/local/ModelRegistry.js +539 -0
- package/dist/local/NetworkMonitor.d.ts +28 -0
- package/dist/local/NetworkMonitor.js +79 -0
- package/dist/local/RuntimeContext.d.ts +52 -0
- package/dist/local/RuntimeContext.js +80 -0
- package/dist/local/SyncClient.d.ts +516 -0
- package/dist/local/SyncClient.js +1754 -0
- package/dist/local/adapters/alwaysOnline.d.ts +14 -0
- package/dist/local/adapters/alwaysOnline.js +17 -0
- package/dist/local/adapters/inMemoryStorage.d.ts +37 -0
- package/dist/local/adapters/inMemoryStorage.js +122 -0
- package/dist/local/client/clientPrelude.d.ts +52 -0
- package/dist/local/client/clientPrelude.js +60 -0
- package/dist/local/client/consoleLogger.d.ts +35 -0
- package/dist/local/client/consoleLogger.js +44 -0
- package/dist/local/client/createInternalComponents.d.ts +50 -0
- package/dist/local/client/createInternalComponents.js +98 -0
- package/dist/local/client/createModelProxy.d.ts +248 -0
- package/dist/local/client/createModelProxy.js +880 -0
- package/dist/local/client/modelRegistration.d.ts +10 -0
- package/dist/local/client/modelRegistration.js +316 -0
- package/dist/local/client/options.d.ts +440 -0
- package/dist/local/client/options.js +7 -0
- package/dist/local/client/reactiveEngine.d.ts +53 -0
- package/dist/local/client/reactiveEngine.js +705 -0
- package/dist/local/client/resourceTypes.d.ts +12 -0
- package/dist/local/client/resourceTypes.js +10 -0
- package/dist/local/client/schemaConfig.d.ts +44 -0
- package/dist/local/client/schemaConfig.js +185 -0
- package/dist/local/client/storeCluster.d.ts +46 -0
- package/dist/local/client/storeCluster.js +133 -0
- package/dist/local/client/storeLifecycle.d.ts +61 -0
- package/dist/local/client/storeLifecycle.js +236 -0
- package/dist/local/client/validateAbloOptions.d.ts +42 -0
- package/dist/local/client/validateAbloOptions.js +43 -0
- package/dist/local/client/wsMutationExecutor.d.ts +27 -0
- package/dist/local/client/wsMutationExecutor.js +72 -0
- package/dist/local/context.d.ts +42 -0
- package/dist/local/context.js +81 -0
- package/dist/local/coordination/ClaimLog.d.ts +26 -0
- package/dist/local/coordination/ClaimLog.js +32 -0
- package/dist/local/interfaces/index.d.ts +311 -0
- package/dist/local/interfaces/index.js +9 -0
- package/dist/local/localModelContract.d.ts +14 -0
- package/dist/local/localModelContract.js +1 -0
- package/dist/local/logPosition.d.ts +31 -0
- package/dist/local/logPosition.js +53 -0
- package/dist/local/mutationPersistence.d.ts +6 -0
- package/dist/local/mutationPersistence.js +1 -0
- package/dist/local/mutators/RecordingMutation.d.ts +36 -0
- package/dist/local/mutators/RecordingMutation.js +182 -0
- package/dist/local/mutators/Transaction.d.ts +40 -0
- package/dist/local/mutators/Transaction.js +58 -0
- package/dist/local/mutators/UndoManager.d.ts +258 -0
- package/dist/local/mutators/UndoManager.js +665 -0
- package/dist/local/mutators/defineMutators.d.ts +60 -0
- package/dist/local/mutators/defineMutators.js +18 -0
- package/dist/local/mutators/inverseOp.d.ts +126 -0
- package/dist/local/mutators/inverseOp.js +71 -0
- package/dist/local/mutators/mutateActions.d.ts +45 -0
- package/dist/local/mutators/mutateActions.js +105 -0
- package/dist/local/mutators/readerActions.d.ts +33 -0
- package/dist/local/mutators/readerActions.js +57 -0
- package/dist/local/mutators/undoApply.d.ts +51 -0
- package/dist/local/mutators/undoApply.js +117 -0
- package/dist/local/persistence.d.ts +7 -0
- package/dist/local/persistence.js +9 -0
- package/dist/local/query/QueryProcessor.d.ts +75 -0
- package/dist/local/query/QueryProcessor.js +255 -0
- package/dist/local/query/client.d.ts +64 -0
- package/dist/local/query/client.js +138 -0
- package/dist/local/query/types.d.ts +85 -0
- package/dist/local/query/types.js +16 -0
- package/dist/local/schema/serialize.d.ts +1 -0
- package/dist/local/schema/serialize.js +1 -0
- package/dist/local/store/queryApi.d.ts +13 -0
- package/dist/local/store/queryApi.js +35 -0
- package/dist/local/storeContract.d.ts +145 -0
- package/dist/local/storeContract.js +12 -0
- package/dist/local/stores/DatabaseManager.d.ts +112 -0
- package/dist/local/stores/DatabaseManager.js +400 -0
- package/dist/local/stores/ObjectStore.d.ts +115 -0
- package/dist/local/stores/ObjectStore.js +393 -0
- package/dist/local/stores/ObjectStoreContract.d.ts +38 -0
- package/dist/local/stores/ObjectStoreContract.js +1 -0
- package/dist/local/stores/StoreManager.d.ts +114 -0
- package/dist/local/stores/StoreManager.js +304 -0
- package/dist/local/stores/SyncActionStore.d.ts +99 -0
- package/dist/local/stores/SyncActionStore.js +506 -0
- package/dist/local/stores/openIDBWithTimeout.d.ts +65 -0
- package/dist/local/stores/openIDBWithTimeout.js +153 -0
- package/dist/local/stores/persistenceCleanup.d.ts +7 -0
- package/dist/local/stores/persistenceCleanup.js +26 -0
- package/dist/local/stores/persistenceIdentity.d.ts +27 -0
- package/dist/local/stores/persistenceIdentity.js +38 -0
- package/dist/local/stores/syncAction.d.ts +26 -0
- package/dist/local/stores/syncAction.js +16 -0
- package/dist/local/stores/v1PersistenceDeletion.d.ts +8 -0
- package/dist/local/stores/v1PersistenceDeletion.js +16 -0
- package/dist/local/sync/BootstrapFetcher.d.ts +284 -0
- package/dist/local/sync/BootstrapFetcher.js +964 -0
- package/dist/local/sync/ConnectionManager.d.ts +8 -0
- package/dist/local/sync/ConnectionManager.js +8 -0
- package/dist/local/sync/OnDemandLoader.d.ts +231 -0
- package/dist/local/sync/OnDemandLoader.js +743 -0
- package/dist/local/sync/SubscriptionManager.d.ts +159 -0
- package/dist/local/sync/SubscriptionManager.js +243 -0
- package/dist/local/sync/SyncWebSocket.d.ts +173 -0
- package/dist/local/sync/SyncWebSocket.js +438 -0
- package/dist/local/sync/bootstrapApply.d.ts +73 -0
- package/dist/local/sync/bootstrapApply.js +73 -0
- package/dist/local/sync/commitFrames.d.ts +8 -0
- package/dist/local/sync/commitFrames.js +8 -0
- package/dist/local/sync/connectionManagerLifecycle.d.ts +23 -0
- package/dist/local/sync/connectionManagerLifecycle.js +126 -0
- package/dist/local/sync/contextPorts.d.ts +18 -0
- package/dist/local/sync/contextPorts.js +31 -0
- package/dist/local/sync/createClaimStream.d.ts +64 -0
- package/dist/local/sync/createClaimStream.js +475 -0
- package/dist/local/sync/createSnapshot.d.ts +29 -0
- package/dist/local/sync/createSnapshot.js +116 -0
- package/dist/local/sync/credentialLifecycle.d.ts +7 -0
- package/dist/local/sync/credentialLifecycle.js +7 -0
- package/dist/local/sync/deltaPipeline.d.ts +116 -0
- package/dist/local/sync/deltaPipeline.js +357 -0
- package/dist/local/sync/groupChange.d.ts +116 -0
- package/dist/local/sync/groupChange.js +244 -0
- package/dist/local/sync/initialize.d.ts +27 -0
- package/dist/local/sync/initialize.js +137 -0
- package/dist/local/sync/participants.d.ts +132 -0
- package/dist/local/sync/participants.js +342 -0
- package/dist/local/sync/persistedPrefix.d.ts +12 -0
- package/dist/local/sync/persistedPrefix.js +22 -0
- package/dist/local/sync/reconnect.d.ts +23 -0
- package/dist/local/sync/reconnect.js +55 -0
- package/dist/local/sync/schemaDrift.d.ts +55 -0
- package/dist/local/sync/schemaDrift.js +53 -0
- package/dist/local/sync/schemas.d.ts +71 -0
- package/dist/local/sync/schemas.js +94 -0
- package/dist/local/sync/socketEventWiring.d.ts +31 -0
- package/dist/local/sync/socketEventWiring.js +130 -0
- package/dist/local/sync/syncCursor.d.ts +40 -0
- package/dist/local/sync/syncCursor.js +55 -0
- package/dist/local/sync/syncPlan.d.ts +54 -0
- package/dist/local/sync/syncPlan.js +50 -0
- package/dist/local/sync/terminalSessionLifecycle.d.ts +20 -0
- package/dist/local/sync/terminalSessionLifecycle.js +50 -0
- package/dist/local/sync/wsFrameHandlers.d.ts +8 -0
- package/dist/local/sync/wsFrameHandlers.js +8 -0
- package/dist/local/transactions/databaseCommitOutbox.d.ts +15 -0
- package/dist/local/transactions/databaseCommitOutbox.js +16 -0
- package/dist/local/transactions/localMutation.d.ts +10 -0
- package/dist/local/transactions/localMutation.js +37 -0
- package/dist/local/transactions/mutations/MutationQueue.d.ts +511 -0
- package/dist/local/transactions/mutations/MutationQueue.js +1498 -0
- package/dist/local/transactions/mutations/MutationStore.d.ts +20 -0
- package/dist/local/transactions/mutations/MutationStore.js +53 -0
- package/dist/local/transactions/mutations/UnconfirmedWrites.d.ts +82 -0
- package/dist/local/transactions/mutations/UnconfirmedWrites.js +104 -0
- package/dist/local/transactions/mutations/batchProcessing.d.ts +64 -0
- package/dist/local/transactions/mutations/batchProcessing.js +349 -0
- package/dist/local/transactions/mutations/coalesceRules.d.ts +58 -0
- package/dist/local/transactions/mutations/coalesceRules.js +140 -0
- package/dist/local/transactions/mutations/commitApi.d.ts +19 -0
- package/dist/local/transactions/mutations/commitApi.js +74 -0
- package/dist/local/transactions/mutations/commitLane.d.ts +70 -0
- package/dist/local/transactions/mutations/commitLane.js +140 -0
- package/dist/local/transactions/mutations/commitLatency.d.ts +52 -0
- package/dist/local/transactions/mutations/commitLatency.js +130 -0
- package/dist/local/transactions/mutations/commitPayload.d.ts +165 -0
- package/dist/local/transactions/mutations/commitPayload.js +152 -0
- package/dist/local/transactions/mutations/commitTransport.d.ts +36 -0
- package/dist/local/transactions/mutations/commitTransport.js +104 -0
- package/dist/local/transactions/mutations/deltaConfirmation.d.ts +63 -0
- package/dist/local/transactions/mutations/deltaConfirmation.js +235 -0
- package/dist/local/transactions/mutations/durableCommitRestore.d.ts +17 -0
- package/dist/local/transactions/mutations/durableCommitRestore.js +95 -0
- package/dist/local/transactions/mutations/durableWriteStore.d.ts +14 -0
- package/dist/local/transactions/mutations/durableWriteStore.js +12 -0
- package/dist/local/transactions/mutations/executionSelection.d.ts +6 -0
- package/dist/local/transactions/mutations/executionSelection.js +42 -0
- package/dist/local/transactions/mutations/failureHandling.d.ts +16 -0
- package/dist/local/transactions/mutations/failureHandling.js +130 -0
- package/dist/local/transactions/mutations/failurePolicy.d.ts +13 -0
- package/dist/local/transactions/mutations/failurePolicy.js +48 -0
- package/dist/local/transactions/mutations/localMutation.d.ts +58 -0
- package/dist/local/transactions/mutations/localMutation.js +75 -0
- package/dist/local/transactions/mutations/modelOperations.d.ts +44 -0
- package/dist/local/transactions/mutations/modelOperations.js +144 -0
- package/dist/local/transactions/mutations/mutationPersistence.d.ts +25 -0
- package/dist/local/transactions/mutations/mutationPersistence.js +188 -0
- package/dist/local/transactions/mutations/pendingDrain.d.ts +33 -0
- package/dist/local/transactions/mutations/pendingDrain.js +112 -0
- package/dist/local/transactions/mutations/processingScheduler.d.ts +14 -0
- package/dist/local/transactions/mutations/processingScheduler.js +24 -0
- package/dist/local/transactions/mutations/queueCoalescing.d.ts +13 -0
- package/dist/local/transactions/mutations/queueCoalescing.js +35 -0
- package/dist/local/transactions/mutations/replayValidation.d.ts +187 -0
- package/dist/local/transactions/mutations/replayValidation.js +164 -0
- package/dist/local/transactions/reconnectDrain.d.ts +11 -0
- package/dist/local/transactions/reconnectDrain.js +13 -0
- package/dist/local/utils/mobxSetup.d.ts +53 -0
- package/dist/local/utils/mobxSetup.js +330 -0
- package/dist/local/views/QueryView.d.ts +79 -0
- package/dist/local/views/QueryView.js +218 -0
- package/dist/local/views/ViewRegistry.d.ts +20 -0
- package/dist/local/views/ViewRegistry.js +57 -0
- package/dist/local/views/incrementalView.d.ts +45 -0
- package/dist/local/views/incrementalView.js +69 -0
- package/dist/plugin.d.ts +285 -0
- package/dist/plugin.js +106 -0
- package/dist/presenceStream.d.ts +69 -0
- package/dist/presenceStream.js +200 -0
- package/dist/react/AbloProvider.d.ts +242 -0
- package/dist/react/AbloProvider.js +456 -0
- package/dist/react/ClientSideSuspense.d.ts +36 -0
- package/dist/react/ClientSideSuspense.js +17 -0
- package/dist/react/DefaultFallback.d.ts +24 -0
- package/dist/react/DefaultFallback.js +43 -0
- package/dist/react/context.d.ts +55 -0
- package/dist/react/context.js +29 -0
- package/dist/react/createAbloReact.d.ts +50 -0
- package/dist/react/createAbloReact.js +48 -0
- package/dist/react/internalContext.d.ts +33 -0
- package/dist/react/internalContext.js +3 -0
- package/dist/react/useAblo.d.ts +96 -0
- package/dist/react/useAblo.js +120 -0
- package/dist/react/useCurrentUserId.d.ts +2 -0
- package/dist/react/useCurrentUserId.js +12 -0
- package/dist/react/useErrorListener.d.ts +2 -0
- package/dist/react/useErrorListener.js +14 -0
- package/dist/react/useMutationFailureListener.d.ts +8 -0
- package/dist/react/useMutationFailureListener.js +19 -0
- package/dist/react/useMutators.d.ts +56 -0
- package/dist/react/useMutators.js +84 -0
- package/dist/react/useSyncStatus.d.ts +19 -0
- package/dist/react/useSyncStatus.js +37 -0
- package/dist/react/useUndoScope.d.ts +34 -0
- package/dist/react/useUndoScope.js +73 -0
- package/dist/react.d.ts +18 -0
- package/dist/react.js +14 -0
- package/dist/reactRuntime.d.ts +4 -0
- package/dist/reactRuntime.js +2 -0
- package/dist/surface.d.ts +36 -0
- package/dist/surface.js +77 -0
- package/dist/useReactive.d.ts +6 -0
- package/dist/useReactive.js +43 -0
- package/package.json +119 -0
- package/src/Ablo.ts +456 -0
- package/src/client.ts +374 -0
- package/src/core.ts +104 -0
- package/src/humans.ts +61 -0
- package/src/index.ts +40 -0
- package/src/local/BaseSyncedStore.ts +1991 -0
- package/src/local/Database.ts +2052 -0
- package/src/local/InstanceCache.ts +1503 -0
- package/src/local/LazyReferenceCollection.ts +563 -0
- package/src/local/Model.ts +1124 -0
- package/src/local/ModelRegistry.ts +762 -0
- package/src/local/NetworkMonitor.ts +88 -0
- package/src/local/RuntimeContext.ts +141 -0
- package/src/local/SyncClient.ts +2131 -0
- package/src/local/adapters/alwaysOnline.ts +20 -0
- package/src/local/adapters/inMemoryStorage.ts +141 -0
- package/src/local/client/clientPrelude.ts +112 -0
- package/src/local/client/consoleLogger.ts +60 -0
- package/src/local/client/createInternalComponents.ts +163 -0
- package/src/local/client/createModelProxy.ts +1390 -0
- package/src/local/client/modelRegistration.ts +350 -0
- package/src/local/client/options.ts +526 -0
- package/src/local/client/reactiveEngine.ts +935 -0
- package/src/local/client/resourceTypes.ts +37 -0
- package/src/local/client/schemaConfig.ts +194 -0
- package/src/local/client/storeCluster.ts +172 -0
- package/src/local/client/storeLifecycle.ts +343 -0
- package/src/local/client/validateAbloOptions.ts +95 -0
- package/src/local/client/wsMutationExecutor.ts +110 -0
- package/src/local/context.ts +96 -0
- package/src/local/coordination/ClaimLog.ts +39 -0
- package/src/local/interfaces/index.ts +468 -0
- package/src/local/localModelContract.ts +15 -0
- package/src/local/logPosition.ts +84 -0
- package/src/local/mutationPersistence.ts +7 -0
- package/src/local/mutators/RecordingMutation.ts +222 -0
- package/src/local/mutators/Transaction.ts +97 -0
- package/src/local/mutators/UndoManager.ts +741 -0
- package/src/local/mutators/defineMutators.ts +76 -0
- package/src/local/mutators/inverseOp.ts +83 -0
- package/src/local/mutators/mutateActions.ts +167 -0
- package/src/local/mutators/readerActions.ts +99 -0
- package/src/local/mutators/undoApply.ts +141 -0
- package/src/local/persistence.ts +16 -0
- package/src/local/query/QueryProcessor.ts +347 -0
- package/src/local/query/client.ts +197 -0
- package/src/local/query/types.ts +102 -0
- package/src/local/schema/serialize.ts +1 -0
- package/src/local/store/queryApi.ts +56 -0
- package/src/local/storeContract.ts +146 -0
- package/src/local/stores/DatabaseManager.ts +507 -0
- package/src/local/stores/ObjectStore.ts +449 -0
- package/src/local/stores/ObjectStoreContract.ts +48 -0
- package/src/local/stores/StoreManager.ts +388 -0
- package/src/local/stores/SyncActionStore.ts +579 -0
- package/src/local/stores/openIDBWithTimeout.ts +195 -0
- package/src/local/stores/persistenceCleanup.ts +43 -0
- package/src/local/stores/persistenceIdentity.ts +83 -0
- package/src/local/stores/syncAction.ts +21 -0
- package/src/local/stores/v1PersistenceDeletion.ts +21 -0
- package/src/local/sync/BootstrapFetcher.ts +1224 -0
- package/src/local/sync/ConnectionManager.ts +15 -0
- package/src/local/sync/OnDemandLoader.ts +927 -0
- package/src/local/sync/SubscriptionManager.ts +300 -0
- package/src/local/sync/SyncWebSocket.ts +584 -0
- package/src/local/sync/bootstrapApply.ts +130 -0
- package/src/local/sync/commitFrames.ts +16 -0
- package/src/local/sync/connectionManagerLifecycle.ts +158 -0
- package/src/local/sync/contextPorts.ts +37 -0
- package/src/local/sync/createClaimStream.ts +668 -0
- package/src/local/sync/createSnapshot.ts +160 -0
- package/src/local/sync/credentialLifecycle.ts +18 -0
- package/src/local/sync/deltaPipeline.ts +473 -0
- package/src/local/sync/groupChange.ts +343 -0
- package/src/local/sync/initialize.ts +205 -0
- package/src/local/sync/participants.ts +564 -0
- package/src/local/sync/persistedPrefix.ts +27 -0
- package/src/local/sync/reconnect.ts +88 -0
- package/src/local/sync/schemaDrift.ts +86 -0
- package/src/local/sync/schemas.ts +118 -0
- package/src/local/sync/socketEventWiring.ts +196 -0
- package/src/local/sync/syncCursor.ts +62 -0
- package/src/local/sync/syncPlan.ts +89 -0
- package/src/local/sync/terminalSessionLifecycle.ts +66 -0
- package/src/local/sync/wsFrameHandlers.ts +20 -0
- package/src/local/transactions/databaseCommitOutbox.ts +33 -0
- package/src/local/transactions/localMutation.ts +58 -0
- package/src/local/transactions/mutations/MutationQueue.ts +1998 -0
- package/src/local/transactions/mutations/MutationStore.ts +65 -0
- package/src/local/transactions/mutations/UnconfirmedWrites.ts +133 -0
- package/src/local/transactions/mutations/batchProcessing.ts +469 -0
- package/src/local/transactions/mutations/coalesceRules.ts +192 -0
- package/src/local/transactions/mutations/commitApi.ts +97 -0
- package/src/local/transactions/mutations/commitLane.ts +191 -0
- package/src/local/transactions/mutations/commitLatency.ts +164 -0
- package/src/local/transactions/mutations/commitPayload.ts +281 -0
- package/src/local/transactions/mutations/commitTransport.ts +174 -0
- package/src/local/transactions/mutations/deltaConfirmation.ts +298 -0
- package/src/local/transactions/mutations/durableCommitRestore.ts +128 -0
- package/src/local/transactions/mutations/durableWriteStore.ts +21 -0
- package/src/local/transactions/mutations/executionSelection.ts +42 -0
- package/src/local/transactions/mutations/failureHandling.ts +154 -0
- package/src/local/transactions/mutations/failurePolicy.ts +61 -0
- package/src/local/transactions/mutations/localMutation.ts +135 -0
- package/src/local/transactions/mutations/modelOperations.ts +210 -0
- package/src/local/transactions/mutations/mutationPersistence.ts +231 -0
- package/src/local/transactions/mutations/pendingDrain.ts +160 -0
- package/src/local/transactions/mutations/processingScheduler.ts +35 -0
- package/src/local/transactions/mutations/queueCoalescing.ts +45 -0
- package/src/local/transactions/mutations/replayValidation.ts +192 -0
- package/src/local/transactions/reconnectDrain.ts +24 -0
- package/src/local/utils/mobxSetup.ts +388 -0
- package/src/local/views/QueryView.ts +311 -0
- package/src/local/views/ViewRegistry.ts +61 -0
- package/src/local/views/incrementalView.ts +92 -0
- package/src/plugin.ts +396 -0
- package/src/presenceStream.ts +279 -0
- package/src/react/AbloProvider.tsx +744 -0
- package/src/react/ClientSideSuspense.tsx +57 -0
- package/src/react/DefaultFallback.tsx +60 -0
- package/src/react/context.ts +89 -0
- package/src/react/createAbloReact.ts +116 -0
- package/src/react/internalContext.ts +38 -0
- package/src/react/useAblo.ts +280 -0
- package/src/react/useCurrentUserId.ts +17 -0
- package/src/react/useErrorListener.ts +22 -0
- package/src/react/useMutationFailureListener.ts +34 -0
- package/src/react/useMutators.ts +184 -0
- package/src/react/useSyncStatus.ts +42 -0
- package/src/react/useUndoScope.ts +143 -0
- package/src/react.ts +69 -0
- package/src/reactRuntime.ts +10 -0
- package/src/surface.ts +106 -0
- package/src/useReactive.ts +51 -0
|
@@ -0,0 +1,1516 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The base class that application-specific sync stores extend. It supplies the
|
|
3
|
+
* shared orchestration for reads, writes, delta processing, and bootstrap, and
|
|
4
|
+
* exports the core types those stores build on.
|
|
5
|
+
*
|
|
6
|
+
* A subclass adds its own domain behavior — lazy-loaded relations,
|
|
7
|
+
* collaboration events, and model enrichment — by overriding the protected
|
|
8
|
+
* extension points defined here. The heavy lifting is delegated to injected
|
|
9
|
+
* collaborators: {@link SyncClient} owns pool writes and the transaction
|
|
10
|
+
* queue, {@link Database} owns local persistence, {@link InstanceCache} holds the
|
|
11
|
+
* in-memory models, and {@link ModelRegistry} holds their metadata.
|
|
12
|
+
*/
|
|
13
|
+
import { makeObservable, observable, action, computed, runInAction } from 'mobx';
|
|
14
|
+
import { AbloConnectionError, AbloValidationError, toAbloError } from '@abloatai/transaction/errors';
|
|
15
|
+
import { ConnectionManager } from './sync/ConnectionManager.js';
|
|
16
|
+
import { contextLogger, contextSocketObservability } from './sync/contextPorts.js';
|
|
17
|
+
import { SubscriptionManager } from './sync/SubscriptionManager.js';
|
|
18
|
+
import { resolveParticipantSyncGroups, } from './sync/participants.js';
|
|
19
|
+
import { ModelRegistry } from './ModelRegistry.js';
|
|
20
|
+
import { PropertyType } from '@abloatai/transaction/types';
|
|
21
|
+
import { SyncWebSocket, } from './sync/SyncWebSocket.js';
|
|
22
|
+
import { QueryProcessor } from './query/QueryProcessor.js';
|
|
23
|
+
import { Model, rowAsModel } from './Model.js';
|
|
24
|
+
import { globalRuntime } from './context.js';
|
|
25
|
+
import { AbloSessionError, isAccessCredentialExpiryCloseReason } from '@abloatai/transaction/errors';
|
|
26
|
+
import { ModelScope } from './InstanceCache.js';
|
|
27
|
+
import { LazyReferenceCollection } from './LazyReferenceCollection.js';
|
|
28
|
+
import { deriveSyncPlanFromSchema } from './sync/syncPlan.js';
|
|
29
|
+
import { CredentialLifecycle } from './sync/credentialLifecycle.js';
|
|
30
|
+
import { TerminalSessionLifecycle } from './sync/terminalSessionLifecycle.js';
|
|
31
|
+
import { wireSocketEvents } from './sync/socketEventWiring.js';
|
|
32
|
+
import { performReconnect as runReconnect } from './sync/reconnect.js';
|
|
33
|
+
import { initialize as runInitialize } from './sync/initialize.js';
|
|
34
|
+
import { createConnectionManager as runCreateConnectionManager, startConnectionManager as runStartConnectionManager, waitForWebSocketConnected as runWaitForWebSocketConnected, } from './sync/connectionManagerLifecycle.js';
|
|
35
|
+
import * as groupChange from './sync/groupChange.js';
|
|
36
|
+
import * as bootstrapApply from './sync/bootstrapApply.js';
|
|
37
|
+
import * as deltaPipeline from './sync/deltaPipeline.js';
|
|
38
|
+
import { queryByClass as runQueryByClass, countModels } from './store/queryApi.js';
|
|
39
|
+
/**
|
|
40
|
+
* Bootstrap retry configuration.
|
|
41
|
+
*
|
|
42
|
+
* There is deliberately no overall timeout here. How long one attempt may run
|
|
43
|
+
* is not a policy this layer gets to invent — it is a property of the fetcher's
|
|
44
|
+
* watchdogs, read from `BootstrapFetcher.budgetMs`. A second number kept here
|
|
45
|
+
* would only be able to disagree with them, which is exactly what it used to do.
|
|
46
|
+
*/
|
|
47
|
+
export const BOOTSTRAP_CONFIG = {
|
|
48
|
+
MAX_RETRY_ATTEMPTS: 3,
|
|
49
|
+
RETRY_DELAY_MS: 500,
|
|
50
|
+
};
|
|
51
|
+
// Re-export for clean API
|
|
52
|
+
export { ModelScope };
|
|
53
|
+
// deriveSyncPlanFromSchema derives a sync plan from a schema and is
|
|
54
|
+
// re-exported here.
|
|
55
|
+
export { deriveSyncPlanFromSchema } from './sync/syncPlan.js';
|
|
56
|
+
// ── Base class ──────────────────────────────────────────────────────────────
|
|
57
|
+
/**
|
|
58
|
+
* The abstract base class that application-specific sync stores extend. It
|
|
59
|
+
* carries the injected collaborators, the observable sync status, and the
|
|
60
|
+
* orchestration for initialization, delta processing, bootstrap, and the
|
|
61
|
+
* read and write API. A subclass supplies its own domain behavior by
|
|
62
|
+
* overriding the protected extension points defined here and by typing its
|
|
63
|
+
* collaboration events through the generic parameter.
|
|
64
|
+
*
|
|
65
|
+
* A subclass must call `super(dependencies, config)` and then set up its own
|
|
66
|
+
* MobX observables.
|
|
67
|
+
*
|
|
68
|
+
* Generic over `TCollaboration` — an app-defined event map for real-time
|
|
69
|
+
* collaboration events (cursors, selections, presence beyond the core set).
|
|
70
|
+
* Subclasses pass their own event map to get typed `subscribe()` calls on
|
|
71
|
+
* the underlying SyncWebSocket without casts:
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* interface EditorEvents {
|
|
75
|
+
* 'document:selection': [SelectionEvent];
|
|
76
|
+
* 'document:cursor': [CursorEvent];
|
|
77
|
+
* }
|
|
78
|
+
* class EditorStore extends BaseSyncedStore<EditorEvents> {
|
|
79
|
+
* subscribeToCursor(handler: (e: CursorEvent) => void) {
|
|
80
|
+
* return this.syncWebSocket.subscribe('document:cursor', handler);
|
|
81
|
+
* }
|
|
82
|
+
* }
|
|
83
|
+
*/
|
|
84
|
+
export class BaseSyncedStore {
|
|
85
|
+
// ── Observable sync status for UI ──
|
|
86
|
+
syncStatus = {
|
|
87
|
+
state: 'idle',
|
|
88
|
+
progress: 0,
|
|
89
|
+
pendingChanges: 0,
|
|
90
|
+
isSessionError: false,
|
|
91
|
+
};
|
|
92
|
+
// ── Injected dependencies ──
|
|
93
|
+
/** The owning client's runtime; the module-global bridge when constructed directly. */
|
|
94
|
+
runtime;
|
|
95
|
+
/** The installed plugins the delta pipeline dispatches stage handlers to. */
|
|
96
|
+
stagePlugins;
|
|
97
|
+
syncClient;
|
|
98
|
+
database;
|
|
99
|
+
objectPool;
|
|
100
|
+
modelRegistry;
|
|
101
|
+
auth;
|
|
102
|
+
/**
|
|
103
|
+
* Schema the store was constructed with. Used by the schema-typed
|
|
104
|
+
* `create(key, data)` factory and model self-healing.
|
|
105
|
+
*/
|
|
106
|
+
schema;
|
|
107
|
+
// ── Real-time sync ──
|
|
108
|
+
/**
|
|
109
|
+
* The connection, owned by whoever built this store (ADR 0016 follow-up
|
|
110
|
+
* 3b): the host constructs it and hands it in, the store seeds its late
|
|
111
|
+
* values during `initialize()` and owns the lifecycle from there. One
|
|
112
|
+
* instance for the store's whole lifetime — reconnects replace the socket
|
|
113
|
+
* inside it, never the object.
|
|
114
|
+
*/
|
|
115
|
+
syncWebSocket;
|
|
116
|
+
/**
|
|
117
|
+
* Dynamic read interest (area-of-interest) over the connection's sync
|
|
118
|
+
* groups. Constructed with the connection; the permanent base scopes are
|
|
119
|
+
* seeded in `setupWebSocketSync` once identity resolves.
|
|
120
|
+
*/
|
|
121
|
+
areaOfInterest;
|
|
122
|
+
/** Sync groups whose current state has been backfilled into the pool
|
|
123
|
+
* (hydrate-on-enter). Cleared when the pool is reset on (re)bootstrap. */
|
|
124
|
+
hydratedGroups = new Set();
|
|
125
|
+
/** In-flight scoped hydrations, keyed by group — single-flights concurrent
|
|
126
|
+
* enters of the same scope so they share one fetch. */
|
|
127
|
+
hydratingGroups = new Map();
|
|
128
|
+
_syncServerUrl;
|
|
129
|
+
/** Application-declared collaboration event types; empty unless configured. */
|
|
130
|
+
_collaborationEvents = [];
|
|
131
|
+
/**
|
|
132
|
+
* Public accessor for the underlying SyncWebSocket. Used by the
|
|
133
|
+
* factory in `createSyncEngine` to wire the default mutation
|
|
134
|
+
* executor — the executor needs the WS handle to send commit
|
|
135
|
+
* frames, and the factory can't reach `protected` state through
|
|
136
|
+
* normal typing.
|
|
137
|
+
*/
|
|
138
|
+
getSyncWebSocket() {
|
|
139
|
+
return this.syncWebSocket;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Subscribe to pushed frames — deltas, presence updates, claim grants and
|
|
143
|
+
* losses, connection changes, and this store's collaboration events.
|
|
144
|
+
* Durable by construction: the connection object exists for the store's
|
|
145
|
+
* whole lifetime (reconnects replace only the socket inside it), so a
|
|
146
|
+
* subscription made before the first connect starts delivering when the
|
|
147
|
+
* socket opens and keeps delivering across every reconnect. Returns the
|
|
148
|
+
* unsubscribe function.
|
|
149
|
+
*/
|
|
150
|
+
subscribe(event, handler) {
|
|
151
|
+
return this.syncWebSocket.subscribe(event, handler);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Send a collaboration event (an app-specific real-time message from this
|
|
155
|
+
* store's `TCollaboration` map). A no-op while the connection is down —
|
|
156
|
+
* presence-grade traffic is not queued.
|
|
157
|
+
*/
|
|
158
|
+
sendCollaborationEvent(messageType, payload) {
|
|
159
|
+
this.syncWebSocket.sendCollaborationEvent(messageType, payload);
|
|
160
|
+
}
|
|
161
|
+
// ── Area-of-interest (dynamic read subscription) ─────────────────
|
|
162
|
+
//
|
|
163
|
+
// `enterScope`/`leaveScope` move the connection's read interest as the
|
|
164
|
+
// user navigates (open or close a record); `pinScope`/`unpinScope`
|
|
165
|
+
// express prominence (an active claim keeps a group subscribed). All four
|
|
166
|
+
// resolve the scope to sync-group strings through the same resolver the
|
|
167
|
+
// claim path uses (`resolveParticipantSyncGroups`), so read interest and
|
|
168
|
+
// write claims always agree on the string for a given entity. Before the
|
|
169
|
+
// connection opens they record interest without a wire send, and they
|
|
170
|
+
// never reject when the transport is offline (see
|
|
171
|
+
// {@link SubscriptionManager.reconcile}); the on-connect `resync` pushes
|
|
172
|
+
// whatever interest accumulated.
|
|
173
|
+
scopeToGroups(scope) {
|
|
174
|
+
return resolveParticipantSyncGroups(scope, this.schema);
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Bring a scope into view and subscribe to its sync groups. With
|
|
178
|
+
* `{ hydrate: true }`, also backfill the groups' current state into the pool
|
|
179
|
+
* once the subscription is active. The order matters: subscribing first
|
|
180
|
+
* guarantees no live delta is missed in the gap before the snapshot lands.
|
|
181
|
+
* Hydration is best-effort — a failed backfill never rejects `enterScope`,
|
|
182
|
+
* and the live delta stream keeps flowing regardless.
|
|
183
|
+
*/
|
|
184
|
+
enterScope(scope, opts) {
|
|
185
|
+
const groups = this.scopeToGroups(scope);
|
|
186
|
+
const subscribed = Promise.all(groups.map((g) => this.areaOfInterest.enter(g))).then(() => undefined);
|
|
187
|
+
if (!opts?.hydrate)
|
|
188
|
+
return subscribed;
|
|
189
|
+
return subscribed.then(() => this.hydrateGroups(groups));
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Backfill the current state of `syncGroups` into the pool with a side-effect-free
|
|
193
|
+
* scoped snapshot fetch followed by the version-guarded scoped apply. The call
|
|
194
|
+
* is idempotent (it skips groups already hydrated) and single-flight (concurrent
|
|
195
|
+
* enters of the same group share one fetch). On error the groups are left
|
|
196
|
+
* unmarked, so a later re-enter retries.
|
|
197
|
+
*/
|
|
198
|
+
async hydrateGroups(syncGroups) {
|
|
199
|
+
const need = syncGroups.filter((g) => !this.hydratedGroups.has(g) && !this.hydratingGroups.has(g));
|
|
200
|
+
if (need.length === 0) {
|
|
201
|
+
// Nothing new to fetch, but await any in-flight hydration for the
|
|
202
|
+
// requested groups so callers can sequence on completion.
|
|
203
|
+
await Promise.all(syncGroups
|
|
204
|
+
.map((g) => this.hydratingGroups.get(g))
|
|
205
|
+
.filter((p) => p !== undefined));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const work = (async () => {
|
|
209
|
+
try {
|
|
210
|
+
const data = await this.database.fetchScopedBootstrapData(need);
|
|
211
|
+
this.syncClient.applyBootstrapDataToPool(data, undefined, { scoped: true });
|
|
212
|
+
for (const g of need)
|
|
213
|
+
this.hydratedGroups.add(g);
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
this.runtime.logger.debug('[BaseSyncedStore] scoped hydrate failed', {
|
|
217
|
+
syncGroups: need,
|
|
218
|
+
error: err instanceof Error ? err.message : String(err),
|
|
219
|
+
});
|
|
220
|
+
// Soft-fail — leave `need` un-hydrated so a re-enter retries.
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
for (const g of need)
|
|
224
|
+
this.hydratingGroups.delete(g);
|
|
225
|
+
}
|
|
226
|
+
})();
|
|
227
|
+
for (const g of need)
|
|
228
|
+
this.hydratingGroups.set(g, work);
|
|
229
|
+
await work;
|
|
230
|
+
}
|
|
231
|
+
/** Leave a scope → its groups go warm (hysteresis), then drop on sweep. */
|
|
232
|
+
leaveScope(scope) {
|
|
233
|
+
return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.leave(g))).then(() => undefined);
|
|
234
|
+
}
|
|
235
|
+
/** Pin a scope (active claim / prominence) → never warms while pinned. */
|
|
236
|
+
pinScope(scope) {
|
|
237
|
+
return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.pin(g))).then(() => undefined);
|
|
238
|
+
}
|
|
239
|
+
/** Release a pin → the group transitions to warm rather than dropping. */
|
|
240
|
+
unpinScope(scope) {
|
|
241
|
+
return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.unpin(g))).then(() => undefined);
|
|
242
|
+
}
|
|
243
|
+
// ── Internal helpers ──
|
|
244
|
+
queryProcessor;
|
|
245
|
+
/**
|
|
246
|
+
* Runtime behavior flags only — the schema/config arrays
|
|
247
|
+
* (`enrichmentPlan`, `foreignKeyIndexes`) are consumed at construction
|
|
248
|
+
* time and stored on the instance as `enrichmentPlan` and
|
|
249
|
+
* pool-registered indexes. They don't need to persist on `this.config`.
|
|
250
|
+
*/
|
|
251
|
+
config;
|
|
252
|
+
disposers = [];
|
|
253
|
+
initialized = false;
|
|
254
|
+
dataReady = false;
|
|
255
|
+
// ── User context ──
|
|
256
|
+
// The identity the consumer supplied to `initialize()`: user id,
|
|
257
|
+
// organization id, and optional team ids. Reads are scoped to this
|
|
258
|
+
// identity, and the sync-group subscription is derived from it.
|
|
259
|
+
userContext = null;
|
|
260
|
+
// ── Smart sync ──
|
|
261
|
+
/**
|
|
262
|
+
* Declarative enrichment plan: "for model X, when a delta arrives,
|
|
263
|
+
* read data[foreignKey] and attach the matching parent from the pool
|
|
264
|
+
* as data[relationKey]." Merged from schema-derived + config at
|
|
265
|
+
* construction time. Replaces the `enrichRelations` subclass override
|
|
266
|
+
* pattern.
|
|
267
|
+
*/
|
|
268
|
+
enrichmentPlan = [];
|
|
269
|
+
smartSyncOptions;
|
|
270
|
+
pendingDeltas = [];
|
|
271
|
+
batchTimer = null;
|
|
272
|
+
syncPromise = null;
|
|
273
|
+
/** Resume/ack cursor — delegates to the shared LogPosition (see
|
|
274
|
+
* logPosition.ts). Advances only after IDB persistence. */
|
|
275
|
+
get lastAckedId() {
|
|
276
|
+
return this.syncClient.position.persisted;
|
|
277
|
+
}
|
|
278
|
+
/** Pool-applied cursor — delegates to the shared LogPosition. */
|
|
279
|
+
get highestProcessedSyncId() {
|
|
280
|
+
return this.syncClient.position.applied;
|
|
281
|
+
}
|
|
282
|
+
// ── Delta queuing during bootstrap ──
|
|
283
|
+
bootstrapDeltaQueue = null;
|
|
284
|
+
activeBootstrapCount = 0;
|
|
285
|
+
/** The live deadline for the bootstrap attempt in flight, if any. */
|
|
286
|
+
bootstrapDeadlineTimer = null;
|
|
287
|
+
// ── Delete tracking ──
|
|
288
|
+
pendingDeletes = new Set();
|
|
289
|
+
// ── Model type hydration ──
|
|
290
|
+
modelTypesHydrated = new Set();
|
|
291
|
+
modelTypeHydrationInFlight = new Map();
|
|
292
|
+
constructor(dependencies, config = {}) {
|
|
293
|
+
this.runtime = dependencies.runtime ?? globalRuntime;
|
|
294
|
+
this.stagePlugins = dependencies.stagePlugins ?? [];
|
|
295
|
+
this.syncClient = dependencies.syncClient;
|
|
296
|
+
this.database = dependencies.database;
|
|
297
|
+
this.objectPool = dependencies.objectPool;
|
|
298
|
+
this.modelRegistry = dependencies.modelRegistry;
|
|
299
|
+
this.auth = dependencies.auth;
|
|
300
|
+
this.schema = dependencies.schema;
|
|
301
|
+
this.terminalSessionLifecycle = new TerminalSessionLifecycle({
|
|
302
|
+
runtime: this.runtime,
|
|
303
|
+
listeners: this.sessionErrorListeners,
|
|
304
|
+
purgeAuthenticatedState: () => this.purge(),
|
|
305
|
+
updateSyncStatus: (updates) => { this.updateSyncStatus(updates); },
|
|
306
|
+
});
|
|
307
|
+
this._syncServerUrl = dependencies.url;
|
|
308
|
+
this._collaborationEvents = config.collaborationEvents ?? [];
|
|
309
|
+
// The connection exists from construction (ADR 0016 follow-up 3b): the
|
|
310
|
+
// host hands one in, or the store builds its own. `deferConnect` holds
|
|
311
|
+
// it closed until `initialize()` has seeded identity and read scope, so
|
|
312
|
+
// nothing can open an unscoped connection in between.
|
|
313
|
+
this.syncWebSocket =
|
|
314
|
+
dependencies.syncWebSocket ??
|
|
315
|
+
new SyncWebSocket({
|
|
316
|
+
baseUrl: this._syncServerUrl,
|
|
317
|
+
collaborationEvents: [...this._collaborationEvents],
|
|
318
|
+
getAuthToken: this.auth?.getAuthToken,
|
|
319
|
+
deferConnect: true,
|
|
320
|
+
capabilities: {
|
|
321
|
+
partialBootstrap: true,
|
|
322
|
+
compressedDeltas: true,
|
|
323
|
+
streamingBootstrap: true,
|
|
324
|
+
batchedDeltas: true,
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
this.areaOfInterest = new SubscriptionManager({ transport: this.syncWebSocket });
|
|
328
|
+
this.wireSocketEvents();
|
|
329
|
+
// QueuedMutation events for pendingChanges tracking — connection-
|
|
330
|
+
// independent, wired once for the store's lifetime.
|
|
331
|
+
this.disposers.push(this.syncClient.onTransactionEvent('created', () => { this.incrementPendingChanges(); }), this.syncClient.onTransactionEvent('completed', () => { this.decrementPendingChanges(); }), this.syncClient.onTransactionEvent('failed', () => { this.decrementPendingChanges(); }));
|
|
332
|
+
// Set this store as the global Model store
|
|
333
|
+
Model.setStore(this);
|
|
334
|
+
// ── Schema-derived sync plan ───────────────────────────────────────
|
|
335
|
+
//
|
|
336
|
+
// When a schema is provided, derive foreign-key indexes and the
|
|
337
|
+
// enrichment plan from the declarative annotations on its `belongsTo`
|
|
338
|
+
// relations. Explicit config fields layer on top, so a subclass can
|
|
339
|
+
// pass hardcoded arrays without supplying a full schema.
|
|
340
|
+
//
|
|
341
|
+
// Order matters: schema-derived entries are registered first and
|
|
342
|
+
// config entries second, so that when a caller supplies both, the
|
|
343
|
+
// explicit config entries win and are never shadowed by derivation.
|
|
344
|
+
const derived = dependencies.schema
|
|
345
|
+
? deriveSyncPlanFromSchema(dependencies.schema)
|
|
346
|
+
: { enrichmentPlan: [], foreignKeyIndexes: [] };
|
|
347
|
+
const mergedForeignKeyIndexes = [
|
|
348
|
+
...derived.foreignKeyIndexes,
|
|
349
|
+
...(config.foreignKeyIndexes ?? []),
|
|
350
|
+
];
|
|
351
|
+
for (const { modelName, fieldName } of mergedForeignKeyIndexes) {
|
|
352
|
+
this.objectPool.registerForeignKey(modelName, fieldName);
|
|
353
|
+
}
|
|
354
|
+
// Override hook — called after schema-driven registration so a subclass
|
|
355
|
+
// can add more foreign keys on top of the declarative set.
|
|
356
|
+
this.registerForeignKeys();
|
|
357
|
+
this.enrichmentPlan = [
|
|
358
|
+
...derived.enrichmentPlan,
|
|
359
|
+
...(config.enrichmentPlan ?? []),
|
|
360
|
+
];
|
|
361
|
+
// Set dependencies for LazyReferenceCollection
|
|
362
|
+
LazyReferenceCollection.setDependencies(this.database, this.objectPool);
|
|
363
|
+
// Apply config defaults
|
|
364
|
+
this.config = {
|
|
365
|
+
enableOffline: config.enableOffline ?? true,
|
|
366
|
+
enableCache: config.enableCache ?? true,
|
|
367
|
+
enableTelemetry: config.enableTelemetry ?? false,
|
|
368
|
+
};
|
|
369
|
+
// Smart sync options
|
|
370
|
+
this.smartSyncOptions = {
|
|
371
|
+
maxDeltasBeforeBootstrap: 1000,
|
|
372
|
+
maxBootstrapSize: 10 * 1024 * 1024,
|
|
373
|
+
batchingDelay: 100,
|
|
374
|
+
maxBatchSize: 50,
|
|
375
|
+
};
|
|
376
|
+
// Create internal helpers
|
|
377
|
+
this.queryProcessor = new QueryProcessor({
|
|
378
|
+
enableCache: this.config.enableCache,
|
|
379
|
+
});
|
|
380
|
+
// Auto-invalidate query cache when SyncClient modifies the pool.
|
|
381
|
+
// Replaces all manual queryProcessor.invalidateCache() calls.
|
|
382
|
+
this.syncClient.on('models:changed', (modelNames) => {
|
|
383
|
+
for (const name of modelNames) {
|
|
384
|
+
this.queryProcessor.invalidateCache(`.*${name}.*`);
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
// Make the sync-status fields observable so consumer code can do
|
|
388
|
+
// reaction(() => store.isReady, ...)
|
|
389
|
+
// observer(() => store.isOffline)
|
|
390
|
+
// and actually receive notifications. Without these annotations,
|
|
391
|
+
// `syncStatus` and `dataReady` are plain properties, and the derived
|
|
392
|
+
// getters (isReady, isSyncing, isOffline, and the rest) never emit
|
|
393
|
+
// change signals — so a `reaction` on `store.isReady` would never fire.
|
|
394
|
+
makeObservable(this, {
|
|
395
|
+
syncStatus: observable,
|
|
396
|
+
dataReady: observable,
|
|
397
|
+
isReady: computed,
|
|
398
|
+
isSyncing: computed,
|
|
399
|
+
isOffline: computed,
|
|
400
|
+
isReconnecting: computed,
|
|
401
|
+
isError: computed,
|
|
402
|
+
hasUnsyncedChanges: computed,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
// ── Protected extension points ────────────────────────────────────────────
|
|
406
|
+
/**
|
|
407
|
+
* Register foreign-key indexes for constant-time lookups.
|
|
408
|
+
*
|
|
409
|
+
* This is an override hook. The preferred way to declare a foreign-key
|
|
410
|
+
* index is `config.foreignKeyIndexes` at construction time, or marking the
|
|
411
|
+
* `belongsTo` relation with `{ index: true }` in the schema. The hook fires
|
|
412
|
+
* after the schema-derived and config registrations, so a subclass can
|
|
413
|
+
* layer additional indexes on top.
|
|
414
|
+
*/
|
|
415
|
+
registerForeignKeys() { }
|
|
416
|
+
/**
|
|
417
|
+
* Enrich delta data with related models from the InstanceCache.
|
|
418
|
+
*
|
|
419
|
+
* Base implementation walks `this.enrichmentPlan` — entries populated
|
|
420
|
+
* from the schema's `{ enrich: true }` relations and from
|
|
421
|
+
* `config.enrichmentPlan`. Subclasses can still override for bespoke
|
|
422
|
+
* logic, calling `super.enrichRelations(modelName, data)` first to
|
|
423
|
+
* apply the declarative plan before layering on custom work.
|
|
424
|
+
*
|
|
425
|
+
* Enrichment is best-effort: if the parent isn't yet in the pool
|
|
426
|
+
* (e.g., a child delta arrives before its parent in a bootstrap
|
|
427
|
+
* batch), the entry is silently skipped and the data passes through
|
|
428
|
+
* untouched. The next delta for the same child will re-enrich.
|
|
429
|
+
*/
|
|
430
|
+
enrichRelations(modelName, data) {
|
|
431
|
+
for (const entry of this.enrichmentPlan) {
|
|
432
|
+
if (entry.modelName !== modelName)
|
|
433
|
+
continue;
|
|
434
|
+
const fkValue = data[entry.foreignKey];
|
|
435
|
+
if (typeof fkValue !== 'string')
|
|
436
|
+
continue;
|
|
437
|
+
const parent = this.objectPool.get(fkValue);
|
|
438
|
+
if (parent) {
|
|
439
|
+
data[entry.relationKey] = parent;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return data;
|
|
443
|
+
}
|
|
444
|
+
/** Check if a model name represents a custom/dynamic entity type. */
|
|
445
|
+
isCustomEntity(modelName) {
|
|
446
|
+
return !this.objectPool.registry.getModelByName(modelName);
|
|
447
|
+
}
|
|
448
|
+
/** Create a custom entity instance from delta data. Override for domain-specific custom entities. */
|
|
449
|
+
createCustomEntity(_modelName, _modelId, _data) {
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
/** Called before save for domain-specific validation/self-healing. */
|
|
453
|
+
beforeSave(_model) { }
|
|
454
|
+
/** Connection lifecycle event callback — set by subclass to wire connection state machine. */
|
|
455
|
+
onConnectionEvent;
|
|
456
|
+
/**
|
|
457
|
+
* Internal connection FSM. Owns network probe + backoff + reconnect
|
|
458
|
+
* orchestration for the default path. Constructed lazily once we
|
|
459
|
+
* have a user context + a WebSocket (see `wireWebSocketEvents`);
|
|
460
|
+
* driven by the `onConnectionEvent` hook AND browser online/offline
|
|
461
|
+
* events it sets up itself.
|
|
462
|
+
*
|
|
463
|
+
* Every consumer gets production-grade offline-to-online recovery
|
|
464
|
+
* out of the box. Subclasses that want their own lifecycle owner
|
|
465
|
+
* can disable this by overriding `createConnectionManager()` to
|
|
466
|
+
* return null.
|
|
467
|
+
*/
|
|
468
|
+
connectionManager = null;
|
|
469
|
+
/**
|
|
470
|
+
* Access-credential re-mint + proactive pre-roll — extracted to
|
|
471
|
+
* sync/credentialLifecycle.ts. Owns the refresher hook, the single-flight
|
|
472
|
+
* guard, and the browser-only refresh timer / wake listener; talks back
|
|
473
|
+
* through three lazily-resolved callbacks (the ConnectionManager doesn't
|
|
474
|
+
* exist until `setupWebSocketSync`). The `setCredentialRefresher` /
|
|
475
|
+
* `performCredentialRefresh` / `startCredentialLifecycle` methods below
|
|
476
|
+
* are thin delegates so the store's public surface is unchanged.
|
|
477
|
+
*/
|
|
478
|
+
credentialLifecycle = new CredentialLifecycle({
|
|
479
|
+
setAuthToken: (token) => { this.auth?.setAuthToken(token); },
|
|
480
|
+
nudgeReconnect: () => { this.nudgeReconnect(); },
|
|
481
|
+
reportSessionExpired: () => {
|
|
482
|
+
this.connectionManager?.send({ type: 'BOOTSTRAP_FAILED_SESSION' });
|
|
483
|
+
},
|
|
484
|
+
}, contextLogger);
|
|
485
|
+
/**
|
|
486
|
+
* Listeners registered via `subscribeSessionError()`. Fired when the
|
|
487
|
+
* WebSocket closes with a session-invalid code (1008/4001/4003) or a
|
|
488
|
+
* session-error event is received. Separate from `onConnectionEvent`
|
|
489
|
+
* (which exists for the ConnectionStore FSM) so multiple consumers —
|
|
490
|
+
* typically `<AbloProvider>` and a connection-lifecycle owner — can
|
|
491
|
+
* both react without racing on the single-callback slot.
|
|
492
|
+
*/
|
|
493
|
+
sessionErrorListeners = new Set();
|
|
494
|
+
terminalSessionLifecycle;
|
|
495
|
+
/**
|
|
496
|
+
* Subscribe to session-error events. The returned function removes
|
|
497
|
+
* the listener. Safe to call multiple times from different consumers
|
|
498
|
+
* (each gets its own slot in the listener set).
|
|
499
|
+
*/
|
|
500
|
+
subscribeSessionError(listener) {
|
|
501
|
+
this.sessionErrorListeners.add(listener);
|
|
502
|
+
return () => { this.sessionErrorListeners.delete(listener); };
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Subscribe to per-mutation failure payloads. Forwarded from the
|
|
506
|
+
* underlying `SyncClient.mutationQueue` so consumers (toast layer,
|
|
507
|
+
* route-level reverted boundaries, telemetry) can react without
|
|
508
|
+
* reaching across the store. Returns an unsubscribe function.
|
|
509
|
+
*
|
|
510
|
+
* Why this lives on the base store rather than SyncClient: the React
|
|
511
|
+
* `<AbloProvider>` binds against this surface, so adding it here
|
|
512
|
+
* keeps the engine's internal wiring private while still giving the
|
|
513
|
+
* SDK a single hook to expose. Mirrors `subscribeSessionError` —
|
|
514
|
+
* same shape, same lifecycle.
|
|
515
|
+
*/
|
|
516
|
+
subscribeMutationFailure(listener) {
|
|
517
|
+
return this.syncClient.onMutationFailure(listener);
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Subscribe to commit round-trip latency. Forwarded from the underlying
|
|
521
|
+
* `SyncClient` for the same reason as `subscribeMutationFailure` — the
|
|
522
|
+
* React provider binds against this surface, so the engine's wiring stays
|
|
523
|
+
* private while the SDK keeps one hook to expose.
|
|
524
|
+
*/
|
|
525
|
+
subscribeCommitLatency(listener) {
|
|
526
|
+
return this.syncClient.onCommitLatency(listener);
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Wait for the in-flight transaction for (modelName, modelId) to be
|
|
530
|
+
* confirmed by the server. See `SyncClient.waitForConfirmation` for the
|
|
531
|
+
* lookup contract; resolves immediately if nothing is in flight.
|
|
532
|
+
*/
|
|
533
|
+
waitForConfirmation(modelName, modelId) {
|
|
534
|
+
return this.syncClient.waitForConfirmation(modelName, modelId);
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Observe the LOCAL mutation stream for undo recording (see
|
|
538
|
+
* {@link import('./storeContract.js').LocalMutation}). Taps the
|
|
539
|
+
* MutationQueue's `transaction:created` event — fired once per local
|
|
540
|
+
* create/update/delete/archive with `previousData` already captured.
|
|
541
|
+
* Remote/collaborator deltas apply via `applyDeltaBatchToPool` and never
|
|
542
|
+
* emit here, so undo is naturally local-only (you can't undo a teammate).
|
|
543
|
+
*/
|
|
544
|
+
subscribeLocalMutations(handler) {
|
|
545
|
+
// Tap the MutationQueue directly via `onLocalTransaction`. The previous
|
|
546
|
+
// `syncClient.subscribe('transaction:created', …)` route registered the
|
|
547
|
+
// handler on SyncClient's OWN emitter, which never fires that event (only
|
|
548
|
+
// the queue's emitter does) — so undo recorded nothing. See
|
|
549
|
+
// `SyncClient.onLocalTransaction` for the full rationale.
|
|
550
|
+
return this.syncClient.onLocalTransaction((tx) => {
|
|
551
|
+
if (!tx.modelName || !tx.modelId)
|
|
552
|
+
return;
|
|
553
|
+
handler({
|
|
554
|
+
type: tx.type,
|
|
555
|
+
modelName: tx.modelName,
|
|
556
|
+
modelId: tx.modelId,
|
|
557
|
+
data: tx.data ?? null,
|
|
558
|
+
previousData: tx.previousData ?? null,
|
|
559
|
+
});
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
// ── Bootstrap + Retry ────────────────────────────────────────────────────
|
|
563
|
+
/**
|
|
564
|
+
* Execute a bootstrap function with timeout protection and automatic retry.
|
|
565
|
+
* Prevents the common issue where bootstrap hangs on startup.
|
|
566
|
+
*/
|
|
567
|
+
async executeBootstrapWithTimeout(bootstrapFn, _context, signal) {
|
|
568
|
+
let lastError = null;
|
|
569
|
+
// An aborted initialize has to stop the transfer, not just stop waiting for
|
|
570
|
+
// it. Without this the caller returns while a cold start keeps downloading,
|
|
571
|
+
// and those chunks are still in flight when the next initialize begins.
|
|
572
|
+
const onCallerAbort = () => { this.database.helper.abort(); };
|
|
573
|
+
signal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
574
|
+
try {
|
|
575
|
+
for (let attempt = 1; attempt <= BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS; attempt++) {
|
|
576
|
+
if (signal?.aborted) {
|
|
577
|
+
throw new DOMException('Initialization aborted', 'AbortError');
|
|
578
|
+
}
|
|
579
|
+
// `navigator.onLine === false` is the MDN-reliable "definitely
|
|
580
|
+
// offline" signal. Don't use `!navigator.onLine`: Node 22+ exposes
|
|
581
|
+
// `globalThis.navigator` with `onLine === undefined`, so the
|
|
582
|
+
// negation false-positives every server-side bootstrap (e.g. the
|
|
583
|
+
// server-side agent.run dispatch path through `connectAgent`).
|
|
584
|
+
const navigatorOnline = typeof navigator === 'undefined' ? undefined : navigator.onLine;
|
|
585
|
+
if (navigatorOnline === false) {
|
|
586
|
+
this.runtime.observability.breadcrumb(`Bootstrap attempt ${attempt} skipped - offline`, 'sync.bootstrap', 'warning');
|
|
587
|
+
throw new AbloConnectionError('Bootstrap skipped - device is offline', {
|
|
588
|
+
code: 'bootstrap_offline',
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
try {
|
|
592
|
+
this.runtime.logger.info(`[BaseSyncedStore] Bootstrap attempt ${attempt}/${BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS}`);
|
|
593
|
+
const result = (await Promise.race([
|
|
594
|
+
bootstrapFn(),
|
|
595
|
+
this.createBootstrapTimeout(attempt),
|
|
596
|
+
]));
|
|
597
|
+
this.runtime.logger.info('[BaseSyncedStore] Bootstrap completed successfully', { attempt });
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
lastError = error;
|
|
602
|
+
const isTimeout = error instanceof Error && error.message.includes('timed out');
|
|
603
|
+
const isAbort = error instanceof DOMException && error.name === 'AbortError';
|
|
604
|
+
const isNetworkError = error instanceof TypeError && error.message.includes('fetch');
|
|
605
|
+
if (isAbort)
|
|
606
|
+
throw error;
|
|
607
|
+
if (AbloSessionError.isSessionError(error))
|
|
608
|
+
throw error;
|
|
609
|
+
const navigatorOnline = typeof navigator === 'undefined' ? undefined : navigator.onLine;
|
|
610
|
+
if (isNetworkError && navigatorOnline === false) {
|
|
611
|
+
this.runtime.observability.captureBootstrapFailure(error, { type: 'network-offline' });
|
|
612
|
+
throw error;
|
|
613
|
+
}
|
|
614
|
+
this.runtime.observability.breadcrumb(`Bootstrap attempt ${attempt} failed`, 'sync.bootstrap', 'warning', { isTimeout, isNetworkError, willRetry: attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS });
|
|
615
|
+
if (isTimeout && attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS) {
|
|
616
|
+
this.runtime.logger.info('[BaseSyncedStore] Resetting state before bootstrap retry');
|
|
617
|
+
this.resetBootstrapState();
|
|
618
|
+
await new Promise((resolve) => setTimeout(resolve, BOOTSTRAP_CONFIG.RETRY_DELAY_MS));
|
|
619
|
+
}
|
|
620
|
+
else if (!isTimeout && attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS) {
|
|
621
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
finally {
|
|
625
|
+
// Disarm this attempt's deadline the moment it settles — a live timer
|
|
626
|
+
// would abort whatever the next attempt puts in flight.
|
|
627
|
+
this.clearBootstrapDeadline();
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
throw lastError
|
|
631
|
+
? toAbloError(lastError)
|
|
632
|
+
: new AbloConnectionError('Bootstrap failed after all retry attempts', {
|
|
633
|
+
code: 'bootstrap_fetch_timeout',
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
finally {
|
|
637
|
+
signal?.removeEventListener('abort', onCallerAbort);
|
|
638
|
+
this.clearBootstrapDeadline();
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* The outer deadline for one bootstrap attempt.
|
|
643
|
+
*
|
|
644
|
+
* The length is DERIVED from the fetcher's own watchdog budget, not chosen. A
|
|
645
|
+
* chosen number is what broke this: the previous fixed 15s was shorter than a
|
|
646
|
+
* single model chunk's allowance — 20s waiting for response headers plus 15s
|
|
647
|
+
* of stall grace — so on any workspace with one slow model the deadline fired
|
|
648
|
+
* before the watchdogs it was meant to backstop, and every attempt timed out
|
|
649
|
+
* by construction. The watchdogs below are progress-based and already
|
|
650
|
+
* guarantee termination; this deadline exists only for a hang somewhere other
|
|
651
|
+
* than the network, so it must sit above them, and it can only do that
|
|
652
|
+
* reliably by asking them how long they take.
|
|
653
|
+
*
|
|
654
|
+
* Reaching it aborts the work in flight. `Promise.race` merely stops waiting:
|
|
655
|
+
* without the abort the losing bootstrap keeps running, keeps its sockets, and
|
|
656
|
+
* races the retry that replaced it — which is how one page load turned into
|
|
657
|
+
* dozens of overlapping requests.
|
|
658
|
+
*/
|
|
659
|
+
createBootstrapTimeout(attempt) {
|
|
660
|
+
const timeoutMs = this.database.helper.budgetMs;
|
|
661
|
+
return new Promise((_, reject) => {
|
|
662
|
+
this.clearBootstrapDeadline();
|
|
663
|
+
this.bootstrapDeadlineTimer = setTimeout(() => {
|
|
664
|
+
this.database.helper.abort();
|
|
665
|
+
reject(new AbloConnectionError(`Bootstrap timed out after ${timeoutMs}ms (attempt ${attempt})`, { code: 'bootstrap_fetch_timeout' }));
|
|
666
|
+
}, timeoutMs);
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
/** Disarm the deadline once its attempt has settled. Load-bearing now that
|
|
670
|
+
* firing it aborts real work: a leftover timer would cancel a later,
|
|
671
|
+
* unrelated bootstrap. */
|
|
672
|
+
clearBootstrapDeadline() {
|
|
673
|
+
if (this.bootstrapDeadlineTimer !== null) {
|
|
674
|
+
clearTimeout(this.bootstrapDeadlineTimer);
|
|
675
|
+
this.bootstrapDeadlineTimer = null;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
/** Reset bootstrap-related state for a clean retry */
|
|
679
|
+
resetBootstrapState() {
|
|
680
|
+
try {
|
|
681
|
+
this.objectPool.clear({ preserveObserved: true });
|
|
682
|
+
this.queryProcessor.clearCache();
|
|
683
|
+
runInAction(() => { this.dataReady = false; });
|
|
684
|
+
this.modelTypesHydrated.clear();
|
|
685
|
+
this.modelTypeHydrationInFlight.clear();
|
|
686
|
+
// The pool is being wiped + re-bootstrapped, so the scoped-hydrate ledger
|
|
687
|
+
// is stale — clear it so re-entered groups backfill again.
|
|
688
|
+
this.hydratedGroups.clear();
|
|
689
|
+
this.hydratingGroups.clear();
|
|
690
|
+
this.runtime.logger.info('[BaseSyncedStore] Bootstrap state reset complete');
|
|
691
|
+
}
|
|
692
|
+
catch {
|
|
693
|
+
this.runtime.observability.breadcrumb('Error resetting bootstrap state', 'sync.bootstrap', 'warning');
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// ── Reconnection ─────────────────────────────────────────────────────────
|
|
697
|
+
/** Perform reconnect: bootstrap + WS reconnect. Returns outcome for state machine. */
|
|
698
|
+
async performReconnect() {
|
|
699
|
+
const thisStore = this;
|
|
700
|
+
return runReconnect({
|
|
701
|
+
get userContext() { return thisStore.userContext; },
|
|
702
|
+
database: this.database,
|
|
703
|
+
syncClient: this.syncClient,
|
|
704
|
+
objectPool: this.objectPool,
|
|
705
|
+
syncWebSocket: this.syncWebSocket,
|
|
706
|
+
runtime: this.runtime,
|
|
707
|
+
get dataReady() { return thisStore.dataReady; },
|
|
708
|
+
set dataReady(value) { thisStore.dataReady = value; },
|
|
709
|
+
checkSyncGroupShrinkage: () => this.checkSyncGroupShrinkage(),
|
|
710
|
+
resolveSyncGroups: (context) => this.resolveSyncGroups(context),
|
|
711
|
+
applyBootstrapToPool: (result) => this.applyBootstrapToPool(result),
|
|
712
|
+
updateSyncStatus: (updates) => { this.updateSyncStatus(updates); },
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Register the access-credential re-mint hook. Called by the React provider
|
|
717
|
+
* with a thunk that mints a fresh `ek_`/`rk_` (typically its `getToken`).
|
|
718
|
+
* See {@link CredentialLifecycle.setRefresher}.
|
|
719
|
+
*/
|
|
720
|
+
setCredentialRefresher(refresher) {
|
|
721
|
+
this.credentialLifecycle.setRefresher(refresher);
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Re-mint the short-lived access credential and push it into the credential
|
|
725
|
+
* source, reporting a tri-state outcome the {@link ConnectionManager} maps to
|
|
726
|
+
* its FSM. Single-flight; no refresher wired ⇒ `'refreshed'` (a no-op
|
|
727
|
+
* re-probe). Full contract on {@link CredentialLifecycle.refresh}.
|
|
728
|
+
*/
|
|
729
|
+
async performCredentialRefresh() {
|
|
730
|
+
return this.credentialLifecycle.refresh();
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* The authentication-recovery path for HTTP transports, such as the lazy
|
|
734
|
+
* query lane. It runs a single-flight credential re-mint driven by the
|
|
735
|
+
* rejection's recovery class, routing outcomes through the same state
|
|
736
|
+
* machine the WebSocket probe uses. `'retry'` means a fresh credential is
|
|
737
|
+
* now in the credential source and the request should be replayed once.
|
|
738
|
+
* Full contract on {@link CredentialLifecycle.recoverFromAuthRejection}.
|
|
739
|
+
*/
|
|
740
|
+
async recoverFromAuthRejection(recovery) {
|
|
741
|
+
return this.credentialLifecycle.recoverFromAuthRejection(recovery);
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Nudge the connection FSM to re-probe with the current credential. Idempotent
|
|
745
|
+
* and safe in any state (ignored while `connected`). Call after pushing a
|
|
746
|
+
* freshly-minted token via `setAuthToken`, or on an OS-wake signal, so a
|
|
747
|
+
* connection parked in `offline` / `backoff` / `auth_blocked` picks the new
|
|
748
|
+
* credential up immediately instead of waiting for the 30s watchdog.
|
|
749
|
+
*/
|
|
750
|
+
nudgeReconnect() {
|
|
751
|
+
this.connectionManager?.send({ type: 'CREDENTIAL_REFRESHED' });
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Install the client-owned access-credential lifecycle: register `getToken`
|
|
755
|
+
* as the reactive re-mint hook and arm the browser-only proactive refresh
|
|
756
|
+
* (a refresh timer plus an OS-wake re-mint). Idempotent — a second call
|
|
757
|
+
* replaces the first — and torn down on {@link disconnect}. Full rationale
|
|
758
|
+
* on {@link CredentialLifecycle.start}.
|
|
759
|
+
*/
|
|
760
|
+
startCredentialLifecycle(getToken, opts) {
|
|
761
|
+
this.credentialLifecycle.start(getToken, opts);
|
|
762
|
+
}
|
|
763
|
+
/** Tear down the proactive credential lifecycle (idempotent). */
|
|
764
|
+
stopCredentialLifecycle() {
|
|
765
|
+
this.credentialLifecycle.stop();
|
|
766
|
+
}
|
|
767
|
+
// ── Sync group management ────────────────────────────────────────────────
|
|
768
|
+
//
|
|
769
|
+
// The implementation lives in the sync/groupChange module. The methods
|
|
770
|
+
// below are thin protected delegates that keep their signatures, so
|
|
771
|
+
// subclass override points still work; the module routes cross-handler
|
|
772
|
+
// calls back through `groupChangeContext()` to preserve dynamic dispatch.
|
|
773
|
+
/** Narrow context the group-change leaf talks back through. */
|
|
774
|
+
groupChangeContext() {
|
|
775
|
+
return {
|
|
776
|
+
runtime: this.runtime,
|
|
777
|
+
database: this.database,
|
|
778
|
+
objectPool: this.objectPool,
|
|
779
|
+
getSubscribedSyncGroups: () => this.syncWebSocket.getSyncGroups(),
|
|
780
|
+
getCurrentSyncGroups: () => this.userContext ? this.resolveSyncGroups(this.userContext) : null,
|
|
781
|
+
getBootstrapMode: () => this.userContext?.bootstrapMode,
|
|
782
|
+
disconnectWebSocket: () => { this.syncWebSocket.disconnect(); },
|
|
783
|
+
emitConnectionEvent: (event) => { this.onConnectionEvent?.(event); },
|
|
784
|
+
handleGroupAdded: (payload, syncId) => this.handleGroupAdded(payload, syncId),
|
|
785
|
+
computeUpdatedSyncGroups: (payload) => this.computeUpdatedSyncGroups(payload),
|
|
786
|
+
forceFullRebootstrap: () => { this.forceFullRebootstrap(); },
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Handle an actionType 'G' delta — incremental `{ group, userId }` or
|
|
791
|
+
* legacy `{ addedGroups, removedGroups }` payloads. Full pathway doc on
|
|
792
|
+
* {@link groupChange.handleSyncGroupChange}.
|
|
793
|
+
*/
|
|
794
|
+
async handleSyncGroupChange(delta) {
|
|
795
|
+
return groupChange.handleSyncGroupChange(this.groupChangeContext(), delta);
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Handle an incremental GroupAdded delta — metadata only, no re-bootstrap
|
|
799
|
+
* (covering deltas bring the entities). See {@link groupChange.handleGroupAdded}.
|
|
800
|
+
*/
|
|
801
|
+
async handleGroupAdded(payload, syncId) {
|
|
802
|
+
return groupChange.handleGroupAdded(this.groupChangeContext(), payload, syncId);
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Handle an actionType 'S' (GroupRemoved) delta: for safety, clear the
|
|
806
|
+
* revoked local state and trigger a full re-bootstrap. See
|
|
807
|
+
* {@link groupChange.handleGroupRemoved}.
|
|
808
|
+
*/
|
|
809
|
+
async handleGroupRemoved(delta) {
|
|
810
|
+
return groupChange.handleGroupRemoved(this.groupChangeContext(), delta);
|
|
811
|
+
}
|
|
812
|
+
/** Compute new sync groups after applying additions and removals */
|
|
813
|
+
computeUpdatedSyncGroups(payload) {
|
|
814
|
+
return groupChange.computeUpdatedSyncGroups(this.groupChangeContext(), payload);
|
|
815
|
+
}
|
|
816
|
+
/** Force a full re-bootstrap via connection lifecycle event (no-op for
|
|
817
|
+
* `bootstrapMode: 'none'` participants — see {@link groupChange.forceFullRebootstrap}). */
|
|
818
|
+
forceFullRebootstrap() {
|
|
819
|
+
groupChange.forceFullRebootstrap(this.groupChangeContext());
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Single source of truth for the sync-group list this session is
|
|
823
|
+
* subscribed to. Server-issued (`context.syncGroups`) is authoritative.
|
|
824
|
+
* When absent, the SDK subscribes to no explicit groups. Both
|
|
825
|
+
* `checkSyncGroupShrinkage` and `setupWebSocketSync` resolve through
|
|
826
|
+
* here so the WS subscription and the security-critical shrinkage
|
|
827
|
+
* check can never disagree.
|
|
828
|
+
*/
|
|
829
|
+
resolveSyncGroups(context) {
|
|
830
|
+
return groupChange.resolveSyncGroups(context);
|
|
831
|
+
}
|
|
832
|
+
/** Check if sync groups shrank since last session — force full bootstrap if so */
|
|
833
|
+
async checkSyncGroupShrinkage() {
|
|
834
|
+
return groupChange.checkSyncGroupShrinkage(this.groupChangeContext());
|
|
835
|
+
}
|
|
836
|
+
// ── Bootstrap apply ──────────────────────────────────────────────────────
|
|
837
|
+
//
|
|
838
|
+
// The implementation lives in the sync/bootstrapApply module. The protected
|
|
839
|
+
// delegates below keep their signatures and subclass overridability; the
|
|
840
|
+
// module talks back through `poolContext()`, with enrichment pre-bound to
|
|
841
|
+
// `this.enrichRelations` so that override point still applies.
|
|
842
|
+
/** Narrow context the bootstrap-apply leaf talks back through. */
|
|
843
|
+
poolContext() {
|
|
844
|
+
const store = this;
|
|
845
|
+
return {
|
|
846
|
+
runtime: this.runtime,
|
|
847
|
+
applyDeltaBatchToPool: (results) => {
|
|
848
|
+
this.syncClient.applyDeltaBatchToPool(results, (name, data) => this.enrichRelations(name, data));
|
|
849
|
+
},
|
|
850
|
+
applyBootstrapDataToPool: (bootstrapData, protectedIds) => this.syncClient.applyBootstrapDataToPool(bootstrapData, protectedIds),
|
|
851
|
+
getPoolSize: () => this.objectPool.size,
|
|
852
|
+
getAllPoolIds: () => this.objectPool.getAllIds(),
|
|
853
|
+
get bootstrapDeltaQueue() { return store.bootstrapDeltaQueue; },
|
|
854
|
+
set bootstrapDeltaQueue(queue) { store.bootstrapDeltaQueue = queue; },
|
|
855
|
+
applyDeltaFrame: (deltas) => { this.applyDeltaFrame(deltas); },
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
/** Apply bootstrap data to the {@link InstanceCache}, removing entities that are no longer present (ghost removal). Pool writes are delegated to {@link SyncClient}. */
|
|
859
|
+
applyBootstrapToPool(bootstrapResult, protectedIds) {
|
|
860
|
+
return bootstrapApply.applyBootstrapToPool(this.poolContext(), bootstrapResult, protectedIds);
|
|
861
|
+
}
|
|
862
|
+
// ── Initialize + Lifecycle ───────────────────────────────────────────────
|
|
863
|
+
/**
|
|
864
|
+
* Initialize the sync engine with user context.
|
|
865
|
+
* Offline-first: hydrate from IDB → show UI → bootstrap from server in background.
|
|
866
|
+
*/
|
|
867
|
+
*initialize(context, signal) {
|
|
868
|
+
const thisStore = this;
|
|
869
|
+
return yield* runInitialize({
|
|
870
|
+
get initialized() { return thisStore.initialized; },
|
|
871
|
+
set initialized(value) { thisStore.initialized = value; },
|
|
872
|
+
get userContext() {
|
|
873
|
+
const value = thisStore.userContext;
|
|
874
|
+
if (!value)
|
|
875
|
+
throw new Error('User context is unavailable during initialization');
|
|
876
|
+
return value;
|
|
877
|
+
},
|
|
878
|
+
set userContext(value) { thisStore.userContext = value; },
|
|
879
|
+
get dataReady() { return thisStore.dataReady; },
|
|
880
|
+
set dataReady(value) { thisStore.dataReady = value; },
|
|
881
|
+
runtime: this.runtime,
|
|
882
|
+
database: this.database,
|
|
883
|
+
syncClient: this.syncClient,
|
|
884
|
+
objectPool: this.objectPool,
|
|
885
|
+
syncWebSocket: this.syncWebSocket,
|
|
886
|
+
updateSyncStatus: (updates) => { this.updateSyncStatus(updates); },
|
|
887
|
+
setupWebSocketSync: (nextContext, lastSyncId) => { this.setupWebSocketSync(nextContext, lastSyncId); },
|
|
888
|
+
waitForWebSocketConnected: (timeoutMs) => this.waitForWebSocketConnected(timeoutMs),
|
|
889
|
+
performBackgroundBootstrap: (requirements, nextContext, nextSignal) => this.performBackgroundBootstrap(requirements, nextContext, nextSignal),
|
|
890
|
+
executeBootstrapWithTimeout: (fn, nextContext, nextSignal) => this.executeBootstrapWithTimeout(fn, nextContext, nextSignal),
|
|
891
|
+
resolveSyncGroups: (nextContext) => this.resolveSyncGroups(nextContext),
|
|
892
|
+
}, context, signal);
|
|
893
|
+
}
|
|
894
|
+
/** Background bootstrap — non-blocking, user sees cached data while this runs */
|
|
895
|
+
async performBackgroundBootstrap(requirements, context, signal) {
|
|
896
|
+
await this.withDeltaQueuing(async () => {
|
|
897
|
+
try {
|
|
898
|
+
const preBootstrapIds = new Set(this.objectPool.getAllIds());
|
|
899
|
+
const bootstrapResult = await this.database.bootstrapFromServer(requirements, this.resolveSyncGroups(context));
|
|
900
|
+
const deltaProtectedIds = this.collectDeltaProtectedIds(preBootstrapIds);
|
|
901
|
+
this.applyBootstrapToPool(bootstrapResult, deltaProtectedIds);
|
|
902
|
+
this.updateSyncStatus({ state: 'idle', progress: 100 });
|
|
903
|
+
}
|
|
904
|
+
catch (error) {
|
|
905
|
+
this.runtime.logger.debug('[sync-engine] Background bootstrap failed', {
|
|
906
|
+
error: error instanceof Error ? error.message : String(error),
|
|
907
|
+
cause: error,
|
|
908
|
+
});
|
|
909
|
+
this.runtime.observability.captureBootstrapFailure(error, { type: 'background' });
|
|
910
|
+
if (AbloSessionError.isSessionError(error)) {
|
|
911
|
+
this.syncWebSocket.setSessionErrorDetected();
|
|
912
|
+
this.syncWebSocket.disconnect();
|
|
913
|
+
this.updateSyncStatus({ state: 'error', error: error });
|
|
914
|
+
}
|
|
915
|
+
else if (!this.syncWebSocket.isConnected()) {
|
|
916
|
+
this.updateSyncStatus({ state: 'offline', offlineSince: new Date() });
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
/** Run bootstrap with delta queuing to prevent race conditions */
|
|
922
|
+
async withDeltaQueuing(fn) {
|
|
923
|
+
this.activeBootstrapCount++;
|
|
924
|
+
if (this.bootstrapDeltaQueue === null)
|
|
925
|
+
this.bootstrapDeltaQueue = [];
|
|
926
|
+
try {
|
|
927
|
+
return await fn();
|
|
928
|
+
}
|
|
929
|
+
finally {
|
|
930
|
+
this.activeBootstrapCount--;
|
|
931
|
+
if (this.activeBootstrapCount === 0)
|
|
932
|
+
this.replayQueuedDeltas();
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
/** Collect IDs that must survive ghost removal (added by deltas during bootstrap) */
|
|
936
|
+
collectDeltaProtectedIds(preBootstrapIds) {
|
|
937
|
+
return bootstrapApply.collectDeltaProtectedIds(this.poolContext(), preBootstrapIds);
|
|
938
|
+
}
|
|
939
|
+
/** Replay deltas queued during bootstrap (atomically, via `applyDeltaFrame`). */
|
|
940
|
+
replayQueuedDeltas() {
|
|
941
|
+
bootstrapApply.replayQueuedDeltas(this.poolContext());
|
|
942
|
+
}
|
|
943
|
+
createConnectionManager(kind) {
|
|
944
|
+
return runCreateConnectionManager({
|
|
945
|
+
syncServerUrl: this._syncServerUrl,
|
|
946
|
+
auth: this.auth,
|
|
947
|
+
syncWebSocket: this.syncWebSocket,
|
|
948
|
+
}, kind);
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Disconnect and clean up all resources. Terminal: this means "the client
|
|
952
|
+
* is finished", not "close and reopen later" — the connection object stays
|
|
953
|
+
* assigned but closed, the event wiring is torn down, and nothing
|
|
954
|
+
* re-initializes a disconnected store. (Mid-session closes during recovery
|
|
955
|
+
* go through the connection FSM's `onDisconnectWebSocket`, which closes
|
|
956
|
+
* the transport without touching the store.)
|
|
957
|
+
*/
|
|
958
|
+
async disconnect() {
|
|
959
|
+
this.stopCredentialLifecycle();
|
|
960
|
+
if (this.batchTimer) {
|
|
961
|
+
clearTimeout(this.batchTimer);
|
|
962
|
+
this.batchTimer = null;
|
|
963
|
+
}
|
|
964
|
+
this.pendingDeltas = [];
|
|
965
|
+
for (const dispose of this.disposers)
|
|
966
|
+
dispose();
|
|
967
|
+
this.disposers = [];
|
|
968
|
+
if (this.connectionManager) {
|
|
969
|
+
this.connectionManager.dispose();
|
|
970
|
+
this.connectionManager = null;
|
|
971
|
+
}
|
|
972
|
+
try {
|
|
973
|
+
const last = this.syncWebSocket.getLastSyncId();
|
|
974
|
+
if (last > 0)
|
|
975
|
+
await this.database.updateWorkspaceMetadata({ lastSyncId: last });
|
|
976
|
+
}
|
|
977
|
+
catch { }
|
|
978
|
+
this.syncWebSocket.disconnect();
|
|
979
|
+
this.syncClient.disconnect();
|
|
980
|
+
this.queryProcessor.clearCache();
|
|
981
|
+
// Stop the pool's GC interval — the one timer the pool arms itself.
|
|
982
|
+
// Without this a discarded store retains its whole pool via the interval
|
|
983
|
+
// closure (and a Node process without `unref` support can't exit).
|
|
984
|
+
this.objectPool.stopGC();
|
|
985
|
+
this.updateSyncStatus({ state: 'offline' });
|
|
986
|
+
}
|
|
987
|
+
/** Stop access and await deletion of this identity's local state. */
|
|
988
|
+
async purge() {
|
|
989
|
+
// Clear the bearer first so no request started during teardown can carry
|
|
990
|
+
// the terminal credential.
|
|
991
|
+
this.auth?.setAuthToken(null);
|
|
992
|
+
await this.disconnect();
|
|
993
|
+
this.objectPool.clear();
|
|
994
|
+
this.queryProcessor.clearCache();
|
|
995
|
+
await this.database.purgePersistence();
|
|
996
|
+
}
|
|
997
|
+
// ── WebSocket Setup ───────────────────────────────────────────────────────
|
|
998
|
+
/**
|
|
999
|
+
* Create WebSocket connection and wire all event handlers.
|
|
1000
|
+
* Handles: deltas, batches, presence, bootstrap_required, errors, reconnection.
|
|
1001
|
+
*/
|
|
1002
|
+
/**
|
|
1003
|
+
* Block until the WebSocket reports a `connected` event, or until
|
|
1004
|
+
* `timeoutMs` elapses (returns false on timeout, true on connect).
|
|
1005
|
+
* Used by `initialize()` for `bootstrapMode: 'none'` consumers to
|
|
1006
|
+
* honor `ready()`'s "WS is connected when this resolves" contract
|
|
1007
|
+
* — `setupWebSocketSync` is fire-and-forget on the upgrade, and
|
|
1008
|
+
* without an explicit wait the next mutation can race the open.
|
|
1009
|
+
*
|
|
1010
|
+
* Resolves immediately if the WS is already connected (e.g., warm
|
|
1011
|
+
* reconnect after redeploy). Resolves false on timeout rather than
|
|
1012
|
+
* throwing so initialize() can complete and let the caller's first
|
|
1013
|
+
* mutation attempt surface a clearer error.
|
|
1014
|
+
*/
|
|
1015
|
+
async waitForWebSocketConnected(timeoutMs) {
|
|
1016
|
+
return runWaitForWebSocketConnected({
|
|
1017
|
+
syncWebSocket: this.syncWebSocket,
|
|
1018
|
+
runtime: this.runtime,
|
|
1019
|
+
}, timeoutMs);
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Seed the connection's late values and open it. The socket itself exists
|
|
1023
|
+
* from construction; what identity resolution supplies — the participant
|
|
1024
|
+
* kind, the credential, the read scope, and the resume cursor — is seeded
|
|
1025
|
+
* here, and only then is the held first connect released. A retried
|
|
1026
|
+
* `initialize()` after a failed `ready()` re-runs this against the same
|
|
1027
|
+
* connection object: the reconnect counter is reset for a clean slate,
|
|
1028
|
+
* while the session-error latch deliberately survives (only the
|
|
1029
|
+
* credential-expiry recovery clears it).
|
|
1030
|
+
*/
|
|
1031
|
+
setupWebSocketSync(context, lastSyncId) {
|
|
1032
|
+
if (!context.userId || !context.organizationId) {
|
|
1033
|
+
this.runtime.observability.breadcrumb('Cannot setup WebSocket sync without user context', 'sync.websocket', 'warning');
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
if (context.kind)
|
|
1037
|
+
this.syncWebSocket.setKind(context.kind);
|
|
1038
|
+
if (context.capabilityToken) {
|
|
1039
|
+
this.syncWebSocket.setCapabilityToken(context.capabilityToken);
|
|
1040
|
+
}
|
|
1041
|
+
const syncGroups = this.resolveSyncGroups(context);
|
|
1042
|
+
this.syncWebSocket.setSyncGroups(syncGroups);
|
|
1043
|
+
this.syncWebSocket.setLastSyncId(lastSyncId || 0);
|
|
1044
|
+
// The permanent base scopes for read interest — same set the connection
|
|
1045
|
+
// subscribes to at upgrade, so the two can never disagree.
|
|
1046
|
+
this.areaOfInterest.setBaseGroups(syncGroups);
|
|
1047
|
+
// ── Connection FSM ────────────────────────────────────────────
|
|
1048
|
+
// Instantiate + start the SDK's ConnectionManager so every consumer
|
|
1049
|
+
// gets correct online/offline recovery. Guarded: a retried
|
|
1050
|
+
// `initialize()` reuses the manager it already started.
|
|
1051
|
+
if (!this.connectionManager)
|
|
1052
|
+
this.startConnectionManager(context.kind);
|
|
1053
|
+
this.syncWebSocket.resetReconnectAttempts();
|
|
1054
|
+
this.syncWebSocket.allowConnect();
|
|
1055
|
+
this.syncWebSocket.connect();
|
|
1056
|
+
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Wire the store's handlers onto the connection. Runs once, at
|
|
1059
|
+
* construction — the connection object is stable for the store's
|
|
1060
|
+
* lifetime, so the wiring is too.
|
|
1061
|
+
*/
|
|
1062
|
+
wireSocketEvents() {
|
|
1063
|
+
const thisStore = this;
|
|
1064
|
+
wireSocketEvents({
|
|
1065
|
+
syncWebSocket: this.syncWebSocket,
|
|
1066
|
+
syncClient: this.syncClient,
|
|
1067
|
+
database: this.database,
|
|
1068
|
+
objectPool: this.objectPool,
|
|
1069
|
+
areaOfInterest: this.areaOfInterest,
|
|
1070
|
+
runtime: this.runtime,
|
|
1071
|
+
get dataReady() { return thisStore.dataReady; },
|
|
1072
|
+
connectionManager: this.connectionManager,
|
|
1073
|
+
disposers: this.disposers,
|
|
1074
|
+
onConnectionEvent: this.onConnectionEvent,
|
|
1075
|
+
updateSyncStatus: (updates) => { this.updateSyncStatus(updates); },
|
|
1076
|
+
processDeltaWithBatching: (delta) => { this.processDeltaWithBatching(delta); },
|
|
1077
|
+
applyDeltaFrame: (deltas) => { this.applyDeltaFrame(deltas); },
|
|
1078
|
+
handleBootstrapRequired: (hint) => { this.handleBootstrapRequired(hint); },
|
|
1079
|
+
handleBootstrapData: (data) => { this.handleBootstrapData(data); },
|
|
1080
|
+
handlePresenceUpdate: (data) => { this.handlePresenceUpdate(data); },
|
|
1081
|
+
performCredentialRefresh: () => this.performCredentialRefresh(),
|
|
1082
|
+
handleTerminalSessionError: (error) => { this.terminalSessionLifecycle.start(error); },
|
|
1083
|
+
nudgeReconnect: () => { this.nudgeReconnect(); },
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
/*
|
|
1087
|
+
* Kept as a distinct method so subclasses retain the original override
|
|
1088
|
+
* point; transport wiring itself lives in sync/socketEventWiring.ts.
|
|
1089
|
+
*/
|
|
1090
|
+
/**
|
|
1091
|
+
* Build and start the connection FSM. The `onConnectionEvent` hook is the
|
|
1092
|
+
* bridge — WS events fire the hook, the hook forwards into the FSM. Called
|
|
1093
|
+
* from `setupWebSocketSync` because the FSM's shape depends on the resolved
|
|
1094
|
+
* participant kind (agents get none — see {@link createConnectionManager}).
|
|
1095
|
+
*/
|
|
1096
|
+
startConnectionManager(kind) {
|
|
1097
|
+
const thisStore = this;
|
|
1098
|
+
runStartConnectionManager({
|
|
1099
|
+
get connectionManager() { return thisStore.connectionManager; },
|
|
1100
|
+
set connectionManager(value) { thisStore.connectionManager = value; },
|
|
1101
|
+
get onConnectionEvent() { return thisStore.onConnectionEvent; },
|
|
1102
|
+
set onConnectionEvent(value) { thisStore.onConnectionEvent = value; },
|
|
1103
|
+
syncWebSocket: this.syncWebSocket,
|
|
1104
|
+
get syncStatus() { return thisStore.syncStatus; },
|
|
1105
|
+
createConnectionManager: (nextKind) => this.createConnectionManager(nextKind),
|
|
1106
|
+
performReconnect: () => this.performReconnect(),
|
|
1107
|
+
performCredentialRefresh: () => this.performCredentialRefresh(),
|
|
1108
|
+
handleTerminalSessionError: (error) => { this.terminalSessionLifecycle.start(error); },
|
|
1109
|
+
updateSyncStatus: (updates) => { this.updateSyncStatus(updates); },
|
|
1110
|
+
runtime: this.runtime,
|
|
1111
|
+
}, kind);
|
|
1112
|
+
}
|
|
1113
|
+
// ── Delta processing pipeline ─────────────────────────────────────────────
|
|
1114
|
+
//
|
|
1115
|
+
// The implementation lives in the sync/deltaPipeline module (deduplication,
|
|
1116
|
+
// enqueue bookkeeping, debounce, flush). The methods below are thin protected
|
|
1117
|
+
// delegates with unchanged signatures, and the module routes every call to a
|
|
1118
|
+
// protected override point back through `deltaPipelineContext`, so subclass
|
|
1119
|
+
// dynamic dispatch is preserved. `applyDeltaFrame`, the authoritative-apply
|
|
1120
|
+
// correctness point, deliberately stays here.
|
|
1121
|
+
/** Memoized pipeline context — `enqueueDelta` runs once per delta, so the
|
|
1122
|
+
* accessor object is built once and reused (the get/set accessors always
|
|
1123
|
+
* read the live host fields). */
|
|
1124
|
+
_deltaPipelineContext = null;
|
|
1125
|
+
get deltaPipelineContext() {
|
|
1126
|
+
if (this._deltaPipelineContext)
|
|
1127
|
+
return this._deltaPipelineContext;
|
|
1128
|
+
const store = this;
|
|
1129
|
+
this._deltaPipelineContext = {
|
|
1130
|
+
runtime: this.runtime,
|
|
1131
|
+
stagePlugins: this.stagePlugins,
|
|
1132
|
+
// Shared pipeline state, backed by the host fields.
|
|
1133
|
+
get pendingDeltas() { return store.pendingDeltas; },
|
|
1134
|
+
set pendingDeltas(deltas) { store.pendingDeltas = deltas; },
|
|
1135
|
+
get batchTimer() { return store.batchTimer; },
|
|
1136
|
+
set batchTimer(timer) { store.batchTimer = timer; },
|
|
1137
|
+
get bootstrapDeltaQueue() { return store.bootstrapDeltaQueue; },
|
|
1138
|
+
get smartSyncOptions() { return store.smartSyncOptions; },
|
|
1139
|
+
get highestProcessedSyncId() { return store.highestProcessedSyncId; },
|
|
1140
|
+
get lastAckedId() { return store.lastAckedId; },
|
|
1141
|
+
// SyncClient position/transaction bookkeeping.
|
|
1142
|
+
onDeltaReceived: (syncId, transactionId, correlationId) => {
|
|
1143
|
+
this.syncClient.onDeltaReceived(syncId, transactionId, correlationId);
|
|
1144
|
+
},
|
|
1145
|
+
advanceApplied: (syncId) => { this.syncClient.position.advanceApplied(syncId); },
|
|
1146
|
+
advancePersisted: (syncId) => { this.syncClient.position.advancePersisted(syncId); },
|
|
1147
|
+
// Persistence + pool writes.
|
|
1148
|
+
processDeltaBatch: (deltas) => this.database.processDeltaBatch(deltas),
|
|
1149
|
+
applyDeltaBatchToPool: (results) => { this.applyChangesToPool(results); },
|
|
1150
|
+
acknowledge: (syncId) => { this.syncWebSocket.acknowledge(syncId); },
|
|
1151
|
+
get objectPool() { return store.objectPool; },
|
|
1152
|
+
// Dynamic-dispatch hooks — protected override points on this class.
|
|
1153
|
+
getStateFields: (modelName) => this.getStateFields(modelName),
|
|
1154
|
+
isCustomEntity: (modelName) => this.isCustomEntity(modelName),
|
|
1155
|
+
createCustomEntity: (modelName, modelId, data) => this.createCustomEntity(modelName, modelId, data),
|
|
1156
|
+
deduplicateDeltas: (deltas) => this.deduplicateDeltas(deltas),
|
|
1157
|
+
flushPendingDeltas: () => this.flushPendingDeltas(),
|
|
1158
|
+
handleFlushError: (error) => { this.handleFlushError(error); },
|
|
1159
|
+
handleSyncGroupChange: (delta) => this.handleSyncGroupChange(delta),
|
|
1160
|
+
handleGroupRemoved: (delta) => this.handleGroupRemoved(delta),
|
|
1161
|
+
forceFullRebootstrap: () => { this.forceFullRebootstrap(); },
|
|
1162
|
+
cascadeCancelTransactionsForDeletedParent: (parentModelName, parentId) => {
|
|
1163
|
+
this.cascadeCancelTransactionsForDeletedParent(parentModelName, parentId);
|
|
1164
|
+
},
|
|
1165
|
+
};
|
|
1166
|
+
return this._deltaPipelineContext;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Lands persisted changes in the in-memory pool, with this store's
|
|
1170
|
+
* relation enrichment bound. The one apply path: the pipeline's bridge
|
|
1171
|
+
* (no plugins installed) and the `humans()` apply handler both call it.
|
|
1172
|
+
*/
|
|
1173
|
+
applyChangesToPool(changes) {
|
|
1174
|
+
this.syncClient.applyDeltaBatchToPool(changes, (name, data) => this.enrichRelations(name, data));
|
|
1175
|
+
}
|
|
1176
|
+
/** Get fields that represent meaningful state for deduplication. Override for model-specific fields. */
|
|
1177
|
+
getStateFields(_modelName) {
|
|
1178
|
+
return ['status', 'state', 'isActive'];
|
|
1179
|
+
}
|
|
1180
|
+
/** Deduplicate deltas to the same entity — keep meaningful state transitions only */
|
|
1181
|
+
deduplicateDeltas(deltas) {
|
|
1182
|
+
return deltaPipeline.deduplicateDeltas(this.deltaPipelineContext, deltas);
|
|
1183
|
+
}
|
|
1184
|
+
/** Process incoming delta with smart batching */
|
|
1185
|
+
processDeltaWithBatching(delta) {
|
|
1186
|
+
if (!this.enqueueDelta(delta))
|
|
1187
|
+
return;
|
|
1188
|
+
this.scheduleDeltaFlush();
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Apply a complete, server-delivered delta frame atomically.
|
|
1192
|
+
*
|
|
1193
|
+
* A `delta_batch` WebSocket event (a reconnect or catch-up replay) already
|
|
1194
|
+
* carries the full set of missed deltas. Routing it through the per-delta
|
|
1195
|
+
* `processDeltaWithBatching` path would re-chunk it via the live-traffic
|
|
1196
|
+
* debounce timer and `maxBatchSize` force-flush, so a 300-delta catch-up
|
|
1197
|
+
* would fan out into several separate `flushPendingDeltas` cycles — each its
|
|
1198
|
+
* own local write, pool mutation, `models:changed` emit, and re-render, so
|
|
1199
|
+
* the UI visibly repaints once per chunk.
|
|
1200
|
+
*
|
|
1201
|
+
* Instead, this runs the per-delta bookkeeping (deduplication, ack, version
|
|
1202
|
+
* vector, watermark, group-change routing, delete cascade) for every delta
|
|
1203
|
+
* without scheduling a flush, then flushes once — collapsing the whole frame
|
|
1204
|
+
* into a single local write, pool mutation, `models:changed` emit, and
|
|
1205
|
+
* re-render. The post-bootstrap replay of deltas queued during bootstrap
|
|
1206
|
+
* uses the same path.
|
|
1207
|
+
*
|
|
1208
|
+
* It is named `applyDeltaFrame`, not `processDeltaBatch`, to avoid confusion
|
|
1209
|
+
* with {@link Database.processDeltaBatch} — the lower-level local write this
|
|
1210
|
+
* eventually drives through `flushPendingDeltas`.
|
|
1211
|
+
*/
|
|
1212
|
+
applyDeltaFrame(deltas) {
|
|
1213
|
+
deltaPipeline.applyDeltaFrame(this.deltaPipelineContext, deltas);
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Per-delta bookkeeping + enqueue. Returns `true` when the delta was
|
|
1217
|
+
* pushed onto `pendingDeltas` (a regular batchable I/U/C/D delta that a
|
|
1218
|
+
* subsequent flush must drain), `false` when it was skipped (dedup),
|
|
1219
|
+
* deferred (bootstrap queue), or handled immediately out-of-band (G/S
|
|
1220
|
+
* sync-group mutations). Does NOT schedule a flush — callers decide
|
|
1221
|
+
* whether to debounce (live) or flush atomically (catch-up frame).
|
|
1222
|
+
*/
|
|
1223
|
+
enqueueDelta(delta, options = {}) {
|
|
1224
|
+
return deltaPipeline.enqueueDelta(this.deltaPipelineContext, delta, options);
|
|
1225
|
+
}
|
|
1226
|
+
/** Debounce a flush for live single-delta traffic. */
|
|
1227
|
+
scheduleDeltaFlush() {
|
|
1228
|
+
deltaPipeline.scheduleDeltaFlush(this.deltaPipelineContext);
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Cancel pending transactions for child entities when a parent is deleted.
|
|
1232
|
+
*
|
|
1233
|
+
* Uses `pool.getByForeignKey` (O(1) via the FK index registered at
|
|
1234
|
+
* schema build time) to find children. The previous implementation did
|
|
1235
|
+
* `getByType(ctor).filter(e => e.toJSON()[foreignKey] === parentId)` —
|
|
1236
|
+
* a full pool scan per child model + a `toJSON()` allocation per
|
|
1237
|
+
* candidate. For a report delete with 10K blocks in the pool, that was
|
|
1238
|
+
* 10K toJSON allocations per cascade level. The FK-indexed lookup
|
|
1239
|
+
* skips both the scan AND the allocation.
|
|
1240
|
+
*/
|
|
1241
|
+
cascadeCancelTransactionsForDeletedParent(parentModelName, parentId) {
|
|
1242
|
+
const reg = this.objectPool.registry;
|
|
1243
|
+
const childModels = reg.getChildModels(parentModelName);
|
|
1244
|
+
if (childModels.length === 0)
|
|
1245
|
+
return;
|
|
1246
|
+
let totalCancelled = 0;
|
|
1247
|
+
for (const { childModel, foreignKey } of childModels) {
|
|
1248
|
+
const cancelled = this.syncClient.cancelTransactionsByForeignKey(childModel, foreignKey, parentId);
|
|
1249
|
+
totalCancelled += cancelled;
|
|
1250
|
+
// O(1) FK-index lookup — skips the prior `getByType().filter(toJSON)` scan.
|
|
1251
|
+
const children = this.objectPool.getByForeignKey(childModel, foreignKey, parentId);
|
|
1252
|
+
for (const child of children) {
|
|
1253
|
+
this.cascadeCancelTransactionsForDeletedParent(childModel, child.id);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
if (totalCancelled > 0) {
|
|
1257
|
+
this.runtime.logger.info('[BaseSyncedStore] Cascade cancelled orphaned transactions', {
|
|
1258
|
+
parentModel: parentModelName,
|
|
1259
|
+
parentId: parentId.slice(0, 12),
|
|
1260
|
+
totalCancelled,
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/** Flush pending deltas with deduplication. Pool writes are delegated to {@link SyncClient}. */
|
|
1265
|
+
async flushPendingDeltas() {
|
|
1266
|
+
return deltaPipeline.flushPendingDeltas(this.deltaPipelineContext);
|
|
1267
|
+
}
|
|
1268
|
+
// ── Core mutations (thin delegation to SyncClient) ────────────────────────
|
|
1269
|
+
//
|
|
1270
|
+
// This class orchestrates; it does not implement the writes. {@link SyncClient}
|
|
1271
|
+
// owns the object-pool operations, the transaction queue, and local writes.
|
|
1272
|
+
// This class owns validation, lifecycle hooks, and pending-delete tracking.
|
|
1273
|
+
/** Check if a model type is local-only (no sync). Override for domain-specific models. */
|
|
1274
|
+
isLocalOnlyModel(_modelName) {
|
|
1275
|
+
return false;
|
|
1276
|
+
}
|
|
1277
|
+
/** Validate model against schema before save */
|
|
1278
|
+
validateModel(model) {
|
|
1279
|
+
const modelName = model.getModelName();
|
|
1280
|
+
const properties = this.modelRegistry.getPropertiesForModel(modelName);
|
|
1281
|
+
const modelData = model.toJSON();
|
|
1282
|
+
for (const [propName, metadata] of properties) {
|
|
1283
|
+
if (metadata.type === PropertyType.referenceModel)
|
|
1284
|
+
continue;
|
|
1285
|
+
if (metadata.type === PropertyType.ephemeralProperty)
|
|
1286
|
+
continue;
|
|
1287
|
+
if (!metadata.optional && (modelData[propName] === null || modelData[propName] === undefined)) {
|
|
1288
|
+
throw new AbloValidationError(`Required field ${propName} is missing on ${modelName}`, { code: 'model_required_field_missing' });
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Save a model (create or update).
|
|
1294
|
+
*
|
|
1295
|
+
* Accepts any entity shape with `{ id: string }` so consumers can pass the
|
|
1296
|
+
* Zod-inferred model types from `Model<Schema, K>` without knowing
|
|
1297
|
+
* about the internal `Model` base class. At runtime, every entity reaching
|
|
1298
|
+
* this method came through the object pool (via `store.create`, a query
|
|
1299
|
+
* accessor, or an optimistic insert) and IS a `Model` instance — the one
|
|
1300
|
+
* cast below preserves that invariant inside the SDK.
|
|
1301
|
+
*/
|
|
1302
|
+
async save(entity, options) {
|
|
1303
|
+
const model = rowAsModel(entity);
|
|
1304
|
+
this.beforeSave(model);
|
|
1305
|
+
if (!options?.skipValidation)
|
|
1306
|
+
this.validateModel(model);
|
|
1307
|
+
if (!model.createdAt)
|
|
1308
|
+
model.createdAt = new Date();
|
|
1309
|
+
// SyncClient.add/update handles: optimistic pool add, transaction queue, IDB write
|
|
1310
|
+
const isCreate = !this.objectPool.get(model.id);
|
|
1311
|
+
if (isCreate) {
|
|
1312
|
+
model.updatedAt = new Date();
|
|
1313
|
+
this.syncClient.add(model);
|
|
1314
|
+
}
|
|
1315
|
+
else {
|
|
1316
|
+
this.syncClient.update(model);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
/** Save with an atomic server mutation (e.g., createSectionWithBlocks) */
|
|
1320
|
+
async saveWithAtomicMutation(model, mutation) {
|
|
1321
|
+
this.objectPool.add(model, ModelScope.live);
|
|
1322
|
+
await mutation(this.syncClient.gql);
|
|
1323
|
+
}
|
|
1324
|
+
/** Delete a model. Accepts schema-inferred entity shapes (see `save`). */
|
|
1325
|
+
async delete(entity) {
|
|
1326
|
+
const model = rowAsModel(entity);
|
|
1327
|
+
this.pendingDeletes.add(model.id);
|
|
1328
|
+
// SyncClient.delete handles: pool remove, transaction queue
|
|
1329
|
+
this.syncClient.delete(model);
|
|
1330
|
+
}
|
|
1331
|
+
/** Archive a model. Accepts schema-inferred entity shapes (see `save`). */
|
|
1332
|
+
async archive(entity) {
|
|
1333
|
+
const model = rowAsModel(entity);
|
|
1334
|
+
model.archivedAt = new Date();
|
|
1335
|
+
this.syncClient.archive(model);
|
|
1336
|
+
}
|
|
1337
|
+
/** Unarchive a model. Accepts schema-inferred entity shapes (see `save`). */
|
|
1338
|
+
async unarchive(entity) {
|
|
1339
|
+
const model = rowAsModel(entity);
|
|
1340
|
+
model.archivedAt = null;
|
|
1341
|
+
this.syncClient.update(model);
|
|
1342
|
+
}
|
|
1343
|
+
// ── Query API ────────────────────────────────────────────────────────────
|
|
1344
|
+
// `ablo.<model>.local.get` / `.local.list` is the read surface for
|
|
1345
|
+
// application code. Custom mutators read transactionally through
|
|
1346
|
+
// `tx.<model>`, backed by `createReaderActions`.
|
|
1347
|
+
/** Retrieve a single entity by id. Synchronous pool read. */
|
|
1348
|
+
retrieve(_modelClass, id) {
|
|
1349
|
+
return this.objectPool.get(id);
|
|
1350
|
+
}
|
|
1351
|
+
/** Find any entity by ID regardless of type */
|
|
1352
|
+
findAnyById(id) {
|
|
1353
|
+
return this.objectPool.get(id);
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Lookup a model by ID alone. Matches the `SyncStoreRef.getById` contract
|
|
1357
|
+
* that schema-defined computeds use when they need to resolve a related
|
|
1358
|
+
* entity without holding onto its constructor.
|
|
1359
|
+
*/
|
|
1360
|
+
getById(id) {
|
|
1361
|
+
return this.objectPool.get(id);
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Create a model instance locally, typed via the schema.
|
|
1365
|
+
*
|
|
1366
|
+
* ```ts
|
|
1367
|
+
* const ledger = store.create('ledgers', { name, reportId });
|
|
1368
|
+
* // ledger: Ledger | null — no cast needed
|
|
1369
|
+
* ```
|
|
1370
|
+
*
|
|
1371
|
+
* The `typename` arg is the schema key (camelCase plural, e.g.
|
|
1372
|
+
* `'ledgers'`); the returned instance has the
|
|
1373
|
+
* `Model<Schema, K>` shape including computeds + relation accessors.
|
|
1374
|
+
* Wraps `pool.create(...)` — the underlying runtime is unchanged, just
|
|
1375
|
+
* type-narrowed.
|
|
1376
|
+
*/
|
|
1377
|
+
create(typename, data) {
|
|
1378
|
+
if (!this.schema) {
|
|
1379
|
+
throw new AbloValidationError('store.create requires a schema to be passed to the BaseSyncedStore constructor.', { code: 'store_create_schema_missing' });
|
|
1380
|
+
}
|
|
1381
|
+
const modelDef = this.schema.models[typename];
|
|
1382
|
+
const wireTypename = modelDef?.typename ?? typename;
|
|
1383
|
+
// Same boundary-cast idiom used by `createReaderActions.findById` — the
|
|
1384
|
+
// runtime instance IS the schema-typed shape (the dynamic class was
|
|
1385
|
+
// built from the same Zod shape), TypeScript just can't unify the SDK's
|
|
1386
|
+
// static `Model` class with the schema's object-literal type.
|
|
1387
|
+
return this.objectPool.create(wireTypename, data);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Query entry point for callers that hold a {@link Model} constructor and an
|
|
1391
|
+
* options object. It filters, orders, and paginates the matching models from
|
|
1392
|
+
* the pool. Prefer the schema-typed read surface (`ablo.<model>.list`) where
|
|
1393
|
+
* you can, since it infers concrete row types without a class value or cast.
|
|
1394
|
+
*/
|
|
1395
|
+
queryByClass(modelClass, options) {
|
|
1396
|
+
return runQueryByClass(this.objectPool, this.pendingDeletes, modelClass, options);
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Get all models of a type. Returns Model[] honestly — callers that need
|
|
1400
|
+
* narrow types should use `useAblo((ablo) => ablo.<model>.list(...))`
|
|
1401
|
+
* which does proper inference via `Model<S, K>`.
|
|
1402
|
+
*/
|
|
1403
|
+
allModelsOfType(modelClass, scope) {
|
|
1404
|
+
return this.objectPool.getByType(modelClass, scope ?? ModelScope.live);
|
|
1405
|
+
}
|
|
1406
|
+
/** Error handler for fire-and-forget flushPendingDeltas calls */
|
|
1407
|
+
handleFlushError = (error) => {
|
|
1408
|
+
this.runtime.observability.captureMutationFailure({
|
|
1409
|
+
context: 'flush-pending-deltas',
|
|
1410
|
+
modelName: 'batch',
|
|
1411
|
+
modelId: 'batch',
|
|
1412
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
1413
|
+
});
|
|
1414
|
+
this.runtime.logger.debug('[BaseSyncedStore] Delta flush error', {
|
|
1415
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1416
|
+
});
|
|
1417
|
+
};
|
|
1418
|
+
/** Process a single delta (used for immediate DELETE processing). Override for domain-specific handling. */
|
|
1419
|
+
async processDelta(delta) {
|
|
1420
|
+
const dbResult = await this.database.processDelta({
|
|
1421
|
+
syncId: delta.id,
|
|
1422
|
+
actionType: delta.actionType,
|
|
1423
|
+
modelName: delta.modelName,
|
|
1424
|
+
modelId: delta.modelId,
|
|
1425
|
+
data: typeof delta.data === 'string' ? JSON.parse(delta.data) : delta.data,
|
|
1426
|
+
});
|
|
1427
|
+
// Track pending deletes for query filtering
|
|
1428
|
+
if (dbResult.action === 'remove') {
|
|
1429
|
+
this.pendingDeletes.add(dbResult.modelId);
|
|
1430
|
+
}
|
|
1431
|
+
// Delegate pool writes to SyncClient (auto-invalidates cache via 'models:changed' event)
|
|
1432
|
+
this.syncClient.applyDeltaBatchToPool([dbResult], (name, data) => this.enrichRelations(name, data));
|
|
1433
|
+
// This path runs after the delta was written to IDB — advance both
|
|
1434
|
+
// cursors through the shared position.
|
|
1435
|
+
this.syncClient.position.advancePersisted(delta.id);
|
|
1436
|
+
}
|
|
1437
|
+
/** Handle bootstrap_required event */
|
|
1438
|
+
handleBootstrapRequired(_hint) {
|
|
1439
|
+
// Subclass implements — triggers background bootstrap
|
|
1440
|
+
}
|
|
1441
|
+
/** Handle bootstrap_data event. Override in subclass. */
|
|
1442
|
+
handleBootstrapData(_data) {
|
|
1443
|
+
this.updateSyncStatus({ state: 'syncing' });
|
|
1444
|
+
}
|
|
1445
|
+
/** Handle presence_update event. Override in subclass. */
|
|
1446
|
+
handlePresenceUpdate(_data) { }
|
|
1447
|
+
// ── Pending changes tracking ─────────────────────────────────────────────
|
|
1448
|
+
incrementPendingChanges() {
|
|
1449
|
+
runInAction(() => { this.syncStatus.pendingChanges++; });
|
|
1450
|
+
}
|
|
1451
|
+
decrementPendingChanges() {
|
|
1452
|
+
runInAction(() => {
|
|
1453
|
+
if (this.syncStatus.pendingChanges > 0)
|
|
1454
|
+
this.syncStatus.pendingChanges--;
|
|
1455
|
+
});
|
|
1456
|
+
}
|
|
1457
|
+
// ── Status helpers ───────────────────────────────────────────────────────
|
|
1458
|
+
updateSyncStatus(updates) {
|
|
1459
|
+
runInAction(() => {
|
|
1460
|
+
Object.assign(this.syncStatus, updates);
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
// ── Accessors ─────────────────────────────────────────────────────────────
|
|
1464
|
+
get pool() {
|
|
1465
|
+
return this.objectPool;
|
|
1466
|
+
}
|
|
1467
|
+
get lastSyncId() {
|
|
1468
|
+
return this.lastAckedId;
|
|
1469
|
+
}
|
|
1470
|
+
// ── Status convenience getters ──────────────────────────────────────────
|
|
1471
|
+
// Thin wrappers over `syncStatus` for consumer ergonomics.
|
|
1472
|
+
get isReady() {
|
|
1473
|
+
// Ready if: fully synced (idle + 100%) OR local data loaded (dataReady + syncing in background)
|
|
1474
|
+
return (this.syncStatus.state === 'idle' && this.syncStatus.progress >= 100)
|
|
1475
|
+
|| (this.dataReady && this.syncStatus.state === 'syncing');
|
|
1476
|
+
}
|
|
1477
|
+
get isSyncing() {
|
|
1478
|
+
return this.syncStatus.state === 'syncing';
|
|
1479
|
+
}
|
|
1480
|
+
get isOffline() {
|
|
1481
|
+
return this.syncStatus.state === 'offline';
|
|
1482
|
+
}
|
|
1483
|
+
get isReconnecting() {
|
|
1484
|
+
return this.syncStatus.state === 'reconnecting';
|
|
1485
|
+
}
|
|
1486
|
+
get isError() {
|
|
1487
|
+
return this.syncStatus.state === 'error';
|
|
1488
|
+
}
|
|
1489
|
+
get hasUnsyncedChanges() {
|
|
1490
|
+
return this.syncStatus.pendingChanges > 0;
|
|
1491
|
+
}
|
|
1492
|
+
/** The SyncWebSocket handle — for collaboration events. */
|
|
1493
|
+
get ws() {
|
|
1494
|
+
return this.syncWebSocket;
|
|
1495
|
+
}
|
|
1496
|
+
/** The Database instance — for demand loaders and direct IDB operations. */
|
|
1497
|
+
get db() {
|
|
1498
|
+
return this.database;
|
|
1499
|
+
}
|
|
1500
|
+
/** The SyncClient instance — for assignment operations and other direct sync actions. */
|
|
1501
|
+
get sc() {
|
|
1502
|
+
return this.syncClient;
|
|
1503
|
+
}
|
|
1504
|
+
/** The current organization ID — from the last initialize() call. */
|
|
1505
|
+
get orgId() {
|
|
1506
|
+
return this.userContext?.organizationId;
|
|
1507
|
+
}
|
|
1508
|
+
/** Count models matching a predicate. */
|
|
1509
|
+
count(modelClass, predicate) {
|
|
1510
|
+
return countModels(this.objectPool, modelClass, this.pendingDeletes, predicate);
|
|
1511
|
+
}
|
|
1512
|
+
/** Get entities by foreign key (used by Model subclasses via Model.store) */
|
|
1513
|
+
getByForeignKey(modelName, foreignKey, id) {
|
|
1514
|
+
return this.objectPool.getByForeignKey(modelName, foreignKey, id);
|
|
1515
|
+
}
|
|
1516
|
+
}
|