Skip to content

Room

Defined in: src/models/room.ts:338

new Room(roomId, client, myUserId, opts?): Room

Defined in: src/models/room.ts:483

Construct a new Room.

For a room, we store an ordered sequence of timelines, which may or may not be continuous. Each timeline lists a series of events, as well as tracking the room state at the start and the end of the timeline. It also tracks forward and backward pagination tokens, as well as containing links to the next timeline in the sequence.

There is one special timeline - the 'live' timeline, which represents the timeline to which events are being added in real-time as they are received from the /sync API. Note that you should not retain references to this timeline - even if it is the current timeline right now, it may not remain so if the server gives us a timeline gap in /sync.

In order that we can find events from their ids later, we also maintain a map from event_id to timeline and index.

string

Required. The ID of this room.

DigitalWorldClient

Required. The client, used to lazy load members.

string

Required. The ID of the syncing user.

IOpts = {}

Configuration options

Room

ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap>.constructor

accountData: Map<string, DigitalWorldEvent>

Defined in: src/models/room.ts:401

accountData Dict of per-room account_data events; the keys are the event type and the values are the events.


readonly cachedThreadReadReceipts: Map<string, CachedReceiptStructure[]>

Defined in: src/models/room.ts:344


readonly client: DigitalWorldClient

Defined in: src/models/room.ts:485

Required. The client, used to lazy load members.


currentState: RoomState

Defined in: src/models/room.ts:419

currentState The state of the room at the time of the newest event in the timeline.


readonly myUserId: string

Defined in: src/models/room.ts:486

Required. The ID of the syncing user.


name: string

Defined in: src/models/room.ts:387

The human-readable display name for this room.


normalizedName: string

Defined in: src/models/room.ts:391

The un-homoglyphed name for this room.


oldState: RoomState

Defined in: src/models/room.ts:412

oldState The state of the room at the time of the oldest event in the live timeline.


readonly polls: Map<string, Poll>

Defined in: src/models/room.ts:353


readonly reEmitter: TypedReEmitter<RoomEmittedEvents, RoomEventHandlerMap>

Defined in: src/models/room.ts:339


readonly relations: RelationsContainer

Defined in: src/models/room.ts:421


readonly roomId: string

Defined in: src/models/room.ts:484

Required. The ID of this room.


summary: RoomSummary | null = null

Defined in: src/models/room.ts:405

The room summary.


tags: Record<string, Record<string, any>> = {}

Defined in: src/models/room.ts:396

Dict of room tags; the keys are the tag name and the values are any metadata associated with the tag - e.g. { "fav" : { order: 1 } }


readonly threadsTimelineSets: [] | [EventTimelineSet, EventTimelineSet] = []

Defined in: src/models/room.ts:360

Empty array if the timeline sets have not been initialised. After initialisation: 0: All threads 1: Threads the current user has participated in


static captureRejections: boolean

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:425

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

v13.4.0, v12.16.0

ReadReceipt.captureRejections


readonly static captureRejectionSymbol: typeof captureRejectionSymbol

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:418

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

v13.4.0, v12.16.0

ReadReceipt.captureRejectionSymbol


static defaultMaxListeners: number

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:464

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for allEventEmitter instances, the events.defaultMaxListeners property can be used. If this value is not a positive number, a RangeError is thrown.

Take caution when setting the events.defaultMaxListeners because the change affects all EventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a “possible EventEmitter memory leak” has been detected. For any single EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to temporarily avoid this warning:

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event’s name and the number of attached listeners, respectively. Its name property is set to 'MaxListenersExceededWarning'.

v0.11.2

ReadReceipt.defaultMaxListeners


readonly static errorMonitor: typeof errorMonitor

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:411

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an 'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

v13.6.0, v12.17.0

ReadReceipt.errorMonitor

get threadsAggregateNotificationType(): NotificationCountType | null

Defined in: src/models/room.ts:1612

NotificationCountType | null

the notification count type for all the threads in the room


get timeline(): DigitalWorldEvent[]

Defined in: src/models/room.ts:807

The live event timeline for this room, with the oldest event at index 0.

DigitalWorldEvent[]

ReadReceipt.timeline

_unstable_getKeyedStickyEvent(sender, type, stickyKey): StickyDigitalWorldEvent | undefined

Defined in: src/models/room.ts:3460

Get a sticky event that match the given type, sender, and stickyKey

string

The sender of the sticky event.

string

The event type.

string

The sticky key used by the event.

StickyDigitalWorldEvent | undefined

A matching active sticky event, or undefined.


_unstable_getStickyEvents(): Iterable<StickyDigitalWorldEvent>

Defined in: src/models/room.ts:3448

Get an iterator of currently active sticky events.

Iterable<StickyDigitalWorldEvent>


_unstable_getUnkeyedStickyEvent(sender, type): StickyDigitalWorldEvent[]

Defined in: src/models/room.ts:3475

Get active sticky events without a sticky key that match the given type and sender.

string

The sender of the sticky event.

string

The event type.

StickyDigitalWorldEvent[]

An array of matching sticky events.


optional [captureRejectionSymbol]<K>(error, event, …args): void

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:103

K

Error

string | symbol

AnyRest

void

ReadReceipt.[captureRejectionSymbol]


addAccountData(events): void

