@fishjam-cloud/ts-client 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/index.d.mts +1308 -0
  2. package/dist/index.mjs +1 -0
  3. package/package.json +23 -33
  4. package/dist/src/FishjamClient.d.ts +0 -511
  5. package/dist/src/FishjamClient.js +0 -669
  6. package/dist/src/auth.d.ts +0 -3
  7. package/dist/src/auth.js +0 -8
  8. package/dist/src/connectEventsHandler.d.ts +0 -2
  9. package/dist/src/connectEventsHandler.js +0 -22
  10. package/dist/src/index.d.ts +0 -7
  11. package/dist/src/index.js +0 -3
  12. package/dist/src/protos/fishjam/peer_notifications.d.ts +0 -51
  13. package/dist/src/protos/fishjam/peer_notifications.js +0 -309
  14. package/dist/src/protos/index.d.ts +0 -1
  15. package/dist/src/protos/index.js +0 -1
  16. package/dist/src/reconnection.d.ts +0 -27
  17. package/dist/src/reconnection.js +0 -119
  18. package/dist/src/webrtc/CommandsQueue.d.ts +0 -23
  19. package/dist/src/webrtc/CommandsQueue.js +0 -87
  20. package/dist/src/webrtc/ConnectionManager.d.ts +0 -27
  21. package/dist/src/webrtc/ConnectionManager.js +0 -65
  22. package/dist/src/webrtc/bitrate.d.ts +0 -12
  23. package/dist/src/webrtc/bitrate.js +0 -12
  24. package/dist/src/webrtc/deferred.d.ts +0 -8
  25. package/dist/src/webrtc/deferred.js +0 -17
  26. package/dist/src/webrtc/index.d.ts +0 -3
  27. package/dist/src/webrtc/index.js +0 -1
  28. package/dist/src/webrtc/internal.d.ts +0 -26
  29. package/dist/src/webrtc/internal.js +0 -34
  30. package/dist/src/webrtc/mediaEvent.d.ts +0 -10
  31. package/dist/src/webrtc/mediaEvent.js +0 -16
  32. package/dist/src/webrtc/tracks/Local.d.ts +0 -50
  33. package/dist/src/webrtc/tracks/Local.js +0 -280
  34. package/dist/src/webrtc/tracks/LocalTrack.d.ts +0 -62
  35. package/dist/src/webrtc/tracks/LocalTrack.js +0 -225
  36. package/dist/src/webrtc/tracks/LocalTrackManager.d.ts +0 -38
  37. package/dist/src/webrtc/tracks/LocalTrackManager.js +0 -77
  38. package/dist/src/webrtc/tracks/Remote.d.ts +0 -38
  39. package/dist/src/webrtc/tracks/Remote.js +0 -200
  40. package/dist/src/webrtc/tracks/RemoteTrack.d.ts +0 -39
  41. package/dist/src/webrtc/tracks/RemoteTrack.js +0 -64
  42. package/dist/src/webrtc/tracks/TrackCommon.d.ts +0 -8
  43. package/dist/src/webrtc/tracks/TrackCommon.js +0 -1
  44. package/dist/src/webrtc/tracks/bandwidth.d.ts +0 -1
  45. package/dist/src/webrtc/tracks/bandwidth.js +0 -27
  46. package/dist/src/webrtc/tracks/encodings.d.ts +0 -1
  47. package/dist/src/webrtc/tracks/encodings.js +0 -5
  48. package/dist/src/webrtc/tracks/muteTrackUtils.d.ts +0 -3
  49. package/dist/src/webrtc/tracks/muteTrackUtils.js +0 -19
  50. package/dist/src/webrtc/tracks/transceivers.d.ts +0 -2
  51. package/dist/src/webrtc/tracks/transceivers.js +0 -91
  52. package/dist/src/webrtc/types.d.ts +0 -314
  53. package/dist/src/webrtc/types.js +0 -2
  54. package/dist/src/webrtc/voiceActivityDetection.d.ts +0 -2
  55. package/dist/src/webrtc/voiceActivityDetection.js +0 -2
  56. package/dist/src/webrtc/webRTCEndpoint.d.ts +0 -297
  57. package/dist/src/webrtc/webRTCEndpoint.js +0 -686
