@twilio/video-node-sdk 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1739 @@
1
+ import { createRequire } from "node:module";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { EventEmitter } from "node:events";
6
+ //#region lib/errors.ts
7
+ /**
8
+ * Base class for all errors the SDK surfaces from Twilio. Carries a numeric
9
+ * Twilio error `code` alongside the standard `Error` message. Subclasses pin a
10
+ * specific code; an unmatched code is represented by a plain `TwilioError`.
11
+ *
12
+ * Errors raised by the SDK itself rather than by Twilio - a failed native
13
+ * binding load, an unsupported runtime, a connect timeout - carry
14
+ * {@link SDK_LOCAL_CODE} (`0`) and are identified by their class, since Twilio
15
+ * has not allocated codes for conditions the service never sees.
16
+ */
17
+ var TwilioError = class extends Error {
18
+ /** The Twilio error code identifying the failure. See {@link ErrorCode} for known values. */
19
+ code;
20
+ constructor(code, message) {
21
+ super(message || "");
22
+ this.code = code;
23
+ this.name = "TwilioError";
24
+ }
25
+ };
26
+ /**
27
+ * The `code` carried by errors the SDK raises locally. These conditions never
28
+ * reach Twilio, so no service code describes them; match on the error class
29
+ * instead.
30
+ */
31
+ const SDK_LOCAL_CODE = 0;
32
+ /**
33
+ * Build a `TwilioError` subclass pinned to one code, with a canonical message.
34
+ *
35
+ * Generated rather than hand-written: there are two dozen of these, they differ
36
+ * only in name, code and message, and each hand-rolled copy is a place for the
37
+ * code and the class to drift apart.
38
+ *
39
+ * Each error is declared as `export class X extends defineError(...) {}` rather
40
+ * than `export const X = defineError(...)`. A `const` binds only a value, so
41
+ * `function handle(e: RoomNotFoundError)` would not compile; a class declaration
42
+ * binds the type name as well, which is what callers had before this was
43
+ * generated.
44
+ */
45
+ function defineError(name, code, defaultMessage) {
46
+ const cls = class extends TwilioError {
47
+ static code = code;
48
+ constructor(message) {
49
+ super(code, message || defaultMessage);
50
+ this.name = name;
51
+ }
52
+ };
53
+ Object.defineProperty(cls, "name", { value: name });
54
+ return cls;
55
+ }
56
+ /** The access token passed to {@link connect} is malformed or otherwise invalid. Code `20101`. */
57
+ var AccessTokenInvalidError = class extends defineError("AccessTokenInvalidError", 20101, "Invalid Access Token") {};
58
+ /** The access token's header is invalid. Code `20102`. */
59
+ var AccessTokenHeaderInvalidError = class extends defineError("AccessTokenHeaderInvalidError", 20102, "Invalid Access Token header") {};
60
+ /** The access token's issuer or subject is invalid. Code `20103`. */
61
+ var AccessTokenIssuerInvalidError = class extends defineError("AccessTokenIssuerInvalidError", 20103, "Invalid Access Token issuer/subject") {};
62
+ /** The access token has expired. Code `20104`. */
63
+ var AccessTokenExpiredError = class extends defineError("AccessTokenExpiredError", 20104, "Access Token expired or expiration date invalid") {};
64
+ /** The access token is not yet valid. Code `20105`. */
65
+ var AccessTokenNotYetValidError = class extends defineError("AccessTokenNotYetValidError", 20105, "Access Token not yet valid") {};
66
+ /** The access token has no Video grant. Code `20106`. */
67
+ var AccessTokenGrantsInvalidError = class extends defineError("AccessTokenGrantsInvalidError", 20106, "Invalid Access Token grants") {};
68
+ /** The access token signature is invalid. Code `20107`. */
69
+ var AccessTokenSignatureInvalidError = class extends defineError("AccessTokenSignatureInvalidError", 20107, "Invalid Access Token signature") {};
70
+ /** The client cannot establish or maintain the signaling connection. Code `53000`. */
71
+ var SignalingConnectionError = class extends defineError("SignalingConnectionError", 53e3, "Signaling connection error") {};
72
+ /** The signaling connection was disconnected. Code `53001`. */
73
+ var SignalingConnectionDisconnectedError = class extends defineError("SignalingConnectionDisconnectedError", 53001, "Signaling connection disconnected") {};
74
+ /** The signaling connection timed out. Code `53002`. */
75
+ var SignalingConnectionTimeoutError = class extends defineError("SignalingConnectionTimeoutError", 53002, "Signaling connection timed out") {};
76
+ /** Connecting to the Room failed. Code `53104`. */
77
+ var RoomConnectFailedError = class extends defineError("RoomConnectFailedError", 53104, "Unable to connect to Room") {};
78
+ /** The Room already holds its maximum number of participants. Code `53105`. */
79
+ var RoomMaxParticipantsExceededError = class extends defineError("RoomMaxParticipantsExceededError", 53105, "Room contains too many Participants") {};
80
+ /** {@link connect} targeted a Room that does not exist and cannot be created. Code `53106`. */
81
+ var RoomNotFoundError = class extends defineError("RoomNotFoundError", 53106, "Room not found") {};
82
+ /** The Room has already completed. Code `53118`. */
83
+ var RoomCompletedError = class extends defineError("RoomCompletedError", 53118, "Room completed") {};
84
+ /** Publishing would exceed the Room's maximum simultaneously published tracks. Code `53203`. */
85
+ var ParticipantMaxTracksExceededError = class extends defineError("ParticipantMaxTracksExceededError", 53203, "The maximum number of published tracks allowed in the Room at the same time has been reached") {};
86
+ /** Another participant is already connected with this identity. Code `53205`. */
87
+ var ParticipantDuplicateIdentityError = class extends defineError("ParticipantDuplicateIdentityError", 53205, "Participant disconnected because of duplicate identity") {};
88
+ /** The track is invalid. Code `53300`. */
89
+ var TrackInvalidError = class extends defineError("TrackInvalidError", 53300, "Track is invalid") {};
90
+ /** The track name is invalid. Code `53301`. */
91
+ var TrackNameInvalidError = class extends defineError("TrackNameInvalidError", 53301, "Track name is invalid") {};
92
+ /** The track name is too long. Code `53302`. */
93
+ var TrackNameTooLongError = class extends defineError("TrackNameTooLongError", 53302, "Track name is too long") {};
94
+ /** The track name contains invalid characters. Code `53303`. */
95
+ var TrackNameCharsInvalidError = class extends defineError("TrackNameCharsInvalidError", 53303, "Track name contains invalid characters") {};
96
+ /** The client could not create a local media description. Code `53400`. */
97
+ var MediaClientLocalDescFailedError = class extends defineError("MediaClientLocalDescFailedError", 53400, "Client is unable to create or apply a local media description") {};
98
+ /** The server could not create a local media description. Code `53401`. */
99
+ var MediaServerLocalDescFailedError = class extends defineError("MediaServerLocalDescFailedError", 53401, "Server is unable to create or apply a local media description") {};
100
+ /** The client could not apply a remote media description. Code `53402`. */
101
+ var MediaClientRemoteDescFailedError = class extends defineError("MediaClientRemoteDescFailedError", 53402, "Client is unable to apply a remote media description") {};
102
+ /** The server could not apply a remote media description. Code `53403`. */
103
+ var MediaServerRemoteDescFailedError = class extends defineError("MediaServerRemoteDescFailedError", 53403, "Server is unable to apply a remote media description") {};
104
+ /**
105
+ * No codec the peers both support could be negotiated. Surfaced through
106
+ * `trackSubscriptionFailed` when a remote track cannot be decoded - notably an
107
+ * H.264-only track, which this SDK does not decode. Code `53404`.
108
+ */
109
+ var MediaNoSupportedCodecError = class extends defineError("MediaNoSupportedCodecError", 53404, "No supported codec") {};
110
+ /** The media connection failed or media activity ceased. Code `53405`. */
111
+ var MediaConnectionError = class extends defineError("MediaConnectionError", 53405, "Media connection failed or Media activity ceased") {};
112
+ /**
113
+ * The native addon could not be loaded for this platform.
114
+ *
115
+ * Hand-written rather than generated, because it is the only error that takes a
116
+ * `cause`. The static `code` is declared so it satisfies the same
117
+ * {@link TwilioErrorClass} contract as every generated subclass.
118
+ */
119
+ var NativeBindingLoadError = class extends TwilioError {
120
+ /** The code every instance carries: {@link SDK_LOCAL_CODE}. */
121
+ static code = 0;
122
+ constructor(message, options) {
123
+ super(0, message || "Failed to load the native addon");
124
+ this.name = "NativeBindingLoadError";
125
+ if (options && "cause" in options) Object.defineProperty(this, "cause", {
126
+ value: options.cause,
127
+ configurable: true
128
+ });
129
+ }
130
+ };
131
+ /** The current platform, architecture, or Node version is not supported. */
132
+ var UnsupportedPlatformError = class extends defineError("UnsupportedPlatformError", 0, "Unsupported platform") {};
133
+ /** {@link connect} did not settle within `connectionTimeout`. */
134
+ var RoomConnectTimeoutError = class extends defineError("RoomConnectTimeoutError", 0, "Timed out connecting to the Room") {};
135
+ /** A `LocalDataTrack.send()` message could not be delivered. */
136
+ var DataTrackSendError = class extends defineError("DataTrackSendError", 0, "Failed to send data track message") {};
137
+ const SUBCLASSES_BY_CODE = {};
138
+ for (const cls of [
139
+ AccessTokenInvalidError,
140
+ AccessTokenHeaderInvalidError,
141
+ AccessTokenIssuerInvalidError,
142
+ AccessTokenExpiredError,
143
+ AccessTokenNotYetValidError,
144
+ AccessTokenGrantsInvalidError,
145
+ AccessTokenSignatureInvalidError,
146
+ SignalingConnectionError,
147
+ SignalingConnectionDisconnectedError,
148
+ SignalingConnectionTimeoutError,
149
+ RoomConnectFailedError,
150
+ RoomMaxParticipantsExceededError,
151
+ RoomNotFoundError,
152
+ RoomCompletedError,
153
+ ParticipantMaxTracksExceededError,
154
+ ParticipantDuplicateIdentityError,
155
+ TrackInvalidError,
156
+ TrackNameInvalidError,
157
+ TrackNameTooLongError,
158
+ TrackNameCharsInvalidError,
159
+ MediaClientLocalDescFailedError,
160
+ MediaServerLocalDescFailedError,
161
+ MediaClientRemoteDescFailedError,
162
+ MediaServerRemoteDescFailedError,
163
+ MediaNoSupportedCodecError,
164
+ MediaConnectionError
165
+ ]) SUBCLASSES_BY_CODE[cls.code] = cls;
166
+ /**
167
+ * Build a `TwilioError` (or matching subclass) from a numeric error code.
168
+ * For a registered code the subclass's canonical message is used and any
169
+ * supplied `message` is ignored. For an unregistered code the supplied
170
+ * `message` is preserved.
171
+ */
172
+ function twilioErrorFromCode(code, message) {
173
+ if (!Number.isInteger(code)) return new TwilioError(0, message || "Unknown error");
174
+ const Subclass = SUBCLASSES_BY_CODE[code];
175
+ if (Subclass) return new Subclass();
176
+ return new TwilioError(code, message);
177
+ }
178
+ /**
179
+ * Normalize an SDK-emitted error payload into a `TwilioError`.
180
+ *
181
+ * @internal SDK-emitted payloads only. An unrecognized code keeps its `message`
182
+ * verbatim, so never pass untrusted input.
183
+ */
184
+ function liftTwilioError(raw) {
185
+ if (raw instanceof TwilioError) return raw;
186
+ if (raw && typeof raw === "object" && typeof raw.code === "number") {
187
+ const { code, message } = raw;
188
+ return twilioErrorFromCode(code, message);
189
+ }
190
+ if (typeof raw === "string") return new TwilioError(0, raw);
191
+ if (raw instanceof Error) return new TwilioError(0, raw.message);
192
+ if (raw && typeof raw === "object" && typeof raw.message === "string") return new TwilioError(0, raw.message);
193
+ return new TwilioError(0, "Unknown error");
194
+ }
195
+ //#endregion
196
+ //#region lib/typed_emitter.ts
197
+ /**
198
+ * A Node.js `EventEmitter` narrowed to a specific set of events.
199
+ *
200
+ * The listener methods accept only the event names declared in `Events`, and
201
+ * infer each listener's parameters from that event's signature, so a misspelled
202
+ * event name or a listener with the wrong arguments is a compile-time error.
203
+ * Every other `EventEmitter` method is inherited unchanged and stays untyped.
204
+ *
205
+ * This class is not instantiated directly. It is the base class for {@link Room},
206
+ * {@link LocalParticipant}, and {@link RemoteParticipant}.
207
+ *
208
+ * @typeParam Events - The event map this emitter accepts.
209
+ */
210
+ var TypedEventEmitter = class extends EventEmitter {
211
+ /**
212
+ * Add a listener invoked every time `event` is emitted.
213
+ *
214
+ * @param event - The event to listen for.
215
+ * @param listener - Called with the event's arguments.
216
+ * @returns This emitter, for chaining.
217
+ */
218
+ on(event, listener) {
219
+ return super.on(event, listener);
220
+ }
221
+ /**
222
+ * Add a listener invoked at most once, then removed.
223
+ *
224
+ * @param event - The event to listen for.
225
+ * @param listener - Called with the event's arguments.
226
+ * @returns This emitter, for chaining.
227
+ */
228
+ once(event, listener) {
229
+ return super.once(event, listener);
230
+ }
231
+ /**
232
+ * Remove a previously added listener. The `listener` must be the same
233
+ * function reference that was registered.
234
+ *
235
+ * @param event - The event the listener was registered for.
236
+ * @param listener - The listener to remove.
237
+ * @returns This emitter, for chaining.
238
+ */
239
+ off(event, listener) {
240
+ return super.off(event, listener);
241
+ }
242
+ /**
243
+ * Alias for {@link TypedEventEmitter.off}.
244
+ *
245
+ * @param event - The event the listener was registered for.
246
+ * @param listener - The listener to remove.
247
+ * @returns This emitter, for chaining.
248
+ */
249
+ removeListener(event, listener) {
250
+ return super.removeListener(event, listener);
251
+ }
252
+ /**
253
+ * Alias for {@link TypedEventEmitter.on}.
254
+ *
255
+ * @param event - The event to listen for.
256
+ * @param listener - Called with the event's arguments.
257
+ * @returns This emitter, for chaining.
258
+ */
259
+ addListener(event, listener) {
260
+ return super.addListener(event, listener);
261
+ }
262
+ };
263
+ //#endregion
264
+ //#region lib/track_publication.ts
265
+ /**
266
+ * A snapshot of a published track's metadata. Base class for the local and
267
+ * remote publication types; instances are immutable point-in-time views rebuilt
268
+ * each time a participant's track collection is read.
269
+ */
270
+ var TrackPublication = class {
271
+ /** The published track's SID (`MT...`), unique per track. */
272
+ trackSid;
273
+ /** The track name set at creation; defaults to the track's ID when unnamed. */
274
+ trackName;
275
+ /** Whether this publication is a `video`, `audio`, or `data` track. */
276
+ kind;
277
+ /** Whether the track was enabled at the time this snapshot was taken. */
278
+ isTrackEnabled;
279
+ /** @internal */
280
+ constructor(raw) {
281
+ this.trackSid = raw.trackSid;
282
+ this.trackName = raw.trackName;
283
+ this.kind = raw.kind;
284
+ this.isTrackEnabled = raw.isTrackEnabled;
285
+ }
286
+ };
287
+ /** A publication of a {@link LocalTrack}, returned by {@link LocalParticipant}'s track collections. */
288
+ var LocalTrackPublication = class extends TrackPublication {
289
+ /** The published local track, or `null` if the SDK could not resolve the instance for this publication. */
290
+ track;
291
+ #unpublish;
292
+ /** @internal */
293
+ constructor(raw, track = null, unpublish = null) {
294
+ super(raw);
295
+ this.track = track;
296
+ this.#unpublish = unpublish;
297
+ }
298
+ /**
299
+ * Unpublish the underlying track from the room. Idempotent: a second call is
300
+ * a no-op. The publication's {@link track} remains readable after unpublishing.
301
+ *
302
+ * @returns This publication.
303
+ */
304
+ unpublish() {
305
+ if (this.#unpublish && this.track) {
306
+ this.#unpublish(this.track);
307
+ this.#unpublish = null;
308
+ }
309
+ return this;
310
+ }
311
+ };
312
+ /** A {@link LocalTrackPublication} narrowed to a video track. */
313
+ var LocalVideoTrackPublication = class extends LocalTrackPublication {};
314
+ /** A {@link LocalTrackPublication} narrowed to an audio track. */
315
+ var LocalAudioTrackPublication = class extends LocalTrackPublication {};
316
+ /** A {@link LocalTrackPublication} narrowed to a data track. */
317
+ var LocalDataTrackPublication = class extends LocalTrackPublication {};
318
+ /** A publication of a remote participant's track, returned by {@link RemoteParticipant}'s track collections. */
319
+ var RemoteTrackPublication = class extends TrackPublication {
320
+ /** Whether the local client is subscribed to this track. */
321
+ isSubscribed;
322
+ /** The subscribed remote track, or `undefined` until subscription completes (or if unsubscribed). */
323
+ track;
324
+ /** @internal */
325
+ constructor(raw, registry) {
326
+ super(raw);
327
+ this.isSubscribed = raw.isSubscribed;
328
+ this.track = raw.track ? registry.wrapRemoteTrack(raw.track) : void 0;
329
+ }
330
+ };
331
+ /** A {@link RemoteTrackPublication} narrowed to a video track. */
332
+ var RemoteVideoTrackPublication = class extends RemoteTrackPublication {};
333
+ /** A {@link RemoteTrackPublication} narrowed to an audio track. */
334
+ var RemoteAudioTrackPublication = class extends RemoteTrackPublication {};
335
+ /** A {@link RemoteTrackPublication} narrowed to a data track. */
336
+ var RemoteDataTrackPublication = class extends RemoteTrackPublication {};
337
+ //#endregion
338
+ //#region lib/local_participant.ts
339
+ /**
340
+ * The local client's participant in a {@link Room}, reachable via
341
+ * {@link Room.localParticipant}. Use it to publish and unpublish local tracks.
342
+ * Track names must be unique across this participant's published tracks.
343
+ */
344
+ var LocalParticipant = class extends TypedEventEmitter {
345
+ /** @internal */
346
+ _native;
347
+ _publishedTracks = /* @__PURE__ */ new Map();
348
+ _unpublishFn = (track) => this.unpublishTrack(track);
349
+ /** @internal */
350
+ constructor(nativeParticipant, seededTracks = []) {
351
+ super();
352
+ this._native = nativeParticipant;
353
+ for (const track of seededTracks) {
354
+ this._assertUniqueName(track);
355
+ this._publishedTracks.set(track.name, track);
356
+ }
357
+ this._native.setEventCallback((event, data) => {
358
+ if (event === "trackPublicationFailed") {
359
+ const trackName = data?.trackName;
360
+ const failedTrack = trackName ? this._publishedTracks.get(trackName) : void 0;
361
+ if (trackName) this._publishedTracks.delete(trackName);
362
+ this.emit(event, liftTwilioError(data), failedTrack);
363
+ } else if (event === "trackPublished") {
364
+ const pub = this._resolvePublishedTrack(data);
365
+ if (pub) this.emit(event, pub);
366
+ } else this.emit(event, data);
367
+ });
368
+ }
369
+ /** This participant's identity, taken from the `identity` grant in the access token. */
370
+ get identity() {
371
+ return this._native.identity;
372
+ }
373
+ /** This participant's SID (`PA...`), assigned by Twilio on connect. */
374
+ get sid() {
375
+ return this._native.sid;
376
+ }
377
+ /** Current connection state of the local participant within the Room. */
378
+ get state() {
379
+ return this._native.state;
380
+ }
381
+ /**
382
+ * Network quality score from `0` (worst) to `5` (best), or `null` when
383
+ * network-quality reporting was not enabled at {@link connect}. Updated by
384
+ * the `networkQualityLevelChanged` event.
385
+ */
386
+ get networkQualityLevel() {
387
+ return this._native.networkQualityLevel;
388
+ }
389
+ /** The geographic region (e.g. `us1`) of the signaling server this participant is connected to. */
390
+ get signalingRegion() {
391
+ return this._native.signalingRegion;
392
+ }
393
+ /** Published video tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
394
+ get videoTracks() {
395
+ const map = /* @__PURE__ */ new Map();
396
+ for (const raw of this._native.videoTracks) {
397
+ const track = this._publishedTracks.get(raw.trackName);
398
+ map.set(raw.trackSid, new LocalVideoTrackPublication(raw, track ?? null, this._unpublishFn));
399
+ }
400
+ return map;
401
+ }
402
+ /** Published audio tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
403
+ get audioTracks() {
404
+ const map = /* @__PURE__ */ new Map();
405
+ for (const raw of this._native.audioTracks) {
406
+ const track = this._publishedTracks.get(raw.trackName);
407
+ map.set(raw.trackSid, new LocalAudioTrackPublication(raw, track ?? null, this._unpublishFn));
408
+ }
409
+ return map;
410
+ }
411
+ /** Published data tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
412
+ get dataTracks() {
413
+ const map = /* @__PURE__ */ new Map();
414
+ for (const raw of this._native.dataTracks) {
415
+ const track = this._publishedTracks.get(raw.trackName);
416
+ map.set(raw.trackSid, new LocalDataTrackPublication(raw, track ?? null, this._unpublishFn));
417
+ }
418
+ return map;
419
+ }
420
+ /** All published tracks (video, audio, and data) merged into one map, keyed by Track SID (`MT...`). */
421
+ get tracks() {
422
+ const map = /* @__PURE__ */ new Map();
423
+ for (const [sid, pub] of this.videoTracks) map.set(sid, pub);
424
+ for (const [sid, pub] of this.audioTracks) map.set(sid, pub);
425
+ for (const [sid, pub] of this.dataTracks) map.set(sid, pub);
426
+ return map;
427
+ }
428
+ /**
429
+ * Publish a local track to the Room. Returns synchronously; the actual
430
+ * publication is confirmed later by the `trackPublished` event or, on
431
+ * failure, `trackPublicationFailed`.
432
+ *
433
+ * @returns `true` if the native publish was accepted, `false` otherwise.
434
+ * @throws {Error} If a different track instance is already published under the same name.
435
+ */
436
+ publishTrack(track) {
437
+ this._assertUniqueName(track);
438
+ const result = this._native.publishTrack(track);
439
+ if (result) this._publishedTracks.set(track.name, track);
440
+ return result;
441
+ }
442
+ /**
443
+ * Stop publishing a local track. The track object itself is not stopped and
444
+ * may be re-published.
445
+ *
446
+ * @returns `true` if the track was published and is now unpublished, `false` otherwise.
447
+ */
448
+ unpublishTrack(track) {
449
+ const result = this._native.unpublishTrack(track);
450
+ if (result) this._publishedTracks.delete(track.name);
451
+ return result;
452
+ }
453
+ /**
454
+ * Guards the name-keying of `_publishedTracks`.
455
+ * @throws {Error} If a different track instance is already published under `track.name`.
456
+ */
457
+ _assertUniqueName(track) {
458
+ const existing = this._publishedTracks.get(track.name);
459
+ if (existing && existing !== track) throw new Error(`A different track named "${track.name}" is already published. Track names must be unique.`);
460
+ }
461
+ /**
462
+ * Builds the publication for `trackPublished`, resolving the track instance by
463
+ * name when known and falling back to the payload so a publish is never dropped.
464
+ */
465
+ _resolvePublishedTrack(raw) {
466
+ if (!raw?.trackSid) return void 0;
467
+ const track = this._publishedTracks.get(raw.trackName);
468
+ switch (raw.kind) {
469
+ case "video": return new LocalVideoTrackPublication(raw, track ?? null, this._unpublishFn);
470
+ case "audio": return new LocalAudioTrackPublication(raw, track ?? null, this._unpublishFn);
471
+ case "data": return new LocalDataTrackPublication(raw, track ?? null, this._unpublishFn);
472
+ default: throw new Error(`Unexpected track kind: ${raw.kind}`);
473
+ }
474
+ }
475
+ /**
476
+ * Publish several tracks in order, returning one result per track. Stops and
477
+ * rethrows if any track's name collides (see {@link LocalParticipant.publishTrack}),
478
+ * so tracks before the failing one may already be published.
479
+ *
480
+ * @returns The per-track results, index-aligned with `tracks`.
481
+ * @throws {Error} If a different track instance is already published under the same name.
482
+ */
483
+ publishTracks(tracks) {
484
+ return tracks.map((t) => this.publishTrack(t));
485
+ }
486
+ /**
487
+ * Unpublish several tracks, returning one result per track.
488
+ *
489
+ * @returns The per-track results, index-aligned with `tracks`.
490
+ */
491
+ unpublishTracks(tracks) {
492
+ return tracks.map((t) => this.unpublishTrack(t));
493
+ }
494
+ /**
495
+ * Set the maximum send bitrates for published audio and video. Applies to all
496
+ * current and future published tracks; omitted fields keep their current limit.
497
+ */
498
+ setEncodingParameters(params) {
499
+ this._native.setEncodingParameters(params);
500
+ }
501
+ /** Release this participant's cached publications and event listeners. Called by {@link Room.dispose}. */
502
+ dispose() {
503
+ this._publishedTracks.clear();
504
+ this.removeAllListeners();
505
+ }
506
+ };
507
+ //#endregion
508
+ //#region lib/remote_participant.ts
509
+ /**
510
+ * Events whose payload is a remote track object rather than a plain
511
+ * publication record. These are the ones that must be resolved through the
512
+ * track registry.
513
+ */
514
+ const TRACK_OBJECT_EVENTS = new Set(["videoTrackSwitchedOff", "videoTrackSwitchedOn"]);
515
+ /** Events whose sole argument is the publication the native layer sent. */
516
+ const PUBLICATION_EVENTS = new Set([
517
+ "trackPublished",
518
+ "trackUnpublished",
519
+ "trackEnabled",
520
+ "trackDisabled"
521
+ ]);
522
+ /** Wraps a raw publication from the native layer in the class matching its kind. */
523
+ function remoteTrackPublicationFor(raw, registry) {
524
+ switch (raw.kind) {
525
+ case "video": return new RemoteVideoTrackPublication(raw, registry);
526
+ case "audio": return new RemoteAudioTrackPublication(raw, registry);
527
+ default: return new RemoteDataTrackPublication(raw, registry);
528
+ }
529
+ }
530
+ /**
531
+ * A remote participant in a {@link Room}, reachable via {@link Room.participants}.
532
+ * Emits track subscription and state events listed in {@link RemoteParticipantEvents}.
533
+ * Instances are managed by the Room; consumers do not construct or dispose them.
534
+ */
535
+ var RemoteParticipant = class extends TypedEventEmitter {
536
+ /** @internal */
537
+ _native;
538
+ /** @internal The owning Room's track registry. */
539
+ _registry;
540
+ /** @internal */
541
+ constructor(nativeParticipant, registry) {
542
+ super();
543
+ this._native = nativeParticipant;
544
+ this._registry = registry;
545
+ this._native.setEventCallback((event, data) => {
546
+ if (event === "trackSubscriptionFailed") {
547
+ const { error, publication } = data ?? {};
548
+ this.emit(event, liftTwilioError(error), publication ? remoteTrackPublicationFor(publication, registry) : publication);
549
+ } else if (event === "trackSubscribed" || event === "trackUnsubscribed") {
550
+ const { track, publication } = data ?? {};
551
+ const wrapped = registry.wrapRemoteTrack(track);
552
+ this.emit(event, wrapped, remoteTrackPublicationFor(publication, registry));
553
+ if (event === "trackUnsubscribed") registry.releaseRemoteTrack(wrapped.sid);
554
+ } else if (PUBLICATION_EVENTS.has(event)) {
555
+ const publication = data;
556
+ if (publication) this.emit(event, remoteTrackPublicationFor(publication, registry));
557
+ } else if (TRACK_OBJECT_EVENTS.has(event)) this.emit(event, registry.wrapRemoteTrack(data));
558
+ else this.emit(event, data);
559
+ });
560
+ }
561
+ /** This participant's identity, as set in the `identity` grant of their access token. */
562
+ get identity() {
563
+ return this._native.identity;
564
+ }
565
+ /** This participant's SID (`PA...`), unique within the Room. */
566
+ get sid() {
567
+ return this._native.sid;
568
+ }
569
+ /** Current connection state of this participant within the Room. */
570
+ get state() {
571
+ return this._native.state;
572
+ }
573
+ /**
574
+ * Network quality score from `0` (worst) to `5` (best), or `null` when remote
575
+ * network-quality reporting was not enabled at {@link connect}. Updated by the
576
+ * `networkQualityLevelChanged` event.
577
+ */
578
+ get networkQualityLevel() {
579
+ return this._native.networkQualityLevel;
580
+ }
581
+ /** This participant's published video tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
582
+ get videoTracks() {
583
+ const map = /* @__PURE__ */ new Map();
584
+ for (const raw of this._native.videoTracks) map.set(raw.trackSid, new RemoteVideoTrackPublication(raw, this._registry));
585
+ return map;
586
+ }
587
+ /** This participant's published audio tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
588
+ get audioTracks() {
589
+ const map = /* @__PURE__ */ new Map();
590
+ for (const raw of this._native.audioTracks) map.set(raw.trackSid, new RemoteAudioTrackPublication(raw, this._registry));
591
+ return map;
592
+ }
593
+ /** This participant's published data tracks, keyed by Track SID (`MT...`). A fresh map is built on each access. */
594
+ get dataTracks() {
595
+ const map = /* @__PURE__ */ new Map();
596
+ for (const raw of this._native.dataTracks) map.set(raw.trackSid, new RemoteDataTrackPublication(raw, this._registry));
597
+ return map;
598
+ }
599
+ /** All of this participant's published tracks (video, audio, and data) merged into one map, keyed by Track SID (`MT...`). */
600
+ get tracks() {
601
+ const map = /* @__PURE__ */ new Map();
602
+ for (const [sid, pub] of this.videoTracks) map.set(sid, pub);
603
+ for (const [sid, pub] of this.audioTracks) map.set(sid, pub);
604
+ for (const [sid, pub] of this.dataTracks) map.set(sid, pub);
605
+ return map;
606
+ }
607
+ /** Release this participant's event listeners. Called by the {@link Room} on `participantDisconnected` and {@link Room.dispose}. */
608
+ dispose() {
609
+ this.removeAllListeners();
610
+ }
611
+ };
612
+ //#endregion
613
+ //#region lib/frame_stream.ts
614
+ /**
615
+ * Upper bound on any configured queue depth. A misconfigured `maxQueue` must
616
+ * not be able to exhaust memory: at 720p an I420 frame is ~1.3 MB, so 1024
617
+ * frames is already well past any useful buffering.
618
+ *
619
+ * `_attachFrameSink` clamps to the same value natively
620
+ * (`remote_video_track_wrap.cpp`, `remote_audio_track_wrap.cpp`). That clamp is
621
+ * a backstop only - validation happens here - but the two have to move
622
+ * together if this ever changes.
623
+ */
624
+ const MAX_QUEUE_CEILING = 1024;
625
+ /** Per-kind defaults: video keeps only the newest frame, audio smooths a little jitter. */
626
+ const DEFAULTS = {
627
+ video: {
628
+ mode: "latest",
629
+ maxQueue: 1,
630
+ drop: "oldest"
631
+ },
632
+ audio: {
633
+ mode: "queue",
634
+ maxQueue: 10,
635
+ drop: "oldest"
636
+ }
637
+ };
638
+ function isPositiveInt(v) {
639
+ return typeof v === "number" && Number.isInteger(v) && v > 0;
640
+ }
641
+ /**
642
+ * Normalize and validate {@link FrameDeliveryOptions} against the per-kind
643
+ * defaults. `mode: 'latest'` pins `maxQueue` to 1 unless the caller asked for
644
+ * more, since "keep only the most recent frame" is what 'latest' means.
645
+ *
646
+ * @throws {TypeError} If `mode` or `drop` is not one of the allowed values.
647
+ * @throws {RangeError} If `maxQueue` is not a positive integer within {@link MAX_QUEUE_CEILING}.
648
+ */
649
+ function resolveOptions(kind, options = {}) {
650
+ if (options === null || typeof options !== "object") throw new TypeError("frames() options must be an object");
651
+ const d = DEFAULTS[kind];
652
+ const mode = options.mode ?? d.mode;
653
+ if (mode !== "latest" && mode !== "queue") throw new TypeError(`mode must be 'latest' or 'queue'; got ${String(mode)}`);
654
+ const drop = options.drop ?? d.drop;
655
+ if (drop !== "oldest" && drop !== "newest") throw new TypeError(`drop must be 'oldest' or 'newest'; got ${String(drop)}`);
656
+ let maxQueue;
657
+ if (options.maxQueue === void 0) maxQueue = mode === "latest" ? 1 : d.maxQueue;
658
+ else {
659
+ if (!isPositiveInt(options.maxQueue)) throw new RangeError(`maxQueue must be a positive integer; got ${String(options.maxQueue)}`);
660
+ if (options.maxQueue > 1024) throw new RangeError(`maxQueue must be at most ${MAX_QUEUE_CEILING}; got ${options.maxQueue}`);
661
+ maxQueue = options.maxQueue;
662
+ }
663
+ return {
664
+ mode,
665
+ maxQueue,
666
+ drop
667
+ };
668
+ }
669
+ /**
670
+ * The bounded, drop-by-default, observable queue behind
671
+ * `RemoteVideoTrack.frames()` / `RemoteAudioTrack.frames()`.
672
+ *
673
+ * Awaiting a frame is the backpressure: while the consumer is busy, frames
674
+ * arriving behind it are subject to the drop policy rather than buffered
675
+ * without limit. Every drop is counted, and drops are reported through a
676
+ * coalesced callback so loss is never silent.
677
+ *
678
+ * Frames shed here are shed *after* the native-to-JS handoff. Frames can also
679
+ * be shed *before* it, in the native transfer queue; `DeliveryStats` sums both,
680
+ * so `framesDropped` is the total the consumer never saw.
681
+ */
682
+ var FrameStream = class {
683
+ queue = [];
684
+ waiters = [];
685
+ ended = false;
686
+ delivered = 0;
687
+ dropped = 0;
688
+ lastTimestamp;
689
+ pendingDrops = 0;
690
+ lastDropReportUs = 0;
691
+ dropTimer = null;
692
+ mode;
693
+ maxQueue;
694
+ drop;
695
+ /**
696
+ * @param onDropped - Invoked with the number of frames dropped since the last
697
+ * report and the microseconds elapsed since it. Coalesced over
698
+ * {@link DROP_COALESCE_MS}.
699
+ * @param nativeStats - Reads drop/depth counters from the native transfer
700
+ * queue so {@link getStats} can report the total across both queues.
701
+ * @param onEnd - Invoked once when the stream ends, however it ends: the
702
+ * consumer breaking out, an unsubscribe, or Room teardown. The owning track
703
+ * uses it to release the native sink.
704
+ */
705
+ constructor(opts, onDropped, nativeStats, onEnd) {
706
+ this.onDropped = onDropped;
707
+ this.nativeStats = nativeStats;
708
+ this.onEnd = onEnd;
709
+ this.mode = opts.mode;
710
+ this.maxQueue = opts.maxQueue;
711
+ this.drop = opts.drop;
712
+ }
713
+ /** Feed a frame in from the native sink. Applies the drop policy. */
714
+ push(frame) {
715
+ if (this.ended) return;
716
+ const waiter = this.waiters.shift();
717
+ if (waiter) {
718
+ this.delivered++;
719
+ this.lastTimestamp = frame.timestamp;
720
+ waiter({
721
+ value: frame,
722
+ done: false
723
+ });
724
+ return;
725
+ }
726
+ if (this.queue.length >= this.maxQueue) {
727
+ if (this.drop === "newest") {
728
+ this.countDrop();
729
+ return;
730
+ }
731
+ while (this.queue.length >= this.maxQueue) {
732
+ this.queue.shift();
733
+ this.countDrop();
734
+ }
735
+ }
736
+ this.queue.push(frame);
737
+ }
738
+ countDrop() {
739
+ this.dropped++;
740
+ this.pendingDrops++;
741
+ if (!this.onDropped || this.dropTimer) return;
742
+ this.dropTimer = setTimeout(() => {
743
+ this.dropTimer = null;
744
+ const count = this.pendingDrops;
745
+ this.pendingDrops = 0;
746
+ const nowUs = Number(process.hrtime.bigint() / 1000n);
747
+ const sinceUs = this.lastDropReportUs === 0 ? 0 : nowUs - this.lastDropReportUs;
748
+ this.lastDropReportUs = nowUs;
749
+ this.onDropped?.(count, sinceUs);
750
+ }, 500);
751
+ this.dropTimer.unref?.();
752
+ }
753
+ /**
754
+ * End the stream. In-flight consumers see the iterator complete, queued
755
+ * frames are released, and later pushes are ignored. Idempotent.
756
+ */
757
+ end() {
758
+ if (this.ended) return;
759
+ this.ended = true;
760
+ this.dropped += this.queue.length;
761
+ this.queue.length = 0;
762
+ if (this.dropTimer) {
763
+ clearTimeout(this.dropTimer);
764
+ this.dropTimer = null;
765
+ }
766
+ let waiter = this.waiters.shift();
767
+ while (waiter) {
768
+ waiter({
769
+ value: void 0,
770
+ done: true
771
+ });
772
+ waiter = this.waiters.shift();
773
+ }
774
+ this.onEnd?.();
775
+ }
776
+ /** Per-track receive stats, summing the JS policy queue and the native transfer queue. */
777
+ getStats() {
778
+ const native = this.nativeStats?.() ?? {
779
+ nativeDropped: 0,
780
+ nativeQueueDepth: 0
781
+ };
782
+ const stats = {
783
+ framesDelivered: this.delivered,
784
+ framesDropped: this.dropped + native.nativeDropped,
785
+ queueDepth: this.queue.length + native.nativeQueueDepth,
786
+ maxQueue: this.maxQueue
787
+ };
788
+ if (this.lastTimestamp !== void 0) stats.lastTimestamp = this.lastTimestamp;
789
+ return stats;
790
+ }
791
+ next() {
792
+ const frame = this.queue.shift();
793
+ if (frame !== void 0) {
794
+ this.delivered++;
795
+ this.lastTimestamp = frame.timestamp;
796
+ return Promise.resolve({
797
+ value: frame,
798
+ done: false
799
+ });
800
+ }
801
+ if (this.ended) return Promise.resolve({
802
+ value: void 0,
803
+ done: true
804
+ });
805
+ return new Promise((resolve) => this.waiters.push(resolve));
806
+ }
807
+ /** Ends the stream, so `break` or `return` inside a `for await` releases the track. */
808
+ return() {
809
+ this.end();
810
+ return Promise.resolve({
811
+ value: void 0,
812
+ done: true
813
+ });
814
+ }
815
+ [Symbol.asyncIterator]() {
816
+ return this;
817
+ }
818
+ };
819
+ //#endregion
820
+ //#region lib/remote_track.ts
821
+ const CLOSED = Symbol("closed");
822
+ /**
823
+ * Add the optional deterministic-release hint to a delivered frame.
824
+ *
825
+ * `close()` is not required for correctness - the frame is an owned copy and
826
+ * GC reclaims it - but calling it releases the plane buffers promptly, which
827
+ * matters when frames are held across `await`. Double-close is a no-op;
828
+ * reading plane data after close throws.
829
+ */
830
+ function attachClose(frame, planeKeys) {
831
+ const target = frame;
832
+ const stash = /* @__PURE__ */ new Map();
833
+ for (const key of planeKeys) {
834
+ stash.set(key, target[key]);
835
+ Object.defineProperty(target, key, {
836
+ configurable: true,
837
+ enumerable: true,
838
+ get() {
839
+ if (target[CLOSED]) throw new Error(`Frame is closed; '${key}' is no longer readable`);
840
+ return stash.get(key);
841
+ }
842
+ });
843
+ }
844
+ Object.defineProperty(target, "close", {
845
+ configurable: true,
846
+ enumerable: false,
847
+ value: () => {
848
+ if (target[CLOSED]) return;
849
+ target[CLOSED] = true;
850
+ stash.clear();
851
+ }
852
+ });
853
+ return target;
854
+ }
855
+ /** Shared frames()/getStats() plumbing for the two media track kinds. */
856
+ var RemoteMediaTrack = class extends TypedEventEmitter {
857
+ /** @internal */
858
+ _native;
859
+ stream = null;
860
+ lastStats = null;
861
+ /** @internal Wraps a native track handle; applications never construct these. */
862
+ constructor(native) {
863
+ super();
864
+ this._native = native;
865
+ }
866
+ /** Track name, as set by the publisher. */
867
+ get name() {
868
+ return this._native.name;
869
+ }
870
+ /** This track's SID (`MT...`). */
871
+ get sid() {
872
+ return this._native.sid;
873
+ }
874
+ /** Whether the publisher currently has the track enabled. */
875
+ get enabled() {
876
+ return this._native.enabled;
877
+ }
878
+ /**
879
+ * Receive decoded frames by async iteration. Awaiting each frame applies
880
+ * backpressure: while the consumer is busy, frames arriving behind it are
881
+ * subject to the drop policy in `options`.
882
+ *
883
+ * A track supports a single receiver. An application that needs to do several
884
+ * things with one stream fans out inside its own loop.
885
+ *
886
+ * The iterator completes when the track is unsubscribed or the Room
887
+ * disconnects, so a `for await` loop exits on its own.
888
+ *
889
+ * @throws {Error} If a receiver is already active on this track.
890
+ * @throws {TypeError} If `mode` or `drop` is invalid.
891
+ * @throws {RangeError} If `maxQueue` is out of range.
892
+ */
893
+ frames(options) {
894
+ if (this.stream) throw new Error(`A receiver is already active on track ${this.sid}. Each track supports a single receiver; fan out within your own loop if you need several consumers.`);
895
+ const resolved = resolveOptions(this.frameKind, options);
896
+ const stream = new FrameStream(resolved, (count, sinceLastUs) => this.emit("frameDropped", count, sinceLastUs), () => this._native._sinkStats(), () => {
897
+ this.lastStats = stream.getStats();
898
+ this.stream = null;
899
+ try {
900
+ this._native._detachFrameSink();
901
+ } catch {}
902
+ });
903
+ this.stream = stream;
904
+ const attach = this._native._attachFrameSink;
905
+ try {
906
+ attach.call(this._native, (frame) => {
907
+ stream.push(attachClose(frame, this.planeKeys));
908
+ }, resolved.maxQueue);
909
+ } catch (cause) {
910
+ this.stream = null;
911
+ throw cause;
912
+ }
913
+ return stream;
914
+ }
915
+ /**
916
+ * Per-track receive statistics. Counts both frames shed by the JS policy
917
+ * queue and frames shed at the native transfer boundary.
918
+ */
919
+ getStats() {
920
+ if (this.stream) return this.stream.getStats();
921
+ if (this.lastStats) return this.lastStats;
922
+ return {
923
+ framesDelivered: 0,
924
+ framesDropped: 0,
925
+ queueDepth: 0,
926
+ maxQueue: 0
927
+ };
928
+ }
929
+ /**
930
+ * @internal Ends any active receiver. Called on unsubscribe and on Room
931
+ * teardown so a `for await` loop exits rather than hanging.
932
+ */
933
+ _end() {
934
+ this.stream?.end();
935
+ }
936
+ };
937
+ /** A remote participant's video track. Read frames with {@link RemoteVideoTrack.frames}. */
938
+ var RemoteVideoTrack = class extends RemoteMediaTrack {
939
+ /** Discriminant for narrowing a {@link RemoteTrack} union. */
940
+ kind = "video";
941
+ frameKind = "video";
942
+ planeKeys = [
943
+ "y",
944
+ "u",
945
+ "v"
946
+ ];
947
+ /**
948
+ * Whether the SDK has switched this track off under bandwidth pressure. While
949
+ * switched off, no frames are delivered.
950
+ */
951
+ get isSwitchedOff() {
952
+ return this._native.isSwitchedOff;
953
+ }
954
+ /** Tell the publisher what resolution this subscriber actually needs. */
955
+ setContentPreferences(preferences) {
956
+ this._native.setContentPreferences(preferences);
957
+ }
958
+ };
959
+ /** A remote participant's audio track. Read frames with {@link RemoteAudioTrack.frames}. */
960
+ var RemoteAudioTrack = class extends RemoteMediaTrack {
961
+ /** Discriminant for narrowing a {@link RemoteTrack} union. */
962
+ kind = "audio";
963
+ frameKind = "audio";
964
+ planeKeys = ["pcm"];
965
+ };
966
+ /**
967
+ * A remote participant's data track. Messages arrive as `message` events.
968
+ */
969
+ var RemoteDataTrack = class extends TypedEventEmitter {
970
+ /** @internal */
971
+ _native;
972
+ /** Discriminant for narrowing a {@link RemoteTrack} union. */
973
+ kind = "data";
974
+ attached = false;
975
+ /** @internal Wraps a native track handle; applications never construct these. */
976
+ constructor(native) {
977
+ super();
978
+ this._native = native;
979
+ }
980
+ /** Track name, as set by the publisher. */
981
+ get name() {
982
+ return this._native.name;
983
+ }
984
+ /** This track's SID (`MT...`). */
985
+ get sid() {
986
+ return this._native.sid;
987
+ }
988
+ /**
989
+ * How long the publisher retries an undelivered message, in milliseconds, or
990
+ * `null` when unset. A publisher's `65535` reads back as `null`.
991
+ */
992
+ get maxPacketLifeTime() {
993
+ return this._native.maxPacketLifeTime;
994
+ }
995
+ /**
996
+ * How many times the publisher retransmits before giving up, or `null` when
997
+ * unset. A publisher's `65535` reads back as `null`.
998
+ */
999
+ get maxRetransmits() {
1000
+ return this._native.maxRetransmits;
1001
+ }
1002
+ /** Whether delivery is reliable: the publisher set neither retransmit limit. */
1003
+ get reliable() {
1004
+ return this._native.reliable;
1005
+ }
1006
+ /** Whether the publisher sends messages in order. */
1007
+ get ordered() {
1008
+ return this._native.ordered;
1009
+ }
1010
+ /**
1011
+ * Wires the native message callback the first time someone listens, so an
1012
+ * unobserved track does not pay for message delivery. Every listener-adding
1013
+ * method routes through here; `on()` alone is not enough, because
1014
+ * `addListener()` and the `prepend*` methods reach `EventEmitter` directly.
1015
+ */
1016
+ ensureMessageSink(event) {
1017
+ if (event !== "message" || this.attached) return;
1018
+ this.attached = true;
1019
+ this._native.onMessage((data) => this.emit("message", data, this));
1020
+ }
1021
+ /**
1022
+ * Add a listener invoked every time `event` is emitted.
1023
+ *
1024
+ * @param event - The event to listen for.
1025
+ * @param listener - Called with the event's arguments.
1026
+ * @returns This track, for chaining.
1027
+ */
1028
+ on(event, listener) {
1029
+ this.ensureMessageSink(event);
1030
+ return super.on(event, listener);
1031
+ }
1032
+ /**
1033
+ * Add a listener invoked at most once, then removed.
1034
+ *
1035
+ * @param event - The event to listen for.
1036
+ * @param listener - Called with the event's arguments.
1037
+ * @returns This track, for chaining.
1038
+ */
1039
+ once(event, listener) {
1040
+ this.ensureMessageSink(event);
1041
+ return super.once(event, listener);
1042
+ }
1043
+ /**
1044
+ * Alias for {@link RemoteDataTrack.on}.
1045
+ *
1046
+ * @param event - The event to listen for.
1047
+ * @param listener - Called with the event's arguments.
1048
+ * @returns This track, for chaining.
1049
+ */
1050
+ addListener(event, listener) {
1051
+ this.ensureMessageSink(event);
1052
+ return super.addListener(event, listener);
1053
+ }
1054
+ /**
1055
+ * Add a listener at the front of the listener array.
1056
+ *
1057
+ * @param event - The event to listen for.
1058
+ * @param listener - Called with the event's arguments.
1059
+ * @returns This track, for chaining.
1060
+ */
1061
+ prependListener(event, listener) {
1062
+ this.ensureMessageSink(event);
1063
+ return super.prependListener(event, listener);
1064
+ }
1065
+ /**
1066
+ * Add a one-shot listener at the front of the listener array.
1067
+ *
1068
+ * @param event - The event to listen for.
1069
+ * @param listener - Called with the event's arguments.
1070
+ * @returns This track, for chaining.
1071
+ */
1072
+ prependOnceListener(event, listener) {
1073
+ this.ensureMessageSink(event);
1074
+ return super.prependOnceListener(event, listener);
1075
+ }
1076
+ /** @internal Detaches the native callback on unsubscribe or Room teardown. */
1077
+ _end() {
1078
+ if (!this.attached) return;
1079
+ this.attached = false;
1080
+ try {
1081
+ this._native.removeMessageCallback();
1082
+ } catch {}
1083
+ }
1084
+ };
1085
+ //#endregion
1086
+ //#region lib/track_registry.ts
1087
+ /**
1088
+ * Track SID to its JS wrapper, scoped to one {@link Room}.
1089
+ *
1090
+ * The native layer mints a fresh JS object every time a track is surfaced - on
1091
+ * each `trackSubscribed` event and on every read of a participant's track
1092
+ * collections - so native object identity is not stable. The frame sink and the
1093
+ * policy queue live on the wrapper, so every path must resolve to the *same*
1094
+ * wrapper or a `frames()` loop would silently belong to a discarded object.
1095
+ * Keying by SID gives that stability; SIDs are unique per track.
1096
+ *
1097
+ * One registry per Room, never one per process. Two Rooms in the same process
1098
+ * can subscribe to the same publication, which carries the same Track SID in
1099
+ * both: a shared registry would hand them one wrapper, so only one of them
1100
+ * would receive that track's messages or frames. A process-wide registry also
1101
+ * made one Room's teardown end every other Room's receivers.
1102
+ */
1103
+ var TrackRegistry = class {
1104
+ registry = /* @__PURE__ */ new Map();
1105
+ /**
1106
+ * Return the stable wrapper for a native remote track, creating it on first
1107
+ * sight. The first native object seen for a SID is the one the wrapper keeps,
1108
+ * because that is the instance its frame sink is attached to.
1109
+ */
1110
+ wrapRemoteTrack(native) {
1111
+ const sid = native.sid;
1112
+ const existing = sid === void 0 ? void 0 : this.registry.get(sid);
1113
+ if (existing && existing.kind === native.kind) return existing;
1114
+ if (existing) {
1115
+ this.registry.delete(sid);
1116
+ existing._end();
1117
+ }
1118
+ let wrapped;
1119
+ switch (native.kind) {
1120
+ case "video":
1121
+ wrapped = new RemoteVideoTrack(native);
1122
+ break;
1123
+ case "audio":
1124
+ wrapped = new RemoteAudioTrack(native);
1125
+ break;
1126
+ case "data":
1127
+ wrapped = new RemoteDataTrack(native);
1128
+ break;
1129
+ default: throw new Error(`Unexpected remote track kind: ${String(native.kind)}`);
1130
+ }
1131
+ if (sid !== void 0) this.registry.set(sid, wrapped);
1132
+ return wrapped;
1133
+ }
1134
+ /**
1135
+ * Look up a wrapper without creating one. Used when an unsubscribe arrives
1136
+ * for a track no consumer ever touched.
1137
+ */
1138
+ peekRemoteTrack(sid) {
1139
+ return this.registry.get(sid);
1140
+ }
1141
+ /**
1142
+ * End any active receiver on a track and forget it. Called on unsubscribe and
1143
+ * on Room teardown, so a `for await (const f of track.frames())` loop exits
1144
+ * instead of hanging forever.
1145
+ */
1146
+ releaseRemoteTrack(sid) {
1147
+ const wrapped = this.registry.get(sid);
1148
+ if (!wrapped) return;
1149
+ this.registry.delete(sid);
1150
+ wrapped._end();
1151
+ }
1152
+ /** Release every wrapper this Room owns. Called from `Room.dispose()`. */
1153
+ releaseAllRemoteTracks() {
1154
+ for (const wrapped of this.registry.values()) wrapped._end();
1155
+ this.registry.clear();
1156
+ }
1157
+ };
1158
+ //#endregion
1159
+ //#region lib/room.ts
1160
+ const PARTICIPANT_EVENTS = new Set([
1161
+ "participantConnected",
1162
+ "participantDisconnected",
1163
+ "participantReconnecting",
1164
+ "participantReconnected",
1165
+ "dominantSpeakerChanged"
1166
+ ]);
1167
+ const ROOM_ERROR_EVENTS = new Set(["connectFailure"]);
1168
+ const ROOM_OPTIONAL_ERROR_EVENTS = new Set(["disconnected", "reconnecting"]);
1169
+ const BUBBLED_TRACK_EVENTS = [
1170
+ "trackSubscribed",
1171
+ "trackUnsubscribed",
1172
+ "trackSubscriptionFailed",
1173
+ "trackPublished",
1174
+ "trackUnpublished",
1175
+ "trackEnabled",
1176
+ "trackDisabled",
1177
+ "videoTrackSwitchedOff",
1178
+ "videoTrackSwitchedOn"
1179
+ ];
1180
+ /**
1181
+ * A connected Group Room. Obtained by awaiting {@link connect}; the SDK never
1182
+ * constructs one directly for consumers. Emits the lifecycle, participant, and
1183
+ * track events listed in {@link RoomEvents}. Call {@link Room.dispose} when done
1184
+ * to release native resources and listeners.
1185
+ */
1186
+ var Room = class extends TypedEventEmitter {
1187
+ /** @internal */
1188
+ _native;
1189
+ /**
1190
+ * @internal Remote-track wrappers for this Room only. Scoped here rather
1191
+ * than module-wide so two Rooms in one process subscribed to the same
1192
+ * publication each get their own wrapper, and so one Room's teardown does
1193
+ * not end another Room's receivers.
1194
+ */
1195
+ _tracks = new TrackRegistry();
1196
+ _localParticipant = null;
1197
+ _remoteParticipantCache = /* @__PURE__ */ new Map();
1198
+ _seededTracks;
1199
+ /**
1200
+ * @internal `onConnected` fires once for the native connect signal, which is
1201
+ * already consumed by {@link connect} before the Room is handed to the caller.
1202
+ */
1203
+ constructor(nativeRoom, seededTracks = [], onConnected) {
1204
+ super();
1205
+ this._native = nativeRoom;
1206
+ this._seededTracks = seededTracks;
1207
+ this._native.setEventCallback((event, data) => {
1208
+ if (event === "connected") {
1209
+ this._seedExistingParticipants();
1210
+ onConnected?.();
1211
+ onConnected = void 0;
1212
+ } else if (PARTICIPANT_EVENTS.has(event)) {
1213
+ const wrapped = data ? this._wrapRemoteParticipant(data) : null;
1214
+ this.emit(event, wrapped);
1215
+ if (event === "participantDisconnected" && wrapped) {
1216
+ wrapped.dispose();
1217
+ this._remoteParticipantCache.delete(wrapped.sid);
1218
+ }
1219
+ } else if (event === "disconnected") {
1220
+ this._tracks.releaseAllRemoteTracks();
1221
+ this.emit(event, this, data ? liftTwilioError(data) : void 0);
1222
+ } else if (ROOM_ERROR_EVENTS.has(event)) this.emit(event, liftTwilioError(data));
1223
+ else if (ROOM_OPTIONAL_ERROR_EVENTS.has(event)) this.emit(event, data ? liftTwilioError(data) : void 0);
1224
+ else this.emit(event, data);
1225
+ });
1226
+ }
1227
+ /** The name passed to {@link connect}, or the Room SID if no name was given. */
1228
+ get name() {
1229
+ return this._native.name;
1230
+ }
1231
+ /** This Room's SID (`RM...`), unique per room instance. */
1232
+ get sid() {
1233
+ return this._native.sid;
1234
+ }
1235
+ /** Current connection state. Transitions are mirrored by the corresponding lifecycle events. */
1236
+ get state() {
1237
+ return this._native.state;
1238
+ }
1239
+ /** The geographic region (e.g. `us1`) where the Room's media is being processed. */
1240
+ get mediaRegion() {
1241
+ return this._native.mediaRegion;
1242
+ }
1243
+ /** Whether the Room is currently being recorded. Tracks the `recordingStarted`/`recordingStopped` events. */
1244
+ get isRecording() {
1245
+ return this._native.isRecording;
1246
+ }
1247
+ /**
1248
+ * The participant currently speaking loudest, or `null` when no one is
1249
+ * dominant. Only populated when the Room was connected with dominant-speaker
1250
+ * detection enabled. Updated by the `dominantSpeakerChanged` event.
1251
+ */
1252
+ get dominantSpeaker() {
1253
+ const native = this._native.dominantSpeaker;
1254
+ if (!native) return null;
1255
+ return this._wrapRemoteParticipant(native);
1256
+ }
1257
+ /** The {@link LocalParticipant} representing this client. Lazily created and cached on first access. */
1258
+ get localParticipant() {
1259
+ if (!this._localParticipant) this._localParticipant = new LocalParticipant(this._native.localParticipant, this._seededTracks);
1260
+ return this._localParticipant;
1261
+ }
1262
+ /**
1263
+ * The remote participants currently connected, keyed by Participant SID
1264
+ * (`PA...`). A fresh map is returned on each access; the {@link RemoteParticipant}
1265
+ * instances are cached, so repeated reads return the same objects.
1266
+ */
1267
+ get participants() {
1268
+ const natives = this._native.remoteParticipants;
1269
+ const map = /* @__PURE__ */ new Map();
1270
+ for (const native of natives) map.set(native.sid, this._wrapRemoteParticipant(native));
1271
+ return map;
1272
+ }
1273
+ /** @deprecated Use `participants` instead. */
1274
+ get remoteParticipants() {
1275
+ return [...this.participants.values()];
1276
+ }
1277
+ /**
1278
+ * Sample current media statistics, one {@link StatsReport} per underlying
1279
+ * peer connection.
1280
+ *
1281
+ * @returns A promise that rejects if the Room is already `disconnected`.
1282
+ */
1283
+ getStats() {
1284
+ if (this.state === "disconnected") return Promise.reject(/* @__PURE__ */ new Error("Room is disconnected"));
1285
+ return new Promise((resolve, reject) => {
1286
+ this._native.getStats((error, reports) => {
1287
+ if (error) reject(error);
1288
+ else resolve(reports);
1289
+ });
1290
+ });
1291
+ }
1292
+ /**
1293
+ * Leave the Room. Triggers the `disconnected` event once teardown completes;
1294
+ * does not release the JS-side wrapper — call {@link Room.dispose} for that.
1295
+ */
1296
+ disconnect() {
1297
+ this._native.disconnect();
1298
+ }
1299
+ /**
1300
+ * Disconnect (if still connected) and release all native resources, cached
1301
+ * participant wrappers, and event listeners. The Room is unusable afterward.
1302
+ */
1303
+ dispose() {
1304
+ if (this._localParticipant) {
1305
+ this._localParticipant.dispose();
1306
+ this._localParticipant = null;
1307
+ }
1308
+ for (const participant of this._remoteParticipantCache.values()) participant.dispose();
1309
+ this._remoteParticipantCache.clear();
1310
+ this._tracks.releaseAllRemoteTracks();
1311
+ this._native.dispose();
1312
+ this.removeAllListeners();
1313
+ }
1314
+ /**
1315
+ * Wraps every participant already in the Room, so their track events are
1316
+ * observable from the moment the Room connects.
1317
+ */
1318
+ _seedExistingParticipants() {
1319
+ for (const native of this._native.remoteParticipants) this._wrapRemoteParticipant(native);
1320
+ }
1321
+ _bubbleTrackEvents(participant) {
1322
+ for (const event of BUBBLED_TRACK_EVENTS) participant.on(event, ((...args) => {
1323
+ this.emit(event, ...args, participant);
1324
+ }));
1325
+ }
1326
+ _wrapRemoteParticipant(native) {
1327
+ const sid = native.sid;
1328
+ let wrapped = this._remoteParticipantCache.get(sid);
1329
+ if (!wrapped) {
1330
+ wrapped = new RemoteParticipant(native, this._tracks);
1331
+ this._bubbleTrackEvents(wrapped);
1332
+ this._remoteParticipantCache.set(sid, wrapped);
1333
+ }
1334
+ return wrapped;
1335
+ }
1336
+ };
1337
+ //#endregion
1338
+ //#region lib/index.ts
1339
+ /**
1340
+ * Server-side Node.js SDK for Twilio Video Group Rooms with raw media frame
1341
+ * access.
1342
+ *
1343
+ * {@link connect} joins a Group Room and resolves with a {@link Room}. From
1344
+ * there, {@link Room.localParticipant} publishes tracks and
1345
+ * {@link Room.participants} exposes the remote participants whose tracks can be
1346
+ * subscribed to. Local tracks come from {@link createLocalVideoTrack},
1347
+ * {@link createLocalAudioTrack}, {@link createLocalDataTrack}, and
1348
+ * {@link createLocalTracks}.
1349
+ *
1350
+ * Video frames are I420 planar and audio is 48 kHz mono S16LE PCM, in both
1351
+ * directions. Timestamps are plain numbers of **microseconds**. Receive frames
1352
+ * with `for await (const frame of track.frames())`; awaiting each frame is what
1353
+ * applies backpressure. Call {@link Room.dispose} when finished to release
1354
+ * native resources.
1355
+ *
1356
+ *
1357
+ * @packageDocumentation
1358
+ */
1359
+ const __filename_ = fileURLToPath(import.meta.url);
1360
+ const __dirname_ = path.dirname(__filename_);
1361
+ const nativeRequire = createRequire(import.meta.url);
1362
+ const ROOT = fs.existsSync(path.join(__dirname_, "..", "package.json")) ? path.join(__dirname_, "..") : path.join(__dirname_, "..", "..");
1363
+ const PKG = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf-8"));
1364
+ const SDK_VERSION = PKG.version;
1365
+ function getPlatformDir() {
1366
+ return `${process.platform}-${process.arch}`;
1367
+ }
1368
+ function getPrebuiltPath(platformDir) {
1369
+ return path.join(ROOT, "prebuilds", platformDir, `twilio_video_sdk_node-${platformDir}.node`);
1370
+ }
1371
+ /**
1372
+ * Platforms the native addon is built for, derived from the `os` and `cpu`
1373
+ * fields npm itself enforces at install time. Deriving rather than restating
1374
+ * them means the runtime check cannot drift from what the package declares.
1375
+ */
1376
+ const SUPPORTED_PLATFORMS = (PKG.os ?? ["darwin", "linux"]).flatMap((o) => (PKG.cpu ?? ["x64"]).map((c) => `${o}-${c}`));
1377
+ function loadAddon() {
1378
+ const platformDir = getPlatformDir();
1379
+ const prebuiltPath = getPrebuiltPath(platformDir);
1380
+ for (const buildType of ["Release", "Debug"]) {
1381
+ const localPath = path.join(ROOT, "build", buildType, "twilio_video_sdk_node.node");
1382
+ if (!fs.existsSync(localPath)) continue;
1383
+ try {
1384
+ return nativeRequire(localPath);
1385
+ } catch (cause) {
1386
+ throw new NativeBindingLoadError(`The local build at ${localPath} failed to load. This usually means it was built for a different Node ABI (this is Node ${process.version}, modules ${process.versions.modules}) or a required system library is missing. Rebuild with \`npm run build\`.`, { cause });
1387
+ }
1388
+ }
1389
+ if (fs.existsSync(prebuiltPath)) try {
1390
+ return nativeRequire(prebuiltPath);
1391
+ } catch (cause) {
1392
+ throw new NativeBindingLoadError(`The prebuilt binary at ${prebuiltPath} failed to load. This usually means it was built for a different Node ABI (this is Node ${process.version}, modules ${process.versions.modules}) or a required system library is missing. Rebuild from source with \`npm run build\`.`, { cause });
1393
+ }
1394
+ if (!SUPPORTED_PLATFORMS.includes(platformDir)) throw new UnsupportedPlatformError(`${platformDir} is not a supported platform. This SDK supports linux-x64; the native addon can also load on ${SUPPORTED_PLATFORMS.join(" and ")}. ` + (process.platform === "darwin" && process.arch === "arm64" ? "There is no arm64 build. On Apple Silicon, run Node under Rosetta so process.arch reports x64 (install once with `softwareupdate --install-rosetta`, then use an x64 Node)." : "Contact the Twilio Video team for access to other platforms."));
1395
+ const depsPresent = fs.existsSync(path.join(ROOT, "deps", "twilio-video"));
1396
+ throw new NativeBindingLoadError(`No prebuilt binary for ${platformDir}, and no local build in build/Release or build/Debug. ` + (depsPresent ? "Build it with `npm run build`." : "Fetch the native dependencies first with `npm run fetch-deps`, then build with `npm run build`. On Linux the build also needs the X11 development packages (see DEVELOPER_GUIDE.md)."));
1397
+ }
1398
+ const addon = loadAddon();
1399
+ /**
1400
+ * Default {@link ConnectOptions.connectionTimeout}. Long enough to absorb a slow
1401
+ * signaling round trip and ICE gathering on a congested network, short enough
1402
+ * that a wedged connect surfaces rather than hanging a server process.
1403
+ */
1404
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 3e4;
1405
+ /**
1406
+ * How long a timed-out connect waits for the native layer to report
1407
+ * `disconnected` before disposing anyway. Only a backstop against a disconnect
1408
+ * that never lands.
1409
+ */
1410
+ const DISPOSE_GRACE_MS = 5e3;
1411
+ /** Upper bound for a data track's `maxPacketLifeTime`/`maxRetransmits`; both are `unsigned short` in RTCDataChannelInit. */
1412
+ const MAX_DATA_TRACK_LIMIT = 65535;
1413
+ let defaultFactory = null;
1414
+ function getDefaultMediaFactory() {
1415
+ if (!defaultFactory) defaultFactory = new addon.MediaFactory();
1416
+ return defaultFactory;
1417
+ }
1418
+ /**
1419
+ * Connect to a Twilio Group Room. The returned promise resolves once the Room
1420
+ * emits `connected`, and rejects with a {@link TwilioError} if it emits
1421
+ * `connectFailure` first (the partially-built Room is disposed on failure).
1422
+ *
1423
+ * @param token - A Twilio access token with a Video grant.
1424
+ * @param options - Room name, tracks to publish on join, and feature toggles.
1425
+ * @returns A promise resolving to the connected {@link Room}.
1426
+ * @throws {TypeError} (as a rejection) If `token` is not a non-empty string, or `options` is not an object.
1427
+ * @throws {RangeError} (as a rejection) If `options.networkQuality` verbosities are out of range.
1428
+ *
1429
+ * @example
1430
+ * const audioTrack = createLocalAudioTrack('mic');
1431
+ * const room = await connect(token, { name: 'my-room', audioTracks: [audioTrack] });
1432
+ */
1433
+ function connect(token, options = {}) {
1434
+ if (!token || typeof token !== "string") return Promise.reject(/* @__PURE__ */ new TypeError("token must be a non-empty string"));
1435
+ if (typeof options !== "object" || options === null) return Promise.reject(/* @__PURE__ */ new TypeError("options must be an object"));
1436
+ const { networkQuality, connectionTimeout, ...rest } = options;
1437
+ if (connectionTimeout !== void 0) {
1438
+ if (!Number.isFinite(connectionTimeout) || connectionTimeout < 0) return Promise.reject(/* @__PURE__ */ new RangeError(`connectionTimeout must be a non-negative finite number of milliseconds; got ${String(connectionTimeout)}`));
1439
+ }
1440
+ const timeoutMs = connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS;
1441
+ const internalOpts = { ...rest };
1442
+ delete internalOpts.enableNetworkQuality;
1443
+ delete internalOpts.networkQualityConfiguration;
1444
+ if (networkQuality === true) {
1445
+ internalOpts.enableNetworkQuality = true;
1446
+ internalOpts.networkQualityConfiguration = {
1447
+ local: 1,
1448
+ remote: 0
1449
+ };
1450
+ } else if (networkQuality && typeof networkQuality === "object") {
1451
+ let normalized;
1452
+ try {
1453
+ normalized = normalizeNetworkQualityConfig(networkQuality);
1454
+ } catch (err) {
1455
+ return Promise.reject(err);
1456
+ }
1457
+ internalOpts.enableNetworkQuality = true;
1458
+ internalOpts.networkQualityConfiguration = normalized;
1459
+ } else internalOpts.enableNetworkQuality = false;
1460
+ internalOpts.platformInfo = {
1461
+ sdkVersion: SDK_VERSION,
1462
+ platformName: "nodejs",
1463
+ platformVersion: process.version.replace(/^v/, ""),
1464
+ deviceArchitecture: process.arch
1465
+ };
1466
+ internalOpts.mediaFactory = getDefaultMediaFactory();
1467
+ return new Promise((resolve, reject) => {
1468
+ const nativeRoom = addon.connect(token, internalOpts);
1469
+ const seededTracks = [
1470
+ ...options.videoTracks ?? [],
1471
+ ...options.audioTracks ?? [],
1472
+ ...options.dataTracks ?? []
1473
+ ];
1474
+ let room;
1475
+ let timer = null;
1476
+ let settled = false;
1477
+ const clearTimer = () => {
1478
+ if (timer) {
1479
+ clearTimeout(timer);
1480
+ timer = null;
1481
+ }
1482
+ };
1483
+ const onFailure = (error) => {
1484
+ if (settled) return;
1485
+ settled = true;
1486
+ clearTimer();
1487
+ room?.dispose();
1488
+ reject(error || /* @__PURE__ */ new Error("Connection failed"));
1489
+ };
1490
+ room = new Room(nativeRoom, seededTracks, () => {
1491
+ if (settled) return;
1492
+ settled = true;
1493
+ clearTimer();
1494
+ room?.removeListener("connectFailure", onFailure);
1495
+ resolve(room);
1496
+ });
1497
+ room.once("connectFailure", onFailure);
1498
+ if (timeoutMs > 0) {
1499
+ timer = setTimeout(() => {
1500
+ timer = null;
1501
+ if (settled) return;
1502
+ settled = true;
1503
+ const timedOutRoom = room;
1504
+ timedOutRoom?.removeListener("connectFailure", onFailure);
1505
+ reject(new RoomConnectTimeoutError(`Timed out after ${timeoutMs} ms connecting to the Room. Raise connectionTimeout, or pass 0 to wait indefinitely.`));
1506
+ if (!timedOutRoom) return;
1507
+ let disposed = false;
1508
+ const disposeOnce = () => {
1509
+ if (disposed) return;
1510
+ disposed = true;
1511
+ timedOutRoom.dispose();
1512
+ };
1513
+ timedOutRoom.once("disconnected", disposeOnce);
1514
+ try {
1515
+ timedOutRoom.disconnect();
1516
+ } catch {}
1517
+ setTimeout(disposeOnce, DISPOSE_GRACE_MS).unref?.();
1518
+ }, timeoutMs);
1519
+ timer.unref?.();
1520
+ }
1521
+ });
1522
+ }
1523
+ function resolveName(options, methodName) {
1524
+ if (options === void 0) return void 0;
1525
+ if (typeof options === "string") {
1526
+ if (options.length === 0) throw new TypeError("name must be a non-empty string");
1527
+ return options;
1528
+ }
1529
+ if (typeof options !== "object" || options === null) throw new TypeError(`${methodName} expects a string or options object`);
1530
+ const name = options.name;
1531
+ if (name === void 0) return void 0;
1532
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("name must be a non-empty string");
1533
+ return name;
1534
+ }
1535
+ function normalizeNetworkQualityConfig(config) {
1536
+ const local = config.local ?? 1;
1537
+ const remote = config.remote ?? 0;
1538
+ if (local !== 1) throw new RangeError(`networkQuality.local must be 1; to disable network-quality reporting, pass \`networkQuality: false\`. Got ${local}`);
1539
+ if (!Number.isInteger(remote) || remote < 0 || remote > 1) throw new RangeError(`networkQuality.remote must be 0 (disabled) or 1 (enabled); got ${remote}`);
1540
+ return {
1541
+ local,
1542
+ remote
1543
+ };
1544
+ }
1545
+ /**
1546
+ * Create a {@link LocalVideoTrack}. The track is a sink for caller-supplied
1547
+ * frames, delivered via {@link LocalVideoTrack.write}. Frames pushed before
1548
+ * the room emits `connected` are silently dropped.
1549
+ *
1550
+ * @param options - A track name, or a {@link CreateLocalVideoTrackOptions} object.
1551
+ * @returns The created {@link LocalVideoTrack}.
1552
+ * @throws {TypeError} If `options.name` is provided and is not a non-empty string.
1553
+ *
1554
+ * @example
1555
+ * // Create a track and connect with it.
1556
+ * const videoTrack = createLocalVideoTrack('camera');
1557
+ * const room = await connect(token, { videoTracks: [videoTrack] });
1558
+ *
1559
+ * @example
1560
+ * // Add video to an already-connected room.
1561
+ * const videoTrack = createLocalVideoTrack({ name: 'camera' });
1562
+ * room.localParticipant.publishTrack(videoTrack);
1563
+ */
1564
+ function createLocalVideoTrack(options) {
1565
+ const name = resolveName(options, "createLocalVideoTrack");
1566
+ const source = typeof options === "object" && options !== null ? options.source : void 0;
1567
+ if (source !== void 0) validateVideoSource(source);
1568
+ const track = getDefaultMediaFactory().createVideoTrack(name ? { name } : {});
1569
+ if (source) track._configureSource(source);
1570
+ return track;
1571
+ }
1572
+ function validateVideoSource(source) {
1573
+ if (typeof source !== "object" || source === null) throw new TypeError("source must be an object");
1574
+ if (source.type !== "raw") throw new TypeError(`source.type must be 'raw'; got ${String(source.type)}`);
1575
+ if (source.format !== "I420") throw new TypeError(`source.format must be 'I420'; got ${String(source.format)}`);
1576
+ for (const key of ["width", "height"]) {
1577
+ const v = source[key];
1578
+ if (!Number.isInteger(v) || v <= 0) throw new RangeError(`source.${key} must be a positive integer; got ${String(v)}`);
1579
+ if (v % 2 !== 0) throw new RangeError(`source.${key} must be even; got ${String(v)}`);
1580
+ }
1581
+ if (source.fps !== void 0 && (!Number.isInteger(source.fps) || source.fps <= 0)) throw new RangeError(`source.fps must be a positive integer; got ${String(source.fps)}`);
1582
+ }
1583
+ function validateAudioSource(source) {
1584
+ if (typeof source !== "object" || source === null) throw new TypeError("source must be an object");
1585
+ if (source.type !== "raw") throw new TypeError(`source.type must be 'raw'; got ${String(source.type)}`);
1586
+ if (source.format !== "PCM_S16LE") throw new TypeError(`source.format must be 'PCM_S16LE'; got ${String(source.format)}`);
1587
+ if (source.sampleRate !== 48e3) throw new RangeError(`source.sampleRate must be 48000; got ${String(source.sampleRate)}`);
1588
+ if (source.channels !== 1) throw new RangeError(`source.channels must be 1; got ${String(source.channels)}`);
1589
+ if (source.maxQueue !== void 0) {
1590
+ if (!Number.isInteger(source.maxQueue) || source.maxQueue <= 0) throw new RangeError(`source.maxQueue must be a positive integer; got ${String(source.maxQueue)}`);
1591
+ if (source.maxQueue > 1024) throw new RangeError(`source.maxQueue must be at most ${MAX_QUEUE_CEILING}; got ${source.maxQueue}`);
1592
+ }
1593
+ }
1594
+ /**
1595
+ * Create a {@link LocalAudioTrack}. The track is a sink for caller-supplied
1596
+ * PCM samples, delivered via {@link LocalAudioTrack.write}. Audio input is
1597
+ * fixed at **48 kHz mono S16LE**.
1598
+ *
1599
+ * @param options - A track name, or a {@link CreateLocalAudioTrackOptions} object.
1600
+ * @returns The created {@link LocalAudioTrack}.
1601
+ * @throws {TypeError} If `options.name` is provided and is not a non-empty string.
1602
+ *
1603
+ * @example
1604
+ * // Create a track and connect with it.
1605
+ * const audioTrack = createLocalAudioTrack('microphone');
1606
+ * const room = await connect(token, { audioTracks: [audioTrack] });
1607
+ *
1608
+ * @example
1609
+ * // Add audio to an already-connected room.
1610
+ * const audioTrack = createLocalAudioTrack({ name: 'microphone' });
1611
+ * room.localParticipant.publishTrack(audioTrack);
1612
+ */
1613
+ function createLocalAudioTrack(options) {
1614
+ const name = resolveName(options, "createLocalAudioTrack");
1615
+ const source = typeof options === "object" && options !== null ? options.source : void 0;
1616
+ if (source !== void 0) validateAudioSource(source);
1617
+ const track = getDefaultMediaFactory().createAudioTrack(name ? { name } : {});
1618
+ if (source) track._configureSource(source);
1619
+ return track;
1620
+ }
1621
+ /**
1622
+ * Create a {@link LocalDataTrack} for sending arbitrary string or binary
1623
+ * messages. The track defaults to reliable, ordered delivery; pass
1624
+ * `maxRetransmits` or `maxPacketLifeTime` to make it unreliable.
1625
+ *
1626
+ * @param options - A track name, or a {@link LocalDataTrackOptions} object.
1627
+ * @returns The created {@link LocalDataTrack}.
1628
+ * @throws {TypeError} If `options` is not a string or object, if `name` is not a non-empty string,
1629
+ * or if `ordered` is not a boolean.
1630
+ * @throws {Error} If both `maxRetransmits` and `maxPacketLifeTime` are set.
1631
+ * @throws {RangeError} If either `maxRetransmits` or `maxPacketLifeTime` is not an integer in [0, 65535].
1632
+ *
1633
+ * @example
1634
+ * // Reliable, ordered messaging.
1635
+ * const dataTrack = createLocalDataTrack('chat');
1636
+ * room.localParticipant.publishTrack(dataTrack);
1637
+ * dataTrack.send('hello');
1638
+ *
1639
+ * @example
1640
+ * // Unreliable, time-bounded delivery.
1641
+ * const dataTrack = createLocalDataTrack({ name: 'telemetry', maxPacketLifeTime: 1000 });
1642
+ */
1643
+ function createLocalDataTrack(options = {}) {
1644
+ const name = resolveName(options, "createLocalDataTrack");
1645
+ const opts = typeof options === "string" ? {} : options;
1646
+ if (opts.ordered !== void 0 && typeof opts.ordered !== "boolean") throw new TypeError("ordered must be a boolean");
1647
+ if (opts.maxRetransmits != null && opts.maxPacketLifeTime != null) throw new Error("maxRetransmits and maxPacketLifeTime are mutually exclusive");
1648
+ for (const key of ["maxRetransmits", "maxPacketLifeTime"]) {
1649
+ const value = opts[key];
1650
+ if (value != null && (!Number.isInteger(value) || value < 0 || value > MAX_DATA_TRACK_LIMIT)) throw new RangeError(`${key} must be an integer between 0 and ${MAX_DATA_TRACK_LIMIT}; got ${value}`);
1651
+ }
1652
+ return getDefaultMediaFactory().createDataTrack({
1653
+ ...opts,
1654
+ name
1655
+ });
1656
+ }
1657
+ /**
1658
+ * Create {@link LocalAudioTrack}s and {@link LocalVideoTrack}s. By default,
1659
+ * returns both a {@link LocalAudioTrack} and a {@link LocalVideoTrack}. If
1660
+ * either `audio` or `video` is provided, the unspecified kind is omitted.
1661
+ * Each key accepts a boolean or a per-track options object.
1662
+ *
1663
+ * @param options - Track selection and per-track configuration.
1664
+ * @returns A promise that resolves with the created local tracks, or rejects
1665
+ * with a `TypeError` if a per-track option fails validation.
1666
+ *
1667
+ * @example
1668
+ * // Create both audio and video tracks.
1669
+ * const tracks = await createLocalTracks();
1670
+ *
1671
+ * @example
1672
+ * // Create only an audio track and connect with it.
1673
+ * const tracks = await createLocalTracks({ audio: true });
1674
+ * const room = await connect(token, { audioTracks: tracks });
1675
+ *
1676
+ * @example
1677
+ * // Create both with custom names.
1678
+ * const tracks = await createLocalTracks({
1679
+ * audio: { name: 'microphone' },
1680
+ * video: { name: 'camera' },
1681
+ * });
1682
+ */
1683
+ async function createLocalTracks(options = {}) {
1684
+ const defaultEnabled = !("audio" in options) && !("video" in options);
1685
+ const audio = options.audio ?? defaultEnabled;
1686
+ const video = options.video ?? defaultEnabled;
1687
+ const tracks = [];
1688
+ if (audio) tracks.push(createLocalAudioTrack(typeof audio === "object" ? audio : void 0));
1689
+ if (video) tracks.push(createLocalVideoTrack(typeof video === "object" ? video : void 0));
1690
+ return tracks;
1691
+ }
1692
+ /**
1693
+ * Known Twilio error codes, mapping a descriptive name to its numeric code.
1694
+ * Match against {@link TwilioError.code} to identify a failure without
1695
+ * depending on the error message.
1696
+ */
1697
+ const ErrorCode = Object.freeze({
1698
+ ACCESS_TOKEN_INVALID: 20101,
1699
+ ACCESS_TOKEN_HEADER_INVALID: 20102,
1700
+ ACCESS_TOKEN_ISSUER_INVALID: 20103,
1701
+ ACCESS_TOKEN_EXPIRED: 20104,
1702
+ ACCESS_TOKEN_NOT_YET_VALID: 20105,
1703
+ ACCESS_TOKEN_GRANT_INVALID: 20106,
1704
+ ACCESS_TOKEN_SIGNATURE_INVALID: 20107,
1705
+ SIGNALING_CONNECTION_ERROR: 53e3,
1706
+ SIGNALING_CONNECTION_DISCONNECTED: 53001,
1707
+ SIGNALING_CONNECTION_TIMEOUT: 53002,
1708
+ ROOM_NOT_FOUND: 53106,
1709
+ ROOM_CONNECT_FAILED: 53104,
1710
+ ROOM_MAX_PARTICIPANTS_EXCEEDED: 53105,
1711
+ ROOM_COMPLETED: 53118,
1712
+ PARTICIPANT_MAX_TRACKS_EXCEEDED: 53203,
1713
+ PARTICIPANT_DUPLICATE_IDENTITY: 53205,
1714
+ TRACK_INVALID: 53300,
1715
+ TRACK_NAME_INVALID: 53301,
1716
+ TRACK_NAME_TOO_LONG: 53302,
1717
+ TRACK_NAME_CHARS_INVALID: 53303,
1718
+ MEDIA_CLIENT_LOCAL_DESC_FAILED: 53400,
1719
+ MEDIA_SERVER_LOCAL_DESC_FAILED: 53401,
1720
+ MEDIA_CLIENT_REMOTE_DESC_FAILED: 53402,
1721
+ MEDIA_SERVER_REMOTE_DESC_FAILED: 53403,
1722
+ MEDIA_NO_SUPPORTED_CODEC: 53404,
1723
+ MEDIA_CONNECTION_ERROR: 53405
1724
+ });
1725
+ /** The version of the underlying native rtc-cpp engine (distinct from this package's version). */
1726
+ function getVersion() {
1727
+ return addon.getVersion();
1728
+ }
1729
+ /**
1730
+ * Set the verbosity of the native SDK's logging. Process-global and effective
1731
+ * immediately for all current and future Rooms.
1732
+ *
1733
+ * @param level - A {@link LogLevel} name or its equivalent native numeric level.
1734
+ */
1735
+ function setLogLevel(level) {
1736
+ addon.setLogLevel(level);
1737
+ }
1738
+ //#endregion
1739
+ export { AccessTokenExpiredError, AccessTokenGrantsInvalidError, AccessTokenHeaderInvalidError, AccessTokenInvalidError, AccessTokenIssuerInvalidError, AccessTokenNotYetValidError, AccessTokenSignatureInvalidError, DataTrackSendError, ErrorCode, LocalAudioTrackPublication, LocalDataTrackPublication, LocalParticipant, LocalTrackPublication, LocalVideoTrackPublication, MAX_QUEUE_CEILING, MediaClientLocalDescFailedError, MediaClientRemoteDescFailedError, MediaConnectionError, MediaNoSupportedCodecError, MediaServerLocalDescFailedError, MediaServerRemoteDescFailedError, NativeBindingLoadError, ParticipantDuplicateIdentityError, ParticipantMaxTracksExceededError, RemoteAudioTrack, RemoteAudioTrackPublication, RemoteDataTrack, RemoteDataTrackPublication, RemoteParticipant, RemoteTrackPublication, RemoteVideoTrack, RemoteVideoTrackPublication, Room, RoomCompletedError, RoomConnectFailedError, RoomConnectTimeoutError, RoomMaxParticipantsExceededError, RoomNotFoundError, SDK_LOCAL_CODE, SignalingConnectionDisconnectedError, SignalingConnectionError, SignalingConnectionTimeoutError, TrackInvalidError, TrackNameCharsInvalidError, TrackNameInvalidError, TrackNameTooLongError, TrackPublication, TwilioError, TypedEventEmitter, UnsupportedPlatformError, connect, createLocalAudioTrack, createLocalDataTrack, createLocalTracks, createLocalVideoTrack, getVersion, setLogLevel, twilioErrorFromCode };