Defined in: src/models/room.ts:3423

Update the account_data events for this room, overwriting events of the same type.

DigitalWorldEvent[]

an array of account_data events to add

void


addEphemeralEvents(events): void

Defined in: src/models/room.ts:3308

Adds/handles ephemeral events such as typing notifications and read receipts.

DigitalWorldEvent[]

A list of events to process

void


addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken?): void

Defined in: src/models/room.ts:1864

Add events to a timeline

Will fire "Room.timeline" for each event added.

DigitalWorldEvent[]

A list of events to add.

boolean

True to add these events to the start (oldest) instead of the end (newest) of the timeline. If true, the oldest event will be the last element of ‘events’.

boolean

EventTimeline

timeline to add events to.

string

token for the next batch of events

void

Fires RoomEvent.Timeline


addListener<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:70

Alias for on.

T extends EventEmitterEvents | RoomEmittedEvents

T

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

this

ReadReceipt.addListener


addLiveEvents(events, addLiveEventOptions): Promise<void>

Defined in: src/models/room.ts:3087

Add some events to this room. This can include state events, message events and typing notifications. These events are treated as “live” so they will go to the end of the timeline.

DigitalWorldEvent[]

A list of events to add.

IAddLiveEventOptions

addLiveEvent options

Promise<void>

If duplicateStrategy is not falsey, ‘replace’ or ‘ignore’.


addLocalEchoReceipt(userId, e, receiptType, unthreaded?): void

Defined in: src/models/read-receipt.ts:383

Add a temporary local-echo receipt to the room to reflect in the client the fact that we’ve sent one.

string

The user ID if the receipt sender

DigitalWorldEvent

The event that is to be acknowledged

ReceiptType

The type of receipt

boolean = false

the receipt is unthreaded

void

ReadReceipt.addLocalEchoReceipt


addPendingEvent(event, txnId): void

Defined in: src/models/room.ts:2784

Add a pending outgoing event to this room.

The event is added to either the pendingEventList, or the live timeline, depending on the setting of opts.pendingEventOrdering.

This is an internal method, intended for use by DigitalWorldClient.

DigitalWorldEvent

The event to add.

string

Transaction id for this outgoing event

void

if the event doesn’t have status SENDING, or we aren’t given a unique transaction id.

Fires RoomEvent.LocalEchoUpdated


addReceipt(event, synthetic?): void

Defined in: src/models/room.ts:3230

Add a receipt event to the room.

DigitalWorldEvent

The m.receipt event.

boolean = false

True if this event is implicit.

void

ReadReceipt.addReceipt


addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic): void

Defined in: src/models/read-receipt.ts:242

string

ReceiptType

string

Receipt

boolean

void

ReadReceipt.addReceiptToStructure


addTags(event): void

Defined in: src/models/room.ts:3402

Update the room-tag event for the room. The previous one is overwritten.

DigitalWorldEvent

the m.tag event

void


addTimeline(): EventTimeline

Defined in: src/models/room.ts:1485

Add a new timeline to this room’s unfiltered timeline set

EventTimeline

newly-created timeline


canInvite(userId): boolean

Defined in: src/models/room.ts:3515

Returns whether the given user has permissions to issue an invite for this room.

string

the ID of the user to check permissions for

boolean

true if the user should be permitted to issue invites for this room.


clearLoadedMembersIfNeeded(): Promise<void>

Defined in: src/models/room.ts:1157

Removes the lazily loaded members from storage if needed

Promise<void>


compareEventOrdering(leftEventId, rightEventId): number | null

Defined in: src/models/room.ts:4011

Determine the order of two events in this room.

In principle this should use the same order as the server, but in practice this is difficult for events that were not received over the Sync API. See MSC4033 for details.

This implementation leans on the order of events within their timelines, and falls back to comparing event timestamps when they are in different timelines.

This is a known limitation; see the project’s issue tracker for status.

string

the id of the first event

string

the id of the second event

number | null

-1 if left < right, 1 if left > right, 0 if left == right, null if we can’t tell (because we can’t find the events).


createThread(threadId, rootEvent, events?, toStartOfTimeline): Thread

Defined in: src/models/room.ts:2528

string

DigitalWorldEvent | undefined

DigitalWorldEvent[] = []

boolean

Thread


createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null>

Defined in: src/models/room.ts:542

Promise<[EventTimelineSet, EventTimelineSet] | null>


decryptAllEvents(): Promise<void>

Defined in: src/models/room.ts:598

Bulk decrypt events in a room

Promise<void>

Signals when all events have been decrypted


decryptCriticalEvents(): Promise<void>

Defined in: src/models/room.ts:576

Bulk decrypt critical events in a room

Critical events represents the minimal set of events to decrypt for a typical UI to function properly

  • Last event of every room (to generate likely message preview)
  • All events up to the read receipt (to calculate an accurate notification count)

Promise<void>

Signals when all events have been decrypted


emit<T>(event, …args): boolean

Defined in: src/models/typed-event-emitter.ts:86

Synchronously calls each of the listeners registered for the event named event, in the order they were registered, passing the supplied arguments to each.

T extends RoomEmittedEvents

T

The name of the event to emit

Parameters<RoomEventHandlerMap[T]>

Arguments to pass to the listener

boolean

