@ermis-network/ermis-chat-sdk 1.0.9 → 2.0.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.
Files changed (54) hide show
  1. package/README.md +330 -0
  2. package/bin/init-call.js +9 -0
  3. package/dist/encryption/index.browser.cjs +13045 -0
  4. package/dist/encryption/index.browser.cjs.map +1 -0
  5. package/dist/encryption/index.browser.mjs +12959 -0
  6. package/dist/encryption/index.browser.mjs.map +1 -0
  7. package/dist/encryption/index.cjs +13045 -0
  8. package/dist/encryption/index.cjs.map +1 -0
  9. package/dist/encryption/index.d.mts +3 -0
  10. package/dist/encryption/index.d.ts +3 -0
  11. package/dist/encryption/index.mjs +12959 -0
  12. package/dist/encryption/index.mjs.map +1 -0
  13. package/dist/index-CcvHIY5q.d.mts +4988 -0
  14. package/dist/index-CcvHIY5q.d.ts +4988 -0
  15. package/dist/index.browser.cjs +20399 -6823
  16. package/dist/index.browser.cjs.map +1 -1
  17. package/dist/index.browser.full-bundle.min.js +20 -18
  18. package/dist/index.browser.full-bundle.min.js.map +1 -1
  19. package/dist/index.browser.mjs +20315 -6790
  20. package/dist/index.browser.mjs.map +1 -1
  21. package/dist/index.cjs +20400 -6824
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.mts +167 -1356
  24. package/dist/index.d.ts +167 -1356
  25. package/dist/index.mjs +20312 -6787
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/wasm_worker.worker.mjs +1600 -0
  28. package/dist/wasm_worker.worker.mjs.map +1 -0
  29. package/package.json +22 -7
  30. package/public/e2ee-media-stream-worker.js +627 -0
  31. package/public/ermis_call_node_wasm_bg.wasm +0 -0
  32. package/public/openmls_wasm_bg.wasm +0 -0
  33. package/src/attachment_utils.ts +0 -148
  34. package/src/auth.ts +0 -352
  35. package/src/channel.ts +0 -1806
  36. package/src/channel_state.ts +0 -607
  37. package/src/client.ts +0 -1617
  38. package/src/client_state.ts +0 -55
  39. package/src/connection.ts +0 -587
  40. package/src/ermis_call_node.ts +0 -978
  41. package/src/errors.ts +0 -60
  42. package/src/events.ts +0 -46
  43. package/src/hevc_decoder_config.ts +0 -305
  44. package/src/index.ts +0 -16
  45. package/src/media_stream_receiver.ts +0 -525
  46. package/src/media_stream_sender.ts +0 -400
  47. package/src/shims/empty.ts +0 -1
  48. package/src/signal_message.ts +0 -146
  49. package/src/system_message.ts +0 -117
  50. package/src/token_manager.ts +0 -48
  51. package/src/types.ts +0 -581
  52. package/src/utils.ts +0 -534
  53. package/src/wasm/ermis_call_node_wasm.d.ts +0 -154
  54. package/src/wasm/ermis_call_node_wasm.js +0 -1498