@@ -1,669 +0,0 @@
1
- import { WebRTCEndpoint } from './webrtc';
2
- import { EventEmitter } from 'events';
3
- import { PeerMessage } from './protos';
4
- import { ReconnectManager } from './reconnection';
5
- import { isAuthError } from './auth';
6
- import { connectEventsHandler } from './connectEventsHandler';
7
- const STATISTICS_INTERVAL = 10_000;
8
- const isPeer = (endpoint) => endpoint.type === 'webrtc';
9
- const isComponent = (endpoint) => endpoint.type === 'recording' ||
10
- endpoint.type === 'hls' ||
11
- endpoint.type === 'file' ||
12
- endpoint.type === 'rtsp' ||
13
- endpoint.type === 'sip';
14
- const WEBSOCKET_PATH = 'socket/peer/websocket';
15
- /**
16
- * FishjamClient is the main class to interact with Fishjam.
17
- *
18
- * @example
19
- * ```typescript
20
- * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
21
- * const peerToken = "YOUR_PEER_TOKEN";
22
- *
23
- * // You can listen to events emitted by the client
24
- * client.on("joined", (peerId, peersInRoom) => {
25
- * console.log("join success");
26
- * });
27
- *
28
- * // Start the peer connection
29
- * client.connect({
30
- * peerMetadata: {},
31
- * isSimulcastOn: false,
32
- * token: peerToken
33
- * });
34
- *
35
- * // Close the peer connection
36
- * client.disconnect();
37
- * ```
38
- *
39
- * You can register callbacks to handle the events emitted by the Client.
40
- *
41
- * @example
42
- * ```typescript
43
- *
44
- * client.on("trackReady", (ctx) => {
45
- * console.log("On track ready");
46
- * });
47
- * ```
48
- */
49
- export class FishjamClient extends EventEmitter {
50
- websocket = null;
51
- webrtc = null;
52
- removeEventListeners = null;
53
- status = 'new';
54
- connectConfig = null;
55
- reconnectManager;
56
- sendStatisticsInterval = undefined;
57
- peerMetadataParser;
58
- trackMetadataParser;
59
- constructor(config) {
60
- super();
61
- this.peerMetadataParser = config?.peerMetadataParser ?? ((x) => x);
62
- this.trackMetadataParser = config?.trackMetadataParser ?? ((x) => x);
63
- this.reconnectManager = new ReconnectManager(this, (peerMetadata) => this.initConnection(peerMetadata), config?.reconnect);
64
- }
65
- /**
66
- * Uses the {@link !WebSocket} connection and {@link !WebRTCEndpoint | WebRTCEndpoint} to join to the room. Registers the callbacks to
67
- * handle the events emitted by the {@link !WebRTCEndpoint | WebRTCEndpoint}. Make sure that peer metadata is serializable.
68
- *
69
- * @example
70
- * ```typescript
71
- * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
72
- *
73
- * client.connect({
74
- * peerMetadata: {},
75
- * token: peerToken
76
- * });
77
- * ```
78
- *
79
- * @param {ConnectConfig} config - Configuration object for the client
80
- */
81
- async connect(config) {
82
- this.emit('connectionStarted');
83
- const result = connectEventsHandler(this);
84
- this.reconnectManager.reset(config.peerMetadata);
85
- this.connectConfig = config;
86
- this.initConnection(config.peerMetadata);
87
- return result;
88
- }
89
- async initConnection(peerMetadata) {
90
- if (this.status === 'initialized') {
91
- this.disconnect();
92
- }
93
- this.webrtc = new WebRTCEndpoint({
94
- endpointMetadataParser: this.peerMetadataParser,
95
- trackMetadataParser: this.trackMetadataParser,
96
- });
97
- this.initWebsocket(peerMetadata);
98
- this.setupCallbacks();
99
- this.status = 'initialized';
100
- }
101
- getUrl(url) {
102
- if (url.endsWith('/'))
103
- return `${url}${WEBSOCKET_PATH}`;
104
- return `${url}/${WEBSOCKET_PATH}`;
105
- }
106
- initWebsocket(peerMetadata) {
107
- if (!this.connectConfig)
108
- throw Error('ConnectConfig is null');
109
- const { token, url } = this.connectConfig;
110
- const websocketUrl = this.getUrl(url);
111
- this.websocket = new WebSocket(websocketUrl);
112
- this.websocket.binaryType = 'arraybuffer';
113
- const socketOpenHandler = (event) => {
114
- this.emit('socketOpen', event);
115
- const message = PeerMessage.encode({ authRequest: { token } }).finish();
116
- this.websocket?.send(message);
117
- };
118
- const socketErrorHandler = (event) => {
119
- this.emit('socketError', event);
120
- };
121
- const socketCloseHandler = (event) => {
122
- if (isAuthError(event.reason)) {
123
- this.emit('authError', event.reason);
124
- }
125
- this.emit('socketClose', event);
126
- };
127
- this.websocket.addEventListener('open', socketOpenHandler);
128
- this.websocket.addEventListener('error', socketErrorHandler);
129
- this.websocket.addEventListener('close', socketCloseHandler);
130
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
131
- const messageHandler = (event) => {
132
- const uint8Array = new Uint8Array(event.data);
133
- try {
134
- const data = PeerMessage.decode(uint8Array);
135
- if (data.authenticated !== undefined) {
136
- this.emit('authSuccess');
137
- this.webrtc?.connect(peerMetadata);
138
- }
139
- else if (data.authRequest !== undefined) {
140
- console.warn('Received unexpected control message: authRequest');
141
- }
142
- else if (data.mediaEvent !== undefined) {
143
- this.webrtc?.receiveMediaEvent(data.mediaEvent.data);
144
- }
145
- }
146
- catch (e) {
147
- console.warn(`Received invalid control message, error: ${e}`);
148
- }
149
- };
150
- this.websocket.addEventListener('message', messageHandler);
151
- this.removeEventListeners = () => {
152
- this.websocket?.removeEventListener('open', socketOpenHandler);
153
- this.websocket?.removeEventListener('error', socketErrorHandler);
154
- this.websocket?.removeEventListener('close', socketCloseHandler);
155
- this.websocket?.removeEventListener('message', messageHandler);
156
- };
157
- }
158
- /**
159
- * Retrieves statistics related to the RTCPeerConnection.
160
- * These statistics provide insights into the performance and status of the connection.
161
- *
162
- * @return {Promise<RTCStatsReport>}
163
- *
164
- * @external RTCPeerConnection#getStats()
165
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats | MDN Web Docs: RTCPeerConnection.getStats()}
166
- */
167
- async getStatistics(selector) {
168
- return (await this.webrtc?.getStatistics(selector)) ?? new Map();
169
- }
170
- /**
171
- * Returns a snapshot of currently received remote tracks.
172
- *
173
- * @example
174
- * if (client.getRemoteTracks()[trackId]?.simulcastConfig?.enabled) {
175
- * client.setTargetTrackEncoding(trackId, encoding);
176
- * }
177
- */
178
- getRemoteTracks() {
179
- return this.webrtc?.getRemoteTracks() ?? {};
180
- }
181
- /**
182
- * Returns a snapshot of currently received remote peers.
183
- */
184
- getRemotePeers() {
185
- return Object.entries(this.webrtc?.getRemoteEndpoints() ?? {}).reduce((acc, [id, peer]) => (isPeer(peer) ? { ...acc, [id]: peer } : acc), {});
186
- }
187
- getRemoteComponents() {
188
- return Object.entries(this.webrtc?.getRemoteEndpoints() ?? {}).reduce((acc, [id, component]) => (isComponent(component) ? { ...acc, [id]: component } : acc), {});
189
- }
190
- getLocalPeer() {
191
- return this.webrtc?.getLocalEndpoint() || null;
192
- }
193
- getBandwidthEstimation() {
194
- if (!this.webrtc)
195
- throw Error('Webrtc not initialized');
196
- return this.webrtc?.getBandwidthEstimation();
197
- }
198
- setupCallbacks() {
199
- this.webrtc?.on('sendMediaEvent', (mediaEvent) => {
200
- const message = PeerMessage.encode({
201
- mediaEvent: { data: mediaEvent },
202
- }).finish();
203
- this.websocket?.send(message);
204
- });
205
- this.webrtc?.on('connected', async (peerId, endpointsInRoom) => {
206
- const peers = endpointsInRoom
207
- .filter((endpoint) => isPeer(endpoint))
208
- .map((peer) => peer);
209
- const components = endpointsInRoom
210
- .filter((endpoint) => isComponent(endpoint))
211
- .map((component) => component);
212
- await this.reconnectManager.handleReconnect();
213
- this.sendStatisticsInterval = setInterval(() => this.sendStatistics(), STATISTICS_INTERVAL);
214
- this.emit('joined', peerId, peers, components);
215
- });
216
- this.webrtc?.on('disconnected', () => {
217
- this.emit('disconnected');
218
- clearInterval(this.sendStatisticsInterval);
219
- });
220
- this.webrtc?.on('endpointAdded', (endpoint) => {
221
- if (isPeer(endpoint)) {
222
- this.emit('peerJoined', endpoint);
223
- }
224
- if (isComponent(endpoint)) {
225
- this.emit('componentAdded', endpoint);
226
- }
227
- });
228
- this.webrtc?.on('endpointRemoved', (endpoint) => {
229
- if (isPeer(endpoint)) {
230
- this.emit('peerLeft', endpoint);
231
- }
232
- if (isComponent(endpoint)) {
233
- this.emit('componentRemoved', endpoint);
234
- }
235
- });
236
- this.webrtc?.on('endpointUpdated', (endpoint) => {
237
- if (isPeer(endpoint)) {
238
- this.emit('peerUpdated', endpoint);
239
- }
240
- if (isComponent(endpoint)) {
241
- this.emit('componentUpdated', endpoint);
242
- }
243
- });
244
- this.webrtc?.on('trackReady', (ctx) => {
245
- if (!isPeer(ctx.endpoint))
246
- return;
247
- this.emit('trackReady', ctx);
248
- });
249
- this.webrtc?.on('trackAdded', (ctx) => {
250
- if (!isPeer(ctx.endpoint))
251
- return;
252
- this.emit('trackAdded', ctx);
253
- });
254
- this.webrtc?.on('trackRemoved', (ctx) => {
255
- if (!isPeer(ctx.endpoint))
256
- return;
257
- this.emit('trackRemoved', ctx);
258
- ctx.removeAllListeners();
259
- });
260
- this.webrtc?.on('trackUpdated', (ctx) => {
261
- if (!isPeer(ctx.endpoint))
262
- return;
263
- this.emit('trackUpdated', ctx);
264
- });
265
- this.webrtc?.on('tracksPriorityChanged', (enabledTracks, disabledTracks) => {
266
- this.emit('tracksPriorityChanged', enabledTracks, disabledTracks);
267
- });
268
- this.webrtc?.on('signalingError', (error) => {
269
- this.emit('joinError', error);
270
- });
271
- this.webrtc?.on('connectionError', (error) => {
272
- this.emit('connectionError', error);
273
- });
274
- this.webrtc?.on('bandwidthEstimationChanged', (estimation) => {
275
- this.emit('bandwidthEstimationChanged', estimation);
276
- });
277
- this.webrtc?.on('targetTrackEncodingRequested', (event) => {
278
- this.emit('targetTrackEncodingRequested', event);
279
- });
280
- this.webrtc?.on('localTrackAdded', (event) => {
281
- this.emit('localTrackAdded', event);
282
- });
283
- this.webrtc?.on('localTrackRemoved', (event) => {
284
- this.emit('localTrackRemoved', event);
285
- });
286
- this.webrtc?.on('localTrackReplaced', (event) => {
287
- this.emit('localTrackReplaced', event);
288
- });
289
- this.webrtc?.on('localTrackBandwidthSet', (event) => {
290
- this.emit('localTrackBandwidthSet', event);
291
- });
292
- this.webrtc?.on('localTrackMuted', (event) => {
293
- this.emit('localTrackMuted', event);
294
- });
295
- this.webrtc?.on('localTrackUnmuted', (event) => {
296
- this.emit('localTrackUnmuted', event);
297
- });
298
- this.webrtc?.on('localTrackBandwidthSet', (event) => {
299
- this.emit('localTrackBandwidthSet', event);
300
- });
301
- this.webrtc?.on('localTrackEncodingEnabled', (event) => {
302
- this.emit('localTrackEncodingEnabled', event);
303
- });
304
- this.webrtc?.on('localTrackEncodingDisabled', (event) => {
305
- this.emit('localTrackEncodingDisabled', event);
306
- });
307
- this.webrtc?.on('localEndpointMetadataChanged', (event) => {
308
- this.emit('localPeerMetadataChanged', event);
309
- });
310
- this.webrtc?.on('localTrackMetadataChanged', (event) => {
311
- this.emit('localTrackMetadataChanged', event);
312
- });
313
- this.webrtc?.on('disconnectRequested', (event) => {
314
- this.emit('disconnectRequested', event);
315
- });
316
- }
317
- async sendStatistics() {
318
- const statistics = await this.getStatistics();
319
- const tracksStatistics = {};
320
- statistics.forEach((report, key) => {
321
- if (report.type === 'inbound-rtp' || report.type === 'outbound-rtp')
322
- tracksStatistics[key] = report;
323
- });
324
- const message = PeerMessage.encode({
325
- rtcStatsReport: { data: JSON.stringify(tracksStatistics) },
326
- }).finish();
327
- this.websocket?.send(message);
328
- }
329
- /**
330
- * Register a callback to be called when the event is emitted.
331
- * Full list of callbacks can be found here {@link MessageEvents}.
332
- *
333
- * @example
334
- * ```ts
335
- * const callback = ()=>{ };
336
- *
337
- * client.on("onJoinSuccess", callback);
338
- * ```
339
- *
340
- * @param event - Event name from {@link MessageEvents}
341
- * @param listener - Callback function to be called when the event is emitted
342
- * @returns This
343
- */
344
- on(event, listener) {
345
- return super.on(event, listener);
346
- }
347
- /**
348
- * Remove a callback from the list of callbacks to be called when the event is emitted.
349
- *
350
- * @example
351
- * ```ts
352
- * const callback = ()=>{ };
353
- *
354
- * client.on("onJoinSuccess", callback);
355
- *
356
- * client.off("onJoinSuccess", callback);
357
- * ```
358
- *
359
- * @param event - Event name from {@link MessageEvents}
360
- * @param listener - Reference to function to be removed from called callbacks
361
- * @returns This
362
- */
363
- off(event, listener) {
364
- return super.off(event, listener);
365
- }
366
- handleWebRTCNotInitialized() {
367
- return new Error('WebRTC is not initialized');
368
- }
369
- /**
370
- * Adds track that will be sent to the RTC Engine.
371
- *
372
- * @example
373
- * ```ts
374
- * const localStream: MediaStream = new MediaStream();
375
- * try {
376
- * const localAudioStream = await navigator.mediaDevices.getUserMedia(
377
- * { audio: true }
378
- * );
379
- * localAudioStream
380
- * .getTracks()
381
- * .forEach((track) => localStream.addTrack(track));
382
- * } catch (error) {
383
- * console.error("Couldn't get microphone permission:", error);
384
- * }
385
- *
386
- * try {
387
- * const localVideoStream = await navigator.mediaDevices.getUserMedia(
388
- * { video: true }
389
- * );
390
- * localVideoStream
391
- * .getTracks()
392
- * .forEach((track) => localStream.addTrack(track));
393
- * } catch (error) {
394
- * console.error("Couldn't get camera permission:", error);
395
- * }
396
- *
397
- * localStream
398
- * .getTracks()
399
- * .forEach((track) => client.addTrack(track, localStream));
400
- * ```
401
- *
402
- * @param track - Audio or video track e.g. from your microphone or camera.
403
- * @param stream - Stream that this track belongs to.
404
- * @param trackMetadata - Any information about this track that other peers will receive in
405
- * {@link MessageEvents.peerJoined}. E.g. this can source of the track - wheather it's screensharing, webcam or some
406
- * other media device.
407
- * @param simulcastConfig - Simulcast configuration. By default, simulcast is disabled. For more information refer to
408
- * {@link !SimulcastConfig | SimulcastConfig}.
409
- * @param maxBandwidth - Maximal bandwidth this track can use. Defaults to 0 which is unlimited. This option has no
410
- * effect for simulcast and audio tracks. For simulcast tracks use {@link FishjamClient.setTrackBandwidth}.
411
- * @returns {string} Returns id of added track
412
- */
413
- addTrack(track, trackMetadata, simulcastConfig = {
414
- enabled: false,
415
- activeEncodings: [],
416
- disabledEncodings: [],
417
- }, maxBandwidth = 0) {
418
- if (!this.webrtc)
419
- throw this.handleWebRTCNotInitialized();
420
- return this.webrtc.addTrack(track, trackMetadata, simulcastConfig, maxBandwidth);
421
- }
422
- /**
423
- * Replaces a track that is being sent to the RTC Engine.
424
- *
425
- * @example
426
- * ```ts
427
- * // setup camera
428
- * let localStream: MediaStream = new MediaStream();
429
- * try {
430
- * localVideoStream = await navigator.mediaDevices.getUserMedia(
431
- * VIDEO_CONSTRAINTS
432
- * );
433
- * localVideoStream
434
- * .getTracks()
435
- * .forEach((track) => localStream.addTrack(track));
436
- * } catch (error) {
437
- * console.error("Couldn't get camera permission:", error);
438
- * }
439
- * let oldTrackId;
440
- * localStream
441
- * .getTracks()
442
- * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
443
- *
444
- * // change camera
445
- * const oldTrack = localStream.getVideoTracks()[0];
446
- * let videoDeviceId = "abcd-1234";
447
- * navigator.mediaDevices.getUserMedia({
448
- * video: {
449
- * ...(VIDEO_CONSTRAINTS as {}),
450
- * deviceId: {
451
- * exact: videoDeviceId,
452
- * },
453
- * }
454
- * })
455
- * .then((stream) => {
456
- * let videoTrack = stream.getVideoTracks()[0];
457
- * webrtc.replaceTrack(oldTrackId, videoTrack);
458
- * })
459
- * .catch((error) => {
460
- * console.error('Error switching camera', error);
461
- * })
462
- * ```
463
- *
464
- * @param {string} trackId - Id of audio or video track to replace.
465
- * @param {MediaStreamTrack} newTrack - New audio or video track.
466
- * @returns {Promise<boolean>} Success
467
- */
468
- async replaceTrack(trackId, newTrack) {
469
- if (!this.webrtc)
470
- throw this.handleWebRTCNotInitialized();
471
- return this.webrtc.replaceTrack(trackId, newTrack);
472
- }
473
- /**
474
- * Updates maximum bandwidth for the track identified by trackId. This value directly translates to quality of the
475
- * stream and, in case of video, to the amount of RTP packets being sent. In case trackId points at the simulcast
476
- * track bandwidth is split between all of the variant streams proportionally to their resolution.
477
- *
478
- * @param {string} trackId
479
- * @param {BandwidthLimit} bandwidth In kbps
480
- * @returns {Promise<boolean>} Success
481
- */
482
- async setTrackBandwidth(trackId, bandwidth) {
483
- if (!this.webrtc)
484
- throw this.handleWebRTCNotInitialized();
485
- await this.webrtc.setTrackBandwidth(trackId, bandwidth);
486
- return true;
487
- }
488
- /**
489
- * Updates maximum bandwidth for the given simulcast encoding of the given track.
490
- *
491
- * @param {string} trackId - Id of the track
492
- * @param {string} rid - Rid of the encoding
493
- * @param {BandwidthLimit} bandwidth - Desired max bandwidth used by the encoding (in kbps)
494
- * @returns
495
- */
496
- async setEncodingBandwidth(trackId, rid, bandwidth) {
497
- if (!this.webrtc)
498
- throw this.handleWebRTCNotInitialized();
499
- await this.webrtc.setEncodingBandwidth(trackId, rid, bandwidth);
500
- return true;
501
- }
502
- /**
503
- * Removes a track from connection that was being sent to the RTC Engine.
504
- *
505
- * @example
506
- * ```ts
507
- * // setup camera
508
- * let localStream: MediaStream = new MediaStream();
509
- * try {
510
- * localVideoStream = await navigator.mediaDevices.getUserMedia(
511
- * VIDEO_CONSTRAINTS
512
- * );
513
- * localVideoStream
514
- * .getTracks()
515
- * .forEach((track) => localStream.addTrack(track));
516
- * } catch (error) {
517
- * console.error("Couldn't get camera permission:", error);
518
- * }
519
- *
520
- * let trackId
521
- * localStream
522
- * .getTracks()
523
- * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
524
- *
525
- * // remove track
526
- * webrtc.removeTrack(trackId)
527
- * ```
528
- *
529
- * @param {string} trackId - Id of audio or video track to remove.
530
- */
531
- removeTrack(trackId) {
532
- if (!this.webrtc)
533
- throw this.handleWebRTCNotInitialized();
534
- return this.webrtc.removeTrack(trackId);
535
- }
536
- /**
537
- * Sets track encoding that server should send to the client library.
538
- *
539
- * The encoding will be sent whenever it is available. If chosen encoding is temporarily unavailable, some other
540
- * encoding will be sent until chosen encoding becomes active again.
541
- *
542
- * @example
543
- * ```ts
544
- * webrtc.setTargetTrackEncoding(incomingTrackCtx.trackId, "l")
545
- * ```
546
- *
547
- * @param {string} trackId - Id of track
548
- * @param {Encoding} encoding - Encoding to receive
549
- */
550
- setTargetTrackEncoding(trackId, encoding) {
551
- if (!this.webrtc)
552
- throw this.handleWebRTCNotInitialized();
553
- return this.webrtc.setTargetTrackEncoding(trackId, encoding);
554
- }
555
- /**
556
- * Enables track encoding so that it will be sent to the server.
557
- *
558
- * @example
559
- * ```ts
560
- * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
561
- * webrtc.disableTrackEncoding(trackId, "l");
562
- * // wait some time
563
- * webrtc.enableTrackEncoding(trackId, "l");
564
- * ```
565
- *
566
- * @param {string} trackId - Id of track
567
- * @param {Encoding} encoding - Encoding that will be enabled
568
- */
569
- enableTrackEncoding(trackId, encoding) {
570
- if (!this.webrtc)
571
- throw this.handleWebRTCNotInitialized();
572
- return this.webrtc.enableTrackEncoding(trackId, encoding);
573
- }
574
- /**
575
- * Disables track encoding so that it will be no longer sent to the server.
576
- *
577
- * @example
578
- * ```ts
579
- * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
580
- * webrtc.disableTrackEncoding(trackId, "l");
581
- * ```
582
- *
583
- * @param {string} trackId - Id of track
584
- * @param {rackEncoding} encoding - Encoding that will be disabled
585
- */
586
- disableTrackEncoding(trackId, encoding) {
587
- if (!this.webrtc)
588
- throw this.handleWebRTCNotInitialized();
589
- return this.webrtc.disableTrackEncoding(trackId, encoding);
590
- }
591
- /**
592
- * Updates the metadata for the current peer.
593
- *
594
- * @param peerMetadata - Data about this peer that other peers will receive upon joining.
595
- *
596
- * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.peerUpdated} will
597
- * be emitted for other peers in the room.
598
- */
599
- updatePeerMetadata = (peerMetadata) => {
600
- if (!this.webrtc)
601
- throw this.handleWebRTCNotInitialized();
602
- this.webrtc.updateEndpointMetadata(peerMetadata);
603
- };
604
- /**
605
- * Updates the metadata for a specific track.
606
- *
607
- * @param trackId - TrackId (generated in addTrack) of audio or video track.
608
- * @param trackMetadata - Data about this track that other peers will receive upon joining.
609
- *
610
- * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.trackUpdated} will
611
- * be emitted for other peers in the room.
612
- */
613
- updateTrackMetadata = (trackId, trackMetadata) => {
614
- if (!this.webrtc)
615
- throw this.handleWebRTCNotInitialized();
616
- this.webrtc.updateTrackMetadata(trackId, trackMetadata);
617
- };
618
- isReconnecting() {
619
- return this.reconnectManager.isReconnecting();
620
- }
621
- /**
622
- * Leaves the room. This function should be called when user leaves the room in a clean way e.g. by clicking a
623
- * dedicated, custom button `disconnect`. As a result there will be generated one more media event that should be sent
624
- * to the RTC Engine. Thanks to it each other peer will be notified that peer left in {@link MessageEvents.peerLeft},
625
- */
626
- leave = () => {
627
- if (!this.webrtc)
628
- throw this.handleWebRTCNotInitialized();
629
- this.webrtc.disconnect();
630
- };
631
- // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
632
- isOpen(websocket) {
633
- return websocket?.readyState === 1;
634
- }
635
- /**
636
- * Disconnect from the room, and close the websocket connection. Tries to leave the room gracefully, but if it fails,
637
- * it will close the websocket anyway.
638
- *
639
- * @example
640
- * ```typescript
641
- * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
642
- *
643
- * client.connect({ ... });
644
- *
645
- * client.disconnect();
646
- * ```
647
- */
648
- disconnect() {
649
- try {
650
- this.webrtc?.removeAllListeners();
651
- this.webrtc?.disconnect();
652
- this.webrtc?.cleanUp();
653
- }
654
- catch (e) {
655
- console.warn(e);
656
- }
657
- this.removeEventListeners?.();
658
- this.removeEventListeners = null;
659
- if (this.isOpen(this.websocket || null)) {
660
- this.websocket?.close();
661
- }
662
- this.websocket = null;
663
- this.webrtc = null;
664
- this.emit('disconnected');
665
- }
666
- cleanup() {
667
- this.reconnectManager.cleanup();
668
- }
669
- }
@@ -1,3 +0,0 @@
1
- export declare const AUTH_ERROR_REASONS: readonly ["missing token", "invalid token", "expired token", "room not found", "peer not found"];
2
- export type AuthErrorReason = (typeof AUTH_ERROR_REASONS)[number];
3
- export declare const isAuthError: (error: string) => error is AuthErrorReason;
package/dist/src/auth.js DELETED
@@ -1,8 +0,0 @@
1
- export const AUTH_ERROR_REASONS = [
2
- 'missing token',
3
- 'invalid token',
4
- 'expired token',
5
- 'room not found',
6
- 'peer not found',
7
- ];
8
- export const isAuthError = (error) => AUTH_ERROR_REASONS.includes(error);
@@ -1,2 +0,0 @@
1
- import type { FishjamClient } from './FishjamClient';
2
- export declare function connectEventsHandler<P, T>(fishjamClient: FishjamClient<P, T>): Promise<void>;