true if the event had listeners, false otherwise.

ReadReceipt.emit

emit<T>(event, …args): boolean

Defined in: src/models/typed-event-emitter.ts:87

Synchronously calls each of the listeners registered for the event named event, in the order they were registered, passing the supplied arguments to each.

T extends RoomEmittedEvents

T

The name of the event to emit

Parameters<RoomEventHandlerMap[T]>

Arguments to pass to the listener

boolean

true if the event had listeners, false otherwise.

ReadReceipt.emit


emitPromised<T>(event, …args): Promise<boolean>

Defined in: src/models/typed-event-emitter.ts:98

Similar to emit but calls all listeners within a Promise.all and returns the promise chain

T extends RoomEmittedEvents

T

The name of the event to emit

Parameters<RoomEventHandlerMap[T]>

Arguments to pass to the listener

Promise<boolean>

true if the event had listeners, false otherwise.

ReadReceipt.emitPromised

emitPromised<T>(event, …args): Promise<boolean>

Defined in: src/models/typed-event-emitter.ts:102

Similar to emit but calls all listeners within a Promise.all and returns the promise chain

T extends RoomEmittedEvents

T

The name of the event to emit

Parameters<RoomEventHandlerMap[T]>

Arguments to pass to the listener

Promise<boolean>

true if the event had listeners, false otherwise.

ReadReceipt.emitPromised


eventNames(): (string | symbol)[]

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:967

Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]

(string | symbol)[]

v6.0.0

ReadReceipt.eventNames


eventShouldLiveIn(event, events?, roots?): object

Defined in: src/models/room.ts:2379

Determine which timeline(s) a given event should live in Thread roots live in both the main timeline and their corresponding thread timeline Relations, redactions, replies to thread relation events live only in the thread timeline Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless. Otherwise, the event lives in the main timeline only.

Note: when a redaction is applied, the redacted event, events relating to it, and the redaction event itself, will all move to the main thread. This method classifies them as inside the thread of the redacted event. They are moved later as part of makeRedacted. This will change if MSC3389 is merged.

DigitalWorldEvent

DigitalWorldEvent[]

Set<string>

object

shouldLiveInRoom: boolean

shouldLiveInThread: boolean

optional threadId?: string


fetchRoomThreads(): Promise<void>

Defined in: src/models/room.ts:2154

Fetch the bare minimum of room threads required for the thread list to work reliably. With server support that means fetching one page. Without server support that means fetching as much at once as the server allows us to.

Promise<void>


findEventById(eventId): DigitalWorldEvent | undefined

Defined in: src/models/room.ts:1513

Get an event which is stored in our unfiltered timeline set, or in a thread

string

event ID to look for

DigitalWorldEvent | undefined

the given event, or undefined if unknown

ReadReceipt.findEventById


findPredecessor(msc3946ProcessDynamicPredecessor?): { eventId?: string; roomId: string; viaServers?: string[]; } | null

Defined in: src/models/room.ts:3608

Find the predecessor of this room.

boolean = false

if true, look for an m.room.predecessor state event and use it if found (MSC3946).

{ eventId?: string; roomId: string; viaServers?: string[]; } | null

null if this room has no predecessor. Otherwise, returns the roomId, last eventId and viaServers of the predecessor room.

If msc3946ProcessDynamicPredecessor is true, use m.predecessor events as well as m.room.create events to find predecessors.

Note: if an m.predecessor event is used, eventId may be undefined since last_known_event_id is optional.

Note: viaServers may be undefined, and will definitely be undefined if this predecessor comes from a RoomCreate event (rather than a RoomPredecessor, which has the optional via_servers property).


findThreadForEvent(event?): Thread | null

Defined in: src/models/room.ts:2454

DigitalWorldEvent

Thread | null


fixupNotifications(userId): void

Defined in: src/models/room.ts:3980

This issue should also be addressed on synapse’s side and is tracked as part of https://github.com/matrix-org/synapse/issues/14837

We consider a room fully read if the current user has sent the last event in the live timeline of that context and if the read receipt we have on record matches. This also detects all unread threads and applies the same logic to those contexts

string

void

ReadReceipt.fixupNotifications


getAccountData(type): DigitalWorldEvent | undefined

Defined in: src/models/room.ts:3440

Access account_data event of given event type for this room

string

the type of account_data event to be accessed

DigitalWorldEvent | undefined

the account_data event in question


getAltAliases(): string[]

Defined in: src/models/room.ts:1837

Get this room’s alternative aliases

string[]

The room’s alternative aliases, or an empty array


getAvatarFallbackMember(): RoomMember | undefined

Defined in: src/models/room.ts:945

RoomMember | undefined


getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault?, useAuthentication?): string | null

Defined in: src/models/room.ts:1784

Get the avatar URL for a room if one was set.

string

The hub base URL. See DigitalWorldClient#getHubUrl.

number

The desired width of the thumbnail.

number

The desired height of the thumbnail.

ResizeMethod

The thumbnail resize method to use, either “crop” or “scale”.

boolean = true

True to allow an identicon for this room if an avatar URL wasn’t explicitly set. Default: true. (Deprecated)

boolean = false

(optional) 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. Note also that useAuthentication implies allowRedirects. Defaults to false (unauthenticated endpoints).

string | null

