matrix-js-sdk
Version:
Matrix Client-Server SDK for Javascript
1,198 lines • 161 kB
TypeScript
/**
* This is an internal module. See {@link MatrixClient} for the public class.
*/
import type { IDeviceKeys, IOneTimeKey } from "./@types/crypto.ts";
import { type ISyncStateData, type SetPresence, SyncApi, type SyncApiOptions, SyncState } from "./sync.ts";
import { EventStatus, type IDecryptOptions, type IEvent, MatrixEvent, MatrixEventEvent, type MatrixEventHandlerMap, type PushDetails } from "./models/event.ts";
import { type CallEvent, type CallEventHandlerMap, type MatrixCall } from "./webrtc/call.ts";
import { Filter, type IFilterDefinition } from "./filter.ts";
import { CallEventHandler, type CallEventHandlerEvent, type CallEventHandlerEventHandlerMap } from "./webrtc/callEventHandler.ts";
import { GroupCallEventHandler, type GroupCallEventHandlerEvent, type GroupCallEventHandlerEventHandlerMap } from "./webrtc/groupCallEventHandler.ts";
import { type QueryDict } from "./utils.ts";
import { Direction, EventTimeline } from "./models/event-timeline.ts";
import { type IActionsObject, PushProcessor } from "./pushprocessor.ts";
import { type AutoDiscoveryAction } from "./autodiscovery.ts";
import { TypedReEmitter } from "./ReEmitter.ts";
import { type Logger } from "./logger.ts";
import { SERVICE_TYPES } from "./service-types.ts";
import { type FileType, type HttpApiEvent, type HttpApiEventHandlerMap, type IHttpOpts, type IRequestOpts, MatrixError, MatrixHttpApi, type TokenRefreshFunction, type Upload, type UploadOpts, type UploadResponse } from "./http-api/index.ts";
import { User, UserEvent, type UserEventHandlerMap } from "./models/user.ts";
import { type IIdentityServerProvider } from "./@types/IIdentityServerProvider.ts";
import { type MatrixScheduler } from "./scheduler.ts";
import { type BeaconEvent, type BeaconEventHandlerMap } from "./models/beacon.ts";
import { type AuthDict } from "./interactive-auth.ts";
import { type IMinimalEvent, type IRoomEvent, type IStateEvent, type ReceivedToDeviceMessage } from "./sync-accumulator.ts";
import type { EventTimelineSet } from "./models/event-timeline-set.ts";
import { type Room, type RoomEvent, type RoomEventHandlerMap, type RoomNameState } from "./models/room.ts";
import { RoomMemberEvent, type RoomMemberEventHandlerMap } from "./models/room-member.ts";
import { RoomStateEvent, type RoomStateEventHandlerMap } from "./models/room-state.ts";
import { UpdateDelayedEventAction, type DelayedEventInfo, type IAddThreePidOnlyBody, type IBindThreePidBody, type ICreateRoomOpts, type IEventSearchOpts, type IGuestAccessOpts, type IJoinRoomOpts, type InviteOpts, type IPaginateOpts, type IPresenceOpts, type IRedactOpts, type IRelationsRequestOpts, type IRelationsResponse, type IRoomDirectoryOptions, type ISearchOpts, type ISendEventResponse, type IStatusResponse, type ITagsResponse, type KnockRoomOpts, type SendDelayedEventRequestOpts, type SendDelayedEventResponse } from "./@types/requests.ts";
import { type AccountDataEvents, EventType, RelationType, type RoomAccountDataEvents, RoomType, type StateEvents, type TimelineEvents, type WritableAccountDataEvents } from "./@types/event.ts";
import { type IdServerUnbindResult, type JoinRule, Preset, type Terms, type Visibility } from "./@types/partials.ts";
import { type EventMapper, type MapperOpts } from "./event-mapper.ts";
import { MSC3089TreeSpace } from "./models/MSC3089TreeSpace.ts";
import { type ISignatures } from "./@types/signed.ts";
import { type IStore } from "./store/index.ts";
import { type IEventWithRoomId, type ISearchRequestBody, type ISearchResponse, type ISearchResults, type IStateEventWithRoomId } from "./@types/search.ts";
import { type ISynapseAdminDeactivateResponse, type ISynapseAdminWhoisResponse } from "./@types/synapse.ts";
import { type IHierarchyRoom } from "./@types/spaces.ts";
import { type IPusher, type IPusherRequest, type IPushRule, type IPushRules, type PushRuleAction, PushRuleKind, type RuleId } from "./@types/PushRules.ts";
import { type IThreepid } from "./@types/threepids.ts";
import { type CryptoStore } from "./crypto/store/base.ts";
import { GroupCall, type GroupCallIntent, type GroupCallType, type IGroupCallDataChannelOptions } from "./webrtc/groupCall.ts";
import { MediaHandler } from "./webrtc/mediaHandler.ts";
import { type ILoginFlowsResponse, type IRefreshTokenResponse, type LoginRequest, type LoginResponse, type LoginTokenPostResponse, type SSOAction } from "./@types/auth.ts";
import { TypedEventEmitter } from "./models/typed-event-emitter.ts";
import { ReceiptType } from "./@types/read_receipts.ts";
import { type MSC3575SlidingSyncRequest, type MSC3575SlidingSyncResponse, type SlidingSync } from "./sliding-sync.ts";
import { SlidingSyncSdk } from "./sliding-sync-sdk.ts";
import { FeatureSupport, ThreadFilterType } from "./models/thread.ts";
import { type MBeaconInfoEventContent } from "./@types/beacon.ts";
import { NamespacedValue, UnstableValue } from "./NamespacedValue.ts";
import { type ToDeviceBatch, type ToDevicePayload } from "./models/ToDeviceMessage.ts";
import { IgnoredInvites } from "./models/invites-ignorer.ts";
import { type LocalNotificationSettings } from "./@types/local_notifications.ts";
import { Feature, ServerSupport } from "./feature.ts";
import { type CrossSigningKeyInfo, type CryptoApi, type CryptoCallbacks, CryptoEvent, type CryptoEventHandlerMap } from "./crypto-api/index.ts";
import { type SecretStorageKeyDescription, type ServerSideSecretStorage } from "./secret-storage.ts";
import { type RegisterRequest, type RegisterResponse } from "./@types/registration.ts";
import { MatrixRTCSessionManager } from "./matrixrtc/MatrixRTCSessionManager.ts";
import { type Membership } from "./@types/membership.ts";
import { type RoomMessageEventContent } from "./@types/events.ts";
import { type ImageInfo } from "./@types/media.ts";
import { type Capabilities } from "./serverCapabilities.ts";
import { type OidcClientConfig } from "./oidc/index.ts";
import { type EmptyObject } from "./@types/common.ts";
import { type Transport } from "./matrixrtc/index.ts";
export type Store = IStore;
export type ResetTimelineCallback = (roomId: string) => boolean;
export declare const UNSTABLE_MSC3852_LAST_SEEN_UA: UnstableValue<"last_seen_user_agent", "org.matrix.msc3852.last_seen_user_agent">;
export interface IKeysUploadResponse {
one_time_key_counts: {
[algorithm: string]: number;
};
}
export interface ICreateClientOpts {
baseUrl: string;
idBaseUrl?: string;
/**
* The data store used for sync data from the homeserver. If not specified,
* this client will not store any HTTP responses. The `createClient` helper
* will create a default store if needed.
*/
store?: Store;
/**
* A store to be used for end-to-end crypto session data.
* The `createClient` helper will create a default store if needed. Calls the factory supplied to
* {@link setCryptoStoreFactory} if unspecified; or if no factory has been
* specified, uses a default implementation (indexeddb in the browser,
* in-memory otherwise).
*
* This is only used for the legacy crypto implementation,
* but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device
* previously used legacy crypto (so must be migrated), then this must still be provided, so that the
* data can be migrated from the legacy store.
*/
cryptoStore?: CryptoStore;
/**
* The scheduler to use. If not
* specified, this client will not retry requests on failure. This client
* will supply its own processing function to
* {@link MatrixScheduler#setProcessFunction}.
*/
scheduler?: MatrixScheduler;
/**
* The function to invoke for HTTP requests.
* Most supported environments have a global `fetch` registered to which this will fall back.
*/
fetchFn?: typeof globalThis.fetch;
userId?: string;
/**
* A unique identifier for this device; used for tracking things like crypto
* keys and access tokens. If not specified, end-to-end encryption will be
* disabled.
*/
deviceId?: string;
accessToken?: string;
refreshToken?: string;
/**
* Function used to attempt refreshing access and refresh tokens
* Called by http-api when a possibly expired token is encountered
* and a refreshToken is found
*/
tokenRefreshFunction?: TokenRefreshFunction;
/**
* Identity server provider to retrieve the user's access token when accessing
* the identity server. See also https://github.com/vector-im/element-web/issues/10615
* which seeks to replace the previous approach of manual access tokens params
* with this callback throughout the SDK.
*/
identityServer?: IIdentityServerProvider;
/**
* The default maximum amount of
* time to wait before timing out HTTP requests. If not specified, there is no timeout.
*/
localTimeoutMs?: number;
/**
* Set to false to send the access token to the server via a query parameter rather
* than the Authorization HTTP header.
*
* Note that as of v1.11 of the Matrix spec, sending the access token via a query
* is deprecated.
*
* Default true.
*/
useAuthorizationHeader?: boolean;
/**
* Set to true to enable
* improved timeline support, see {@link MatrixClient#getEventTimeline}.
* It is disabled by default for compatibility with older clients - in particular to
* maintain support for back-paginating the live timeline after a '/sync'
* result with a gap.
*/
timelineSupport?: boolean;
/**
* Extra query parameters to append
* to all requests with this client. Useful for application services which require
* `?user_id=`.
*/
queryParams?: QueryDict;
/**
* Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}.
*
* This must be set to the same value every time the client is initialised for the same device.
*
* This is only used for the legacy crypto implementation,
* but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device
* previously used legacy crypto (so must be migrated), then this must still be provided, so that the
* data can be migrated from the legacy store.
*/
pickleKey?: string;
/**
* Verification methods we should offer to the other side when performing an interactive verification.
* If unset, we will offer all known methods. Currently these are: showing a QR code, scanning a QR code, and SAS
* (aka "emojis").
*
* See {@link types.VerificationMethod} for a set of useful constants for this parameter.
*/
verificationMethods?: Array<string>;
/**
* Whether relaying calls through a TURN server should be forced. Default false.
*/
forceTURN?: boolean;
/**
* Up to this many ICE candidates will be gathered when an incoming call arrives.
* Gathering does not send data to the caller, but will communicate with the configured TURN
* server. Default 0.
*/
iceCandidatePoolSize?: number;
/**
* True to advertise support for call transfers to other parties on Matrix calls. Default false.
*/
supportsCallTransfer?: boolean;
/**
* Whether to allow a fallback ICE server should be used for negotiating a
* WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.
*/
fallbackICEServerAllowed?: boolean;
/**
* If true, to-device signalling for group calls will be encrypted
* with Olm. Default: true.
*/
useE2eForGroupCall?: boolean;
livekitServiceURL?: string;
/**
* Crypto callbacks provided by the application
*/
cryptoCallbacks?: CryptoCallbacks;
/**
* Enable encrypted state events.
*/
enableEncryptedStateEvents?: boolean;
/**
* Method to generate room names for empty rooms and rooms names based on membership.
* Defaults to a built-in English handler with basic pluralisation.
*/
roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;
/**
* If true, participant can join group call without video and audio this has to be allowed. By default, a local
* media stream is needed to establish a group call.
* Default: false.
*/
isVoipWithNoMediaAllowed?: boolean;
/**
* Disable VoIP support (prevents fetching TURN servers, etc.)
* Default: false (VoIP enabled)
*/
disableVoip?: boolean;
/**
* If true, group calls will not establish media connectivity and only create the signaling events,
* so that livekit media can be used in the application layer (js-sdk contains no livekit code).
*/
useLivekitForGroupCalls?: boolean;
/**
* A logger to associate with this MatrixClient.
* Defaults to the built-in global logger; see {@link DebugLogger} for an alternative.
*/
logger?: Logger;
}
export interface IMatrixClientCreateOpts extends ICreateClientOpts {
/**
* Whether to allow sending messages to encrypted rooms when encryption
* is not available internally within this SDK. This is useful if you are using an external
* E2E proxy, for example. Defaults to false.
*/
usingExternalCrypto?: boolean;
}
export declare enum PendingEventOrdering {
Chronological = "chronological",
Detached = "detached"
}
export interface IStartClientOpts {
/**
* The event `limit=` to apply to initial sync. Default: 8.
*/
initialSyncLimit?: number;
/**
* True to put `archived=true</code> on the <code>/initialSync` request. Default: false.
*/
includeArchivedRooms?: boolean;
/**
* True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.
*/
resolveInvitesToProfiles?: boolean;
/**
* Controls where pending messages appear in a room's timeline. If "<b>chronological</b>", messages will
* appear in the timeline when the call to `sendEvent` was made. If "<b>detached</b>",
* pending messages will appear in a separate list, accessible via {@link Room#getPendingEvents}.
* Default: "chronological".
*/
pendingEventOrdering?: PendingEventOrdering;
/**
* The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).
*/
pollTimeout?: number;
/**
* The filter to apply to /sync calls.
*/
filter?: Filter;
/**
* True to perform syncing without automatically updating presence.
*/
disablePresence?: boolean;
/**
* True to not load all membership events during initial sync but fetch them when needed by calling
* `loadOutOfBandMembers` This will override the filter option at this moment.
*/
lazyLoadMembers?: boolean;
/**
* The number of seconds between polls to /.well-known/matrix/client, undefined to disable.
* This should be in the order of hours. Default: undefined.
*/
clientWellKnownPollPeriod?: number;
/**
* Will organises events in threaded conversations when
* a thread relation is encountered
*/
threadSupport?: boolean;
/**
* @experimental
*/
slidingSync?: SlidingSync;
}
export interface IStoredClientOpts extends IStartClientOpts {
}
export declare const GET_LOGIN_TOKEN_CAPABILITY: NamespacedValue<"m.get_login_token", "org.matrix.msc3882.get_login_token">;
export declare const UNSTABLE_MSC2666_SHARED_ROOMS = "uk.half-shot.msc2666";
export declare const UNSTABLE_MSC2666_MUTUAL_ROOMS = "uk.half-shot.msc2666.mutual_rooms";
export declare const UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = "uk.half-shot.msc2666.query_mutual_rooms";
export declare const UNSTABLE_MSC4140_DELAYED_EVENTS = "org.matrix.msc4140";
export declare const UNSTABLE_MSC4354_STICKY_EVENTS = "org.matrix.msc4354";
export declare const UNSTABLE_MSC4133_EXTENDED_PROFILES = "uk.tcpip.msc4133";
export declare const STABLE_MSC4133_EXTENDED_PROFILES = "uk.tcpip.msc4133.stable";
declare enum CrossSigningKeyType {
MasterKey = "master_key",
SelfSigningKey = "self_signing_key",
UserSigningKey = "user_signing_key"
}
export type CrossSigningKeys = Record<CrossSigningKeyType, CrossSigningKeyInfo>;
export type SendToDeviceContentMap = Map<string, Map<string, Record<string, any>>>;
export interface ISignedKey {
keys: Record<string, string>;
signatures: ISignatures;
user_id: string;
algorithms: string[];
device_id: string;
}
export type KeySignatures = Record<string, Record<string, CrossSigningKeyInfo | ISignedKey>>;
export interface IUploadKeySignaturesResponse {
failures: Record<string, Record<string, {
errcode: string;
error: string;
}>>;
}
export interface IPreviewUrlResponse {
[key: string]: undefined | string | number;
"og:title": string;
"og:type": string;
"og:url": string;
"og:image"?: string;
"og:image:type"?: string;
"og:image:height"?: number;
"og:image:width"?: number;
"og:description"?: string;
"matrix:image:size"?: number;
}
export interface ITurnServerResponse {
uris: string[];
username: string;
password: string;
ttl: number;
}
export interface ITurnServer {
urls: string[];
username: string;
credential: string;
}
export interface IServerVersions {
versions: string[];
unstable_features: Record<string, boolean>;
}
export interface IClientWellKnown {
[key: string]: any;
"m.homeserver"?: IWellKnownConfig;
"m.identity_server"?: IWellKnownConfig;
}
export interface IWellKnownConfig<T = IClientWellKnown> {
raw?: T;
action?: AutoDiscoveryAction;
reason?: string;
error?: Error | string;
base_url?: string | null;
server_name?: string;
}
interface IMediaConfig {
[key: string]: any;
"m.upload.size"?: number;
}
interface ITagMetadata {
[key: string]: any;
order?: number;
}
interface IMessagesResponse {
start?: string;
end?: string;
chunk: IRoomEvent[];
state?: IStateEvent[];
}
export interface IRequestTokenResponse {
sid: string;
submit_url?: string;
}
export interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {
msisdn: string;
success: boolean;
intl_fmt: string;
}
export interface IUploadKeysRequest {
"device_keys"?: Required<IDeviceKeys>;
"one_time_keys"?: Record<string, IOneTimeKey>;
"org.matrix.msc2732.fallback_keys"?: Record<string, IOneTimeKey>;
}
export interface IQueryKeysRequest {
device_keys: {
[userId: string]: string[];
};
timeout?: number;
token?: string;
}
export interface IClaimKeysRequest {
one_time_keys: {
[userId: string]: {
[deviceId: string]: string;
};
};
timeout?: number;
}
export interface IOpenIDToken {
access_token: string;
token_type: "Bearer" | string;
matrix_server_name: string;
expires_in: number;
}
interface IRoomInitialSyncResponse {
room_id: string;
membership: Membership;
messages?: {
start?: string;
end?: string;
chunk: IEventWithRoomId[];
};
state?: IStateEventWithRoomId[];
visibility: Visibility;
account_data?: IMinimalEvent[];
presence: Partial<IEvent>;
}
interface IJoinedRoomsResponse {
joined_rooms: string[];
}
interface IJoinedMembersResponse {
joined: {
[userId: string]: {
display_name: string;
avatar_url: string;
};
};
}
export type IRegisterRequestParams = RegisterRequest;
export interface IPublicRoomsChunkRoom {
room_id: string;
name?: string;
avatar_url?: string;
topic?: string;
canonical_alias?: string;
aliases?: string[];
world_readable: boolean;
guest_can_join: boolean;
num_joined_members: number;
room_type?: RoomType | string;
join_rule?: JoinRule.Knock | JoinRule.Public;
}
interface IPublicRoomsResponse {
chunk: IPublicRoomsChunkRoom[];
next_batch?: string;
prev_batch?: string;
total_room_count_estimate?: number;
}
interface IUserDirectoryResponse {
results: {
user_id: string;
display_name?: string;
avatar_url?: string;
}[];
limited: boolean;
}
export interface IMyDevice {
"device_id": string;
"display_name"?: string;
"last_seen_ip"?: string;
"last_seen_ts"?: number;
"last_seen_user_agent"?: string;
"org.matrix.msc3852.last_seen_user_agent"?: string;
}
export interface Keys {
keys: {
[keyId: string]: string;
};
usage: string[];
user_id: string;
}
export interface SigningKeys extends Keys {
signatures: ISignatures;
}
export interface DeviceKeys {
[deviceId: string]: IDeviceKeys & {
unsigned?: {
device_display_name: string;
};
};
}
export interface IDownloadKeyResult {
failures: {
[serverName: string]: object;
};
device_keys: {
[userId: string]: DeviceKeys;
};
master_keys?: {
[userId: string]: Keys;
};
self_signing_keys?: {
[userId: string]: SigningKeys;
};
user_signing_keys?: {
[userId: string]: SigningKeys;
};
}
export interface IClaimOTKsResult {
failures: {
[serverName: string]: object;
};
one_time_keys: {
[userId: string]: {
[deviceId: string]: {
[keyId: string]: {
key: string;
signatures: ISignatures;
};
};
};
};
}
export interface IFieldType {
regexp: string;
placeholder: string;
}
export interface IInstance {
desc: string;
icon?: string;
fields: object;
network_id: string;
instance_id: string;
}
export interface IProtocol {
user_fields: string[];
location_fields: string[];
icon: string;
field_types: Record<string, IFieldType>;
instances: IInstance[];
}
interface IThirdPartyLocation {
alias: string;
protocol: string;
fields: object;
}
interface IThirdPartyUser {
userid: string;
protocol: string;
fields: object;
}
/**
* The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse
* Proposed at https://github.com/matrix-org/matrix-doc/pull/3266
*/
export interface RoomSummary extends Omit<IPublicRoomsChunkRoom, "canonical_alias" | "aliases"> {
/**
* The current membership of this user in the room.
* Usually "leave" if the room is fetched over federation.
*/
"membership"?: Membership;
/**
* Version of the room.
*/
"im.nheko.summary.room_version"?: string;
/**
* The encryption algorithm used for this room, if the room is encrypted.
*/
"im.nheko.summary.encryption"?: string;
}
interface IRoomHierarchy {
rooms: IHierarchyRoom[];
next_batch?: string;
}
export interface TimestampToEventResponse {
event_id: string;
origin_server_ts: number;
}
interface IWhoamiResponse {
user_id: string;
device_id?: string;
is_guest?: boolean;
}
export declare enum ClientEvent {
/**
* Fires whenever the SDK's syncing state is updated. The state can be one of:
* <ul>
*
* <li>PREPARED: The client has synced with the server at least once and is
* ready for methods to be called on it. This will be immediately followed by
* a state of SYNCING. <i>This is the equivalent of "syncComplete" in the
* previous API.</i></li>
*
* <li>CATCHUP: The client has detected the connection to the server might be
* available again and will now try to do a sync again. As this sync might take
* a long time (depending how long ago was last synced, and general server
* performance) the client is put in this mode so the UI can reflect trying
* to catch up with the server after losing connection.</li>
*
* <li>SYNCING : The client is currently polling for new events from the server.
* This will be called <i>after</i> processing latest events from a sync.</li>
*
* <li>ERROR : The client has had a problem syncing with the server. If this is
* called <i>before</i> PREPARED then there was a problem performing the initial
* sync. If this is called <i>after</i> PREPARED then there was a problem polling
* the server for updates. This may be called multiple times even if the state is
* already ERROR. <i>This is the equivalent of "syncError" in the previous
* API.</i></li>
*
* <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that
* should be considered erroneous.
* </li>
*
* <li>STOPPED: The client has stopped syncing with server due to stopClient
* being called.
* </li>
* </ul>
* State transition diagram:
* ```
* +---->STOPPED
* |
* +----->PREPARED -------> SYNCING <--+
* | ^ | ^ |
* | CATCHUP ----------+ | | |
* | ^ V | |
* null ------+ | +------- RECONNECTING |
* | V V |
* +------->ERROR ---------------------+
*
* NB: 'null' will never be emitted by this event.
*
* ```
* Transitions:
* <ul>
*
* <li>`null -> PREPARED` : Occurs when the initial sync is completed
* first time. This involves setting up filters and obtaining push rules.
*
* <li>`null -> ERROR` : Occurs when the initial sync failed first time.
*
* <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds
* after previously failing.
*
* <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning
* to PREPARED. Starts listening for live updates rather than catching up.
*
* <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.
*
* <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls
* continue to fail, but the keepalive calls (to /versions) succeed.
*
* <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails
*
* <li>`ERROR -> SYNCING` : Occurs when the client has performed a
* live update after having previously failed.
*
* <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive
* for a second time or more.</li>
*
* <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live
* update. This is called <i>after</i> processing.</li>
*
* <li>`* -> STOPPED` : Occurs once the client has stopped syncing or
* trying to sync after stopClient has been called.</li>
* </ul>
*
* The payloads consits of the following 3 parameters:
*
* - state - An enum representing the syncing state. One of "PREPARED",
* "SYNCING", "ERROR", "STOPPED".
*
* - prevState - An enum representing the previous syncing state.
* One of "PREPARED", "SYNCING", "ERROR", "STOPPED" <b>or null</b>.
*
* - data - Data about this transition.
*
* @example
* ```
* matrixClient.on("sync", function(state, prevState, data) {
* switch (state) {
* case "ERROR":
* // update UI to say "Connection Lost"
* break;
* case "SYNCING":
* // update UI to remove any "Connection Lost" message
* break;
* case "PREPARED":
* // the client instance is ready to be queried.
* var rooms = matrixClient.getRooms();
* break;
* }
* });
* ```
*/
Sync = "sync",
/**
* Fires whenever the SDK receives a new event.
* <p>
* This is only fired for live events received via /sync - it is not fired for
* events received over context, search, or pagination APIs.
*
* The payload is the matrix event which caused this event to fire.
* @example
* ```
* matrixClient.on("event", function(event){
* var sender = event.getSender();
* });
* ```
*/
Event = "event",
/** @deprecated Use {@link ReceivedToDeviceMessage}.
* Fires whenever the SDK receives a new to-device event.
* The payload is the matrix event ({@link MatrixEvent}) which caused this event to fire.
* @example
* ```
* matrixClient.on("toDeviceEvent", function(event){
* var sender = event.getSender();
* });
* ```
*/
ToDeviceEvent = "toDeviceEvent",
/**
* Fires whenever the SDK receives a new (potentially decrypted) to-device message.
* The payload is the to-device message and the encryption info for that message ({@link ReceivedToDeviceMessage}).
* @example
* ```
* matrixClient.on("receivedToDeviceMessage", function(payload){
* const { message, encryptionInfo } = payload;
* var claimed_sender = encryptionInfo ? encryptionInfo.sender : message.sender;
* var isVerified = encryptionInfo ? encryptionInfo.verified : false;
* var type = message.type;
* });
*/
ReceivedToDeviceMessage = "receivedToDeviceMessage",
/**
* Fires whenever new user-scoped account_data is added.
* The payload is a pair of event ({@link MatrixEvent}) describing the account_data just added, and the previous event, if known:
* - event: The event describing the account_data just added
* - oldEvent: The previous account data, if known.
* @example
* ```
* matrixClient.on("accountData", function(event, oldEvent){
* myAccountData[event.type] = event.content;
* });
* ```
*/
AccountData = "accountData",
/**
* Fires whenever a new Room is added. This will fire when you are invited to a
* room, as well as when you join a room. <strong>This event is experimental and
* may change.</strong>
*
* The payload is the newly created room, fully populated.
* @example
* ```
* matrixClient.on("Room", function(room){
* var roomId = room.roomId;
* });
* ```
*/
Room = "Room",
/**
* Fires whenever a Room is removed. This will fire when you forget a room.
* <strong>This event is experimental and may change.</strong>
* The payload is the roomId of the deleted room.
* @example
* ```
* matrixClient.on("deleteRoom", function(roomId){
* // update UI from getRooms()
* });
* ```
*/
DeleteRoom = "deleteRoom",
SyncUnexpectedError = "sync.unexpectedError",
/**
* Fires when the client .well-known info is fetched.
* The payload is the JSON object (see {@link IClientWellKnown}) returned by the server
*/
ClientWellKnown = "WellKnown.client",
ReceivedVoipEvent = "received_voip_event",
TurnServers = "turnServers",
TurnServersError = "turnServers.error"
}
type RoomEvents = RoomEvent.Name | RoomEvent.Redaction | RoomEvent.RedactionCancelled | RoomEvent.Receipt | RoomEvent.Tags | RoomEvent.LocalEchoUpdated | RoomEvent.HistoryImportedWithinTimeline | RoomEvent.AccountData | RoomEvent.MyMembership | RoomEvent.Timeline | RoomEvent.TimelineReset;
type RoomStateEvents = RoomStateEvent.Events | RoomStateEvent.Members | RoomStateEvent.NewMember | RoomStateEvent.Update | RoomStateEvent.Marker;
type CryptoEvents = (typeof CryptoEvent)[keyof typeof CryptoEvent];
type MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;
type RoomMemberEvents = RoomMemberEvent.Name | RoomMemberEvent.Typing | RoomMemberEvent.PowerLevel | RoomMemberEvent.Membership;
type UserEvents = UserEvent.AvatarUrl | UserEvent.DisplayName | UserEvent.Presence | UserEvent.CurrentlyActive | UserEvent.LastPresenceTs;
export type EmittedEvents = ClientEvent | RoomEvents | RoomStateEvents | CryptoEvents | MatrixEventEvents | RoomMemberEvents | UserEvents | CallEvent | CallEventHandlerEvent.Incoming | GroupCallEventHandlerEvent.Incoming | GroupCallEventHandlerEvent.Outgoing | GroupCallEventHandlerEvent.Ended | GroupCallEventHandlerEvent.Participants | HttpApiEvent.SessionLoggedOut | HttpApiEvent.NoConsent | BeaconEvent;
export type ClientEventHandlerMap = {
[ClientEvent.Sync]: (state: SyncState, prevState: SyncState | null, data?: ISyncStateData) => void;
[ClientEvent.Event]: (event: MatrixEvent) => void;
[ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;
[ClientEvent.ReceivedToDeviceMessage]: (payload: ReceivedToDeviceMessage) => void;
[ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;
[ClientEvent.Room]: (room: Room) => void;
[ClientEvent.DeleteRoom]: (roomId: string) => void;
[ClientEvent.SyncUnexpectedError]: (error: Error) => void;
[ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;
[ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;
[ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;
[ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;
} & RoomEventHandlerMap & RoomStateEventHandlerMap & CryptoEventHandlerMap & MatrixEventHandlerMap & RoomMemberEventHandlerMap & UserEventHandlerMap & CallEventHandlerEventHandlerMap & GroupCallEventHandlerEventHandlerMap & CallEventHandlerMap & HttpApiEventHandlerMap & BeaconEventHandlerMap;
/**
* Represents a Matrix Client. Only directly construct this if you want to use
* custom modules. Normally, {@link createClient} should be used
* as it specifies 'sensible' defaults for these modules.
*/
export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> {
static readonly RESTORE_BACKUP_ERROR_BAD_KEY = "RESTORE_BACKUP_ERROR_BAD_KEY";
private readonly logger;
reEmitter: TypedReEmitter<EmittedEvents, ClientEventHandlerMap>;
olmVersion: [number, number, number] | null;
usingExternalCrypto: boolean;
private _store;
deviceId: string | null;
credentials: {
userId: string | null;
};
/**
* Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.
*
* As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.
* Used for migration from the legacy crypto to the rust crypto
*/
private readonly legacyPickleKey?;
scheduler?: MatrixScheduler;
clientRunning: boolean;
timelineSupport: boolean;
urlPreviewCache: {
[key: string]: Promise<IPreviewUrlResponse>;
};
identityServer?: IIdentityServerProvider;
http: MatrixHttpApi<IHttpOpts & {
onlyData: true;
}>;
private cryptoBackend?;
/**
* Support MSC4362: Simplified Encrypted State Events.
*
* The client must be recreated for changes to this setting to take effect
* reliably.
*
* When this setting is true, if we find a state event that is encrypted
* (within a room that supports encrypted state), we will attempt to decrypt
* it as specified in MSC4362. If the user was in the room at the time an
* encrypted state event was received (meaning we have the key), even if
* this setting was set to false at the time it was received, recreating the
* client with this setting set to true will allow decrypting that event.
*
* When this setting is false, any state event that is encrypted will not be
* decrypted, meaning it will have no effect. This matched the behaviour of
* a client that does not support MSC4362.
*/
enableEncryptedStateEvents: boolean;
cryptoCallbacks: CryptoCallbacks;
callEventHandler?: CallEventHandler;
groupCallEventHandler?: GroupCallEventHandler;
supportsCallTransfer: boolean;
forceTURN: boolean;
iceCandidatePoolSize: number;
idBaseUrl?: string;
baseUrl: string;
readonly isVoipWithNoMediaAllowed: boolean;
disableVoip: boolean;
useLivekitForGroupCalls: boolean;
protected canSupportVoip: boolean;
protected peekSync: SyncApi | null;
protected isGuestAccount: boolean;
protected ongoingScrollbacks: {
[roomId: string]: {
promise?: Promise<Room>;
errorTs?: number;
};
};
protected notifTimelineSet: EventTimelineSet | null;
/**
* Legacy crypto store used for migration from the legacy crypto to the rust crypto
* @private
*/
private readonly legacyCryptoStore?;
protected verificationMethods?: string[];
protected fallbackICEServerAllowed: boolean;
protected syncApi?: SlidingSyncSdk | SyncApi;
roomNameGenerator?: ICreateClientOpts["roomNameGenerator"];
pushRules?: IPushRules;
protected syncLeftRoomsPromise?: Promise<Room[]>;
protected syncedLeftRooms: boolean;
protected clientOpts?: IStoredClientOpts;
protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>;
protected canResetTimelineCallback?: ResetTimelineCallback;
canSupport: Map<Feature, ServerSupport>;
readonly pushProcessor: PushProcessor;
protected serverVersionsPromise?: Promise<IServerVersions>;
protected clientWellKnown?: IClientWellKnown;
protected clientWellKnownPromise?: Promise<IClientWellKnown>;
protected turnServers: ITurnServer[];
protected turnServersExpiry: number;
protected checkTurnServersIntervalID?: ReturnType<typeof setInterval>;
protected txnCtr: number;
protected mediaHandler: MediaHandler;
protected sessionId: string;
/** IDs of events which are currently being encrypted.
*
* This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,
* that tells us that it has been cancelled, and we should not send it.
*/
private eventsBeingEncrypted;
private useE2eForGroupCall;
private toDeviceMessageQueue;
livekitServiceURL?: string;
private _secretStorage;
readonly ignoredInvites: IgnoredInvites;
readonly matrixRTC: MatrixRTCSessionManager;
private serverCapabilitiesService;
constructor(opts: IMatrixClientCreateOpts);
set store(newStore: Store);
get store(): Store;
/**
* High level helper method to begin syncing and poll for new events. To listen for these
* events, add a listener for {@link ClientEvent.Event}
* via {@link MatrixClient#on}. Alternatively, listen for specific
* state change events.
* @param opts - Options to apply when syncing.
*/
startClient(opts?: IStartClientOpts): Promise<void>;
/**
* Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor
*/
protected buildSyncApiOptions(): SyncApiOptions;
/**
* High level helper method to stop the client from polling and allow a
* clean shutdown.
*/
stopClient(): void;
/**
* Clear any data out of the persistent stores used by the client.
*
* @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.
* @returns Promise which resolves when the stores have been cleared.
*/
clearStores(args?: {
cryptoDatabasePrefix?: string;
}): Promise<void>;
/**
* Get the user-id of the logged-in user
*
* @returns MXID for the logged-in user, or null if not logged in
*/
getUserId(): string | null;
/**
* Get the user-id of the logged-in user
*
* @returns MXID for the logged-in user
* @throws Error if not logged in
*/
getSafeUserId(): string;
/**
* Get the domain for this client's MXID
* @returns Domain of this MXID
*/
getDomain(): string | null;
/**
* Get the local part of the current user ID e.g. "foo" in "\@foo:bar".
* @returns The user ID localpart or null.
*/
getUserIdLocalpart(): string | null;
/**
* Get the device ID of this client
* @returns device ID
*/
getDeviceId(): string | null;
/**
* Get the session ID of this client
* @returns session ID
*/
getSessionId(): string;
/**
* Check if the runtime environment supports VoIP calling.
* @returns True if VoIP is supported.
*/
supportsVoip(): boolean;
/**
* @returns
*/
getMediaHandler(): MediaHandler;
/**
* Set whether VoIP calls are forced to use only TURN
* candidates. This is the same as the forceTURN option
* when creating the client.
* @param force - True to force use of TURN servers
*/
setForceTURN(force: boolean): void;
/**
* Set whether to advertise transfer support to other parties on Matrix calls.
* @param support - True to advertise the 'm.call.transferee' capability
*/
setSupportsCallTransfer(support: boolean): void;
/**
* Returns true if to-device signalling for group calls will be encrypted with Olm.
* If false, it will be sent unencrypted.
* @returns boolean Whether group call signalling will be encrypted
*/
getUseE2eForGroupCall(): boolean;
/**
* Creates a new call.
* The place*Call methods on the returned call can be used to actually place a call
*
* @param roomId - The room the call is to be placed in.
* @returns the call or null if the browser doesn't support calling.
*/
createCall(roomId: string): MatrixCall | null;
/**
* Creates a new group call and sends the associated state event
* to alert other members that the room now has a group call.
*
* @param roomId - The room the call is to be placed in.
*/
createGroupCall(roomId: string, type: GroupCallType, isPtt: boolean, intent: GroupCallIntent, dataChannelsEnabled?: boolean, dataChannelOptions?: IGroupCallDataChannelOptions): Promise<GroupCall>;
getLivekitServiceURL(): string | undefined;
setLivekitServiceURL(newURL: string): void;
/**
* Wait until an initial state for the given room has been processed by the
* client and the client is aware of any ongoing group calls. Awaiting on
* the promise returned by this method before calling getGroupCallForRoom()
* avoids races where getGroupCallForRoom is called before the state for that
* room has been processed. It does not, however, fix other races, eg. two
* clients both creating a group call at the same time.
* @param roomId - The room ID to wait for
* @returns A promise that resolves once existing group calls in the room
* have been processed.
*/
waitUntilRoomReadyForGroupCalls(roomId: string): Promise<void>;
/**
* Get an existing group call for the provided room.
* @returns The group call or null if it doesn't already exist.
*/
getGroupCallForRoom(roomId: string): GroupCall | null;
/**
* Get the current sync state.
* @returns the sync state, which may be null.
* @see MatrixClient#event:"sync"
*/
getSyncState(): SyncState | null;
/**
* Returns the additional data object associated with
* the current sync state, or null if there is no
* such data.
* Sync errors, if available, are put in the 'error' key of
* this object.
*/
getSyncStateData(): ISyncStateData | null;
/**
* Whether the initial sync has completed.
* @returns True if at least one sync has happened.
*/
isInitialSyncComplete(): boolean;
/**
* Return whether the client is configured for a guest account.
* @returns True if this is a guest access_token (or no token is supplied).
*/
isGuest(): boolean;
/**
* Set whether this client is a guest account. <b>This method is experimental
* and may change without warning.</b>
* @param guest - True if this is a guest account.
* @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'
* access token, which means that the SDK can determine this entirely without
* the dev manually flipping this flag.
*/
setGuest(guest: boolean): void;
/**
* Return the provided scheduler, if any.
* @returns The scheduler or undefined
*/
getScheduler(): MatrixScheduler | undefined;
/**
* Retry a backed off syncing request immediately. This should only be used when
* the user <b>explicitly</b> attempts to retry their lost connection.
* Will also retry any outbound to-device messages currently in the queue to be sent
* (retries of regular outgoing events are handled separately, per-event).
* @returns True if this resulted in a request being retried.
*/
retryImmediately(): boolean;
/**
* Return the global notification EventTimelineSet, if any
*
* @returns the globl notification EventTimelineSet
*/
getNotifTimelineSet(): EventTimelineSet | null;
/**
* Set the global notification EventTimelineSet
*
*/
setNotifTimelineSet(set: EventTimelineSet): void;
/**
* Gets the cached capabilities of the homeserver, returning cached ones if available.
* If there are no cached capabilities and none can be fetched, throw an exception.
*
* @returns Promise resolving with The capabilities of the homeserver
*/
getCapabilities(): Promise<Capabilities>;
/**
* Gets the cached capabilities of the homeserver. If none have been fetched yet,
* return undefined.
*
* @returns The capabilities of the homeserver
*/
getCachedCapabilities(): Capabilities | undefined;
/**
* Fetches the latest capabilities from the homeserver, ignoring any cached
* versions. The newly returned version is cached.
*
* @returns A promise which resolves to the capabilities of the homeserver
*/
fetchCapabilities(): Promise<Capabilities>;
/**
* Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.
*
* **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to
* the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for
* ensuring that only one `MatrixClient` issue is instantiated at a time.
*
* @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.
* @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.
* Unused if useIndexedDB is 'false'.
* @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly
* 32 bytes of data, and must be the same each time the client is initialised for a given device.
* If both this and `storagePassword` are unspecified, the store will be unencrypted.
* @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to
* encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer
* to pass a `storageKey` directly where possible.
*
* @returns a Promise which will resolve when the crypto layer has been
* successfully initialised.
*/
initRustCrypto(args?: {
useIndexedDB?: boolean;
cryptoDatabasePrefix?: string;
storageKey?: Uint8Array;
storagePassword?: string;
}): Promise<void>;
/**
* Access the server-side secret storage API for this client.
*/
get secretStorage(): ServerSideSecretStorage;
/**
* Access the crypto API for this client.
*
* If end-to-end encryption has been enabled for this client (via {@link initRustCrypto}),
* returns an object giving access to the crypto API. Otherwise, returns `undefined`.
*/
getCrypto(): CryptoApi | undefined;
/**
* Whether encryption is enabled for a room.
* @param roomId - the room id to query.
* @returns whether encryption is enabled.
*
* @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or
* {@link Room.hasEncryptionStateEvent}.
*/
isRoomEncrypted(roomId: string): boolean;
/**
* Check whether the key backup private key is stored in secret storage.
* @returns map of key name to key info the secret is
* encrypted with, or null if it is not present or not encrypted with a
* trusted key
*/
isKeyBackupKeyStored(): Promise<Record<string, SecretStorageKeyDescription> | null>;
private makeKeyBackupPath;
deleteKeysFromBackup(roomId: undefined, sessionId: undefined, version?: string): Promise<void>;
deleteKeysFromBackup(roomId: string, sessionId: undefined, version?: string): Promise<void>;
deleteKeysFromBackup(roomId: string, sessionId: string, version?: string): Promise<void>;
/**
* Get the config for the media repository.
*
* @param useAuthenticatedMedia - If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support
* for authenticated media will *not* be checked - it is the caller's responsibility
* to do so before calling this function.
*
* @returns Promise which resolves with an object containing the config.
*/
getMediaConfig(useAuthenticatedMedia?: boolean): Promise<IMediaConfig>;
/**
* Get the room for the given room ID.
* This function will return a valid room for any room for which a Room event
* has been emitted. Note in particular that other events, eg. RoomState.members
* will be emitted for a room before this function will return t