@unwanted/matrix-sdk-mini 34.12.0-2 → 34.12.0-4
Sign up to get free protection for your applications and to get access to all the features.
- package/git-revision.txt +1 -1
- package/lib/@types/global.d.js +0 -2
- package/lib/@types/global.d.js.map +1 -1
- package/lib/browser-index.d.ts.map +1 -1
- package/lib/browser-index.js +0 -11
- package/lib/browser-index.js.map +1 -1
- package/lib/client.d.ts +2 -1221
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +331 -2821
- package/lib/client.js.map +1 -1
- package/lib/embedded.d.ts +0 -22
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +24 -166
- package/lib/embedded.js.map +1 -1
- package/lib/event-mapper.d.ts.map +1 -1
- package/lib/event-mapper.js +0 -4
- package/lib/event-mapper.js.map +1 -1
- package/lib/matrix.d.ts +0 -19
- package/lib/matrix.d.ts.map +1 -1
- package/lib/matrix.js +1 -26
- package/lib/matrix.js.map +1 -1
- package/lib/models/MSC3089Branch.d.ts.map +1 -1
- package/lib/models/MSC3089Branch.js +0 -3
- package/lib/models/MSC3089Branch.js.map +1 -1
- package/lib/models/event.d.ts +0 -94
- package/lib/models/event.d.ts.map +1 -1
- package/lib/models/event.js +0 -274
- package/lib/models/event.js.map +1 -1
- package/lib/models/poll.d.ts.map +1 -1
- package/lib/models/poll.js +1 -5
- package/lib/models/poll.js.map +1 -1
- package/lib/models/relations-container.d.ts.map +1 -1
- package/lib/models/relations-container.js +1 -7
- package/lib/models/relations-container.js.map +1 -1
- package/lib/models/relations.d.ts +0 -1
- package/lib/models/relations.d.ts.map +1 -1
- package/lib/models/relations.js +0 -8
- package/lib/models/relations.js.map +1 -1
- package/lib/models/room-state.d.ts.map +1 -1
- package/lib/models/room-state.js +10 -26
- package/lib/models/room-state.js.map +1 -1
- package/lib/models/room.d.ts +0 -18
- package/lib/models/room.d.ts.map +1 -1
- package/lib/models/room.js +94 -148
- package/lib/models/room.js.map +1 -1
- package/lib/models/thread.d.ts.map +1 -1
- package/lib/models/thread.js +0 -1
- package/lib/models/thread.js.map +1 -1
- package/lib/sliding-sync-sdk.d.ts +2 -3
- package/lib/sliding-sync-sdk.d.ts.map +1 -1
- package/lib/sliding-sync-sdk.js +41 -90
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sync.d.ts +0 -12
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +1 -73
- package/lib/sync.js.map +1 -1
- package/lib/testing.d.ts +0 -48
- package/lib/testing.d.ts.map +1 -1
- package/lib/testing.js +0 -105
- package/lib/testing.js.map +1 -1
- package/lib/types.d.ts +0 -1
- package/lib/types.d.ts.map +1 -1
- package/lib/types.js.map +1 -1
- package/package.json +1 -3
- package/src/@types/global.d.ts +0 -3
- package/src/browser-index.ts +0 -11
- package/src/client.ts +60 -2882
- package/src/embedded.ts +3 -130
- package/src/event-mapper.ts +0 -4
- package/src/matrix.ts +0 -28
- package/src/models/MSC3089Branch.ts +0 -3
- package/src/models/event.ts +0 -289
- package/src/models/poll.ts +0 -6
- package/src/models/relations-container.ts +1 -8
- package/src/models/relations.ts +0 -8
- package/src/models/room-state.ts +2 -8
- package/src/models/room.ts +0 -62
- package/src/models/thread.ts +0 -1
- package/src/sliding-sync-sdk.ts +2 -72
- package/src/sync.ts +1 -98
- package/src/testing.ts +0 -108
- package/src/types.ts +0 -1
- package/CHANGELOG.md +0 -5910
- package/lib/@types/AESEncryptedSecretStoragePayload.d.ts +0 -14
- package/lib/@types/AESEncryptedSecretStoragePayload.d.ts.map +0 -1
- package/lib/@types/AESEncryptedSecretStoragePayload.js +0 -1
- package/lib/@types/AESEncryptedSecretStoragePayload.js.map +0 -1
- package/lib/@types/crypto.d.ts +0 -47
- package/lib/@types/crypto.d.ts.map +0 -1
- package/lib/@types/crypto.js +0 -1
- package/lib/@types/crypto.js.map +0 -1
- package/lib/@types/matrix-sdk-crypto-wasm.d.js +0 -1
- package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +0 -1
- package/lib/common-crypto/CryptoBackend.d.ts +0 -240
- package/lib/common-crypto/CryptoBackend.d.ts.map +0 -1
- package/lib/common-crypto/CryptoBackend.js +0 -73
- package/lib/common-crypto/CryptoBackend.js.map +0 -1
- package/lib/common-crypto/key-passphrase.d.ts +0 -14
- package/lib/common-crypto/key-passphrase.d.ts.map +0 -1
- package/lib/common-crypto/key-passphrase.js +0 -33
- package/lib/common-crypto/key-passphrase.js.map +0 -1
- package/lib/crypto/CrossSigning.d.ts +0 -184
- package/lib/crypto/CrossSigning.d.ts.map +0 -1
- package/lib/crypto/CrossSigning.js +0 -718
- package/lib/crypto/CrossSigning.js.map +0 -1
- package/lib/crypto/DeviceList.d.ts +0 -216
- package/lib/crypto/DeviceList.d.ts.map +0 -1
- package/lib/crypto/DeviceList.js +0 -892
- package/lib/crypto/DeviceList.js.map +0 -1
- package/lib/crypto/EncryptionSetup.d.ts +0 -152
- package/lib/crypto/EncryptionSetup.d.ts.map +0 -1
- package/lib/crypto/EncryptionSetup.js +0 -356
- package/lib/crypto/EncryptionSetup.js.map +0 -1
- package/lib/crypto/OlmDevice.d.ts +0 -457
- package/lib/crypto/OlmDevice.d.ts.map +0 -1
- package/lib/crypto/OlmDevice.js +0 -1241
- package/lib/crypto/OlmDevice.js.map +0 -1
- package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts +0 -109
- package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts.map +0 -1
- package/lib/crypto/OutgoingRoomKeyRequestManager.js +0 -415
- package/lib/crypto/OutgoingRoomKeyRequestManager.js.map +0 -1
- package/lib/crypto/RoomList.d.ts +0 -26
- package/lib/crypto/RoomList.d.ts.map +0 -1
- package/lib/crypto/RoomList.js +0 -71
- package/lib/crypto/RoomList.js.map +0 -1
- package/lib/crypto/SecretSharing.d.ts +0 -24
- package/lib/crypto/SecretSharing.d.ts.map +0 -1
- package/lib/crypto/SecretSharing.js +0 -194
- package/lib/crypto/SecretSharing.js.map +0 -1
- package/lib/crypto/SecretStorage.d.ts +0 -55
- package/lib/crypto/SecretStorage.d.ts.map +0 -1
- package/lib/crypto/SecretStorage.js +0 -118
- package/lib/crypto/SecretStorage.js.map +0 -1
- package/lib/crypto/aes.d.ts +0 -6
- package/lib/crypto/aes.d.ts.map +0 -1
- package/lib/crypto/aes.js +0 -24
- package/lib/crypto/aes.js.map +0 -1
- package/lib/crypto/algorithms/base.d.ts +0 -156
- package/lib/crypto/algorithms/base.d.ts.map +0 -1
- package/lib/crypto/algorithms/base.js +0 -187
- package/lib/crypto/algorithms/base.js.map +0 -1
- package/lib/crypto/algorithms/index.d.ts +0 -4
- package/lib/crypto/algorithms/index.d.ts.map +0 -1
- package/lib/crypto/algorithms/index.js +0 -20
- package/lib/crypto/algorithms/index.js.map +0 -1
- package/lib/crypto/algorithms/megolm.d.ts +0 -385
- package/lib/crypto/algorithms/megolm.d.ts.map +0 -1
- package/lib/crypto/algorithms/megolm.js +0 -1822
- package/lib/crypto/algorithms/megolm.js.map +0 -1
- package/lib/crypto/algorithms/olm.d.ts +0 -5
- package/lib/crypto/algorithms/olm.d.ts.map +0 -1
- package/lib/crypto/algorithms/olm.js +0 -299
- package/lib/crypto/algorithms/olm.js.map +0 -1
- package/lib/crypto/api.d.ts +0 -32
- package/lib/crypto/api.d.ts.map +0 -1
- package/lib/crypto/api.js +0 -22
- package/lib/crypto/api.js.map +0 -1
- package/lib/crypto/backup.d.ts +0 -227
- package/lib/crypto/backup.d.ts.map +0 -1
- package/lib/crypto/backup.js +0 -824
- package/lib/crypto/backup.js.map +0 -1
- package/lib/crypto/crypto.d.ts +0 -3
- package/lib/crypto/crypto.d.ts.map +0 -1
- package/lib/crypto/crypto.js +0 -19
- package/lib/crypto/crypto.js.map +0 -1
- package/lib/crypto/dehydration.d.ts +0 -34
- package/lib/crypto/dehydration.d.ts.map +0 -1
- package/lib/crypto/dehydration.js +0 -252
- package/lib/crypto/dehydration.js.map +0 -1
- package/lib/crypto/device-converter.d.ts +0 -9
- package/lib/crypto/device-converter.d.ts.map +0 -1
- package/lib/crypto/device-converter.js +0 -42
- package/lib/crypto/device-converter.js.map +0 -1
- package/lib/crypto/deviceinfo.d.ts +0 -99
- package/lib/crypto/deviceinfo.d.ts.map +0 -1
- package/lib/crypto/deviceinfo.js +0 -148
- package/lib/crypto/deviceinfo.js.map +0 -1
- package/lib/crypto/index.d.ts +0 -1209
- package/lib/crypto/index.d.ts.map +0 -1
- package/lib/crypto/index.js +0 -4097
- package/lib/crypto/index.js.map +0 -1
- package/lib/crypto/key_passphrase.d.ts +0 -14
- package/lib/crypto/key_passphrase.d.ts.map +0 -1
- package/lib/crypto/key_passphrase.js +0 -44
- package/lib/crypto/key_passphrase.js.map +0 -1
- package/lib/crypto/keybackup.d.ts +0 -18
- package/lib/crypto/keybackup.d.ts.map +0 -1
- package/lib/crypto/keybackup.js +0 -1
- package/lib/crypto/keybackup.js.map +0 -1
- package/lib/crypto/olmlib.d.ts +0 -129
- package/lib/crypto/olmlib.d.ts.map +0 -1
- package/lib/crypto/olmlib.js +0 -492
- package/lib/crypto/olmlib.js.map +0 -1
- package/lib/crypto/recoverykey.d.ts +0 -2
- package/lib/crypto/recoverykey.d.ts.map +0 -1
- package/lib/crypto/recoverykey.js +0 -19
- package/lib/crypto/recoverykey.js.map +0 -1
- package/lib/crypto/store/base.d.ts +0 -252
- package/lib/crypto/store/base.d.ts.map +0 -1
- package/lib/crypto/store/base.js +0 -64
- package/lib/crypto/store/base.js.map +0 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts +0 -187
- package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts.map +0 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js +0 -1145
- package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +0 -1
- package/lib/crypto/store/indexeddb-crypto-store.d.ts +0 -432
- package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +0 -1
- package/lib/crypto/store/indexeddb-crypto-store.js +0 -728
- package/lib/crypto/store/indexeddb-crypto-store.js.map +0 -1
- package/lib/crypto/store/localStorage-crypto-store.d.ts +0 -119
- package/lib/crypto/store/localStorage-crypto-store.d.ts.map +0 -1
- package/lib/crypto/store/localStorage-crypto-store.js +0 -531
- package/lib/crypto/store/localStorage-crypto-store.js.map +0 -1
- package/lib/crypto/store/memory-crypto-store.d.ts +0 -215
- package/lib/crypto/store/memory-crypto-store.d.ts.map +0 -1
- package/lib/crypto/store/memory-crypto-store.js +0 -622
- package/lib/crypto/store/memory-crypto-store.js.map +0 -1
- package/lib/crypto/verification/Base.d.ts +0 -105
- package/lib/crypto/verification/Base.d.ts.map +0 -1
- package/lib/crypto/verification/Base.js +0 -372
- package/lib/crypto/verification/Base.js.map +0 -1
- package/lib/crypto/verification/Error.d.ts +0 -35
- package/lib/crypto/verification/Error.d.ts.map +0 -1
- package/lib/crypto/verification/Error.js +0 -86
- package/lib/crypto/verification/Error.js.map +0 -1
- package/lib/crypto/verification/IllegalMethod.d.ts +0 -15
- package/lib/crypto/verification/IllegalMethod.d.ts.map +0 -1
- package/lib/crypto/verification/IllegalMethod.js +0 -43
- package/lib/crypto/verification/IllegalMethod.js.map +0 -1
- package/lib/crypto/verification/QRCode.d.ts +0 -51
- package/lib/crypto/verification/QRCode.d.ts.map +0 -1
- package/lib/crypto/verification/QRCode.js +0 -277
- package/lib/crypto/verification/QRCode.js.map +0 -1
- package/lib/crypto/verification/SAS.d.ts +0 -27
- package/lib/crypto/verification/SAS.d.ts.map +0 -1
- package/lib/crypto/verification/SAS.js +0 -485
- package/lib/crypto/verification/SAS.js.map +0 -1
- package/lib/crypto/verification/SASDecimal.d.ts +0 -8
- package/lib/crypto/verification/SASDecimal.d.ts.map +0 -1
- package/lib/crypto/verification/SASDecimal.js +0 -34
- package/lib/crypto/verification/SASDecimal.js.map +0 -1
- package/lib/crypto/verification/request/Channel.d.ts +0 -18
- package/lib/crypto/verification/request/Channel.d.ts.map +0 -1
- package/lib/crypto/verification/request/Channel.js +0 -1
- package/lib/crypto/verification/request/Channel.js.map +0 -1
- package/lib/crypto/verification/request/InRoomChannel.d.ts +0 -113
- package/lib/crypto/verification/request/InRoomChannel.d.ts.map +0 -1
- package/lib/crypto/verification/request/InRoomChannel.js +0 -351
- package/lib/crypto/verification/request/InRoomChannel.js.map +0 -1
- package/lib/crypto/verification/request/ToDeviceChannel.d.ts +0 -105
- package/lib/crypto/verification/request/ToDeviceChannel.d.ts.map +0 -1
- package/lib/crypto/verification/request/ToDeviceChannel.js +0 -328
- package/lib/crypto/verification/request/ToDeviceChannel.js.map +0 -1
- package/lib/crypto/verification/request/VerificationRequest.d.ts +0 -227
- package/lib/crypto/verification/request/VerificationRequest.d.ts.map +0 -1
- package/lib/crypto/verification/request/VerificationRequest.js +0 -937
- package/lib/crypto/verification/request/VerificationRequest.js.map +0 -1
- package/lib/crypto-api/CryptoEvent.d.ts +0 -69
- package/lib/crypto-api/CryptoEvent.d.ts.map +0 -1
- package/lib/crypto-api/CryptoEvent.js +0 -33
- package/lib/crypto-api/CryptoEvent.js.map +0 -1
- package/lib/crypto-api/CryptoEventHandlerMap.d.ts +0 -16
- package/lib/crypto-api/CryptoEventHandlerMap.d.ts.map +0 -1
- package/lib/crypto-api/CryptoEventHandlerMap.js +0 -22
- package/lib/crypto-api/CryptoEventHandlerMap.js.map +0 -1
- package/lib/crypto-api/index.d.ts +0 -978
- package/lib/crypto-api/index.d.ts.map +0 -1
- package/lib/crypto-api/index.js +0 -304
- package/lib/crypto-api/index.js.map +0 -1
- package/lib/crypto-api/key-passphrase.d.ts +0 -11
- package/lib/crypto-api/key-passphrase.d.ts.map +0 -1
- package/lib/crypto-api/key-passphrase.js +0 -51
- package/lib/crypto-api/key-passphrase.js.map +0 -1
- package/lib/crypto-api/keybackup.d.ts +0 -88
- package/lib/crypto-api/keybackup.d.ts.map +0 -1
- package/lib/crypto-api/keybackup.js +0 -1
- package/lib/crypto-api/keybackup.js.map +0 -1
- package/lib/crypto-api/recovery-key.d.ts +0 -11
- package/lib/crypto-api/recovery-key.d.ts.map +0 -1
- package/lib/crypto-api/recovery-key.js +0 -65
- package/lib/crypto-api/recovery-key.js.map +0 -1
- package/lib/crypto-api/verification.d.ts +0 -344
- package/lib/crypto-api/verification.d.ts.map +0 -1
- package/lib/crypto-api/verification.js +0 -91
- package/lib/crypto-api/verification.js.map +0 -1
- package/lib/rendezvous/MSC4108SignInWithQR.d.ts +0 -112
- package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +0 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js +0 -392
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +0 -1
- package/lib/rendezvous/RendezvousChannel.d.ts +0 -27
- package/lib/rendezvous/RendezvousChannel.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousChannel.js +0 -1
- package/lib/rendezvous/RendezvousChannel.js.map +0 -1
- package/lib/rendezvous/RendezvousCode.d.ts +0 -9
- package/lib/rendezvous/RendezvousCode.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousCode.js +0 -1
- package/lib/rendezvous/RendezvousCode.js.map +0 -1
- package/lib/rendezvous/RendezvousError.d.ts +0 -6
- package/lib/rendezvous/RendezvousError.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousError.js +0 -23
- package/lib/rendezvous/RendezvousError.js.map +0 -1
- package/lib/rendezvous/RendezvousFailureReason.d.ts +0 -31
- package/lib/rendezvous/RendezvousFailureReason.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousFailureReason.js +0 -38
- package/lib/rendezvous/RendezvousFailureReason.js.map +0 -1
- package/lib/rendezvous/RendezvousIntent.d.ts +0 -5
- package/lib/rendezvous/RendezvousIntent.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousIntent.js +0 -22
- package/lib/rendezvous/RendezvousIntent.js.map +0 -1
- package/lib/rendezvous/RendezvousTransport.d.ts +0 -36
- package/lib/rendezvous/RendezvousTransport.d.ts.map +0 -1
- package/lib/rendezvous/RendezvousTransport.js +0 -1
- package/lib/rendezvous/RendezvousTransport.js.map +0 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts +0 -58
- package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +0 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.js +0 -246
- package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +0 -1
- package/lib/rendezvous/channels/index.d.ts +0 -2
- package/lib/rendezvous/channels/index.d.ts.map +0 -1
- package/lib/rendezvous/channels/index.js +0 -18
- package/lib/rendezvous/channels/index.js.map +0 -1
- package/lib/rendezvous/index.d.ts +0 -10
- package/lib/rendezvous/index.d.ts.map +0 -1
- package/lib/rendezvous/index.js +0 -23
- package/lib/rendezvous/index.js.map +0 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +0 -61
- package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +0 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js +0 -253
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +0 -1
- package/lib/rendezvous/transports/index.d.ts +0 -2
- package/lib/rendezvous/transports/index.d.ts.map +0 -1
- package/lib/rendezvous/transports/index.js +0 -18
- package/lib/rendezvous/transports/index.js.map +0 -1
- package/lib/rust-crypto/CrossSigningIdentity.d.ts +0 -33
- package/lib/rust-crypto/CrossSigningIdentity.d.ts.map +0 -1
- package/lib/rust-crypto/CrossSigningIdentity.js +0 -157
- package/lib/rust-crypto/CrossSigningIdentity.js.map +0 -1
- package/lib/rust-crypto/DehydratedDeviceManager.d.ts +0 -98
- package/lib/rust-crypto/DehydratedDeviceManager.d.ts.map +0 -1
- package/lib/rust-crypto/DehydratedDeviceManager.js +0 -285
- package/lib/rust-crypto/DehydratedDeviceManager.js.map +0 -1
- package/lib/rust-crypto/KeyClaimManager.d.ts +0 -33
- package/lib/rust-crypto/KeyClaimManager.d.ts.map +0 -1
- package/lib/rust-crypto/KeyClaimManager.js +0 -82
- package/lib/rust-crypto/KeyClaimManager.js.map +0 -1
- package/lib/rust-crypto/OutgoingRequestProcessor.d.ts +0 -43
- package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +0 -1
- package/lib/rust-crypto/OutgoingRequestProcessor.js +0 -195
- package/lib/rust-crypto/OutgoingRequestProcessor.js.map +0 -1
- package/lib/rust-crypto/OutgoingRequestsManager.d.ts +0 -47
- package/lib/rust-crypto/OutgoingRequestsManager.d.ts.map +0 -1
- package/lib/rust-crypto/OutgoingRequestsManager.js +0 -148
- package/lib/rust-crypto/OutgoingRequestsManager.js.map +0 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +0 -120
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts.map +0 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +0 -467
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +0 -1
- package/lib/rust-crypto/RoomEncryptor.d.ts +0 -98
- package/lib/rust-crypto/RoomEncryptor.d.ts.map +0 -1
- package/lib/rust-crypto/RoomEncryptor.js +0 -299
- package/lib/rust-crypto/RoomEncryptor.js.map +0 -1
- package/lib/rust-crypto/backup.d.ts +0 -254
- package/lib/rust-crypto/backup.d.ts.map +0 -1
- package/lib/rust-crypto/backup.js +0 -837
- package/lib/rust-crypto/backup.js.map +0 -1
- package/lib/rust-crypto/constants.d.ts +0 -3
- package/lib/rust-crypto/constants.d.ts.map +0 -1
- package/lib/rust-crypto/constants.js +0 -19
- package/lib/rust-crypto/constants.js.map +0 -1
- package/lib/rust-crypto/device-converter.d.ts +0 -28
- package/lib/rust-crypto/device-converter.d.ts.map +0 -1
- package/lib/rust-crypto/device-converter.js +0 -123
- package/lib/rust-crypto/device-converter.js.map +0 -1
- package/lib/rust-crypto/index.d.ts +0 -61
- package/lib/rust-crypto/index.d.ts.map +0 -1
- package/lib/rust-crypto/index.js +0 -152
- package/lib/rust-crypto/index.js.map +0 -1
- package/lib/rust-crypto/libolm_migration.d.ts +0 -81
- package/lib/rust-crypto/libolm_migration.d.ts.map +0 -1
- package/lib/rust-crypto/libolm_migration.js +0 -459
- package/lib/rust-crypto/libolm_migration.js.map +0 -1
- package/lib/rust-crypto/rust-crypto.d.ts +0 -556
- package/lib/rust-crypto/rust-crypto.d.ts.map +0 -1
- package/lib/rust-crypto/rust-crypto.js +0 -2016
- package/lib/rust-crypto/rust-crypto.js.map +0 -1
- package/lib/rust-crypto/secret-storage.d.ts +0 -22
- package/lib/rust-crypto/secret-storage.d.ts.map +0 -1
- package/lib/rust-crypto/secret-storage.js +0 -63
- package/lib/rust-crypto/secret-storage.js.map +0 -1
- package/lib/rust-crypto/verification.d.ts +0 -319
- package/lib/rust-crypto/verification.d.ts.map +0 -1
- package/lib/rust-crypto/verification.js +0 -816
- package/lib/rust-crypto/verification.js.map +0 -1
- package/lib/secret-storage.d.ts +0 -370
- package/lib/secret-storage.d.ts.map +0 -1
- package/lib/secret-storage.js +0 -466
- package/lib/secret-storage.js.map +0 -1
- package/lib/utils/decryptAESSecretStorageItem.d.ts +0 -12
- package/lib/utils/decryptAESSecretStorageItem.d.ts.map +0 -1
- package/lib/utils/decryptAESSecretStorageItem.js +0 -50
- package/lib/utils/decryptAESSecretStorageItem.js.map +0 -1
- package/lib/utils/encryptAESSecretStorageItem.d.ts +0 -16
- package/lib/utils/encryptAESSecretStorageItem.d.ts.map +0 -1
- package/lib/utils/encryptAESSecretStorageItem.js +0 -68
- package/lib/utils/encryptAESSecretStorageItem.js.map +0 -1
- package/lib/utils/internal/deriveKeys.d.ts +0 -10
- package/lib/utils/internal/deriveKeys.d.ts.map +0 -1
- package/lib/utils/internal/deriveKeys.js +0 -60
- package/lib/utils/internal/deriveKeys.js.map +0 -1
- package/src/@types/AESEncryptedSecretStoragePayload.ts +0 -29
- package/src/@types/crypto.ts +0 -73
- package/src/@types/matrix-sdk-crypto-wasm.d.ts +0 -44
- package/src/common-crypto/CryptoBackend.ts +0 -302
- package/src/common-crypto/README.md +0 -4
- package/src/common-crypto/key-passphrase.ts +0 -43
- package/src/crypto/CrossSigning.ts +0 -773
- package/src/crypto/DeviceList.ts +0 -989
- package/src/crypto/EncryptionSetup.ts +0 -351
- package/src/crypto/OlmDevice.ts +0 -1500
- package/src/crypto/OutgoingRoomKeyRequestManager.ts +0 -485
- package/src/crypto/RoomList.ts +0 -70
- package/src/crypto/SecretSharing.ts +0 -240
- package/src/crypto/SecretStorage.ts +0 -136
- package/src/crypto/aes.ts +0 -23
- package/src/crypto/algorithms/base.ts +0 -236
- package/src/crypto/algorithms/index.ts +0 -20
- package/src/crypto/algorithms/megolm.ts +0 -2216
- package/src/crypto/algorithms/olm.ts +0 -381
- package/src/crypto/api.ts +0 -70
- package/src/crypto/backup.ts +0 -922
- package/src/crypto/crypto.ts +0 -18
- package/src/crypto/dehydration.ts +0 -272
- package/src/crypto/device-converter.ts +0 -45
- package/src/crypto/deviceinfo.ts +0 -158
- package/src/crypto/index.ts +0 -4414
- package/src/crypto/key_passphrase.ts +0 -42
- package/src/crypto/keybackup.ts +0 -47
- package/src/crypto/olmlib.ts +0 -539
- package/src/crypto/recoverykey.ts +0 -18
- package/src/crypto/store/base.ts +0 -348
- package/src/crypto/store/indexeddb-crypto-store-backend.ts +0 -1250
- package/src/crypto/store/indexeddb-crypto-store.ts +0 -845
- package/src/crypto/store/localStorage-crypto-store.ts +0 -579
- package/src/crypto/store/memory-crypto-store.ts +0 -680
- package/src/crypto/verification/Base.ts +0 -409
- package/src/crypto/verification/Error.ts +0 -76
- package/src/crypto/verification/IllegalMethod.ts +0 -50
- package/src/crypto/verification/QRCode.ts +0 -310
- package/src/crypto/verification/SAS.ts +0 -494
- package/src/crypto/verification/SASDecimal.ts +0 -37
- package/src/crypto/verification/request/Channel.ts +0 -34
- package/src/crypto/verification/request/InRoomChannel.ts +0 -371
- package/src/crypto/verification/request/ToDeviceChannel.ts +0 -354
- package/src/crypto/verification/request/VerificationRequest.ts +0 -976
- package/src/crypto-api/CryptoEvent.ts +0 -93
- package/src/crypto-api/CryptoEventHandlerMap.ts +0 -32
- package/src/crypto-api/index.ts +0 -1175
- package/src/crypto-api/key-passphrase.ts +0 -58
- package/src/crypto-api/keybackup.ts +0 -115
- package/src/crypto-api/recovery-key.ts +0 -69
- package/src/crypto-api/verification.ts +0 -408
- package/src/rendezvous/MSC4108SignInWithQR.ts +0 -444
- package/src/rendezvous/RendezvousChannel.ts +0 -48
- package/src/rendezvous/RendezvousCode.ts +0 -25
- package/src/rendezvous/RendezvousError.ts +0 -26
- package/src/rendezvous/RendezvousFailureReason.ts +0 -49
- package/src/rendezvous/RendezvousIntent.ts +0 -20
- package/src/rendezvous/RendezvousTransport.ts +0 -58
- package/src/rendezvous/channels/MSC4108SecureChannel.ts +0 -270
- package/src/rendezvous/channels/index.ts +0 -17
- package/src/rendezvous/index.ts +0 -25
- package/src/rendezvous/transports/MSC4108RendezvousSession.ts +0 -270
- package/src/rendezvous/transports/index.ts +0 -17
- package/src/rust-crypto/CrossSigningIdentity.ts +0 -183
- package/src/rust-crypto/DehydratedDeviceManager.ts +0 -306
- package/src/rust-crypto/KeyClaimManager.ts +0 -86
- package/src/rust-crypto/OutgoingRequestProcessor.ts +0 -236
- package/src/rust-crypto/OutgoingRequestsManager.ts +0 -143
- package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +0 -501
- package/src/rust-crypto/RoomEncryptor.ts +0 -352
- package/src/rust-crypto/backup.ts +0 -881
- package/src/rust-crypto/constants.ts +0 -18
- package/src/rust-crypto/device-converter.ts +0 -128
- package/src/rust-crypto/index.ts +0 -237
- package/src/rust-crypto/libolm_migration.ts +0 -530
- package/src/rust-crypto/rust-crypto.ts +0 -2205
- package/src/rust-crypto/secret-storage.ts +0 -60
- package/src/rust-crypto/verification.ts +0 -830
- package/src/secret-storage.ts +0 -693
- package/src/utils/decryptAESSecretStorageItem.ts +0 -54
- package/src/utils/encryptAESSecretStorageItem.ts +0 -73
- package/src/utils/internal/deriveKeys.ts +0 -63
package/lib/sync.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"sync.js","names":["User","NotificationCountType","Room","RoomEvent","deepCopy","defer","noUnsafeEventProps","promiseMapSeries","unsafeProp","Filter","EventTimeline","logger","ClientEvent","PendingEventOrdering","Method","EventType","RoomStateEvent","RoomMemberEvent","BeaconEvent","UNREAD_THREAD_NOTIFICATIONS","Feature","ServerSupport","KnownMembership","DEBUG","BUFFER_PERIOD_MS","FAILED_SYNC_ERROR_THRESHOLD","SyncState","MSC2716_ROOM_VERSIONS","getFilterName","userId","suffix","concat","debuglog","log","arguments","SetPresence","defaultClientOpts","opts","_objectSpread","initialSyncLimit","resolveInvitesToProfiles","pollTimeout","pendingEventOrdering","Chronological","threadSupport","defaultSyncApiOpts","syncOpts","canResetEntireTimeline","_roomId","SyncApi","constructor","client","_this","_defineProperty","_asyncToGenerator","result","getPushRules","pushRules","err","error","shouldAbortSync","recoverFromSyncStartupError","savedSyncPromise","filter","credentials","canSupport","get","ThreadUnreadNotifications","Unsupported","setUnreadThreadNotifications","isGuest","lazyLoadMembers","buildDefaultFilter","setLazyLoadMembers","_this$syncOpts$crypto","crypto","enableLazyLoading","storeClientOptions","filterId","getOrCreateFilter","getFilter","startKeepAlives","getNotifTimelineSet","reEmitter","reEmit","Timeline","TimelineReset","createRoom","roomId","room","_createAndReEmitRoom","on","Marker","markerEvent","markerFoundOptions","onMarkerStateEvent","timelineWasEmpty","length","undefined","debug","getId","isValidMsc2716Event","includes","getVersion","getSender","getCreator","setTimelineNeedsRefresh","emit","HistoryImportedWithinTimeline","syncLeftRooms","_this2","_data$rooms","setTimelineLimit","setIncludeLeaveRooms","localTimeoutMs","qps","timeout","data","http","authedRequest","Get","leaveRooms","rooms","leave","mapSyncResponseToRoomArray","Promise","all","map","_ref5","leaveObj","isBrandNewRoom","timeline","prev_batch","events","mapSyncEventsFormat","stateEvents","state","getLiveTimeline","setPaginationToken","BACKWARDS","injectRoomEvents","recalculate","store","storeRoom","processEventsForNotifs","_x","apply","Boolean","peek","_this$_peekRoom","limit","_peekRoom","resolve","roomInitialSync","then","response","_this$_peekRoom2","Error","messages","chunk","oldStateEvents","getEventMapper","Array","isArray","presence","forEach","presenceEvent","user","getUser","getContent","user_id","setPresenceEvent","createUser","storeUser","Event","start","oldState","paginationToken","setStateEvents","currentState","resolveInvites","addEventsToTimeline","reverse","peekPoll","stopPeeking","peekRoom","token","_this$abortController","_this3","room_id","String","from","abortSignal","abortController","signal","_ref6","res","e","type","event_id","addLiveEvents","end","_x2","setTimeout","getSyncState","syncState","getSyncStateData","_this$syncStateData","syncStateData","_this4","keepaliveProm","updateSyncState","errcode","warn","stop","sync","_this5","_globalThis$window","_globalThis$window$ad","running","AbortController","globalThis","window","addEventListener","call","onOnline","doSync","savedSyncTokenPromise","getSavedSyncToken","tok","getSavedSync","savedSync","syncFromCache","catch","prepareLazyLoadingForSync","resetNotifTimelineSet","currentSyncRequest","firstSyncFilter","savedSyncToken","initialFilter","setDefinition","getDefinition","JSON","stringify","doSyncRequest","_globalThis$window2","_globalThis$window2$r","_this$abortController2","removeEventListener","abort","keepAliveTimer","clearTimeout","retryImmediately","connectionReturnedDefer","_this6","nextSyncToken","nextBatch","setSyncToken","syncEventData","catchingUp","fromCache","next_batch","roomsData","account_data","accountData","processSyncResponse","storeIsInvalid","Prepared","syncOptions","_this7","syncToken","getSyncToken","onSyncError","failedSyncCount","oldSyncToken","onSyncWillProcess","SyncUnexpectedError","setSyncData","hasSyncedBefore","cryptoCallbacks","onSyncCompleted","Syncing","wantsSave","saveDeviceList","save","reject","Stopped","_this$abortController3","getSyncParams","getGuestFilter","disablePresence","set_presence","Offline","since","_cacheBuster","Date","now","Reconnecting","setPresence","_this8","keepAlivePromise","connDidFail","Catchup","_this9","_data$presence","_data$account_data","_this9$syncOpts$crypt","_data$device_unused_f","prevEventsMap","reduce","m","c","getType","getAccountData","storeAccountDataEvents","accountDataEvent","PushRules","rules","setPushRules","prevEvent","AccountData","to_device","toDeviceMessages","preprocessToDeviceMessages","cancelledKeyVerificationTxns","toDevice","toDeviceEvent","txnId","push","content","msgtype","flagCancelled","ToDeviceEvent","inviteRooms","joinRooms","knockRooms","invite","join","knock","notifEvents","_ref7","inviteObj","_room$currentState$ge","invite_state","inviter","getStateEvents","RoomMember","getUserId","parkedHistory","cryptoStore","takeParkedSharedHistory","parked","senderId","olmDevice","addInboundGroupSession","senderKey","forwardingCurve25519KeyChain","sessionId","sessionKey","keysClaimed","sharedHistory","untrusted","_x3","_ref8","joinObj","_joinObj$UNREAD_THREA","ephemeralEvents","ephemeral","accountDataEvents","encrypted","isRoomEncrypted","unread_notifications","notification_count","_joinObj$unread_notif","setUnreadNotificationCount","Total","getUnreadNotificationCount","Highlight","_joinObj$unread_notif2","highlight_count","unreadThreadNotifications","name","altName","resetThreadUnreadNotificationCountFromSync","Object","keys","threadId","unreadNotification","entries","_unreadNotification$n","setThreadUnreadNotificationCount","hasNoNotifications","getThreadUnreadNotificationCount","_unreadNotification$h","limited","i","eventId","getTimelineForEvent","splice","_syncEventData$oldSyn","resetLiveTimeline","isState","RoomEncryption","getStateKey","onCryptoEvent","summary","setSummary","addEphemeralEvents","addAccountData","emitEvent","decryptCriticalEvents","_x4","_ref9","_x5","_ref10","knockObj","knock_state","_x6","sort","a","b","getTs","event","_client$getNotifTimel","addLiveEvent","device_lists","processDeviceLists","processKeyCounts","device_one_time_keys_count","device_unused_fallback_key_types","delay","Math","floor","random","pokeKeepAlive","bind","promise","_this$abortController4","success","request","prefix","httpStatus","obj","k","getRoom","decrypt","mapper","getMembersWithMembership","Invite","member","requestedProfileInfo","avatar_url","avatarUrl","displayname","displayName","getProfileInfo","info","inviteEvent","membership","setMembershipEvent","findEncryptionEvent","find","stateEventList","timelineEventList","hasEncryptionStateEvent","_arguments","_this10","liveTimeline","getEvents","ev","getPushActionsForEvent","initialiseState","processBeaconEvents","_pushActions$tweaks","pushActions","notify","tweaks","highlight","newState","old","Sync","timelineSupport","Name","Redaction","RedactionCancelled","Receipt","Tags","LocalEchoUpdated","MyMembership","Events","Members","NewMember","Update","New","Destroy","LivenessChange","_client$getUser","Typing","PowerLevel","Membership"],"sources":["../src/sync.ts"],"sourcesContent":["/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport type { SyncCryptoCallbacks } from \"./common-crypto/CryptoBackend.ts\";\nimport { User } from \"./models/user.ts\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.ts\";\nimport { deepCopy, defer, IDeferred, noUnsafeEventProps, promiseMapSeries, unsafeProp } from \"./utils.ts\";\nimport { Filter } from \"./filter.ts\";\nimport { EventTimeline } from \"./models/event-timeline.ts\";\nimport { logger } from \"./logger.ts\";\nimport { ClientEvent, IStoredClientOpts, MatrixClient, PendingEventOrdering, ResetTimelineCallback } from \"./client.ts\";\nimport {\n IEphemeral,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IKnockedRoom,\n IMinimalEvent,\n IRoomEvent,\n IStateEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IToDeviceEvent,\n} from \"./sync-accumulator.ts\";\nimport { MatrixEvent } from \"./models/event.ts\";\nimport { MatrixError, Method } from \"./http-api/index.ts\";\nimport { ISavedSync } from \"./store/index.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { IPushRules } from \"./@types/PushRules.ts\";\nimport { RoomStateEvent, IMarkerFoundOptions } from \"./models/room-state.ts\";\nimport { RoomMemberEvent } from \"./models/room-member.ts\";\nimport { BeaconEvent } from \"./models/beacon.ts\";\nimport { IEventsResponse } from \"./@types/requests.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { Feature, ServerSupport } from \"./feature.ts\";\nimport { Crypto } from \"./crypto/index.ts\";\nimport { KnownMembership } from \"./@types/membership.ts\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nexport enum SyncState {\n /** Emitted after we try to sync more than `FAILED_SYNC_ERROR_THRESHOLD`\n * times and are still failing. Or when we enounter a hard error like the\n * token being invalid. */\n Error = \"ERROR\",\n /** Emitted after the first sync events are ready (this could even be sync\n * events from the cache) */\n Prepared = \"PREPARED\",\n /** Emitted when the sync loop is no longer running */\n Stopped = \"STOPPED\",\n /** Emitted after each sync request happens */\n Syncing = \"SYNCING\",\n /** Emitted after a connectivity error and we're ready to start syncing again */\n Catchup = \"CATCHUP\",\n /** Emitted for each time we try reconnecting. Will switch to `Error` after\n * we reach the `FAILED_SYNC_ERROR_THRESHOLD`\n */\n Reconnecting = \"RECONNECTING\",\n}\n\n// Room versions where \"insertion\", \"batch\", and \"marker\" events are controlled\n// by power-levels. MSC2716 is supported in existing room versions but they\n// should only have special meaning when the room creator sends them.\nconst MSC2716_ROOM_VERSIONS = [\"org.matrix.msc2716v3\"];\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return `FILTER_SYNC_${userId}` + (suffix ? \"_\" + suffix : \"\");\n}\n\n/* istanbul ignore next */\nfunction debuglog(...params: any[]): void {\n if (!DEBUG) return;\n logger.log(...params);\n}\n\n/**\n * Options passed into the constructor of SyncApi by MatrixClient\n */\nexport interface SyncApiOptions {\n /**\n * Crypto manager\n *\n * @deprecated in favour of cryptoCallbacks\n */\n crypto?: Crypto;\n\n /**\n * If crypto is enabled on our client, callbacks into the crypto module\n */\n cryptoCallbacks?: SyncCryptoCallbacks;\n\n /**\n * A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n */\n canResetEntireTimeline?: ResetTimelineCallback;\n}\n\ninterface ISyncOptions {\n filter?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n /**\n * The matrix error if `state=ERROR`.\n */\n error?: Error;\n /**\n * The 'since' token passed to /sync.\n * `null` for the first successful sync since this client was\n * started. Only present if `state=PREPARED` or\n * `state=SYNCING`.\n */\n oldSyncToken?: string;\n /**\n * The 'next_batch' result from /sync, which\n * will become the 'since' token for the next call to /sync. Only present if\n * `state=PREPARED</code> or <code>state=SYNCING`.\n */\n nextSyncToken?: string;\n /**\n * True if we are working our way through a\n * backlog of events after connecting. Only present if `state=SYNCING`.\n */\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\nexport enum SetPresence {\n Offline = \"offline\",\n Online = \"online\",\n Unavailable = \"unavailable\",\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: SetPresence;\n _cacheBuster?: string | number; // not part of the API itself\n}\n\ntype WrappedRoom<T> = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/** add default settings to an IStoredClientOpts */\nexport function defaultClientOpts(opts?: IStoredClientOpts): IStoredClientOpts {\n return {\n initialSyncLimit: 8,\n resolveInvitesToProfiles: false,\n pollTimeout: 30 * 1000,\n pendingEventOrdering: PendingEventOrdering.Chronological,\n threadSupport: false,\n ...opts,\n };\n}\n\nexport function defaultSyncApiOpts(syncOpts?: SyncApiOptions): SyncApiOptions {\n return {\n canResetEntireTimeline: (_roomId): boolean => false,\n ...syncOpts,\n };\n}\n\nexport class SyncApi {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n\n private _peekRoom: Optional<Room> = null;\n private currentSyncRequest?: Promise<ISyncResponse>;\n private abortController?: AbortController;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer?: ReturnType<typeof setTimeout>;\n private connectionReturnedDefer?: IDeferred<boolean>;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n private failedSyncCount = 0; // Number of consecutive failed /sync requests\n private storeIsInvalid = false; // flag set if the store needs to be cleared before we can start\n private presence?: SetPresence;\n\n /**\n * Construct an entity which is able to sync with a homeserver.\n * @param client - The matrix client instance to use.\n * @param opts - client config options\n * @param syncOpts - sync-specific options passed by the client\n * @internal\n */\n public constructor(\n private readonly client: MatrixClient,\n opts?: IStoredClientOpts,\n syncOpts?: SyncApiOptions,\n ) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n }\n\n public createRoom(roomId: string): Room {\n const room = _createAndReEmitRoom(this.client, roomId, this.opts);\n\n room.on(RoomStateEvent.Marker, (markerEvent, markerFoundOptions) => {\n this.onMarkerStateEvent(room, markerEvent, markerFoundOptions);\n });\n\n return room;\n }\n\n /** When we see the marker state change in the room, we know there is some\n * new historical messages imported by MSC2716 `/batch_send` somewhere in\n * the room and we need to throw away the timeline to make sure the\n * historical messages are shown when we paginate `/messages` again.\n * @param room - The room where the marker event was sent\n * @param markerEvent - The new marker event\n * @param setStateOptions - When `timelineWasEmpty` is set\n * as `true`, the given marker event will be ignored\n */\n private onMarkerStateEvent(\n room: Room,\n markerEvent: MatrixEvent,\n { timelineWasEmpty }: IMarkerFoundOptions = {},\n ): void {\n // We don't need to refresh the timeline if it was empty before the\n // marker arrived. This could be happen in a variety of cases:\n // 1. From the initial sync\n // 2. If it's from the first state we're seeing after joining the room\n // 3. Or whether it's coming from `syncFromCache`\n if (timelineWasEmpty) {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} ` +\n `because the timeline was empty before the marker arrived which means there is nothing to refresh.`,\n );\n return;\n }\n\n const isValidMsc2716Event =\n // Check whether the room version directly supports MSC2716, in\n // which case, \"marker\" events are already auth'ed by\n // power_levels\n MSC2716_ROOM_VERSIONS.includes(room.getVersion()) ||\n // MSC2716 is also supported in all existing room versions but\n // special meaning should only be given to \"insertion\", \"batch\",\n // and \"marker\" events when they come from the room creator\n markerEvent.getSender() === room.getCreator();\n\n // It would be nice if we could also specifically tell whether the\n // historical messages actually affected the locally cached client\n // timeline or not. The problem is we can't see the prev_events of\n // the base insertion event that the marker was pointing to because\n // prev_events aren't available in the client API's. In most cases,\n // the history won't be in people's locally cached timelines in the\n // client, so we don't need to bother everyone about refreshing\n // their timeline. This works for a v1 though and there are use\n // cases like initially bootstrapping your bridged room where people\n // are likely to encounter the historical messages affecting their\n // current timeline (think someone signing up for Beeper and\n // importing their Whatsapp history).\n if (isValidMsc2716Event) {\n // Saw new marker event, let's let the clients know they should\n // refresh the timeline.\n logger.debug(\n `MarkerState: Timeline needs to be refreshed because ` +\n `a new markerEventId=${markerEvent.getId()} was sent in roomId=${room.roomId}`,\n );\n room.setTimelineNeedsRefresh(true);\n room.emit(RoomEvent.HistoryImportedWithinTimeline, markerEvent, room);\n } else {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} because ` +\n `MSC2716 is not supported in the room version or for any room version, the marker wasn't sent ` +\n `by the room creator.`,\n );\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise<Room[]> {\n const client = this.client;\n\n // grab a filter with limit=1 and include_leave=true\n const filter = new Filter(this.client.credentials.userId);\n filter.setTimelineLimit(1);\n filter.setIncludeLeaveRooms(true);\n\n const localTimeoutMs = this.opts.pollTimeout! + BUFFER_PERIOD_MS;\n\n const filterId = await client.getOrCreateFilter(\n getFilterName(client.credentials.userId!, \"LEFT_ROOMS\"),\n filter,\n );\n\n const qps: ISyncParams = {\n timeout: 0, // don't want to block since this is a single isolated req\n filter: filterId,\n };\n\n const data = await client.http.authedRequest<ISyncResponse>(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs,\n });\n\n let leaveRooms: WrappedRoom<ILeftRoom>[] = [];\n if (data.rooms?.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n\n const rooms = await Promise.all(\n leaveRooms.map(async (leaveObj) => {\n const room = leaveObj.room;\n if (!leaveObj.isBrandNewRoom) {\n // the intention behind syncLeftRooms is to add in rooms which were\n // *omitted* from the initial /sync. Rooms the user were joined to\n // but then left whilst the app is running will appear in this list\n // and we do not want to bother with them since they will have the\n // current state already (and may get dupe messages if we add\n // yet more timeline events!), so skip them.\n // NB: When we persist rooms to localStorage this will be more\n // complicated...\n return;\n }\n leaveObj.timeline = leaveObj.timeline || {\n prev_batch: null,\n events: [],\n };\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n\n await this.injectRoomEvents(room, stateEvents, events);\n\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n\n this.processEventsForNotifs(room, events);\n return room;\n }),\n );\n\n return rooms.filter(Boolean) as Room[];\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public peek(roomId: string, limit: number = 20): Promise<Room> {\n if (this._peekRoom?.roomId === roomId) {\n return Promise.resolve(this._peekRoom);\n }\n\n const client = this.client;\n this._peekRoom = this.createRoom(roomId);\n return this.client.roomInitialSync(roomId, limit).then((response) => {\n if (this._peekRoom?.roomId !== roomId) {\n throw new Error(\"Peeking aborted\");\n }\n\n // make sure things are init'd\n response.messages = response.messages || { chunk: [] };\n response.messages.chunk = response.messages.chunk || [];\n response.state = response.state || [];\n\n // FIXME: Mostly duplicated from injectRoomEvents but not entirely\n // because \"state\" in this API is at the BEGINNING of the chunk\n const oldStateEvents = deepCopy(response.state).map(client.getEventMapper());\n const stateEvents = response.state.map(client.getEventMapper());\n const messages = response.messages.chunk.map(client.getEventMapper());\n\n // XXX: copypasted from /sync until we kill off this minging v1 API stuff)\n // handle presence events (User objects)\n if (Array.isArray(response.presence)) {\n response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getContent().user_id, client);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // set the pagination token before adding the events in case people\n // fire off pagination requests in response to the Room.timeline\n // events.\n if (response.messages.start) {\n this._peekRoom.oldState.paginationToken = response.messages.start;\n }\n\n // set the state of the room to as it was after the timeline executes\n this._peekRoom.oldState.setStateEvents(oldStateEvents);\n this._peekRoom.currentState.setStateEvents(stateEvents);\n\n this.resolveInvites(this._peekRoom);\n this._peekRoom.recalculate();\n\n // roll backwards to diverge old state. addEventsToTimeline\n // will overwrite the pagination token, so make sure it overwrites\n // it with the right thing.\n this._peekRoom.addEventsToTimeline(\n messages.reverse(),\n true,\n this._peekRoom.getLiveTimeline(),\n response.messages.start,\n );\n\n client.store.storeRoom(this._peekRoom);\n client.emit(ClientEvent.Room, this._peekRoom);\n\n this.peekPoll(this._peekRoom);\n return this._peekRoom;\n });\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n this._peekRoom = null;\n }\n\n /**\n * Do a peek room poll.\n * @param token - from= token\n */\n private peekPoll(peekRoom: Room, token?: string): void {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n\n // FIXME: gut wrenching; hard-coded timeout values\n this.client.http\n .authedRequest<IEventsResponse>(\n Method.Get,\n \"/events\",\n {\n room_id: peekRoom.roomId,\n timeout: String(30 * 1000),\n from: token,\n },\n undefined,\n {\n localTimeoutMs: 50 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n async (res) => {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n // We have a problem that we get presence both from /events and /sync\n // however, /sync only returns presence for users in rooms\n // you're actually joined to.\n // in order to be sure to get presence for all of the users in the\n // peeked room, we handle presence explicitly here. This may result\n // in duplicate presence events firing for some users, which is a\n // performance drain, but such is life.\n // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n res.chunk\n .filter(function (e) {\n return e.type === \"m.presence\";\n })\n .map(this.client.getEventMapper())\n .forEach((presenceEvent) => {\n let user = this.client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getContent().user_id, this.client);\n user.setPresenceEvent(presenceEvent);\n this.client.store.storeUser(user);\n }\n this.client.emit(ClientEvent.Event, presenceEvent);\n });\n\n // strip out events which aren't for the given room_id (e.g presence)\n // and also ephemeral events (which we're assuming is anything without\n // and event ID because the /events API doesn't separate them).\n const events = res.chunk\n .filter(function (e) {\n return e.room_id === peekRoom.roomId && e.event_id;\n })\n .map(this.client.getEventMapper());\n\n await peekRoom.addLiveEvents(events);\n this.peekPoll(peekRoom, res.end);\n },\n (err) => {\n logger.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n setTimeout(() => {\n this.peekPoll(peekRoom, token);\n }, 30 * 1000);\n },\n );\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n public async recoverFromSyncStartupError(savedSyncPromise: Promise<void> | undefined, error: Error): Promise<void> {\n // Wait for the saved sync to complete - we send the pushrules and filter requests\n // before the saved sync has finished so they can run in parallel, but only process\n // the results after the saved sync is done. Equivalently, we wait for it to finish\n // before reporting failures from these functions.\n await savedSyncPromise;\n const keepaliveProm = this.startKeepAlives();\n this.updateSyncState(SyncState.Error, { error });\n await keepaliveProm;\n }\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private getPushRules = async (): Promise<void> => {\n try {\n debuglog(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n debuglog(\"Got push rules\");\n\n this.client.pushRules = result;\n } catch (err) {\n logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) return;\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying push rules...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, <Error>err);\n return this.getPushRules(); // try again\n }\n };\n\n private buildDefaultFilter = (): Filter => {\n const filter = new Filter(this.client.credentials.userId);\n if (this.client.canSupport.get(Feature.ThreadUnreadNotifications) !== ServerSupport.Unsupported) {\n filter.setUnreadThreadNotifications(true);\n }\n return filter;\n };\n\n private prepareLazyLoadingForSync = async (): Promise<void> => {\n debuglog(\"Prepare lazy loading for sync...\");\n if (this.client.isGuest()) {\n this.opts.lazyLoadMembers = false;\n }\n if (this.opts.lazyLoadMembers) {\n debuglog(\"Enabling lazy load on sync filter...\");\n if (!this.opts.filter) {\n this.opts.filter = this.buildDefaultFilter();\n }\n this.opts.filter.setLazyLoadMembers(true);\n }\n if (this.opts.lazyLoadMembers) {\n this.syncOpts.crypto?.enableLazyLoading();\n }\n };\n\n private storeClientOptions = async (): Promise<void> => {\n try {\n debuglog(\"Storing client options...\");\n await this.client.storeClientOptions();\n debuglog(\"Stored client options\");\n } catch (err) {\n logger.error(\"Storing client options failed\", err);\n throw err;\n }\n };\n\n private getFilter = async (): Promise<{\n filterId?: string;\n filter?: Filter;\n }> => {\n debuglog(\"Getting filter...\");\n let filter: Filter;\n if (this.opts.filter) {\n filter = this.opts.filter;\n } else {\n filter = this.buildDefaultFilter();\n }\n\n let filterId: string;\n try {\n filterId = await this.client.getOrCreateFilter(getFilterName(this.client.credentials.userId!), filter);\n } catch (err) {\n logger.error(\"Getting filter failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) return {};\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying filter...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, <Error>err);\n return this.getFilter(); // try again\n }\n return { filter, filterId };\n };\n\n private savedSyncPromise?: Promise<void>;\n\n /**\n * Main entry point\n */\n public async sync(): Promise<void> {\n this.running = true;\n this.abortController = new AbortController();\n\n globalThis.window?.addEventListener?.(\"online\", this.onOnline, false);\n\n if (this.client.isGuest()) {\n // no push rules for guests, no access to POST filter for guests.\n return this.doSync({});\n }\n\n // Pull the saved sync token out first, before the worker starts sending\n // all the sync data which could take a while. This will let us send our\n // first incremental sync request before we've processed our saved data.\n debuglog(\"Getting saved sync token...\");\n const savedSyncTokenPromise = this.client.store.getSavedSyncToken().then((tok) => {\n debuglog(\"Got saved sync token\");\n return tok;\n });\n\n this.savedSyncPromise = this.client.store\n .getSavedSync()\n .then((savedSync) => {\n debuglog(`Got reply from saved sync, exists? ${!!savedSync}`);\n if (savedSync) {\n return this.syncFromCache(savedSync);\n }\n })\n .catch((err) => {\n logger.error(\"Getting saved sync failed\", err);\n });\n\n // We need to do one-off checks before we can begin the /sync loop.\n // These are:\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n // 2) We need to get/create a filter which we can use for /sync.\n // 3) We need to prepare lazy loading for sync\n // 4) We need to store the client options\n\n // Now start the first incremental sync request: this can also\n // take a while so if we set it going now, we can wait for it\n // to finish while we process our saved sync data.\n await this.getPushRules();\n await this.prepareLazyLoadingForSync();\n await this.storeClientOptions();\n\n const { filterId, filter } = await this.getFilter();\n if (!filter) return; // bail, getFilter failed\n\n // reset the notifications timeline to prepare it to paginate from\n // the current point in time.\n // The right solution would be to tie /sync pagination tokens into\n // /notifications API somehow.\n this.client.resetNotifTimelineSet();\n\n if (!this.currentSyncRequest) {\n let firstSyncFilter = filterId;\n const savedSyncToken = await savedSyncTokenPromise;\n\n if (savedSyncToken) {\n debuglog(\"Sending first sync request...\");\n } else {\n debuglog(\"Sending initial sync request...\");\n const initialFilter = this.buildDefaultFilter();\n initialFilter.setDefinition(filter.getDefinition());\n initialFilter.setTimelineLimit(this.opts.initialSyncLimit!);\n // Use an inline filter, no point uploading it for a single usage\n firstSyncFilter = JSON.stringify(initialFilter.getDefinition());\n }\n\n // Send this first sync request here so we can then wait for the saved\n // sync data to finish processing before we process the results of this one.\n this.currentSyncRequest = this.doSyncRequest({ filter: firstSyncFilter }, savedSyncToken);\n }\n\n // Now wait for the saved sync to finish...\n debuglog(\"Waiting for saved sync before starting sync processing...\");\n await this.savedSyncPromise;\n // process the first sync request and continue syncing with the normal filterId\n return this.doSync({ filter: filterId });\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n debuglog(\"SyncApi.stop\");\n // It is necessary to check for the existance of\n // globalThis.window AND globalThis.window.removeEventListener.\n // Some platforms (e.g. React Native) register globalThis.window,\n // but do not have globalThis.window.removeEventListener.\n globalThis.window?.removeEventListener?.(\"online\", this.onOnline, false);\n this.running = false;\n this.abortController?.abort();\n if (this.keepAliveTimer) {\n clearTimeout(this.keepAliveTimer);\n this.keepAliveTimer = undefined;\n }\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n if (!this.connectionReturnedDefer) {\n return false;\n }\n this.startKeepAlives(0);\n return true;\n }\n /**\n * Process a single set of cached sync data.\n * @param savedSync - a saved sync that was persisted by a store. This\n * should have been acquired via client.store.getSavedSync().\n */\n private async syncFromCache(savedSync: ISavedSync): Promise<void> {\n debuglog(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n\n const nextSyncToken = savedSync.nextBatch;\n\n // Set sync token for future incremental syncing\n this.client.store.setSyncToken(nextSyncToken);\n\n // No previous sync, set old token to null\n const syncEventData: ISyncStateData = {\n nextSyncToken,\n catchingUp: false,\n fromCache: true,\n };\n\n const data: ISyncResponse = {\n next_batch: nextSyncToken,\n rooms: savedSync.roomsData,\n account_data: {\n events: savedSync.accountData,\n },\n };\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n logger.error(\"Error processing cached sync\", e);\n }\n\n // Don't emit a prepared if we've bailed because the store is invalid:\n // in this case the client will not be usable until stopped & restarted\n // so this would be useless and misleading.\n if (!this.storeIsInvalid) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n }\n }\n\n /**\n * Invoke me to do /sync calls\n */\n private async doSync(syncOptions: ISyncOptions): Promise<void> {\n while (this.running) {\n const syncToken = this.client.store.getSyncToken();\n\n let data: ISyncResponse;\n try {\n if (!this.currentSyncRequest) {\n this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken);\n }\n data = await this.currentSyncRequest;\n } catch (e) {\n const abort = await this.onSyncError(<MatrixError>e);\n if (abort) return;\n continue;\n } finally {\n this.currentSyncRequest = undefined;\n }\n\n // set the sync token NOW *before* processing the events. We do this so\n // if something barfs on an event we can skip it rather than constantly\n // polling with the same token.\n this.client.store.setSyncToken(data.next_batch);\n\n // Reset after a successful sync\n this.failedSyncCount = 0;\n\n const syncEventData = {\n oldSyncToken: syncToken ?? undefined,\n nextSyncToken: data.next_batch,\n catchingUp: this.catchingUp,\n };\n\n if (this.syncOpts.crypto) {\n // tell the crypto module we're about to process a sync\n // response\n await this.syncOpts.crypto.onSyncWillProcess(syncEventData);\n }\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n // log the exception with stack if we have it, else fall back\n // to the plain description\n logger.error(\"Caught /sync error\", e);\n\n // Emit the exception for client handling\n this.client.emit(ClientEvent.SyncUnexpectedError, <Error>e);\n }\n\n // Persist after processing as `unsigned` may get mutated\n // with an `org.matrix.msc4023.thread_id`\n await this.client.store.setSyncData(data);\n\n // update this as it may have changed\n syncEventData.catchingUp = this.catchingUp;\n\n // emit synced events\n if (!syncOptions.hasSyncedBefore) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n syncOptions.hasSyncedBefore = true;\n }\n\n // tell the crypto module to do its processing. It may block (to do a\n // /keys/changes request).\n if (this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.onSyncCompleted(syncEventData);\n }\n\n // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n this.updateSyncState(SyncState.Syncing, syncEventData);\n\n if (this.client.store.wantsSave()) {\n // We always save the device list (if it's dirty) before saving the sync data:\n // this means we know the saved device list data is at least as fresh as the\n // stored sync data which means we don't have to worry that we may have missed\n // device changes. We can also skip the delay since we're not calling this very\n // frequently (and we don't really want to delay the sync for it).\n if (this.syncOpts.crypto) {\n await this.syncOpts.crypto.saveDeviceList(0);\n }\n\n // tell databases that everything is now in a consistent state and can be saved.\n await this.client.store.save();\n }\n }\n\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting.\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n }\n }\n\n private doSyncRequest(syncOptions: ISyncOptions, syncToken: string | null): Promise<ISyncResponse> {\n const qps = this.getSyncParams(syncOptions, syncToken);\n return this.client.http.authedRequest<ISyncResponse>(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS,\n abortSignal: this.abortController?.signal,\n });\n }\n\n private getSyncParams(syncOptions: ISyncOptions, syncToken: string | null): ISyncParams {\n let timeout = this.opts.pollTimeout!;\n\n if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n this.catchingUp = true;\n timeout = 0;\n }\n\n let filter = syncOptions.filter;\n if (this.client.isGuest() && !filter) {\n filter = this.getGuestFilter();\n }\n\n const qps: ISyncParams = { filter, timeout };\n\n if (this.opts.disablePresence) {\n qps.set_presence = SetPresence.Offline;\n } else if (this.presence !== undefined) {\n qps.set_presence = this.presence;\n }\n\n if (syncToken) {\n qps.since = syncToken;\n } else {\n // use a cachebuster for initialsyncs, to make sure that\n // we don't get a stale sync\n // (https://github.com/vector-im/vector-web/issues/1354)\n qps._cacheBuster = Date.now();\n }\n\n if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState()!)) {\n // we think the connection is dead. If it comes back up, we won't know\n // about it till /sync returns. If the timeout= is high, this could\n // be a long time. Set it to 0 when doing retries so we don't have to wait\n // for an event or a timeout before emiting the SYNCING event.\n qps.timeout = 0;\n }\n\n return qps;\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public setPresence(presence?: SetPresence): void {\n this.presence = presence;\n }\n\n private async onSyncError(err: MatrixError): Promise<boolean> {\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n return true; // abort\n }\n\n logger.error(\"/sync error %s\", err);\n\n if (this.shouldAbortSync(err)) {\n return true; // abort\n }\n\n this.failedSyncCount++;\n logger.log(\"Number of consecutive failed sync requests:\", this.failedSyncCount);\n\n debuglog(\"Starting keep-alive\");\n // Note that we do *not* mark the sync connection as\n // lost yet: we only do this if a keepalive poke\n // fails, since long lived HTTP connections will\n // go away sometimes and we shouldn't treat this as\n // erroneous. We set the state to 'reconnecting'\n // instead, so that clients can observe this state\n // if they wish.\n const keepAlivePromise = this.startKeepAlives();\n\n this.currentSyncRequest = undefined;\n // Transition from RECONNECTING to ERROR after a given number of failed syncs\n this.updateSyncState(\n this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n { error: err },\n );\n\n const connDidFail = await keepAlivePromise;\n\n // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n // it's quite likely the sync will fail again for the same reason and we\n // want to stay in ERROR rather than keep flip-flopping between ERROR\n // and CATCHUP.\n if (connDidFail && this.getSyncState() === SyncState.Error) {\n this.updateSyncState(SyncState.Catchup, {\n catchingUp: true,\n });\n }\n return false;\n }\n\n /**\n * Process data returned from a sync response and propagate it\n * into the model objects\n *\n * @param syncEventData - Object containing sync tokens associated with this sync\n * @param data - The response from /sync\n */\n private async processSyncResponse(syncEventData: ISyncStateData, data: ISyncResponse): Promise<void> {\n const client = this.client;\n\n // data looks like:\n // {\n // next_batch: $token,\n // presence: { events: [] },\n // account_data: { events: [] },\n // device_lists: { changed: [\"@user:server\", ... ]},\n // to_device: { events: [] },\n // device_one_time_keys_count: { signed_curve25519: 42 },\n // rooms: {\n // invite: {\n // $roomid: {\n // invite_state: { events: [] }\n // }\n // },\n // join: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token, limited: true },\n // ephemeral: { events: [] },\n // summary: {\n // m.heroes: [ $user_id ],\n // m.joined_member_count: $count,\n // m.invited_member_count: $count\n // },\n // account_data: { events: [] },\n // unread_notifications: {\n // highlight_count: 0,\n // notification_count: 0,\n // }\n // }\n // },\n // leave: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token }\n // }\n // }\n // }\n // }\n\n // TODO-arch:\n // - Each event we pass through needs to be emitted via 'event', can we\n // do this in one place?\n // - The isBrandNewRoom boilerplate is boilerplatey.\n\n // handle presence events (User objects)\n if (Array.isArray(data.presence?.events)) {\n data.presence!.events.filter(noUnsafeEventProps)\n .map(client.getEventMapper())\n .forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getSender()!);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getSender()!, client);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // handle non-room account_data\n if (Array.isArray(data.account_data?.events)) {\n const events = data.account_data.events.filter(noUnsafeEventProps).map(client.getEventMapper());\n const prevEventsMap = events.reduce<Record<string, MatrixEvent | undefined>>((m, c) => {\n m[c.getType()!] = client.store.getAccountData(c.getType());\n return m;\n }, {});\n client.store.storeAccountDataEvents(events);\n events.forEach(function (accountDataEvent) {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent<IPushRules>();\n client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()!];\n client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n\n // handle to-device events\n if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) {\n let toDeviceMessages: IToDeviceEvent[] = data.to_device.events.filter(noUnsafeEventProps);\n\n if (this.syncOpts.cryptoCallbacks) {\n toDeviceMessages = await this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(toDeviceMessages);\n }\n\n const cancelledKeyVerificationTxns: string[] = [];\n toDeviceMessages\n .map(client.getEventMapper({ toDevice: true }))\n .map((toDeviceEvent) => {\n // map is a cheap inline forEach\n // We want to flag m.key.verification.start events as cancelled\n // if there's an accompanying m.key.verification.cancel event, so\n // we pull out the transaction IDs from the cancellation events\n // so we can flag the verification events as cancelled in the loop\n // below.\n if (toDeviceEvent.getType() === \"m.key.verification.cancel\") {\n const txnId: string = toDeviceEvent.getContent()[\"transaction_id\"];\n if (txnId) {\n cancelledKeyVerificationTxns.push(txnId);\n }\n }\n\n // as mentioned above, .map is a cheap inline forEach, so return\n // the unmodified event.\n return toDeviceEvent;\n })\n .forEach(function (toDeviceEvent) {\n const content = toDeviceEvent.getContent();\n if (toDeviceEvent.getType() == \"m.room.message\" && content.msgtype == \"m.bad.encrypted\") {\n // the mapper already logged a warning.\n logger.log(\"Ignoring undecryptable to-device event from \" + toDeviceEvent.getSender());\n return;\n }\n\n if (\n toDeviceEvent.getType() === \"m.key.verification.start\" ||\n toDeviceEvent.getType() === \"m.key.verification.request\"\n ) {\n const txnId = content[\"transaction_id\"];\n if (cancelledKeyVerificationTxns.includes(txnId)) {\n toDeviceEvent.flagCancelled();\n }\n }\n\n client.emit(ClientEvent.ToDeviceEvent, toDeviceEvent);\n });\n } else {\n // no more to-device events: we can stop polling with a short timeout.\n this.catchingUp = false;\n }\n\n // the returned json structure is a bit crap, so make it into a\n // nicer form (array) after applying sanity to make sure we don't fail\n // on missing keys (on the off chance)\n let inviteRooms: WrappedRoom<IInvitedRoom>[] = [];\n let joinRooms: WrappedRoom<IJoinedRoom>[] = [];\n let leaveRooms: WrappedRoom<ILeftRoom>[] = [];\n let knockRooms: WrappedRoom<IKnockedRoom>[] = [];\n\n if (data.rooms) {\n if (data.rooms.invite) {\n inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite);\n }\n if (data.rooms.join) {\n joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join);\n }\n if (data.rooms.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n if (data.rooms.knock) {\n knockRooms = this.mapSyncResponseToRoomArray(data.rooms.knock);\n }\n }\n\n this.notifEvents = [];\n\n // Handle invites\n await promiseMapSeries(inviteRooms, async (inviteObj) => {\n const room = inviteObj.room;\n const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room);\n\n await this.injectRoomEvents(room, stateEvents);\n\n const inviter = room.currentState.getStateEvents(EventType.RoomMember, client.getUserId()!)?.getSender();\n\n const crypto = client.crypto;\n if (crypto) {\n const parkedHistory = await crypto.cryptoStore.takeParkedSharedHistory(room.roomId);\n for (const parked of parkedHistory) {\n if (parked.senderId === inviter) {\n await crypto.olmDevice.addInboundGroupSession(\n room.roomId,\n parked.senderKey,\n parked.forwardingCurve25519KeyChain,\n parked.sessionId,\n parked.sessionKey,\n parked.keysClaimed,\n true,\n { sharedHistory: true, untrusted: true },\n );\n }\n }\n }\n\n if (inviteObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n } else {\n // Update room state for invite->reject->invite cycles\n room.recalculate();\n }\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // Handle joins\n await promiseMapSeries(joinRooms, async (joinObj) => {\n const room = joinObj.room;\n const stateEvents = this.mapSyncEventsFormat(joinObj.state, room);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n const events = this.mapSyncEventsFormat(joinObj.timeline, room, false);\n const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral);\n const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data);\n\n const encrypted = this.isRoomEncrypted(room, stateEvents, events);\n // We store the server-provided value first so it's correct when any of the events fire.\n if (joinObj.unread_notifications) {\n /**\n * We track unread notifications ourselves in encrypted rooms, so don't\n * bother setting it here. We trust our calculations better than the\n * server's for this case, and therefore will assume that our non-zero\n * count is accurate.\n * XXX: this is known faulty as the push rule for `.m.room.encrypted` may be disabled so server\n * may issue notification counts of 0 which we wrongly trust.\n * https://github.com/matrix-org/matrix-spec-proposals/pull/2654 would fix this\n *\n * @see import(\"./client\").fixNotificationCountOnDecryption\n */\n if (!encrypted || joinObj.unread_notifications.notification_count === 0) {\n // In an encrypted room, if the room has notifications enabled then it's typical for\n // the server to flag all new messages as notifying. However, some push rules calculate\n // events as ignored based on their event contents (e.g. ignoring msgtype=m.notice messages)\n // so we want to calculate this figure on the client in all cases.\n room.setUnreadNotificationCount(\n NotificationCountType.Total,\n joinObj.unread_notifications.notification_count ?? 0,\n );\n }\n\n if (!encrypted || room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {\n // If the locally stored highlight count is zero, use the server provided value.\n room.setUnreadNotificationCount(\n NotificationCountType.Highlight,\n joinObj.unread_notifications.highlight_count ?? 0,\n );\n }\n }\n\n const unreadThreadNotifications =\n joinObj[UNREAD_THREAD_NOTIFICATIONS.name] ?? joinObj[UNREAD_THREAD_NOTIFICATIONS.altName!];\n if (unreadThreadNotifications) {\n // This mirrors the logic above for rooms: take the *total* notification count from\n // the server for unencrypted rooms or is it's zero. Any threads not present in this\n // object implicitly have zero notifications, so start by clearing the total counts\n // for all such threads.\n room.resetThreadUnreadNotificationCountFromSync(Object.keys(unreadThreadNotifications));\n for (const [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) {\n if (!encrypted || unreadNotification.notification_count === 0) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Total,\n unreadNotification.notification_count ?? 0,\n );\n }\n\n const hasNoNotifications =\n room.getThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight) <= 0;\n if (!encrypted || (encrypted && hasNoNotifications)) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Highlight,\n unreadNotification.highlight_count ?? 0,\n );\n }\n }\n } else {\n room.resetThreadUnreadNotificationCountFromSync();\n }\n\n joinObj.timeline = joinObj.timeline || ({} as ITimeline);\n\n if (joinObj.isBrandNewRoom) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n if (joinObj.timeline.prev_batch !== null) {\n room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n }\n } else if (joinObj.timeline.limited) {\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = events.length - 1; i >= 0; i--) {\n const eventId = events[i].getId()!;\n if (room.getTimelineForEvent(eventId)) {\n debuglog(`Already have event ${eventId} in limited sync - not resetting`);\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n events.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n joinObj.timeline.prev_batch,\n this.syncOpts.canResetEntireTimeline!(room.roomId)\n ? null\n : (syncEventData.oldSyncToken ?? null),\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n client.resetNotifTimelineSet();\n }\n }\n\n // process any crypto events *before* emitting the RoomStateEvent events. This\n // avoids a race condition if the application tries to send a message after the\n // state event is processed, but before crypto is enabled, which then causes the\n // crypto layer to complain.\n if (this.syncOpts.cryptoCallbacks) {\n for (const e of stateEvents.concat(events)) {\n if (e.isState() && e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\") {\n await this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n }\n }\n }\n\n try {\n await this.injectRoomEvents(room, stateEvents, events, syncEventData.fromCache);\n } catch (e) {\n logger.error(`Failed to process events on room ${room.roomId}:`, e);\n }\n\n // set summary after processing events,\n // because it will trigger a name calculation\n // which needs the room state to be up to date\n if (joinObj.summary) {\n room.setSummary(joinObj.summary);\n }\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // we deliberately don't add accountData to the timeline\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (joinObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n const emitEvent = (e: MatrixEvent): boolean => client.emit(ClientEvent.Event, e);\n stateEvents.forEach(emitEvent);\n events.forEach(emitEvent);\n ephemeralEvents.forEach(emitEvent);\n accountDataEvents.forEach(emitEvent);\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n });\n\n // Handle leaves (e.g. kicked rooms)\n await promiseMapSeries(leaveRooms, async (leaveObj) => {\n const room = leaveObj.room;\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data);\n\n await this.injectRoomEvents(room, stateEvents, events);\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (leaveObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n events.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n accountDataEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // Handle knocks\n await promiseMapSeries(knockRooms, async (knockObj) => {\n const room = knockObj.room;\n const stateEvents = this.mapSyncEventsFormat(knockObj.knock_state, room);\n\n await this.injectRoomEvents(room, stateEvents);\n\n if (knockObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n } else {\n // Update room state for knock->leave->knock cycles\n room.recalculate();\n }\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // update the notification timeline, if appropriate.\n // we only do this for live events, as otherwise we can't order them sanely\n // in the timeline relative to ones paginated in by /notifications.\n // XXX: we could fix this by making EventTimeline support chronological\n // ordering... but it doesn't, right now.\n if (syncEventData.oldSyncToken && this.notifEvents.length) {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach(function (event) {\n client.getNotifTimelineSet()?.addLiveEvent(event);\n });\n }\n\n // Handle device list updates\n if (data.device_lists) {\n if (this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.processDeviceLists(data.device_lists);\n } else {\n // FIXME if we *don't* have a crypto module, we still need to\n // invalidate the device lists. But that would require a\n // substantial bit of rework :/.\n }\n }\n\n // Handle one_time_keys_count and unused fallback keys\n await this.syncOpts.cryptoCallbacks?.processKeyCounts(\n data.device_one_time_keys_count,\n data.device_unused_fallback_key_types ?? data[\"org.matrix.msc2732.device_unused_fallback_key_types\"],\n );\n }\n\n /**\n * Starts polling the connectivity check endpoint\n * @param delay - How long to delay until the first poll.\n * defaults to a short, randomised interval (to prevent\n * tight-looping if /versions succeeds but /sync etc. fail).\n * @returns which resolves once the connection returns\n */\n private startKeepAlives(delay?: number): Promise<boolean> {\n if (delay === undefined) {\n delay = 2000 + Math.floor(Math.random() * 5000);\n }\n\n if (this.keepAliveTimer !== null) {\n clearTimeout(this.keepAliveTimer);\n }\n if (delay > 0) {\n this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);\n } else {\n this.pokeKeepAlive();\n }\n if (!this.connectionReturnedDefer) {\n this.connectionReturnedDefer = defer();\n }\n return this.connectionReturnedDefer.promise;\n }\n\n /**\n * Make a dummy call to /_matrix/client/versions, to see if the HS is\n * reachable.\n *\n * On failure, schedules a call back to itself. On success, resolves\n * this.connectionReturnedDefer.\n *\n * @param connDidFail - True if a connectivity failure has been detected. Optional.\n */\n private pokeKeepAlive(connDidFail = false): void {\n if (!this.running) {\n // we are in a keepAlive, retrying to connect, but the syncronization\n // was stopped, so we are stopping the retry.\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject(\"SyncApi.stop() was called\");\n this.connectionReturnedDefer = undefined;\n }\n return;\n }\n\n const success = (): void => {\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.resolve(connDidFail);\n this.connectionReturnedDefer = undefined;\n }\n };\n\n this.client.http\n .request(\n Method.Get,\n \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: \"\",\n localTimeoutMs: 15 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n () => {\n success();\n },\n (err) => {\n if (err.httpStatus == 400 || err.httpStatus == 404) {\n // treat this as a success because the server probably just doesn't\n // support /versions: point is, we're getting a response.\n // We wait a short time though, just in case somehow the server\n // is in a mode where it 400s /versions responses and sync etc.\n // responses fail, this will mean we don't hammer in a loop.\n this.keepAliveTimer = setTimeout(success, 2000);\n } else {\n connDidFail = true;\n this.keepAliveTimer = setTimeout(\n this.pokeKeepAlive.bind(this, connDidFail),\n 5000 + Math.floor(Math.random() * 5000),\n );\n // A keepalive has failed, so we emit the\n // error state (whether or not this is the\n // first failure).\n // Note we do this after setting the timer:\n // this lets the unit tests advance the mock\n // clock when they get the error.\n this.updateSyncState(SyncState.Error, { error: err });\n }\n },\n );\n }\n\n private mapSyncResponseToRoomArray<T extends ILeftRoom | IJoinedRoom | IInvitedRoom | IKnockedRoom>(\n obj: Record<string, T>,\n ): Array<WrappedRoom<T>> {\n // Maps { roomid: {stuff}, roomid: {stuff} }\n // to\n // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n const client = this.client;\n return Object.keys(obj)\n .filter((k) => !unsafeProp(k))\n .map((roomId) => {\n let room = client.store.getRoom(roomId);\n let isBrandNewRoom = false;\n if (!room) {\n room = this.createRoom(roomId);\n isBrandNewRoom = true;\n }\n return {\n ...obj[roomId],\n room,\n isBrandNewRoom,\n };\n });\n }\n\n private mapSyncEventsFormat(\n obj: IInviteState | ITimeline | IEphemeral,\n room?: Room,\n decrypt = true,\n ): MatrixEvent[] {\n if (!obj || !Array.isArray(obj.events)) {\n return [];\n }\n const mapper = this.client.getEventMapper({ decrypt });\n type TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n return (obj.events as TaggedEvent[]).filter(noUnsafeEventProps).map(function (e) {\n if (room) {\n e.room_id = room.roomId;\n }\n return mapper(e);\n });\n }\n\n /**\n */\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member;\n if (inviteEvent?.getContent().membership !== KnownMembership.Invite) {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (err) {\n // OH WELL.\n },\n );\n });\n }\n\n private findEncryptionEvent(events?: MatrixEvent[]): MatrixEvent | undefined {\n return events?.find((e) => e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\");\n }\n\n // When processing the sync response we cannot rely on Room.hasEncryptionStateEvent we actually\n // inject the events into the room object, so we have to inspect the events themselves.\n private isRoomEncrypted(room: Room, stateEventList: MatrixEvent[], timelineEventList?: MatrixEvent[]): boolean {\n return (\n room.hasEncryptionStateEvent() ||\n !!this.findEncryptionEvent(stateEventList) ||\n !!this.findEncryptionEvent(timelineEventList)\n );\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events, including threaded. Lower index\n * is earlier in time. Higher index is later.\n * @param fromCache - whether the sync response came from cache\n */\n public async injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList?: MatrixEvent[],\n fromCache = false,\n ): Promise<void> {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList, {\n timelineWasEmpty,\n });\n }\n\n this.resolveInvites(room);\n\n // recalculate the room name at this point as adding events to the timeline\n // may make notifications appear which should have the right name.\n // XXX: This looks suspect: we'll end up recalculating the room once here\n // and then again after adding events (processSyncResponse calls it after\n // calling us) even if no state events were added. It also means that if\n // one of the room events in timelineEventList is something that needs\n // a recalculation (like m.room.name) we won't recalculate until we've\n // finished adding all the events, which will cause the notification to have\n // the old room name rather than the new one.\n room.recalculate();\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList || []);\n room.currentState.setStateEvents(stateEventList || []);\n }\n\n // Execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n await room.addLiveEvents(timelineEventList || [], {\n fromCache,\n timelineWasEmpty,\n });\n this.client.processBeaconEvents(room, timelineEventList);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private processEventsForNotifs(room: Room, timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (this.client.getNotifTimelineSet()) {\n for (const event of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(event);\n if (pushActions?.notify && pushActions.tweaks?.highlight) {\n this.notifEvents.push(event);\n }\n }\n }\n }\n\n private getGuestFilter(): string {\n // Dev note: This used to be conditional to return a filter of 20 events maximum, but\n // the condition never went to the other branch. This is now hardcoded.\n return \"{}\";\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Event handler for the 'online' event\n * This event is generally unreliable and precise behaviour\n * varies between browsers, so we poll for connectivity too,\n * but this might help us reconnect a little faster.\n */\n private onOnline = (): void => {\n debuglog(\"Browser thinks we are back online\");\n this.startKeepAlives(0);\n };\n}\n\n// /!\\ This function is not intended for public use! It's only exported from\n// here in order to share some common logic with sliding-sync-sdk.ts.\nexport function _createAndReEmitRoom(client: MatrixClient, roomId: string, opts: Partial<IStoredClientOpts>): Room {\n const { timelineSupport } = client;\n\n const room = new Room(roomId, client, client.getUserId()!, {\n lazyLoadMembers: opts.lazyLoadMembers,\n pendingEventOrdering: opts.pendingEventOrdering,\n timelineSupport,\n });\n\n client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n\n // We need to add a listener for RoomState.members in order to hook them\n // correctly.\n room.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = client.getUser(member.userId) ?? undefined;\n client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n\n return room;\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,IAAI,QAAQ,kBAAkB;AACvC,SAASC,qBAAqB,EAAEC,IAAI,EAAEC,SAAS,QAAQ,kBAAkB;AACzE,SAASC,QAAQ,EAAEC,KAAK,EAAaC,kBAAkB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,YAAY;AACzG,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,aAAa,QAAQ,4BAA4B;AAC1D,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,WAAW,EAAmCC,oBAAoB,QAA+B,aAAa;AAiBvH,SAAsBC,MAAM,QAAQ,qBAAqB;AAEzD,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,SAASC,cAAc,QAA6B,wBAAwB;AAC5E,SAASC,eAAe,QAAQ,yBAAyB;AACzD,SAASC,WAAW,QAAQ,oBAAoB;AAEhD,SAASC,2BAA2B,QAAQ,kBAAkB;AAC9D,SAASC,OAAO,EAAEC,aAAa,QAAQ,cAAc;AAErD,SAASC,eAAe,QAAQ,wBAAwB;AAExD,IAAMC,KAAK,GAAG,IAAI;;AAElB;AACA;AACA;AACA;AACA,IAAMC,gBAAgB,GAAG,EAAE,GAAG,IAAI;;AAElC;AACA;AACA;AACA,IAAMC,2BAA2B,GAAG,CAAC;AAErC,WAAYC,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;;AAoBrB;AACA;AACA;AACA,IAAMC,qBAAqB,GAAG,CAAC,sBAAs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AyU,eAAA,GAAG7b,MAAM,CAACqH,OAAO,CAACyR,MAAM,CAACpa,MAAM,CAAC,cAAAmd,eAAA,cAAAA,eAAA,GAAI9Y,SAAS;IACxD/C,MAAM,CAACgC,SAAS,CAACC,MAAM,CAAC6W,MAAM,EAAE,CAC5Bhb,eAAe,CAACid,IAAI,EACpBjd,eAAe,CAACge,MAAM,EACtBhe,eAAe,CAACie,UAAU,EAC1Bje,eAAe,CAACke,UAAU,CAC7B,CAAC;EACN,CAAC,CAAC;EAEF,OAAO1Z,IAAI;AACf","ignoreList":[]}
|
1
|
+
{"version":3,"file":"sync.js","names":["User","NotificationCountType","Room","RoomEvent","deepCopy","defer","noUnsafeEventProps","promiseMapSeries","unsafeProp","Filter","EventTimeline","logger","ClientEvent","PendingEventOrdering","Method","EventType","RoomStateEvent","RoomMemberEvent","BeaconEvent","UNREAD_THREAD_NOTIFICATIONS","Feature","ServerSupport","KnownMembership","DEBUG","BUFFER_PERIOD_MS","FAILED_SYNC_ERROR_THRESHOLD","SyncState","MSC2716_ROOM_VERSIONS","getFilterName","userId","suffix","concat","debuglog","log","arguments","SetPresence","defaultClientOpts","opts","_objectSpread","initialSyncLimit","resolveInvitesToProfiles","pollTimeout","pendingEventOrdering","Chronological","threadSupport","defaultSyncApiOpts","syncOpts","canResetEntireTimeline","_roomId","SyncApi","constructor","client","_this","_defineProperty","_asyncToGenerator","result","getPushRules","pushRules","err","error","shouldAbortSync","recoverFromSyncStartupError","savedSyncPromise","filter","credentials","canSupport","get","ThreadUnreadNotifications","Unsupported","setUnreadThreadNotifications","isGuest","lazyLoadMembers","buildDefaultFilter","setLazyLoadMembers","storeClientOptions","filterId","getOrCreateFilter","getFilter","startKeepAlives","getNotifTimelineSet","reEmitter","reEmit","Timeline","TimelineReset","createRoom","roomId","room","_createAndReEmitRoom","on","Marker","markerEvent","markerFoundOptions","onMarkerStateEvent","timelineWasEmpty","length","undefined","debug","getId","isValidMsc2716Event","includes","getVersion","getSender","getCreator","setTimelineNeedsRefresh","emit","HistoryImportedWithinTimeline","syncLeftRooms","_this2","_data$rooms","setTimelineLimit","setIncludeLeaveRooms","localTimeoutMs","qps","timeout","data","http","authedRequest","Get","leaveRooms","rooms","leave","mapSyncResponseToRoomArray","Promise","all","map","_ref5","leaveObj","isBrandNewRoom","timeline","prev_batch","events","mapSyncEventsFormat","stateEvents","state","getLiveTimeline","setPaginationToken","BACKWARDS","injectRoomEvents","recalculate","store","storeRoom","processEventsForNotifs","_x","apply","Boolean","peek","_this$_peekRoom","limit","_peekRoom","resolve","roomInitialSync","then","response","_this$_peekRoom2","Error","messages","chunk","oldStateEvents","getEventMapper","Array","isArray","presence","forEach","presenceEvent","user","getUser","getContent","user_id","setPresenceEvent","createUser","storeUser","Event","start","oldState","paginationToken","setStateEvents","currentState","resolveInvites","addEventsToTimeline","reverse","peekPoll","stopPeeking","peekRoom","token","_this$abortController","_this3","room_id","String","from","abortSignal","abortController","signal","_ref6","res","e","type","event_id","addLiveEvents","end","_x2","setTimeout","getSyncState","syncState","getSyncStateData","_this$syncStateData","syncStateData","_this4","keepaliveProm","updateSyncState","errcode","warn","stop","sync","_this5","_globalThis$window","_globalThis$window$ad","running","AbortController","globalThis","window","addEventListener","call","onOnline","doSync","savedSyncTokenPromise","getSavedSyncToken","tok","getSavedSync","savedSync","syncFromCache","catch","prepareLazyLoadingForSync","resetNotifTimelineSet","currentSyncRequest","firstSyncFilter","savedSyncToken","initialFilter","setDefinition","getDefinition","JSON","stringify","doSyncRequest","_globalThis$window2","_globalThis$window2$r","_this$abortController2","removeEventListener","abort","keepAliveTimer","clearTimeout","retryImmediately","connectionReturnedDefer","_this6","nextSyncToken","nextBatch","setSyncToken","syncEventData","catchingUp","fromCache","next_batch","roomsData","account_data","accountData","processSyncResponse","storeIsInvalid","Prepared","syncOptions","_this7","syncToken","getSyncToken","onSyncError","failedSyncCount","oldSyncToken","SyncUnexpectedError","setSyncData","hasSyncedBefore","Syncing","wantsSave","save","reject","Stopped","_this$abortController3","getSyncParams","getGuestFilter","disablePresence","set_presence","Offline","since","_cacheBuster","Date","now","Reconnecting","setPresence","_this8","keepAlivePromise","connDidFail","Catchup","_this9","_data$presence","_data$account_data","prevEventsMap","reduce","m","c","getType","getAccountData","storeAccountDataEvents","accountDataEvent","PushRules","rules","setPushRules","prevEvent","AccountData","to_device","toDeviceMessages","cancelledKeyVerificationTxns","toDevice","toDeviceEvent","txnId","push","content","msgtype","flagCancelled","ToDeviceEvent","inviteRooms","joinRooms","knockRooms","invite","join","knock","notifEvents","_ref7","inviteObj","invite_state","_x3","_ref8","joinObj","_joinObj$UNREAD_THREA","ephemeralEvents","ephemeral","accountDataEvents","encrypted","isRoomEncrypted","unread_notifications","notification_count","_joinObj$unread_notif","setUnreadNotificationCount","Total","getUnreadNotificationCount","Highlight","_joinObj$unread_notif2","highlight_count","unreadThreadNotifications","name","altName","resetThreadUnreadNotificationCountFromSync","Object","keys","threadId","unreadNotification","entries","_unreadNotification$n","setThreadUnreadNotificationCount","hasNoNotifications","getThreadUnreadNotificationCount","_unreadNotification$h","limited","i","eventId","getTimelineForEvent","splice","_syncEventData$oldSyn","resetLiveTimeline","summary","setSummary","addEphemeralEvents","addAccountData","emitEvent","_x4","_ref9","_x5","_ref10","knockObj","knock_state","_x6","sort","a","b","getTs","event","_client$getNotifTimel","addLiveEvent","delay","Math","floor","random","pokeKeepAlive","bind","promise","_this$abortController4","success","request","prefix","httpStatus","obj","k","getRoom","decrypt","mapper","getMembersWithMembership","Invite","member","requestedProfileInfo","avatar_url","avatarUrl","displayname","displayName","getProfileInfo","info","inviteEvent","membership","setMembershipEvent","findEncryptionEvent","find","RoomEncryption","getStateKey","stateEventList","timelineEventList","hasEncryptionStateEvent","_arguments","_this10","liveTimeline","getEvents","ev","getPushActionsForEvent","initialiseState","processBeaconEvents","_pushActions$tweaks","pushActions","notify","tweaks","highlight","newState","old","Sync","timelineSupport","getUserId","Name","Redaction","RedactionCancelled","Receipt","Tags","LocalEchoUpdated","MyMembership","Events","Members","NewMember","Update","New","Destroy","LivenessChange","_client$getUser","Typing","PowerLevel","Membership"],"sources":["../src/sync.ts"],"sourcesContent":["/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { User } from \"./models/user.ts\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.ts\";\nimport { deepCopy, defer, IDeferred, noUnsafeEventProps, promiseMapSeries, unsafeProp } from \"./utils.ts\";\nimport { Filter } from \"./filter.ts\";\nimport { EventTimeline } from \"./models/event-timeline.ts\";\nimport { logger } from \"./logger.ts\";\nimport { ClientEvent, IStoredClientOpts, MatrixClient, PendingEventOrdering, ResetTimelineCallback } from \"./client.ts\";\nimport {\n IEphemeral,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IKnockedRoom,\n IMinimalEvent,\n IRoomEvent,\n IStateEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IToDeviceEvent,\n} from \"./sync-accumulator.ts\";\nimport { MatrixEvent } from \"./models/event.ts\";\nimport { MatrixError, Method } from \"./http-api/index.ts\";\nimport { ISavedSync } from \"./store/index.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { IPushRules } from \"./@types/PushRules.ts\";\nimport { RoomStateEvent, IMarkerFoundOptions } from \"./models/room-state.ts\";\nimport { RoomMemberEvent } from \"./models/room-member.ts\";\nimport { BeaconEvent } from \"./models/beacon.ts\";\nimport { IEventsResponse } from \"./@types/requests.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { Feature, ServerSupport } from \"./feature.ts\";\nimport { KnownMembership } from \"./@types/membership.ts\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nexport enum SyncState {\n /** Emitted after we try to sync more than `FAILED_SYNC_ERROR_THRESHOLD`\n * times and are still failing. Or when we enounter a hard error like the\n * token being invalid. */\n Error = \"ERROR\",\n /** Emitted after the first sync events are ready (this could even be sync\n * events from the cache) */\n Prepared = \"PREPARED\",\n /** Emitted when the sync loop is no longer running */\n Stopped = \"STOPPED\",\n /** Emitted after each sync request happens */\n Syncing = \"SYNCING\",\n /** Emitted after a connectivity error and we're ready to start syncing again */\n Catchup = \"CATCHUP\",\n /** Emitted for each time we try reconnecting. Will switch to `Error` after\n * we reach the `FAILED_SYNC_ERROR_THRESHOLD`\n */\n Reconnecting = \"RECONNECTING\",\n}\n\n// Room versions where \"insertion\", \"batch\", and \"marker\" events are controlled\n// by power-levels. MSC2716 is supported in existing room versions but they\n// should only have special meaning when the room creator sends them.\nconst MSC2716_ROOM_VERSIONS = [\"org.matrix.msc2716v3\"];\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return `FILTER_SYNC_${userId}` + (suffix ? \"_\" + suffix : \"\");\n}\n\n/* istanbul ignore next */\nfunction debuglog(...params: any[]): void {\n if (!DEBUG) return;\n logger.log(...params);\n}\n\n/**\n * Options passed into the constructor of SyncApi by MatrixClient\n */\nexport interface SyncApiOptions {\n /**\n * A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n */\n canResetEntireTimeline?: ResetTimelineCallback;\n}\n\ninterface ISyncOptions {\n filter?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n /**\n * The matrix error if `state=ERROR`.\n */\n error?: Error;\n /**\n * The 'since' token passed to /sync.\n * `null` for the first successful sync since this client was\n * started. Only present if `state=PREPARED` or\n * `state=SYNCING`.\n */\n oldSyncToken?: string;\n /**\n * The 'next_batch' result from /sync, which\n * will become the 'since' token for the next call to /sync. Only present if\n * `state=PREPARED</code> or <code>state=SYNCING`.\n */\n nextSyncToken?: string;\n /**\n * True if we are working our way through a\n * backlog of events after connecting. Only present if `state=SYNCING`.\n */\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\nexport enum SetPresence {\n Offline = \"offline\",\n Online = \"online\",\n Unavailable = \"unavailable\",\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: SetPresence;\n _cacheBuster?: string | number; // not part of the API itself\n}\n\ntype WrappedRoom<T> = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/** add default settings to an IStoredClientOpts */\nexport function defaultClientOpts(opts?: IStoredClientOpts): IStoredClientOpts {\n return {\n initialSyncLimit: 8,\n resolveInvitesToProfiles: false,\n pollTimeout: 30 * 1000,\n pendingEventOrdering: PendingEventOrdering.Chronological,\n threadSupport: false,\n ...opts,\n };\n}\n\nexport function defaultSyncApiOpts(syncOpts?: SyncApiOptions): SyncApiOptions {\n return {\n canResetEntireTimeline: (_roomId): boolean => false,\n ...syncOpts,\n };\n}\n\nexport class SyncApi {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n\n private _peekRoom: Optional<Room> = null;\n private currentSyncRequest?: Promise<ISyncResponse>;\n private abortController?: AbortController;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer?: ReturnType<typeof setTimeout>;\n private connectionReturnedDefer?: IDeferred<boolean>;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n private failedSyncCount = 0; // Number of consecutive failed /sync requests\n private storeIsInvalid = false; // flag set if the store needs to be cleared before we can start\n private presence?: SetPresence;\n\n /**\n * Construct an entity which is able to sync with a homeserver.\n * @param client - The matrix client instance to use.\n * @param opts - client config options\n * @param syncOpts - sync-specific options passed by the client\n * @internal\n */\n public constructor(\n private readonly client: MatrixClient,\n opts?: IStoredClientOpts,\n syncOpts?: SyncApiOptions,\n ) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n }\n\n public createRoom(roomId: string): Room {\n const room = _createAndReEmitRoom(this.client, roomId, this.opts);\n\n room.on(RoomStateEvent.Marker, (markerEvent, markerFoundOptions) => {\n this.onMarkerStateEvent(room, markerEvent, markerFoundOptions);\n });\n\n return room;\n }\n\n /** When we see the marker state change in the room, we know there is some\n * new historical messages imported by MSC2716 `/batch_send` somewhere in\n * the room and we need to throw away the timeline to make sure the\n * historical messages are shown when we paginate `/messages` again.\n * @param room - The room where the marker event was sent\n * @param markerEvent - The new marker event\n * @param setStateOptions - When `timelineWasEmpty` is set\n * as `true`, the given marker event will be ignored\n */\n private onMarkerStateEvent(\n room: Room,\n markerEvent: MatrixEvent,\n { timelineWasEmpty }: IMarkerFoundOptions = {},\n ): void {\n // We don't need to refresh the timeline if it was empty before the\n // marker arrived. This could be happen in a variety of cases:\n // 1. From the initial sync\n // 2. If it's from the first state we're seeing after joining the room\n // 3. Or whether it's coming from `syncFromCache`\n if (timelineWasEmpty) {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} ` +\n `because the timeline was empty before the marker arrived which means there is nothing to refresh.`,\n );\n return;\n }\n\n const isValidMsc2716Event =\n // Check whether the room version directly supports MSC2716, in\n // which case, \"marker\" events are already auth'ed by\n // power_levels\n MSC2716_ROOM_VERSIONS.includes(room.getVersion()) ||\n // MSC2716 is also supported in all existing room versions but\n // special meaning should only be given to \"insertion\", \"batch\",\n // and \"marker\" events when they come from the room creator\n markerEvent.getSender() === room.getCreator();\n\n // It would be nice if we could also specifically tell whether the\n // historical messages actually affected the locally cached client\n // timeline or not. The problem is we can't see the prev_events of\n // the base insertion event that the marker was pointing to because\n // prev_events aren't available in the client API's. In most cases,\n // the history won't be in people's locally cached timelines in the\n // client, so we don't need to bother everyone about refreshing\n // their timeline. This works for a v1 though and there are use\n // cases like initially bootstrapping your bridged room where people\n // are likely to encounter the historical messages affecting their\n // current timeline (think someone signing up for Beeper and\n // importing their Whatsapp history).\n if (isValidMsc2716Event) {\n // Saw new marker event, let's let the clients know they should\n // refresh the timeline.\n logger.debug(\n `MarkerState: Timeline needs to be refreshed because ` +\n `a new markerEventId=${markerEvent.getId()} was sent in roomId=${room.roomId}`,\n );\n room.setTimelineNeedsRefresh(true);\n room.emit(RoomEvent.HistoryImportedWithinTimeline, markerEvent, room);\n } else {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} because ` +\n `MSC2716 is not supported in the room version or for any room version, the marker wasn't sent ` +\n `by the room creator.`,\n );\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise<Room[]> {\n const client = this.client;\n\n // grab a filter with limit=1 and include_leave=true\n const filter = new Filter(this.client.credentials.userId);\n filter.setTimelineLimit(1);\n filter.setIncludeLeaveRooms(true);\n\n const localTimeoutMs = this.opts.pollTimeout! + BUFFER_PERIOD_MS;\n\n const filterId = await client.getOrCreateFilter(\n getFilterName(client.credentials.userId!, \"LEFT_ROOMS\"),\n filter,\n );\n\n const qps: ISyncParams = {\n timeout: 0, // don't want to block since this is a single isolated req\n filter: filterId,\n };\n\n const data = await client.http.authedRequest<ISyncResponse>(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs,\n });\n\n let leaveRooms: WrappedRoom<ILeftRoom>[] = [];\n if (data.rooms?.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n\n const rooms = await Promise.all(\n leaveRooms.map(async (leaveObj) => {\n const room = leaveObj.room;\n if (!leaveObj.isBrandNewRoom) {\n // the intention behind syncLeftRooms is to add in rooms which were\n // *omitted* from the initial /sync. Rooms the user were joined to\n // but then left whilst the app is running will appear in this list\n // and we do not want to bother with them since they will have the\n // current state already (and may get dupe messages if we add\n // yet more timeline events!), so skip them.\n // NB: When we persist rooms to localStorage this will be more\n // complicated...\n return;\n }\n leaveObj.timeline = leaveObj.timeline || {\n prev_batch: null,\n events: [],\n };\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n\n await this.injectRoomEvents(room, stateEvents, events);\n\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n\n this.processEventsForNotifs(room, events);\n return room;\n }),\n );\n\n return rooms.filter(Boolean) as Room[];\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public peek(roomId: string, limit: number = 20): Promise<Room> {\n if (this._peekRoom?.roomId === roomId) {\n return Promise.resolve(this._peekRoom);\n }\n\n const client = this.client;\n this._peekRoom = this.createRoom(roomId);\n return this.client.roomInitialSync(roomId, limit).then((response) => {\n if (this._peekRoom?.roomId !== roomId) {\n throw new Error(\"Peeking aborted\");\n }\n\n // make sure things are init'd\n response.messages = response.messages || { chunk: [] };\n response.messages.chunk = response.messages.chunk || [];\n response.state = response.state || [];\n\n // FIXME: Mostly duplicated from injectRoomEvents but not entirely\n // because \"state\" in this API is at the BEGINNING of the chunk\n const oldStateEvents = deepCopy(response.state).map(client.getEventMapper());\n const stateEvents = response.state.map(client.getEventMapper());\n const messages = response.messages.chunk.map(client.getEventMapper());\n\n // XXX: copypasted from /sync until we kill off this minging v1 API stuff)\n // handle presence events (User objects)\n if (Array.isArray(response.presence)) {\n response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getContent().user_id, client);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // set the pagination token before adding the events in case people\n // fire off pagination requests in response to the Room.timeline\n // events.\n if (response.messages.start) {\n this._peekRoom.oldState.paginationToken = response.messages.start;\n }\n\n // set the state of the room to as it was after the timeline executes\n this._peekRoom.oldState.setStateEvents(oldStateEvents);\n this._peekRoom.currentState.setStateEvents(stateEvents);\n\n this.resolveInvites(this._peekRoom);\n this._peekRoom.recalculate();\n\n // roll backwards to diverge old state. addEventsToTimeline\n // will overwrite the pagination token, so make sure it overwrites\n // it with the right thing.\n this._peekRoom.addEventsToTimeline(\n messages.reverse(),\n true,\n this._peekRoom.getLiveTimeline(),\n response.messages.start,\n );\n\n client.store.storeRoom(this._peekRoom);\n client.emit(ClientEvent.Room, this._peekRoom);\n\n this.peekPoll(this._peekRoom);\n return this._peekRoom;\n });\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n this._peekRoom = null;\n }\n\n /**\n * Do a peek room poll.\n * @param token - from= token\n */\n private peekPoll(peekRoom: Room, token?: string): void {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n\n // FIXME: gut wrenching; hard-coded timeout values\n this.client.http\n .authedRequest<IEventsResponse>(\n Method.Get,\n \"/events\",\n {\n room_id: peekRoom.roomId,\n timeout: String(30 * 1000),\n from: token,\n },\n undefined,\n {\n localTimeoutMs: 50 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n async (res) => {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n // We have a problem that we get presence both from /events and /sync\n // however, /sync only returns presence for users in rooms\n // you're actually joined to.\n // in order to be sure to get presence for all of the users in the\n // peeked room, we handle presence explicitly here. This may result\n // in duplicate presence events firing for some users, which is a\n // performance drain, but such is life.\n // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n res.chunk\n .filter(function (e) {\n return e.type === \"m.presence\";\n })\n .map(this.client.getEventMapper())\n .forEach((presenceEvent) => {\n let user = this.client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getContent().user_id, this.client);\n user.setPresenceEvent(presenceEvent);\n this.client.store.storeUser(user);\n }\n this.client.emit(ClientEvent.Event, presenceEvent);\n });\n\n // strip out events which aren't for the given room_id (e.g presence)\n // and also ephemeral events (which we're assuming is anything without\n // and event ID because the /events API doesn't separate them).\n const events = res.chunk\n .filter(function (e) {\n return e.room_id === peekRoom.roomId && e.event_id;\n })\n .map(this.client.getEventMapper());\n\n await peekRoom.addLiveEvents(events);\n this.peekPoll(peekRoom, res.end);\n },\n (err) => {\n logger.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n setTimeout(() => {\n this.peekPoll(peekRoom, token);\n }, 30 * 1000);\n },\n );\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n public async recoverFromSyncStartupError(savedSyncPromise: Promise<void> | undefined, error: Error): Promise<void> {\n // Wait for the saved sync to complete - we send the pushrules and filter requests\n // before the saved sync has finished so they can run in parallel, but only process\n // the results after the saved sync is done. Equivalently, we wait for it to finish\n // before reporting failures from these functions.\n await savedSyncPromise;\n const keepaliveProm = this.startKeepAlives();\n this.updateSyncState(SyncState.Error, { error });\n await keepaliveProm;\n }\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private getPushRules = async (): Promise<void> => {\n try {\n debuglog(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n debuglog(\"Got push rules\");\n\n this.client.pushRules = result;\n } catch (err) {\n logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) return;\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying push rules...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, <Error>err);\n return this.getPushRules(); // try again\n }\n };\n\n private buildDefaultFilter = (): Filter => {\n const filter = new Filter(this.client.credentials.userId);\n if (this.client.canSupport.get(Feature.ThreadUnreadNotifications) !== ServerSupport.Unsupported) {\n filter.setUnreadThreadNotifications(true);\n }\n return filter;\n };\n\n private prepareLazyLoadingForSync = async (): Promise<void> => {\n debuglog(\"Prepare lazy loading for sync...\");\n if (this.client.isGuest()) {\n this.opts.lazyLoadMembers = false;\n }\n if (this.opts.lazyLoadMembers) {\n debuglog(\"Enabling lazy load on sync filter...\");\n if (!this.opts.filter) {\n this.opts.filter = this.buildDefaultFilter();\n }\n this.opts.filter.setLazyLoadMembers(true);\n }\n };\n\n private storeClientOptions = async (): Promise<void> => {\n try {\n debuglog(\"Storing client options...\");\n await this.client.storeClientOptions();\n debuglog(\"Stored client options\");\n } catch (err) {\n logger.error(\"Storing client options failed\", err);\n throw err;\n }\n };\n\n private getFilter = async (): Promise<{\n filterId?: string;\n filter?: Filter;\n }> => {\n debuglog(\"Getting filter...\");\n let filter: Filter;\n if (this.opts.filter) {\n filter = this.opts.filter;\n } else {\n filter = this.buildDefaultFilter();\n }\n\n let filterId: string;\n try {\n filterId = await this.client.getOrCreateFilter(getFilterName(this.client.credentials.userId!), filter);\n } catch (err) {\n logger.error(\"Getting filter failed\", err);\n if (this.shouldAbortSync(<MatrixError>err)) return {};\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying filter...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, <Error>err);\n return this.getFilter(); // try again\n }\n return { filter, filterId };\n };\n\n private savedSyncPromise?: Promise<void>;\n\n /**\n * Main entry point\n */\n public async sync(): Promise<void> {\n this.running = true;\n this.abortController = new AbortController();\n\n globalThis.window?.addEventListener?.(\"online\", this.onOnline, false);\n\n if (this.client.isGuest()) {\n // no push rules for guests, no access to POST filter for guests.\n return this.doSync({});\n }\n\n // Pull the saved sync token out first, before the worker starts sending\n // all the sync data which could take a while. This will let us send our\n // first incremental sync request before we've processed our saved data.\n debuglog(\"Getting saved sync token...\");\n const savedSyncTokenPromise = this.client.store.getSavedSyncToken().then((tok) => {\n debuglog(\"Got saved sync token\");\n return tok;\n });\n\n this.savedSyncPromise = this.client.store\n .getSavedSync()\n .then((savedSync) => {\n debuglog(`Got reply from saved sync, exists? ${!!savedSync}`);\n if (savedSync) {\n return this.syncFromCache(savedSync);\n }\n })\n .catch((err) => {\n logger.error(\"Getting saved sync failed\", err);\n });\n\n // We need to do one-off checks before we can begin the /sync loop.\n // These are:\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n // 2) We need to get/create a filter which we can use for /sync.\n // 3) We need to prepare lazy loading for sync\n // 4) We need to store the client options\n\n // Now start the first incremental sync request: this can also\n // take a while so if we set it going now, we can wait for it\n // to finish while we process our saved sync data.\n await this.getPushRules();\n await this.prepareLazyLoadingForSync();\n await this.storeClientOptions();\n\n const { filterId, filter } = await this.getFilter();\n if (!filter) return; // bail, getFilter failed\n\n // reset the notifications timeline to prepare it to paginate from\n // the current point in time.\n // The right solution would be to tie /sync pagination tokens into\n // /notifications API somehow.\n this.client.resetNotifTimelineSet();\n\n if (!this.currentSyncRequest) {\n let firstSyncFilter = filterId;\n const savedSyncToken = await savedSyncTokenPromise;\n\n if (savedSyncToken) {\n debuglog(\"Sending first sync request...\");\n } else {\n debuglog(\"Sending initial sync request...\");\n const initialFilter = this.buildDefaultFilter();\n initialFilter.setDefinition(filter.getDefinition());\n initialFilter.setTimelineLimit(this.opts.initialSyncLimit!);\n // Use an inline filter, no point uploading it for a single usage\n firstSyncFilter = JSON.stringify(initialFilter.getDefinition());\n }\n\n // Send this first sync request here so we can then wait for the saved\n // sync data to finish processing before we process the results of this one.\n this.currentSyncRequest = this.doSyncRequest({ filter: firstSyncFilter }, savedSyncToken);\n }\n\n // Now wait for the saved sync to finish...\n debuglog(\"Waiting for saved sync before starting sync processing...\");\n await this.savedSyncPromise;\n // process the first sync request and continue syncing with the normal filterId\n return this.doSync({ filter: filterId });\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n debuglog(\"SyncApi.stop\");\n // It is necessary to check for the existance of\n // globalThis.window AND globalThis.window.removeEventListener.\n // Some platforms (e.g. React Native) register globalThis.window,\n // but do not have globalThis.window.removeEventListener.\n globalThis.window?.removeEventListener?.(\"online\", this.onOnline, false);\n this.running = false;\n this.abortController?.abort();\n if (this.keepAliveTimer) {\n clearTimeout(this.keepAliveTimer);\n this.keepAliveTimer = undefined;\n }\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n if (!this.connectionReturnedDefer) {\n return false;\n }\n this.startKeepAlives(0);\n return true;\n }\n /**\n * Process a single set of cached sync data.\n * @param savedSync - a saved sync that was persisted by a store. This\n * should have been acquired via client.store.getSavedSync().\n */\n private async syncFromCache(savedSync: ISavedSync): Promise<void> {\n debuglog(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n\n const nextSyncToken = savedSync.nextBatch;\n\n // Set sync token for future incremental syncing\n this.client.store.setSyncToken(nextSyncToken);\n\n // No previous sync, set old token to null\n const syncEventData: ISyncStateData = {\n nextSyncToken,\n catchingUp: false,\n fromCache: true,\n };\n\n const data: ISyncResponse = {\n next_batch: nextSyncToken,\n rooms: savedSync.roomsData,\n account_data: {\n events: savedSync.accountData,\n },\n };\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n logger.error(\"Error processing cached sync\", e);\n }\n\n // Don't emit a prepared if we've bailed because the store is invalid:\n // in this case the client will not be usable until stopped & restarted\n // so this would be useless and misleading.\n if (!this.storeIsInvalid) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n }\n }\n\n /**\n * Invoke me to do /sync calls\n */\n private async doSync(syncOptions: ISyncOptions): Promise<void> {\n while (this.running) {\n const syncToken = this.client.store.getSyncToken();\n\n let data: ISyncResponse;\n try {\n if (!this.currentSyncRequest) {\n this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken);\n }\n data = await this.currentSyncRequest;\n } catch (e) {\n const abort = await this.onSyncError(<MatrixError>e);\n if (abort) return;\n continue;\n } finally {\n this.currentSyncRequest = undefined;\n }\n\n // set the sync token NOW *before* processing the events. We do this so\n // if something barfs on an event we can skip it rather than constantly\n // polling with the same token.\n this.client.store.setSyncToken(data.next_batch);\n\n // Reset after a successful sync\n this.failedSyncCount = 0;\n\n const syncEventData = {\n oldSyncToken: syncToken ?? undefined,\n nextSyncToken: data.next_batch,\n catchingUp: this.catchingUp,\n };\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n // log the exception with stack if we have it, else fall back\n // to the plain description\n logger.error(\"Caught /sync error\", e);\n\n // Emit the exception for client handling\n this.client.emit(ClientEvent.SyncUnexpectedError, <Error>e);\n }\n\n // Persist after processing as `unsigned` may get mutated\n // with an `org.matrix.msc4023.thread_id`\n await this.client.store.setSyncData(data);\n\n // update this as it may have changed\n syncEventData.catchingUp = this.catchingUp;\n\n // emit synced events\n if (!syncOptions.hasSyncedBefore) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n syncOptions.hasSyncedBefore = true;\n }\n\n // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n this.updateSyncState(SyncState.Syncing, syncEventData);\n\n if (this.client.store.wantsSave()) {\n // tell databases that everything is now in a consistent state and can be saved.\n await this.client.store.save();\n }\n }\n\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting.\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n }\n }\n\n private doSyncRequest(syncOptions: ISyncOptions, syncToken: string | null): Promise<ISyncResponse> {\n const qps = this.getSyncParams(syncOptions, syncToken);\n return this.client.http.authedRequest<ISyncResponse>(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS,\n abortSignal: this.abortController?.signal,\n });\n }\n\n private getSyncParams(syncOptions: ISyncOptions, syncToken: string | null): ISyncParams {\n let timeout = this.opts.pollTimeout!;\n\n if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n this.catchingUp = true;\n timeout = 0;\n }\n\n let filter = syncOptions.filter;\n if (this.client.isGuest() && !filter) {\n filter = this.getGuestFilter();\n }\n\n const qps: ISyncParams = { filter, timeout };\n\n if (this.opts.disablePresence) {\n qps.set_presence = SetPresence.Offline;\n } else if (this.presence !== undefined) {\n qps.set_presence = this.presence;\n }\n\n if (syncToken) {\n qps.since = syncToken;\n } else {\n // use a cachebuster for initialsyncs, to make sure that\n // we don't get a stale sync\n // (https://github.com/vector-im/vector-web/issues/1354)\n qps._cacheBuster = Date.now();\n }\n\n if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState()!)) {\n // we think the connection is dead. If it comes back up, we won't know\n // about it till /sync returns. If the timeout= is high, this could\n // be a long time. Set it to 0 when doing retries so we don't have to wait\n // for an event or a timeout before emiting the SYNCING event.\n qps.timeout = 0;\n }\n\n return qps;\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public setPresence(presence?: SetPresence): void {\n this.presence = presence;\n }\n\n private async onSyncError(err: MatrixError): Promise<boolean> {\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n return true; // abort\n }\n\n logger.error(\"/sync error %s\", err);\n\n if (this.shouldAbortSync(err)) {\n return true; // abort\n }\n\n this.failedSyncCount++;\n logger.log(\"Number of consecutive failed sync requests:\", this.failedSyncCount);\n\n debuglog(\"Starting keep-alive\");\n // Note that we do *not* mark the sync connection as\n // lost yet: we only do this if a keepalive poke\n // fails, since long lived HTTP connections will\n // go away sometimes and we shouldn't treat this as\n // erroneous. We set the state to 'reconnecting'\n // instead, so that clients can observe this state\n // if they wish.\n const keepAlivePromise = this.startKeepAlives();\n\n this.currentSyncRequest = undefined;\n // Transition from RECONNECTING to ERROR after a given number of failed syncs\n this.updateSyncState(\n this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n { error: err },\n );\n\n const connDidFail = await keepAlivePromise;\n\n // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n // it's quite likely the sync will fail again for the same reason and we\n // want to stay in ERROR rather than keep flip-flopping between ERROR\n // and CATCHUP.\n if (connDidFail && this.getSyncState() === SyncState.Error) {\n this.updateSyncState(SyncState.Catchup, {\n catchingUp: true,\n });\n }\n return false;\n }\n\n /**\n * Process data returned from a sync response and propagate it\n * into the model objects\n *\n * @param syncEventData - Object containing sync tokens associated with this sync\n * @param data - The response from /sync\n */\n private async processSyncResponse(syncEventData: ISyncStateData, data: ISyncResponse): Promise<void> {\n const client = this.client;\n\n // data looks like:\n // {\n // next_batch: $token,\n // presence: { events: [] },\n // account_data: { events: [] },\n // device_lists: { changed: [\"@user:server\", ... ]},\n // to_device: { events: [] },\n // device_one_time_keys_count: { signed_curve25519: 42 },\n // rooms: {\n // invite: {\n // $roomid: {\n // invite_state: { events: [] }\n // }\n // },\n // join: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token, limited: true },\n // ephemeral: { events: [] },\n // summary: {\n // m.heroes: [ $user_id ],\n // m.joined_member_count: $count,\n // m.invited_member_count: $count\n // },\n // account_data: { events: [] },\n // unread_notifications: {\n // highlight_count: 0,\n // notification_count: 0,\n // }\n // }\n // },\n // leave: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token }\n // }\n // }\n // }\n // }\n\n // TODO-arch:\n // - Each event we pass through needs to be emitted via 'event', can we\n // do this in one place?\n // - The isBrandNewRoom boilerplate is boilerplatey.\n\n // handle presence events (User objects)\n if (Array.isArray(data.presence?.events)) {\n data.presence!.events.filter(noUnsafeEventProps)\n .map(client.getEventMapper())\n .forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getSender()!);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = User.createUser(presenceEvent.getSender()!, client);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // handle non-room account_data\n if (Array.isArray(data.account_data?.events)) {\n const events = data.account_data.events.filter(noUnsafeEventProps).map(client.getEventMapper());\n const prevEventsMap = events.reduce<Record<string, MatrixEvent | undefined>>((m, c) => {\n m[c.getType()!] = client.store.getAccountData(c.getType());\n return m;\n }, {});\n client.store.storeAccountDataEvents(events);\n events.forEach(function (accountDataEvent) {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent<IPushRules>();\n client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()!];\n client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n\n // handle to-device events\n if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) {\n const toDeviceMessages: IToDeviceEvent[] = data.to_device.events.filter(noUnsafeEventProps);\n\n const cancelledKeyVerificationTxns: string[] = [];\n toDeviceMessages\n .map(client.getEventMapper({ toDevice: true }))\n .map((toDeviceEvent) => {\n // map is a cheap inline forEach\n // We want to flag m.key.verification.start events as cancelled\n // if there's an accompanying m.key.verification.cancel event, so\n // we pull out the transaction IDs from the cancellation events\n // so we can flag the verification events as cancelled in the loop\n // below.\n if (toDeviceEvent.getType() === \"m.key.verification.cancel\") {\n const txnId: string = toDeviceEvent.getContent()[\"transaction_id\"];\n if (txnId) {\n cancelledKeyVerificationTxns.push(txnId);\n }\n }\n\n // as mentioned above, .map is a cheap inline forEach, so return\n // the unmodified event.\n return toDeviceEvent;\n })\n .forEach(function (toDeviceEvent) {\n const content = toDeviceEvent.getContent();\n if (toDeviceEvent.getType() == \"m.room.message\" && content.msgtype == \"m.bad.encrypted\") {\n // the mapper already logged a warning.\n logger.log(\"Ignoring undecryptable to-device event from \" + toDeviceEvent.getSender());\n return;\n }\n\n if (\n toDeviceEvent.getType() === \"m.key.verification.start\" ||\n toDeviceEvent.getType() === \"m.key.verification.request\"\n ) {\n const txnId = content[\"transaction_id\"];\n if (cancelledKeyVerificationTxns.includes(txnId)) {\n toDeviceEvent.flagCancelled();\n }\n }\n\n client.emit(ClientEvent.ToDeviceEvent, toDeviceEvent);\n });\n } else {\n // no more to-device events: we can stop polling with a short timeout.\n this.catchingUp = false;\n }\n\n // the returned json structure is a bit crap, so make it into a\n // nicer form (array) after applying sanity to make sure we don't fail\n // on missing keys (on the off chance)\n let inviteRooms: WrappedRoom<IInvitedRoom>[] = [];\n let joinRooms: WrappedRoom<IJoinedRoom>[] = [];\n let leaveRooms: WrappedRoom<ILeftRoom>[] = [];\n let knockRooms: WrappedRoom<IKnockedRoom>[] = [];\n\n if (data.rooms) {\n if (data.rooms.invite) {\n inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite);\n }\n if (data.rooms.join) {\n joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join);\n }\n if (data.rooms.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n if (data.rooms.knock) {\n knockRooms = this.mapSyncResponseToRoomArray(data.rooms.knock);\n }\n }\n\n this.notifEvents = [];\n\n // Handle invites\n await promiseMapSeries(inviteRooms, async (inviteObj) => {\n const room = inviteObj.room;\n const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room);\n\n await this.injectRoomEvents(room, stateEvents);\n\n if (inviteObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n } else {\n // Update room state for invite->reject->invite cycles\n room.recalculate();\n }\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // Handle joins\n await promiseMapSeries(joinRooms, async (joinObj) => {\n const room = joinObj.room;\n const stateEvents = this.mapSyncEventsFormat(joinObj.state, room);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n const events = this.mapSyncEventsFormat(joinObj.timeline, room, false);\n const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral);\n const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data);\n\n const encrypted = this.isRoomEncrypted(room, stateEvents, events);\n // We store the server-provided value first so it's correct when any of the events fire.\n if (joinObj.unread_notifications) {\n /**\n * We track unread notifications ourselves in encrypted rooms, so don't\n * bother setting it here. We trust our calculations better than the\n * server's for this case, and therefore will assume that our non-zero\n * count is accurate.\n * XXX: this is known faulty as the push rule for `.m.room.encrypted` may be disabled so server\n * may issue notification counts of 0 which we wrongly trust.\n * https://github.com/matrix-org/matrix-spec-proposals/pull/2654 would fix this\n *\n * @see import(\"./client\").fixNotificationCountOnDecryption\n */\n if (!encrypted || joinObj.unread_notifications.notification_count === 0) {\n // In an encrypted room, if the room has notifications enabled then it's typical for\n // the server to flag all new messages as notifying. However, some push rules calculate\n // events as ignored based on their event contents (e.g. ignoring msgtype=m.notice messages)\n // so we want to calculate this figure on the client in all cases.\n room.setUnreadNotificationCount(\n NotificationCountType.Total,\n joinObj.unread_notifications.notification_count ?? 0,\n );\n }\n\n if (!encrypted || room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {\n // If the locally stored highlight count is zero, use the server provided value.\n room.setUnreadNotificationCount(\n NotificationCountType.Highlight,\n joinObj.unread_notifications.highlight_count ?? 0,\n );\n }\n }\n\n const unreadThreadNotifications =\n joinObj[UNREAD_THREAD_NOTIFICATIONS.name] ?? joinObj[UNREAD_THREAD_NOTIFICATIONS.altName!];\n if (unreadThreadNotifications) {\n // This mirrors the logic above for rooms: take the *total* notification count from\n // the server for unencrypted rooms or is it's zero. Any threads not present in this\n // object implicitly have zero notifications, so start by clearing the total counts\n // for all such threads.\n room.resetThreadUnreadNotificationCountFromSync(Object.keys(unreadThreadNotifications));\n for (const [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) {\n if (!encrypted || unreadNotification.notification_count === 0) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Total,\n unreadNotification.notification_count ?? 0,\n );\n }\n\n const hasNoNotifications =\n room.getThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight) <= 0;\n if (!encrypted || (encrypted && hasNoNotifications)) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Highlight,\n unreadNotification.highlight_count ?? 0,\n );\n }\n }\n } else {\n room.resetThreadUnreadNotificationCountFromSync();\n }\n\n joinObj.timeline = joinObj.timeline || ({} as ITimeline);\n\n if (joinObj.isBrandNewRoom) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n if (joinObj.timeline.prev_batch !== null) {\n room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n }\n } else if (joinObj.timeline.limited) {\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = events.length - 1; i >= 0; i--) {\n const eventId = events[i].getId()!;\n if (room.getTimelineForEvent(eventId)) {\n debuglog(`Already have event ${eventId} in limited sync - not resetting`);\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n events.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n joinObj.timeline.prev_batch,\n this.syncOpts.canResetEntireTimeline!(room.roomId)\n ? null\n : (syncEventData.oldSyncToken ?? null),\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n client.resetNotifTimelineSet();\n }\n }\n\n try {\n await this.injectRoomEvents(room, stateEvents, events, syncEventData.fromCache);\n } catch (e) {\n logger.error(`Failed to process events on room ${room.roomId}:`, e);\n }\n\n // set summary after processing events,\n // because it will trigger a name calculation\n // which needs the room state to be up to date\n if (joinObj.summary) {\n room.setSummary(joinObj.summary);\n }\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // we deliberately don't add accountData to the timeline\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (joinObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n const emitEvent = (e: MatrixEvent): boolean => client.emit(ClientEvent.Event, e);\n stateEvents.forEach(emitEvent);\n events.forEach(emitEvent);\n ephemeralEvents.forEach(emitEvent);\n accountDataEvents.forEach(emitEvent);\n });\n\n // Handle leaves (e.g. kicked rooms)\n await promiseMapSeries(leaveRooms, async (leaveObj) => {\n const room = leaveObj.room;\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data);\n\n await this.injectRoomEvents(room, stateEvents, events);\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (leaveObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n events.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n accountDataEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // Handle knocks\n await promiseMapSeries(knockRooms, async (knockObj) => {\n const room = knockObj.room;\n const stateEvents = this.mapSyncEventsFormat(knockObj.knock_state, room);\n\n await this.injectRoomEvents(room, stateEvents);\n\n if (knockObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n } else {\n // Update room state for knock->leave->knock cycles\n room.recalculate();\n }\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // update the notification timeline, if appropriate.\n // we only do this for live events, as otherwise we can't order them sanely\n // in the timeline relative to ones paginated in by /notifications.\n // XXX: we could fix this by making EventTimeline support chronological\n // ordering... but it doesn't, right now.\n if (syncEventData.oldSyncToken && this.notifEvents.length) {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach(function (event) {\n client.getNotifTimelineSet()?.addLiveEvent(event);\n });\n }\n }\n\n /**\n * Starts polling the connectivity check endpoint\n * @param delay - How long to delay until the first poll.\n * defaults to a short, randomised interval (to prevent\n * tight-looping if /versions succeeds but /sync etc. fail).\n * @returns which resolves once the connection returns\n */\n private startKeepAlives(delay?: number): Promise<boolean> {\n if (delay === undefined) {\n delay = 2000 + Math.floor(Math.random() * 5000);\n }\n\n if (this.keepAliveTimer !== null) {\n clearTimeout(this.keepAliveTimer);\n }\n if (delay > 0) {\n this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);\n } else {\n this.pokeKeepAlive();\n }\n if (!this.connectionReturnedDefer) {\n this.connectionReturnedDefer = defer();\n }\n return this.connectionReturnedDefer.promise;\n }\n\n /**\n * Make a dummy call to /_matrix/client/versions, to see if the HS is\n * reachable.\n *\n * On failure, schedules a call back to itself. On success, resolves\n * this.connectionReturnedDefer.\n *\n * @param connDidFail - True if a connectivity failure has been detected. Optional.\n */\n private pokeKeepAlive(connDidFail = false): void {\n if (!this.running) {\n // we are in a keepAlive, retrying to connect, but the syncronization\n // was stopped, so we are stopping the retry.\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject(\"SyncApi.stop() was called\");\n this.connectionReturnedDefer = undefined;\n }\n return;\n }\n\n const success = (): void => {\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.resolve(connDidFail);\n this.connectionReturnedDefer = undefined;\n }\n };\n\n this.client.http\n .request(\n Method.Get,\n \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: \"\",\n localTimeoutMs: 15 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n () => {\n success();\n },\n (err) => {\n if (err.httpStatus == 400 || err.httpStatus == 404) {\n // treat this as a success because the server probably just doesn't\n // support /versions: point is, we're getting a response.\n // We wait a short time though, just in case somehow the server\n // is in a mode where it 400s /versions responses and sync etc.\n // responses fail, this will mean we don't hammer in a loop.\n this.keepAliveTimer = setTimeout(success, 2000);\n } else {\n connDidFail = true;\n this.keepAliveTimer = setTimeout(\n this.pokeKeepAlive.bind(this, connDidFail),\n 5000 + Math.floor(Math.random() * 5000),\n );\n // A keepalive has failed, so we emit the\n // error state (whether or not this is the\n // first failure).\n // Note we do this after setting the timer:\n // this lets the unit tests advance the mock\n // clock when they get the error.\n this.updateSyncState(SyncState.Error, { error: err });\n }\n },\n );\n }\n\n private mapSyncResponseToRoomArray<T extends ILeftRoom | IJoinedRoom | IInvitedRoom | IKnockedRoom>(\n obj: Record<string, T>,\n ): Array<WrappedRoom<T>> {\n // Maps { roomid: {stuff}, roomid: {stuff} }\n // to\n // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n const client = this.client;\n return Object.keys(obj)\n .filter((k) => !unsafeProp(k))\n .map((roomId) => {\n let room = client.store.getRoom(roomId);\n let isBrandNewRoom = false;\n if (!room) {\n room = this.createRoom(roomId);\n isBrandNewRoom = true;\n }\n return {\n ...obj[roomId],\n room,\n isBrandNewRoom,\n };\n });\n }\n\n private mapSyncEventsFormat(\n obj: IInviteState | ITimeline | IEphemeral,\n room?: Room,\n decrypt = true,\n ): MatrixEvent[] {\n if (!obj || !Array.isArray(obj.events)) {\n return [];\n }\n const mapper = this.client.getEventMapper({ decrypt });\n type TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n return (obj.events as TaggedEvent[]).filter(noUnsafeEventProps).map(function (e) {\n if (room) {\n e.room_id = room.roomId;\n }\n return mapper(e);\n });\n }\n\n /**\n */\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member;\n if (inviteEvent?.getContent().membership !== KnownMembership.Invite) {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (err) {\n // OH WELL.\n },\n );\n });\n }\n\n private findEncryptionEvent(events?: MatrixEvent[]): MatrixEvent | undefined {\n return events?.find((e) => e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\");\n }\n\n // When processing the sync response we cannot rely on Room.hasEncryptionStateEvent we actually\n // inject the events into the room object, so we have to inspect the events themselves.\n private isRoomEncrypted(room: Room, stateEventList: MatrixEvent[], timelineEventList?: MatrixEvent[]): boolean {\n return (\n room.hasEncryptionStateEvent() ||\n !!this.findEncryptionEvent(stateEventList) ||\n !!this.findEncryptionEvent(timelineEventList)\n );\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events, including threaded. Lower index\n * is earlier in time. Higher index is later.\n * @param fromCache - whether the sync response came from cache\n */\n public async injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList?: MatrixEvent[],\n fromCache = false,\n ): Promise<void> {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList, {\n timelineWasEmpty,\n });\n }\n\n this.resolveInvites(room);\n\n // recalculate the room name at this point as adding events to the timeline\n // may make notifications appear which should have the right name.\n // XXX: This looks suspect: we'll end up recalculating the room once here\n // and then again after adding events (processSyncResponse calls it after\n // calling us) even if no state events were added. It also means that if\n // one of the room events in timelineEventList is something that needs\n // a recalculation (like m.room.name) we won't recalculate until we've\n // finished adding all the events, which will cause the notification to have\n // the old room name rather than the new one.\n room.recalculate();\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList || []);\n room.currentState.setStateEvents(stateEventList || []);\n }\n\n // Execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n await room.addLiveEvents(timelineEventList || [], {\n fromCache,\n timelineWasEmpty,\n });\n this.client.processBeaconEvents(room, timelineEventList);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private processEventsForNotifs(room: Room, timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (this.client.getNotifTimelineSet()) {\n for (const event of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(event);\n if (pushActions?.notify && pushActions.tweaks?.highlight) {\n this.notifEvents.push(event);\n }\n }\n }\n }\n\n private getGuestFilter(): string {\n // Dev note: This used to be conditional to return a filter of 20 events maximum, but\n // the condition never went to the other branch. This is now hardcoded.\n return \"{}\";\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Event handler for the 'online' event\n * This event is generally unreliable and precise behaviour\n * varies between browsers, so we poll for connectivity too,\n * but this might help us reconnect a little faster.\n */\n private onOnline = (): void => {\n debuglog(\"Browser thinks we are back online\");\n this.startKeepAlives(0);\n };\n}\n\n// /!\\ This function is not intended for public use! It's only exported from\n// here in order to share some common logic with sliding-sync-sdk.ts.\nexport function _createAndReEmitRoom(client: MatrixClient, roomId: string, opts: Partial<IStoredClientOpts>): Room {\n const { timelineSupport } = client;\n\n const room = new Room(roomId, client, client.getUserId()!, {\n lazyLoadMembers: opts.lazyLoadMembers,\n pendingEventOrdering: opts.pendingEventOrdering,\n timelineSupport,\n });\n\n client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n\n // We need to add a listener for RoomState.members in order to hook them\n // correctly.\n room.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = client.getUser(member.userId) ?? undefined;\n client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n\n return room;\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,IAAI,QAAQ,kBAAkB;AACvC,SAASC,qBAAqB,EAAEC,IAAI,EAAEC,SAAS,QAAQ,kBAAkB;AACzE,SAASC,QAAQ,EAAEC,KAAK,EAAaC,kBAAkB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,YAAY;AACzG,SAASC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