the avatar URL or null.


getBlacklistUnverifiedDevices(): boolean | null

Defined in: src/models/room.ts:1762

Whether to send encrypted messages to devices within this room.

boolean | null

true if blacklisting unverified devices, null if the global value should be used for this room.


getBumpStamp(): number | undefined

Defined in: src/models/room.ts:1667

Get the bump stamp for this room. This can be used for sorting rooms when the timeline entries are unknown. Used in MSC4186: Simplified Sliding Sync.

number | undefined

The bump stamp for the room, if it exists.


getCanonicalAlias(): string | null

Defined in: src/models/room.ts:1828

Get this room’s canonical alias The alias returned by this function may not necessarily still point to this room.

string | null

The room’s canonical alias, or null if there is none


getCreator(): string | null

Defined in: src/models/room.ts:615

Gets the creator of the room

string | null

The creator of the room, or null if it could not be determined


getDefaultRoomName(userId): string

Defined in: src/models/room.ts:1986

Get the default room name (i.e. what a given user would see if the room had no m.room.name)

string

The userId from whose perspective we want to calculate the default name

string

The default room name


getDMInviter(): string | undefined

Defined in: src/models/room.ts:887

If this room is a DM we’re invited to, try to find out who invited us

string | undefined

user id of the inviter


getEncryptionTargetMembers(): Promise<RoomMember[]>

Defined in: src/models/room.ts:1961

Get a list of members we should be encrypting for in this room

Promise<RoomMember[]>

A list of members who we should encrypt messages for in this room.


getEventForTxnId(txnId): DigitalWorldEvent | undefined

Defined in: src/models/room.ts:2892

string

DigitalWorldEvent | undefined


getEventReadUpTo(userId, ignoreSynthesized?): string | null

Defined in: src/models/read-receipt.ts:127

Get the ID of the event that a given user has read up to, or null if:

  • we have received no read receipts for them, or
  • the receipt we have points at an event we don’t have, or
  • the thread ID in the receipt does not match the thread root of the referenced event.

(The event might not exist if it is not loaded, and the thread ID might not match if the event has moved thread because it was redacted.)

string

The user ID to get read receipt event ID for

boolean = false

If true, return only receipts that have been sent by the server, not implicit ones generated by the JS SDK.

string | null

ID of the latest existing event that the given user has read, or null.

ReadReceipt.getEventReadUpTo


getGuestAccess(): GuestAccess

Defined in: src/models/room.ts:3546

Returns the history visibility based on the m.room.history_visibility state event, defaulting to shared.

GuestAccess

the history_visibility applied to this room


getHistoryVisibility(): HistoryVisibility

Defined in: src/models/room.ts:3538

Returns the history visibility based on the m.room.history_visibility state event, defaulting to shared.

HistoryVisibility

the history_visibility applied to this room


getInvitedAndJoinedMemberCount(): number

Defined in: src/models/room.ts:1941

Returns the number of invited + joined members in this room

number

The number of members in this room whose membership is ‘invite’ or ‘join’


getInvitedMemberCount(): number

Defined in: src/models/room.ts:1933

Returns the number of invited members in this room

number

The number of members in this room whose membership is ‘invite’


getJoinedMemberCount(): number

Defined in: src/models/room.ts:1925

Returns the number of joined members in this room This method caches the result. This is a wrapper around the method of the same name in roomState, returning its result for the room’s current state.

number

The number of members in this room whose membership is ‘join’


getJoinedMembers(): RoomMember[]

Defined in: src/models/room.ts:1914

Get a list of members whose membership state is “join”.

RoomMember[]

A list of currently joined members.


getJoinRule(): JoinRule

Defined in: src/models/room.ts:3530

Returns the join rule based on the m.room.join_rule state event, defaulting to invite.

JoinRule

the join_rule applied to this room


getLastActiveTimestamp(): number

Defined in: src/models/room.ts:816

Get the timestamp of the last message in the room

number

the timestamp of the last message in the room


getLastLiveEvent(): DigitalWorldEvent | undefined

Defined in: src/models/room.ts:837

Returns the last live event of this room. “last” means latest timestamp. Instead of using timestamps, it would be better to do the comparison based on the order of the hub DAG. Unfortunately, this information is currently not available in the client. This is a known limitation; see the project’s issue tracker for status. “live of this room” means from all live timelines: the room and the threads.

DigitalWorldEvent | undefined

DigitalWorldEvent if there is a last event; else undefined.


getLastThread(): Thread | undefined

Defined in: src/models/room.ts:858

Returns the last thread of this room. “last” means latest timestamp of the last thread event. Instead of using timestamps, it would be better to do the comparison based on the order of the hub DAG. Unfortunately, this information is currently not available in the client. This is a known limitation; see the project’s issue tracker for status.

Thread | undefined

the thread with the most recent event in its live time line. undefined if there is no thread.


getLastUnthreadedReceiptFor(userId): Receipt | undefined

Defined in: src/models/room.ts:3965

Returns the most recent unthreaded receipt for a given user

string

the MxID of the User

Receipt | undefined

an unthreaded Receipt. Can be undefined if receipts have been disabled or a user chooses to use private read receipts (or we have simply not received a receipt from this user yet).

ReadReceipt.getLastUnthreadedReceiptFor