@@ -1,55 +0,0 @@
1
- import { UserResponse, ExtendableGenerics, DefaultGenerics } from './types';
2
-
3
- /**
4
- * ClientState - A container class for the client state.
5
- */
6
- export class ClientState<ErmisChatGenerics extends ExtendableGenerics = DefaultGenerics> {
7
- users: {
8
- [key: string]: UserResponse<ErmisChatGenerics>;
9
- };
10
- userChannelReferences: { [key: string]: { [key: string]: boolean } };
11
- constructor() {
12
- // show the status for a certain user...
13
- // ie online, offline etc
14
- this.users = {};
15
- // store which channels contain references to the specified user...
16
- this.userChannelReferences = {};
17
- }
18
-
19
- updateUsers(users: UserResponse<ErmisChatGenerics>[]) {
20
- for (const user of users) {
21
- this.updateUser(user);
22
- }
23
- }
24
-
25
- updateUser(user?: UserResponse<ErmisChatGenerics>) {
26
- if (user != null) {
27
- if (this.users[user.id]) {
28
- // Update existing user's fields, because the user is updated from 2 diffferent servers
29
- const updatedUser = { ...this.users[user.id], ...user };
30
- this.users[user.id] = updatedUser;
31
- } else {
32
- // Add new user
33
- this.users[user.id] = user;
34
- }
35
- }
36
- }
37
-
38
- updateUserReference(user: UserResponse<ErmisChatGenerics>, channelID: string) {
39
- if (user == null) {
40
- return;
41
- }
42
- // dont update user here
43
- // this.updateUser(user);
44
- if (!this.userChannelReferences[user.id]) {
45
- this.userChannelReferences[user.id] = {};
46
- }
47
- this.userChannelReferences[user.id][channelID] = true;
48
- }
49
-
50
- deleteAllChannelReference(channelID: string) {
51
- for (const userID in this.userChannelReferences) {
52
- delete this.userChannelReferences[userID][channelID];
53
- }
54
- }
55
- }
package/src/connection.ts DELETED
@@ -1,587 +0,0 @@
1
- import WebSocket from 'isomorphic-ws';
2
- import {
3
- chatCodes,
4
- sleep,
5
- retryInterval,
6
- randomId,
7
- removeConnectionEventListeners,
8
- addConnectionEventListeners,
9
- } from './utils';
10
-
11
- import { ConnectAPIResponse, ConnectionOpen, ExtendableGenerics, DefaultGenerics, UR, LogLevel } from './types';
12
- import { ErmisChat } from './client';
13
-
14
- // Type guards to check WebSocket error type
15
- const isCloseEvent = (res: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent): res is WebSocket.CloseEvent =>
16
- (res as WebSocket.CloseEvent).code !== undefined;
17
-
18
- const isErrorEvent = (res: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent): res is WebSocket.ErrorEvent =>
19
- (res as WebSocket.ErrorEvent).error !== undefined;
20
-
21
- /**
22
- * StableWSConnection - A WS connection that reconnects upon failure.
23
- * - the browser will sometimes report that you're online or offline
24
- * - the WS connection can break and fail (there is a 30s health check)
25
- * - sometimes your WS connection will seem to work while the user is in fact offline
26
- * - to speed up online/offline detection you can use the window.addEventListener('offline');
27
- *
28
- * There are 4 ways in which a connection can become unhealthy:
29
- * - websocket.onerror is called
30
- * - websocket.onclose is called
31
- * - the health check fails and no event is received for ~40 seconds
32
- * - the browser indicates the connection is now offline
33
- *
34
- * There are 2 assumptions we make about the server:
35
- * - state can be recovered by querying the channel again
36
- * - if the servers fails to publish a message to the client, the WS connection is destroyed
37
- */
38
- export class StableWSConnection<ErmisChatGenerics extends ExtendableGenerics = DefaultGenerics> {
39
- // global from constructor
40
- client: ErmisChat<ErmisChatGenerics>;
41
-
42
- // local vars
43
-
44
- connectionOpen?: ConnectAPIResponse<ErmisChatGenerics>;
45
- consecutiveFailures: number;
46
- pingInterval: number;
47
- healthCheckTimeoutRef?: NodeJS.Timeout;
48
- isConnecting: boolean;
49
- isDisconnected: boolean;
50
- isHealthy: boolean;
51
- isResolved?: boolean;
52
- lastEvent: Date | null;
53
- connectionCheckTimeout: number;
54
- connectionCheckTimeoutRef?: NodeJS.Timeout;
55
- rejectPromise?: (
56
- reason?: Error & { code?: string | number; isWSFailure?: boolean; StatusCode?: string | number },
57
- ) => void;
58
- requestID: string | undefined;
59
- resolvePromise?: (value: ConnectionOpen<ErmisChatGenerics>) => void;
60
- totalFailures: number;
61
- ws?: WebSocket;
62
- wsID: number;
63
-
64
- constructor({ client }: { client: ErmisChat<ErmisChatGenerics> }) {
65
- /** ErmisChat client */
66
- this.client = client;
67
- /** consecutive failures influence the duration of the timeout */
68
- this.consecutiveFailures = 0;
69
- /** keep track of the total number of failures */
70
- this.totalFailures = 0;
71
- /** We only make 1 attempt to reconnect at the same time.. */
72
- this.isConnecting = false;
73
- /** To avoid reconnect if client is disconnected */
74
- this.isDisconnected = false;
75
- /** Boolean that indicates if the connection promise is resolved */
76
- this.isResolved = false;
77
- /** Boolean that indicates if we have a working connection to the server */
78
- this.isHealthy = false;
79
- /** Incremented when a new WS connection is made */
80
- this.wsID = 1;
81
- /** Store the last event time for health checks */
82
- this.lastEvent = null;
83
- /** Send a health check message every 25 seconds */
84
- this.pingInterval = 25 * 1000;
85
- this.connectionCheckTimeout = this.pingInterval + 10 * 1000;
86
-
87
- addConnectionEventListeners(this.onlineStatusChanged);
88
- }
89
-
90
- _log(msg: string, extra: UR = {}, level: LogLevel = 'info') {
91
- this.client.logger(level, 'connection:' + msg, { tags: ['connection'], ...extra });
92
- }
93
-
94
- setClient(client: ErmisChat<ErmisChatGenerics>) {
95
- this.client = client;
96
- }
97
-
98
- async connect(timeout = 15000) {
99
- if (this.isConnecting) {
100
- throw Error(`You've called connect twice, can only attempt 1 connection at the time`);
101
- }
102
-
103
- this.isDisconnected = false;
104
-
105
- try {
106
- const healthCheck = await this._connect();
107
- this.consecutiveFailures = 0;
108
-
109
- this._log(`connect() - Established ws connection with healthcheck: ${healthCheck}`);
110
- } catch (error: any) {
111
- this.isHealthy = false;
112
- this.consecutiveFailures += 1;
113
-
114
- if (error.code === chatCodes.TOKEN_EXPIRED) {
115
- this._log('connect() - WS failure due to expired token');
116
- } else if (!error.isWSFailure) {
117
- // API rejected the connection and we should not retry
118
- throw new Error(
119
- JSON.stringify({
120
- code: error.code,
121
- StatusCode: error.StatusCode,
122
- message: error.message,
123
- isWSFailure: error.isWSFailure,
124
- }),
125
- );
126
- }
127
- }
128
-
129
- return await this._waitForHealthy(timeout);
130
- }
131
-
132
- /**
133
- * _waitForHealthy polls the promise connection to see if its resolved until it times out
134
- * the default 15s timeout allows between 2~3 tries
135
- * @param timeout duration(ms)
136
- */
137
- async _waitForHealthy(timeout = 15000) {
138
- return Promise.race([
139
- (async () => {
140
- const interval = 50; // ms
141
- for (let i = 0; i <= timeout; i += interval) {
142
- try {
143
- return await this.connectionOpen;
144
- } catch (error: any) {
145
- if (i === timeout) {
146
- throw new Error(
147
- JSON.stringify({
148
- code: error.code,
149
- StatusCode: error.StatusCode,
150
- message: error.message,
151
- isWSFailure: error.isWSFailure,
152
- }),
153
- );
154
- }
155
- await sleep(interval);
156
- }
157
- }
158
- })(),
159
- (async () => {
160
- await sleep(timeout);
161
- this.isConnecting = false;
162
- throw new Error(
163
- JSON.stringify({
164
- code: '',
165
- StatusCode: '',
166
- message: 'initial WS connection could not be established',
167
- isWSFailure: true,
168
- }),
169
- );
170
- })(),
171
- ]);
172
- }
173
-
174
- /**
175
- * Builds and returns the url for websocket.
176
- * @private
177
- * @returns url string
178
- */
179
- _buildUrl = () => {
180
- const qs = encodeURIComponent(this.client._buildWSPayload(this.requestID));
181
- const token = this.client.tokenManager.getToken();
182
-
183
- let rawURL = `${this.client.wsBaseURL}/connect?json=${qs}&api_key=${
184
- this.client.apiKey
185
- }&authorization=${token}&stream-auth-type=${this.client.getAuthType()}&X-Stream-Client=${this.client.getUserAgent()}`;
186
- rawURL = encodeURI(rawURL);
187
- return rawURL;
188
- };
189
-
190
- /**
191
- * disconnect - Disconnect the connection and doesn't recover...
192
- *
193
- */
194
- disconnect(timeout?: number) {
195
- this._log(`disconnect() - Closing the websocket connection for wsID ${this.wsID}`);
196
-
197
- this.wsID += 1;
198
- this.isConnecting = false;
199
- this.isDisconnected = true;
200
-
201
- // start by removing all the listeners
202
- if (this.healthCheckTimeoutRef) {
203
- clearInterval(this.healthCheckTimeoutRef);
204
- }
205
- if (this.connectionCheckTimeoutRef) {
206
- clearInterval(this.connectionCheckTimeoutRef);
207
- }
208
-
209
- removeConnectionEventListeners(this.onlineStatusChanged);
210
-
211
- this.isHealthy = false;
212
-
213
- // remove ws handlers...
214
- if (this.ws && this.ws.removeAllListeners) {
215
- this.ws.removeAllListeners();
216
- }
217
-
218
- let isClosedPromise: Promise<void>;
219
- // and finally close...
220
- // Assigning to local here because we will remove it from this before the
221
- // promise resolves.
222
- const { ws } = this;
223
- if (ws && ws.close && ws.readyState === ws.OPEN) {
224
- isClosedPromise = new Promise((resolve) => {
225
- const onclose = (event: WebSocket.CloseEvent) => {
226
- this._log(`disconnect() - resolving isClosedPromise ${event ? 'with' : 'without'} close frame`, { event });
227
- resolve();
228
- };
229
-
230
- ws.onclose = onclose;
231
- // In case we don't receive close frame websocket server in time,
232
- // lets not wait for more than 1 seconds.
233
- setTimeout(onclose, timeout != null ? timeout : 1000);
234
- });
235
-
236
- this._log(`disconnect() - Manually closed connection by calling client.disconnect()`);
237
-
238
- ws.close(chatCodes.WS_CLOSED_SUCCESS, 'Manually closed connection by calling client.disconnect()');
239
- } else {
240
- this._log(`disconnect() - ws connection doesn't exist or it is already closed.`);
241
- isClosedPromise = Promise.resolve();
242
- }
243
-
244
- delete this.ws;
245
-
246
- return isClosedPromise;
247
- }
248
-
249
- async _connect() {
250
- if (this.isConnecting) return; // simply ignore _connect if it's currently trying to connect
251
- this.isConnecting = true;
252
- this.requestID = randomId();
253
-
254
- let isTokenReady = false;
255
- try {
256
- this._log(`_connect() - waiting for token`);
257
- await this.client.tokenManager.tokenReady();
258
- isTokenReady = true;
259
- } catch (e) {
260
- // token provider has failed before, so try again
261
- }
262
-
263
- try {
264
- this._setupConnectionPromise();
265
- const wsURL = this._buildUrl();
266
- this._log(`_connect() - Connecting to ${wsURL}`, { wsURL, requestID: this.requestID });
267
- this.ws = new WebSocket(wsURL);
268
- this.ws.onopen = this.onopen.bind(this, this.wsID);
269
- this.ws.onclose = this.onclose.bind(this, this.wsID);
270
- this.ws.onerror = this.onerror.bind(this, this.wsID);
271
- this.ws.onmessage = this.onmessage.bind(this, this.wsID);
272
- const response = await this.connectionOpen;
273
- this.isConnecting = false;
274
-
275
- if (response) {
276
- return response;
277
- }
278
- } catch (err: any) {
279
- this.isConnecting = false;
280
- this._log(`_connect() - Error - `, err);
281
-
282
- throw err;
283
- }
284
- }
285
-
286
- /**
287
- * _reconnect - Retry the connection to WS endpoint
288
- *
289
- * @param {{ interval?: number; refreshToken?: boolean }} options Following options are available
290
- *
291
- * - `interval` {int} number of ms that function should wait before reconnecting
292
- * - `refreshToken` {boolean} reload/refresh user token be refreshed before attempting reconnection.
293
- */
294
- async _reconnect(options: { interval?: number; refreshToken?: boolean } = {}): Promise<void> {
295
- this._log('_reconnect() - Initiating the reconnect');
296
-
297
- // only allow 1 connection at the time
298
- if (this.isConnecting || this.isHealthy) {
299
- this._log('_reconnect() - Abort (1) since already connecting or healthy');
300
- return;
301
- }
302
-
303
- // reconnect in case of on error or on close
304
- // also reconnect if the health check cycle fails
305
- let interval = options.interval;
306
- if (!interval) {
307
- interval = retryInterval(this.consecutiveFailures);
308
- }
309
- // reconnect, or try again after a little while...
310
- await sleep(interval);
311
-
312
- // Check once again if by some other call to _reconnect is active or connection is
313
- // already restored, then no need to proceed.
314
- if (this.isConnecting || this.isHealthy) {
315
- this._log('_reconnect() - Abort (2) since already connecting or healthy');
316
- return;
317
- }
318
-
319
- if (this.isDisconnected) {
320
- this._log('_reconnect() - Abort (3) since disconnect() is called');
321
- return;
322
- }
323
-
324
- this._log('_reconnect() - Destroying current WS connection');
325
-
326
- // cleanup the old connection
327
- this._destroyCurrentWSConnection();
328
-
329
- try {
330
- await this._connect();
331
- this._log('_reconnect() - Waiting for recoverCallBack');
332
- await this.client.recoverState();
333
- this._log('_reconnect() - Finished recoverCallBack');
334
-
335
- this.consecutiveFailures = 0;
336
- } catch (error: any) {
337
- this.isHealthy = false;
338
- this.consecutiveFailures += 1;
339
-
340
- // reconnect on WS failures, don't reconnect if there is a code bug
341
- if (error.isWSFailure) {
342
- this._log('_reconnect() - WS failure, so going to try to reconnect');
343
-
344
- this._reconnect();
345
- }
346
- }
347
- this._log('_reconnect() - == END ==');
348
- }
349
-
350
- /**
351
- * onlineStatusChanged - this function is called when the browser connects or disconnects from the internet.
352
- *
353
- * @param {Event} event Event with type online or offline
354
- *
355
- */
356
- onlineStatusChanged = (event: Event) => {
357
- if (event.type === 'offline') {
358
- // mark the connection as down
359
- this._log('onlineStatusChanged() - Status changing to offline');
360
- this._setHealth(false);
361
- } else if (event.type === 'online') {
362
- // retry right now...
363
- // We check this.isHealthy, not sure if it's always
364
- // smart to create a new WS connection if the old one is still up and running.
365
- // it's possible we didn't miss any messages, so this process is just expensive and not needed.
366
- this._log(`onlineStatusChanged() - Status changing to online. isHealthy: ${this.isHealthy}`);
367
- if (!this.isHealthy) {
368
- this._reconnect({ interval: 10 });
369
- }
370
- }
371
- };
372
-
373
- onopen = (wsID: number) => {
374
- if (this.wsID !== wsID) return;
375
-
376
- this._log('onopen() - onopen callback', { wsID });
377
- };
378
-
379
- onmessage = (wsID: number, event: WebSocket.MessageEvent) => {
380
- if (this.wsID !== wsID) return;
381
-
382
- this._log('onmessage() - onmessage callback', { event, wsID });
383
- const data = typeof event.data === 'string' ? JSON.parse(event.data) : null;
384
-
385
- // we wait till the first message before we consider the connection open..
386
- // the reason for this is that auth errors and similar errors trigger a ws.onopen and immediately
387
- // after that a ws.onclose..
388
- if (!this.isResolved && data) {
389
- this.isResolved = true;
390
- if (data.error) {
391
- this.rejectPromise?.(this._errorFromWSEvent(data, false));
392
- return;
393
- }
394
-
395
- this.resolvePromise?.(data);
396
- this._setHealth(true);
397
- }
398
-
399
- // trigger the event..
400
- this.lastEvent = new Date();
401
-
402
- if (data && data.type === 'health.check') {
403
- this.scheduleNextPing();
404
- }
405
-
406
- this.client.handleEvent(event);
407
- this.scheduleConnectionCheck();
408
- };
409
-
410
- onclose = (wsID: number, event: WebSocket.CloseEvent) => {
411
- if (this.wsID !== wsID) return;
412
-
413
- this._log('onclose() - onclose callback - ' + event.code, { event, wsID });
414
-
415
- if (event.code === chatCodes.WS_CLOSED_SUCCESS) {
416
- // this is a permanent error raised by stream..
417
- // usually caused by invalid auth details
418
- const error = new Error(`WS connection reject with error ${event.reason}`) as Error & WebSocket.CloseEvent;
419
-
420
- error.reason = event.reason;
421
- error.code = event.code;
422
- error.wasClean = event.wasClean;
423
- error.target = event.target;
424
-
425
- this.rejectPromise?.(error);
426
- this._log(`onclose() - WS connection reject with error ${event.reason}`, { event });
427
- } else {
428
- this.consecutiveFailures += 1;
429
- this.totalFailures += 1;
430
- this._setHealth(false);
431
- this.isConnecting = false;
432
-
433
- this.rejectPromise?.(this._errorFromWSEvent(event));
434
-
435
- this._log(`onclose() - WS connection closed. Calling reconnect ...`, { event });
436
-
437
- // reconnect if its an abnormal failure
438
- this._reconnect();
439
- }
440
- };
441
-
442
- onerror = (wsID: number, event: WebSocket.ErrorEvent) => {
443
- if (this.wsID !== wsID) return;
444
-
445
- this.consecutiveFailures += 1;
446
- this.totalFailures += 1;
447
- this._setHealth(false);
448
- this.isConnecting = false;
449
-
450
- this.rejectPromise?.(this._errorFromWSEvent(event));
451
- this._log(`onerror() - WS connection resulted into error`, { event });
452
-
453
- this._reconnect();
454
- };
455
-
456
- /**
457
- * _setHealth - Sets the connection to healthy or unhealthy.
458
- * Broadcasts an event in case the connection status changed.
459
- *
460
- * @param {boolean} healthy boolean indicating if the connection is healthy or not
461
- *
462
- */
463
- _setHealth = (healthy: boolean) => {
464
- if (healthy === this.isHealthy) return;
465
-
466
- this.isHealthy = healthy;
467
-
468
- if (this.isHealthy) {
469
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
470
- return;
471
- }
472
-
473
- // we're offline, wait few seconds and fire and event if still offline
474
- setTimeout(() => {
475
- if (this.isHealthy) return;
476
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
477
- }, 1000);
478
- };
479
-
480
- /**
481
- * _errorFromWSEvent - Creates an error object for the WS event
482
- *
483
- */
484
- _errorFromWSEvent = (event: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent, isWSFailure = true) => {
485
- let code;
486
- let statusCode;
487
- let message;
488
- if (isCloseEvent(event)) {
489
- code = event.code;
490
- statusCode = 'unknown';
491
- message = event.reason;
492
- }
493
-
494
- if (isErrorEvent(event)) {
495
- code = event.error.code;
496
- statusCode = event.error.StatusCode;
497
- message = event.error.message;
498
- }
499
-
500
- // Keeping this `warn` level log, to avoid cluttering of error logs from ws failures.
501
- this._log(`_errorFromWSEvent() - WS failed with code ${code}`, { event }, 'warn');
502
-
503
- const error = new Error(`WS failed with code ${code} and reason - ${message}`) as Error & {
504
- code?: string | number;
505
- isWSFailure?: boolean;
506
- StatusCode?: string | number;
507
- };
508
- error.code = code;
509
- /**
510
- * StatusCode does not exist on any event types but has been left
511
- * as is to preserve JS functionality during the TS implementation
512
- */
513
- error.StatusCode = statusCode;
514
- error.isWSFailure = isWSFailure;
515
- return error;
516
- };
517
-
518
- /**
519
- * _destroyCurrentWSConnection - Removes the current WS connection
520
- *
521
- */
522
- _destroyCurrentWSConnection() {
523
- // increment the ID, meaning we will ignore all messages from the old
524
- // ws connection from now on.
525
- this.wsID += 1;
526
-
527
- try {
528
- this?.ws?.removeAllListeners();
529
- this?.ws?.close();
530
- } catch (e) {
531
- // we don't care
532
- }
533
- }
534
-
535
- /**
536
- * _setupPromise - sets up the this.connectOpen promise
537
- */
538
- _setupConnectionPromise = () => {
539
- this.isResolved = false;
540
- /** a promise that is resolved once ws.open is called */
541
- this.connectionOpen = new Promise<ConnectionOpen<ErmisChatGenerics>>((resolve, reject) => {
542
- this.resolvePromise = resolve;
543
- this.rejectPromise = reject;
544
- });
545
- };
546
-
547
- /**
548
- * Schedules a next health check ping for websocket.
549
- */
550
- scheduleNextPing = () => {
551
- if (this.healthCheckTimeoutRef) {
552
- clearTimeout(this.healthCheckTimeoutRef);
553
- }
554
-
555
- // 30 seconds is the recommended interval (messenger uses this)
556
- this.healthCheckTimeoutRef = setTimeout(() => {
557
- // send the healthcheck.., server replies with a health check event
558
- const data = [{ type: 'health.check', client_id: this.client.clientID }];
559
- // try to send on the connection
560
- try {
561
- this.ws?.send(JSON.stringify(data));
562
- } catch (e) {
563
- // error will already be detected elsewhere
564
- }
565
- }, this.pingInterval);
566
- };
567
-
568
- /**
569
- * scheduleConnectionCheck - schedules a check for time difference between last received event and now.
570
- * If the difference is more than 35 seconds, it means our health check logic has failed and websocket needs
571
- * to be reconnected.
572
- */
573
- scheduleConnectionCheck = () => {
574
- if (this.connectionCheckTimeoutRef) {
575
- clearTimeout(this.connectionCheckTimeoutRef);
576
- }
577
-
578
- this.connectionCheckTimeoutRef = setTimeout(() => {
579
- const now = new Date();
580
- if (this.lastEvent && now.getTime() - this.lastEvent.getTime() > this.connectionCheckTimeout) {
581
- this._log('scheduleConnectionCheck - going to reconnect');
582
- this._setHealth(false);
583
- this._reconnect();
584
- }
585
- }, this.connectionCheckTimeout);
586
- };
587
- }