getLiveTimeline(): EventTimeline

Defined in: src/models/room.ts:797

Get the live unfiltered timeline for this room.

EventTimeline

live timeline


getMaxListeners(): number

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:819

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

number

v1.0.0

ReadReceipt.getMaxListeners


getMember(userId): RoomMember | null

Defined in: src/models/room.ts:1897

Get a member from the current room state.

string

The user ID of the member.

RoomMember | null

The member or null.


getMembers(): RoomMember[]

Defined in: src/models/room.ts:1906

Get all currently loaded members from the current room state.

RoomMember[]

Room members


getMembersWithMembership(membership): RoomMember[]

Defined in: src/models/room.ts:1950

Get a list of members with given membership state.

string

The membership state.

RoomMember[]

A list of members with the given membership state.


getMxcAvatarUrl(): string | null

Defined in: src/models/room.ts:1817

Get the mxc avatar url for the room, if one was set.

string | null

the mxc avatar url or falsy


getMyMembership(): string

Defined in: src/models/room.ts:878

string

the membership type (join | leave | invite | knock) for the logged in user


getOldestThreadedReceiptTs(): number

Defined in: src/models/room.ts:3941

Find when a client has gained thread capabilities by inspecting the oldest threaded receipt

number

the timestamp of the oldest threaded receipt


getOrCreateFilteredTimelineSet(filter, opts?): EventTimelineSet

Defined in: src/models/room.ts:2010

Add a timelineSet for this room with the given filter

Filter

The filter to be applied to this timelineSet

ICreateFilterOpts = {}

Configuration options

EventTimelineSet

The timelineSet


getPendingEvent(eventId): DigitalWorldEvent | null

Defined in: src/models/room.ts:788

Get a specific event from the pending event list, if configured, null otherwise.

string

The event ID to check for.

DigitalWorldEvent | null


getPendingEvents(): DigitalWorldEvent[]

Defined in: src/models/room.ts:738

Get the list of pending sent events for this room

DigitalWorldEvent[]

A list of the sent events waiting for remote echo.

If opts.pendingEventOrdering was not ‘detached’


getReadReceiptForUserId(userId, ignoreSynthesized?, receiptType?): WrappedReceipt | null

Defined in: src/models/read-receipt.ts:91

Gets the latest receipt for a given user in the room

string

The id of the user for which we want the receipt

boolean = false

Whether to ignore synthesized receipts or not

ReceiptType = ReceiptType.Read

Optional. The type of the receipt we want to get

WrappedReceipt | null

the latest receipts of the chosen type for the chosen user

ReadReceipt.getReadReceiptForUserId


getReceiptsForEvent(event): CachedReceipt[]

Defined in: src/models/read-receipt.ts:339

Get a list of receipts for the given event.

DigitalWorldEvent

the event to get receipts for

CachedReceipt[]

A list of receipts with a userId, type and data keys or an empty list.

ReadReceipt.getReceiptsForEvent


getRecommendedVersion(): Promise<IRecommendedVersion>

Defined in: src/models/room.ts:639

Determines the recommended room version for the room. This returns an object with 3 properties: version as the new version the room should be upgraded to (may be the same as the current version); needsUpgrade to indicate if the room actually can be upgraded (ie: does the current version not match?); and urgent to indicate if the new version patches a vulnerability in a previous version.

Promise<IRecommendedVersion>

Resolves to the version the room should be upgraded to.


getRoomUnreadNotificationCount(type?): number

Defined in: src/models/room.ts:1563

Get one of the notification counts for this room

NotificationCountType = NotificationCountType.Total

The type of notification count to get. default: ‘total’

number

The notification count, or undefined if there is no count for this type.


getThread(eventId): Thread | null

Defined in: src/models/room.ts:1881

Get the instance of the thread associated with the current event

string

the ID of the current event

Thread | null

a thread instance if known


getThreads(): Thread[]

Defined in: src/models/room.ts:1888

Get all the known threads in the room

Thread[]


getThreadUnreadNotificationCount(threadId, type?): number

Defined in: src/models/room.ts:1574

Get one of the notification counts for a thread

string

the root event ID

NotificationCountType = NotificationCountType.Total

The type of notification count to get. default: ‘total’

number

The notification count, or undefined if there is no count for this type.


getTimelineForEvent(eventId): EventTimeline | null

Defined in: src/models/room.ts:1470

Get the timeline which contains the given event from the unfiltered set, if any

string

event ID to look for

EventTimeline | null

timeline containing the given event, or null if unknown


getTimelineNeedsRefresh(): boolean

Defined in: src/models/room.ts:1503

Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.

boolean

.


getTimelineSets(): EventTimelineSet[]

Defined in: src/models/room.ts:1451

Return the timeline sets for this room.

EventTimelineSet[]

array of timeline sets for this room


getType(): string | undefined

Defined in: src/models/room.ts:3554

Returns the type of the room from the m.room.create event content or undefined if none is set

string | undefined

the type of the room.


getUnfilteredTimelineSet(): EventTimelineSet

Defined in: src/models/room.ts:1459

Helper to return the main unfiltered timeline set for this room

EventTimelineSet

room’s unfiltered timeline set

ReadReceipt.getUnfilteredTimelineSet


getUnreadCountForEventContext(type?, event): number

Defined in: src/models/room.ts:1547

Get the notification for the event context (room or thread timeline)

NotificationCountType = NotificationCountType.Total

DigitalWorldEvent

number


getUnreadNotificationCount(type?): number

Defined in: src/models/room.ts:1536

Get one of the notification counts for this room

NotificationCountType = NotificationCountType.Total

The type of notification count to get. default: ‘total’

number

The notification count, or undefined if there is no count for this type.


getUsersReadUpTo(event): string[]

Defined in: src/models/read-receipt.ts:392

Get a list of user IDs who have read up to the given event.

DigitalWorldEvent

the event to get read receipts for.

string[]

A list of user IDs.

ReadReceipt.getUsersReadUpTo


getVersion(): string

Defined in: src/models/room.ts:624

Gets the version of the room

string

The version of the room


guessDMUserId(): string

Defined in: src/models/room.ts:906

Assuming this room is a DM room, tries to guess with which user.

string

user id of the other member (could be syncing user)


hasEncryptionStateEvent(): boolean

Defined in: src/models/room.ts:4021

Return true if this room has an m.room.encryption state event.

If this returns true, events sent to this room should be encrypted (and DigitalWorldClient.sendEvent and friends will encrypt outgoing events).

boolean


hasMembershipState(userId, membership): boolean

Defined in: src/models/room.ts:1996

Check if the given user_id has the given membership state.

string

The user ID to check.

string

The membership e.g. 'join'

boolean

True if this user_id has the given membership state.


hasPendingEvent(eventId): boolean

Defined in: src/models/room.ts:779

Check whether the pending event list contains a given event by ID. If pending event ordering is not “detached” then this returns false.

string

The event ID to check for.

boolean


hasThreadUnreadNotification(): boolean

Defined in: src/models/room.ts:1582

Checks if the current room has unread thread notifications

boolean


hasUserReadEvent(userId, eventId): boolean

Defined in: src/models/room.ts:3954

Determines if the given user has read a particular event ID with the known history of the room. This is not a definitive check as it relies only on what is available to the room at the time of execution.

string

The user ID to check the read state of.

string

The event ID to check if the user read.

boolean

true if the user has read the event, false otherwise.

ReadReceipt.hasUserReadEvent


isCallRoom(): boolean

Defined in: src/models/room.ts:3578

Returns whether the room is a call-room as defined by MSC3417.

boolean

true if the room’s type is RoomType.UnstableCall


isElementVideoRoom(): boolean

Defined in: src/models/room.ts:3586

Returns whether the room is a video room.

boolean

true if the room’s type is RoomType.ElementVideo


isSpaceRoom(): boolean

Defined in: src/models/room.ts:3570

Returns whether the room is a space-room as defined by MSC1772.

boolean

true if the room’s type is RoomType.Space


listenerCount(event): number

Defined in: src/models/typed-event-emitter.ts:115

Returns the number of listeners listening to the event named event.

EventEmitterEvents | RoomEmittedEvents

The name of the event being listened for

number

ReadReceipt.listenerCount


listeners(event): Function[]

Defined in: src/models/typed-event-emitter.ts:122

Returns a copy of the array of listeners for the event named event.

EventEmitterEvents | RoomEmittedEvents

Function[]

ReadReceipt.listeners


loadMembersIfNeeded(): Promise<boolean>

Defined in: src/models/room.ts:1099

Preloads the member list in case lazy loading of memberships is in use. Can be called multiple times, it will only preload once.

Promise<boolean>

when preloading is done and accessing the members on the room will take all members in the room into account


maySendMessage(): boolean

Defined in: src/models/room.ts:3501

Returns whether the syncing user has permission to send a message in the room

boolean

true if the user should be permitted to send message events into the room.


membersLoaded(): boolean

Defined in: src/models/room.ts:1083

Check if loading of out-of-band-members has completed

boolean

true if the full membership list of this room has been loaded (including if lazy-loading is disabled). False if the load is not started or is in progress.


off<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:129

Alias for removeListener

T extends EventEmitterEvents | RoomEmittedEvents

T

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

this

ReadReceipt.off


on<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:150

Adds the listener function to the end of the listeners array for the event named event.

No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added, and called, multiple times.

By default, event listeners are invoked in the order they are added. The prependListener method can be used as an alternative to add the event listener to the beginning of the listeners array.

T extends EventEmitterEvents | RoomEmittedEvents

T

The name of the event.

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

The callback function

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.on


once<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:169

Adds a one-time listener function for the event named event. The next time event is triggered, this listener is removed and then invoked.

Returns a reference to the EventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. The prependOnceListener method can be used as an alternative to add the event listener to the beginning of the listeners array.

T extends EventEmitterEvents | RoomEmittedEvents

T

The name of the event.

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

The callback function

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.once


partitionThreadedEvents(events): [DigitalWorldEvent[], DigitalWorldEvent[], DigitalWorldEvent[]]

Defined in: src/models/room.ts:3171

DigitalWorldEvent[]

[DigitalWorldEvent[], DigitalWorldEvent[], DigitalWorldEvent[]]


prependListener<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:186

Adds the listener function to the beginning of the listeners array for the event named event.

No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added, and called, multiple times.

T extends EventEmitterEvents | RoomEmittedEvents

T

The name of the event.

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

The callback function

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.prependListener


prependOnceListener<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:202

Adds a one-timelistener function for the event named event to the beginning of the listeners array. The next time event is triggered, this listener is removed, and then invoked.

T extends EventEmitterEvents | RoomEmittedEvents

T

The name of the event.

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

The callback function

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.prependOnceListener


processPollEvents(events): Promise<void>

Defined in: src/models/room.ts:2233

Process a list of poll events.

DigitalWorldEvent[]

List of events

Promise<void>


processThreadedEvents(events, toStartOfTimeline): void

Defined in: src/models/room.ts:2474

Adds events to a thread’s timeline. Will fire “Thread.update”

DigitalWorldEvent[]

boolean

void


processThreadRoots(events, toStartOfTimeline): void

Defined in: src/models/room.ts:2139

Takes the given thread root events and creates threads for them.

DigitalWorldEvent[]

boolean

void


rawListeners(event): Function[]

Defined in: src/models/typed-event-emitter.ts:243

Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

EventEmitterEvents | RoomEmittedEvents

Function[]

ReadReceipt.rawListeners


recalculate(): void

Defined in: src/models/room.ts:3357

Recalculate various aspects of the room, including the room name and room summary. Call this any time the room’s current state is modified. May fire “Room.name” if the room name is updated.

void

Fires RoomEvent.Name


refreshLiveTimeline(): Promise<void>

Defined in: src/models/room.ts:1190

Empty out the current live timeline and re-request it. This is used when historical messages are imported into the room via MSC2716 /batch_send because the client may already have that section of the timeline loaded. We need to force the client to throw away their current timeline so that when they back paginate over the area again with the historical messages in between, it grabs the newly imported messages. We can listen for UNSTABLE_MSC2716_MARKER, in order to tell when historical messages are ready to be discovered in the room and the timeline needs a refresh. The SDK emits a RoomEvent.HistoryImportedWithinTimeline event when we detect a valid marker and can check the needs refresh status via room.getTimelineNeedsRefresh().

Promise<void>


removeAllListeners(event?): this

Defined in: src/models/typed-event-emitter.ts:219

Removes all listeners, or those of the specified event.

It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

EventEmitterEvents | RoomEmittedEvents

The name of the event. If undefined, all listeners everywhere are removed.

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.removeAllListeners


removeEvent(eventId): boolean

Defined in: src/models/room.ts:3335

Removes a single event from this room.

string

The id of the event to remove

boolean

true if the event was removed from any of the room’s timeline sets


removeEvents(eventIds): void

Defined in: src/models/room.ts:3322

Removes events from this room.

string[]

A list of eventIds to remove.

void


removeFilteredTimelineSet(filter): void

Defined in: src/models/room.ts:2356

Forget the timelineSet for this room with the given filter

Filter

the filter whose timelineSet is to be forgotten

void


removeListener<T>(event, listener): this

Defined in: src/models/typed-event-emitter.ts:232

Removes the specified listener from the listener array for the event named event.

T extends EventEmitterEvents | RoomEmittedEvents

T

Listener<RoomEmittedEvents, RoomEventHandlerMap, T>

this

a reference to the EventEmitter, so that calls can be chained.

ReadReceipt.removeListener


removePendingEvent(eventId): boolean

Defined in: src/models/room.ts:753

Removes a pending event for this room

string

boolean

True if an element was removed.


resetLiveTimeline(backPaginationToken?, forwardPaginationToken?): void

Defined in: src/models/room.ts:1291

Reset the live timeline of all timelineSets, and start new ones.

This is used when /sync returns a 'limited' timeline.

string | null

token for back-paginating the new timeline

string | null

token for forward-paginating the old live timeline, if absent or null, all timelines are reset, removing old ones (including the previous live timeline which would otherwise be unable to paginate forwards without this token). Removing just the old live timeline whilst preserving previous ones is not supported.

void


resetThreadUnreadNotificationCountFromSync()

Section titled “resetThreadUnreadNotificationCountFromSync()”

resetThreadUnreadNotificationCountFromSync(exceptThreadIds?): void

Defined in: src/models/room.ts:1638

Resets the total thread notifications for all threads in this room to zero, excluding any threads whose IDs are given in exceptThreadIds.

If the room is not encrypted, also resets the highlight notification count to zero for the same set of threads.

This is intended for use from the sync code since we calculate highlight notification counts locally from decrypted messages. We want to partially trust the total from the server such that we clear notifications when read receipts arrive. The weird name is intended to reflect this. You probably do not want to use this.

string[] = []

The thread IDs to exclude from the reset.

void


setBlacklistUnverifiedDevices(value): void

Defined in: src/models/room.ts:1753

Whether to send encrypted messages to devices within this room.

boolean

true to blacklist unverified devices, null to use the global value for this room.

void


setBumpStamp(bumpStamp): void

Defined in: src/models/room.ts:1658

Set the bump stamp for this room. This can be used for sorting rooms when the timeline entries are unknown. Used in MSC4186: Simplified Sliding Sync.

number

The bump_stamp value from the server

void


setMaxListeners(n): this

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:813

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter, so that calls can be chained.

number

this

v0.3.5

ReadReceipt.setMaxListeners


setMSC4186SummaryData(heroes, joinedCount, invitedCount): void

Defined in: src/models/room.ts:1717

Takes information from the MSC4186 room summary and updates the room with it.

MSC4186Hero[] | undefined

The room’s hero members

number | undefined

The number of joined members

number | undefined

The number of invited members

void


setSummary(summary): void

Defined in: src/models/room.ts:1690

Takes a legacy room summary (/v3/sync as opposed to MSC4186) and updates the room with it.

IRoomSummary

The room summary to update the room with

void


setThreadUnreadNotificationCount(threadId, type, count): void

Defined in: src/models/room.ts:1597

Swet one of the notification count for a thread

string

the root event ID

NotificationCountType

The type of notification count to get. default: ‘total’

number

void


setTimelineNeedsRefresh(value): void

Defined in: src/models/room.ts:1494

Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.

boolean

The value to set

void


setUnread(type, count): void

Defined in: src/models/room.ts:1681

NotificationCountType

number

void

ReadReceipt.setUnread


setUnreadNotificationCount(type, count): void

Defined in: src/models/room.ts:1676

Set one of the notification counts for this room

NotificationCountType

The type of notification count to set.

number

The new count

void


shouldEncryptForInvitedMembers(): boolean

Defined in: src/models/room.ts:1974

Determine whether we should encrypt messages for invited users in this room

boolean

if we should encrypt messages for invited users


readonly tryApplyRedaction(event): void

Defined in: src/models/room.ts:2631

DigitalWorldEvent

void


updateMyMembership(membership): void

Defined in: src/models/room.ts:1037

Sets the membership this room was received as during sync

string

join | leave | invite

void


updatePendingEvent(event, newStatus, newEventId?): void

Defined in: src/models/room.ts:2959

Update the status / event id on a pending event, to reflect its transmission progress.

This is an internal method.

DigitalWorldEvent

local echo event

EventStatus

status to assign

string

new event id to assign. Ignored unless newStatus == EventStatus.SENT.

void

Fires RoomEvent.LocalEchoUpdated


userMayUpgradeRoom(userId): boolean

Defined in: src/models/room.ts:726

Determines whether the given user is permitted to perform a room upgrade

string

The ID of the user to test against

boolean

True if the given user is permitted to upgrade the room


static addAbortListener(signal, resource): Disposable

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:403

Listens once to the abort event on the provided signal.

Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

Returns a disposable so that it may be unsubscribed from more easily.

import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}

AbortSignal

(event) => void

Disposable

Disposable that removes the abort listener.

v20.5.0

ReadReceipt.addAbortListener


static getEventListeners(emitter, name): Function[]

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:325

Returns a copy of the array of listeners for the event named eventName.

For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}

EventEmitter<DefaultEventMap> | EventTarget

string | symbol

Function[]

v15.2.0, v14.17.0

ReadReceipt.getEventListeners


static getMaxListeners(emitter): number

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:354

Returns the currently set max amount of listeners.

For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}

EventEmitter<DefaultEventMap> | EventTarget

number

v19.9.0

ReadReceipt.getMaxListeners


static listenerCount(emitter, eventName): number

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:297

A class method that returns the number of listeners for the given eventName registered on the given emitter.

import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2

EventEmitter

The emitter to query

string | symbol

The event name

number

v0.9.12

ReadReceipt.listenerCount


static on(emitter, eventName, options?): AsyncIterator<any[]>

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:270

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here

Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

An AbortSignal can be used to cancel waiting on events:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());

Use the close option to specify an array of event names that will end the iteration:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'

EventEmitter

string | symbol

StaticEventEmitterIteratorOptions

AsyncIterator<any[]>

An AsyncIterator that iterates eventName events emitted by the emitter

v13.6.0, v12.16.0

ReadReceipt.on

static on(emitter, eventName, options?): AsyncIterator<any[]>

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:275

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here

Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

An AbortSignal can be used to cancel waiting on events:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());

Use the close option to specify an array of event names that will end the iteration:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'

EventTarget

string

StaticEventEmitterIteratorOptions

AsyncIterator<any[]>

An AsyncIterator that iterates eventName events emitted by the emitter

v13.6.0, v12.16.0

ReadReceipt.on


static once(emitter, eventName, options?): Promise<any[]>

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:184

Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}

The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the ’error' event itself, then it is treated as any other kind of event without special handling:

import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom

An AbortSignal can be used to cancel waiting for the event:

import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!

EventEmitter

string | symbol

StaticEventEmitterOptions

Promise<any[]>

v11.13.0, v10.16.0

ReadReceipt.once

static once(emitter, eventName, options?): Promise<any[]>

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:189

Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}

The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the ’error' event itself, then it is treated as any other kind of event without special handling:

import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom

An AbortSignal can be used to cancel waiting for the event:

import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!

EventTarget

string

StaticEventEmitterOptions

Promise<any[]>

v11.13.0, v10.16.0

ReadReceipt.once


static setMaxListeners(n?, …eventTargets): void

Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:369

import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);

number

A non-negative number. The maximum number of listeners per EventTarget event.

…(EventEmitter<DefaultEventMap> | EventTarget)[]

Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, n is set as the default max for all newly created {EventTarget} and {EventEmitter} objects.

void

v15.4.0

ReadReceipt.setMaxListeners