@everymatrix/nuts-inbox-widget 1.45.8 → 1.45.9

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.
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const index = require('./index-ae4a5047.js');
6
+ const socket_ioClient = require('socket.io-client');
6
7
 
7
8
  const DEFAULT_LANGUAGE = 'en';
8
9
  const SUPPORTED_LANGUAGES = ['hu', 'en'];
@@ -57,3863 +58,6 @@ const getTranslations = (url) => {
57
58
  });
58
59
  };
59
60
 
60
- const PACKET_TYPES = Object.create(null); // no Map = no polyfill
61
- PACKET_TYPES["open"] = "0";
62
- PACKET_TYPES["close"] = "1";
63
- PACKET_TYPES["ping"] = "2";
64
- PACKET_TYPES["pong"] = "3";
65
- PACKET_TYPES["message"] = "4";
66
- PACKET_TYPES["upgrade"] = "5";
67
- PACKET_TYPES["noop"] = "6";
68
- const PACKET_TYPES_REVERSE = Object.create(null);
69
- Object.keys(PACKET_TYPES).forEach((key) => {
70
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
71
- });
72
- const ERROR_PACKET = { type: "error", data: "parser error" };
73
-
74
- const withNativeBlob$1 = typeof Blob === "function" ||
75
- (typeof Blob !== "undefined" &&
76
- Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
77
- const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
78
- // ArrayBuffer.isView method is not defined in IE10
79
- const isView$1 = (obj) => {
80
- return typeof ArrayBuffer.isView === "function"
81
- ? ArrayBuffer.isView(obj)
82
- : obj && obj.buffer instanceof ArrayBuffer;
83
- };
84
- const encodePacket = ({ type, data }, supportsBinary, callback) => {
85
- if (withNativeBlob$1 && data instanceof Blob) {
86
- if (supportsBinary) {
87
- return callback(data);
88
- }
89
- else {
90
- return encodeBlobAsBase64(data, callback);
91
- }
92
- }
93
- else if (withNativeArrayBuffer$2 &&
94
- (data instanceof ArrayBuffer || isView$1(data))) {
95
- if (supportsBinary) {
96
- return callback(data);
97
- }
98
- else {
99
- return encodeBlobAsBase64(new Blob([data]), callback);
100
- }
101
- }
102
- // plain string
103
- return callback(PACKET_TYPES[type] + (data || ""));
104
- };
105
- const encodeBlobAsBase64 = (data, callback) => {
106
- const fileReader = new FileReader();
107
- fileReader.onload = function () {
108
- const content = fileReader.result.split(",")[1];
109
- callback("b" + (content || ""));
110
- };
111
- return fileReader.readAsDataURL(data);
112
- };
113
- function toArray(data) {
114
- if (data instanceof Uint8Array) {
115
- return data;
116
- }
117
- else if (data instanceof ArrayBuffer) {
118
- return new Uint8Array(data);
119
- }
120
- else {
121
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
122
- }
123
- }
124
- let TEXT_ENCODER;
125
- function encodePacketToBinary(packet, callback) {
126
- if (withNativeBlob$1 && packet.data instanceof Blob) {
127
- return packet.data.arrayBuffer().then(toArray).then(callback);
128
- }
129
- else if (withNativeArrayBuffer$2 &&
130
- (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
131
- return callback(toArray(packet.data));
132
- }
133
- encodePacket(packet, false, (encoded) => {
134
- if (!TEXT_ENCODER) {
135
- TEXT_ENCODER = new TextEncoder();
136
- }
137
- callback(TEXT_ENCODER.encode(encoded));
138
- });
139
- }
140
-
141
- // imported from https://github.com/socketio/base64-arraybuffer
142
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
143
- // Use a lookup table to find the index.
144
- const lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
145
- for (let i = 0; i < chars.length; i++) {
146
- lookup$1[chars.charCodeAt(i)] = i;
147
- }
148
- const decode$1 = (base64) => {
149
- let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
150
- if (base64[base64.length - 1] === '=') {
151
- bufferLength--;
152
- if (base64[base64.length - 2] === '=') {
153
- bufferLength--;
154
- }
155
- }
156
- const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
157
- for (i = 0; i < len; i += 4) {
158
- encoded1 = lookup$1[base64.charCodeAt(i)];
159
- encoded2 = lookup$1[base64.charCodeAt(i + 1)];
160
- encoded3 = lookup$1[base64.charCodeAt(i + 2)];
161
- encoded4 = lookup$1[base64.charCodeAt(i + 3)];
162
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
163
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
164
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
165
- }
166
- return arraybuffer;
167
- };
168
-
169
- const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
170
- const decodePacket = (encodedPacket, binaryType) => {
171
- if (typeof encodedPacket !== "string") {
172
- return {
173
- type: "message",
174
- data: mapBinary(encodedPacket, binaryType),
175
- };
176
- }
177
- const type = encodedPacket.charAt(0);
178
- if (type === "b") {
179
- return {
180
- type: "message",
181
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
182
- };
183
- }
184
- const packetType = PACKET_TYPES_REVERSE[type];
185
- if (!packetType) {
186
- return ERROR_PACKET;
187
- }
188
- return encodedPacket.length > 1
189
- ? {
190
- type: PACKET_TYPES_REVERSE[type],
191
- data: encodedPacket.substring(1),
192
- }
193
- : {
194
- type: PACKET_TYPES_REVERSE[type],
195
- };
196
- };
197
- const decodeBase64Packet = (data, binaryType) => {
198
- if (withNativeArrayBuffer$1) {
199
- const decoded = decode$1(data);
200
- return mapBinary(decoded, binaryType);
201
- }
202
- else {
203
- return { base64: true, data }; // fallback for old browsers
204
- }
205
- };
206
- const mapBinary = (data, binaryType) => {
207
- switch (binaryType) {
208
- case "blob":
209
- if (data instanceof Blob) {
210
- // from WebSocket + binaryType "blob"
211
- return data;
212
- }
213
- else {
214
- // from HTTP long-polling or WebTransport
215
- return new Blob([data]);
216
- }
217
- case "arraybuffer":
218
- default:
219
- if (data instanceof ArrayBuffer) {
220
- // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
221
- return data;
222
- }
223
- else {
224
- // from WebTransport (Uint8Array)
225
- return data.buffer;
226
- }
227
- }
228
- };
229
-
230
- const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
231
- const encodePayload = (packets, callback) => {
232
- // some packets may be added to the array while encoding, so the initial length must be saved
233
- const length = packets.length;
234
- const encodedPackets = new Array(length);
235
- let count = 0;
236
- packets.forEach((packet, i) => {
237
- // force base64 encoding for binary packets
238
- encodePacket(packet, false, (encodedPacket) => {
239
- encodedPackets[i] = encodedPacket;
240
- if (++count === length) {
241
- callback(encodedPackets.join(SEPARATOR));
242
- }
243
- });
244
- });
245
- };
246
- const decodePayload = (encodedPayload, binaryType) => {
247
- const encodedPackets = encodedPayload.split(SEPARATOR);
248
- const packets = [];
249
- for (let i = 0; i < encodedPackets.length; i++) {
250
- const decodedPacket = decodePacket(encodedPackets[i], binaryType);
251
- packets.push(decodedPacket);
252
- if (decodedPacket.type === "error") {
253
- break;
254
- }
255
- }
256
- return packets;
257
- };
258
- function createPacketEncoderStream() {
259
- return new TransformStream({
260
- transform(packet, controller) {
261
- encodePacketToBinary(packet, (encodedPacket) => {
262
- const payloadLength = encodedPacket.length;
263
- let header;
264
- // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
265
- if (payloadLength < 126) {
266
- header = new Uint8Array(1);
267
- new DataView(header.buffer).setUint8(0, payloadLength);
268
- }
269
- else if (payloadLength < 65536) {
270
- header = new Uint8Array(3);
271
- const view = new DataView(header.buffer);
272
- view.setUint8(0, 126);
273
- view.setUint16(1, payloadLength);
274
- }
275
- else {
276
- header = new Uint8Array(9);
277
- const view = new DataView(header.buffer);
278
- view.setUint8(0, 127);
279
- view.setBigUint64(1, BigInt(payloadLength));
280
- }
281
- // first bit indicates whether the payload is plain text (0) or binary (1)
282
- if (packet.data && typeof packet.data !== "string") {
283
- header[0] |= 0x80;
284
- }
285
- controller.enqueue(header);
286
- controller.enqueue(encodedPacket);
287
- });
288
- },
289
- });
290
- }
291
- let TEXT_DECODER;
292
- function totalLength(chunks) {
293
- return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
294
- }
295
- function concatChunks(chunks, size) {
296
- if (chunks[0].length === size) {
297
- return chunks.shift();
298
- }
299
- const buffer = new Uint8Array(size);
300
- let j = 0;
301
- for (let i = 0; i < size; i++) {
302
- buffer[i] = chunks[0][j++];
303
- if (j === chunks[0].length) {
304
- chunks.shift();
305
- j = 0;
306
- }
307
- }
308
- if (chunks.length && j < chunks[0].length) {
309
- chunks[0] = chunks[0].slice(j);
310
- }
311
- return buffer;
312
- }
313
- function createPacketDecoderStream(maxPayload, binaryType) {
314
- if (!TEXT_DECODER) {
315
- TEXT_DECODER = new TextDecoder();
316
- }
317
- const chunks = [];
318
- let state = 0 /* State.READ_HEADER */;
319
- let expectedLength = -1;
320
- let isBinary = false;
321
- return new TransformStream({
322
- transform(chunk, controller) {
323
- chunks.push(chunk);
324
- while (true) {
325
- if (state === 0 /* State.READ_HEADER */) {
326
- if (totalLength(chunks) < 1) {
327
- break;
328
- }
329
- const header = concatChunks(chunks, 1);
330
- isBinary = (header[0] & 0x80) === 0x80;
331
- expectedLength = header[0] & 0x7f;
332
- if (expectedLength < 126) {
333
- state = 3 /* State.READ_PAYLOAD */;
334
- }
335
- else if (expectedLength === 126) {
336
- state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
337
- }
338
- else {
339
- state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
340
- }
341
- }
342
- else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
343
- if (totalLength(chunks) < 2) {
344
- break;
345
- }
346
- const headerArray = concatChunks(chunks, 2);
347
- expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
348
- state = 3 /* State.READ_PAYLOAD */;
349
- }
350
- else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
351
- if (totalLength(chunks) < 8) {
352
- break;
353
- }
354
- const headerArray = concatChunks(chunks, 8);
355
- const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
356
- const n = view.getUint32(0);
357
- if (n > Math.pow(2, 53 - 32) - 1) {
358
- // the maximum safe integer in JavaScript is 2^53 - 1
359
- controller.enqueue(ERROR_PACKET);
360
- break;
361
- }
362
- expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
363
- state = 3 /* State.READ_PAYLOAD */;
364
- }
365
- else {
366
- if (totalLength(chunks) < expectedLength) {
367
- break;
368
- }
369
- const data = concatChunks(chunks, expectedLength);
370
- controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
371
- state = 0 /* State.READ_HEADER */;
372
- }
373
- if (expectedLength === 0 || expectedLength > maxPayload) {
374
- controller.enqueue(ERROR_PACKET);
375
- break;
376
- }
377
- }
378
- },
379
- });
380
- }
381
- const protocol$1 = 4;
382
-
383
- /**
384
- * Initialize a new `Emitter`.
385
- *
386
- * @api public
387
- */
388
-
389
- function Emitter(obj) {
390
- if (obj) return mixin(obj);
391
- }
392
-
393
- /**
394
- * Mixin the emitter properties.
395
- *
396
- * @param {Object} obj
397
- * @return {Object}
398
- * @api private
399
- */
400
-
401
- function mixin(obj) {
402
- for (var key in Emitter.prototype) {
403
- obj[key] = Emitter.prototype[key];
404
- }
405
- return obj;
406
- }
407
-
408
- /**
409
- * Listen on the given `event` with `fn`.
410
- *
411
- * @param {String} event
412
- * @param {Function} fn
413
- * @return {Emitter}
414
- * @api public
415
- */
416
-
417
- Emitter.prototype.on =
418
- Emitter.prototype.addEventListener = function(event, fn){
419
- this._callbacks = this._callbacks || {};
420
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
421
- .push(fn);
422
- return this;
423
- };
424
-
425
- /**
426
- * Adds an `event` listener that will be invoked a single
427
- * time then automatically removed.
428
- *
429
- * @param {String} event
430
- * @param {Function} fn
431
- * @return {Emitter}
432
- * @api public
433
- */
434
-
435
- Emitter.prototype.once = function(event, fn){
436
- function on() {
437
- this.off(event, on);
438
- fn.apply(this, arguments);
439
- }
440
-
441
- on.fn = fn;
442
- this.on(event, on);
443
- return this;
444
- };
445
-
446
- /**
447
- * Remove the given callback for `event` or all
448
- * registered callbacks.
449
- *
450
- * @param {String} event
451
- * @param {Function} fn
452
- * @return {Emitter}
453
- * @api public
454
- */
455
-
456
- Emitter.prototype.off =
457
- Emitter.prototype.removeListener =
458
- Emitter.prototype.removeAllListeners =
459
- Emitter.prototype.removeEventListener = function(event, fn){
460
- this._callbacks = this._callbacks || {};
461
-
462
- // all
463
- if (0 == arguments.length) {
464
- this._callbacks = {};
465
- return this;
466
- }
467
-
468
- // specific event
469
- var callbacks = this._callbacks['$' + event];
470
- if (!callbacks) return this;
471
-
472
- // remove all handlers
473
- if (1 == arguments.length) {
474
- delete this._callbacks['$' + event];
475
- return this;
476
- }
477
-
478
- // remove specific handler
479
- var cb;
480
- for (var i = 0; i < callbacks.length; i++) {
481
- cb = callbacks[i];
482
- if (cb === fn || cb.fn === fn) {
483
- callbacks.splice(i, 1);
484
- break;
485
- }
486
- }
487
-
488
- // Remove event specific arrays for event types that no
489
- // one is subscribed for to avoid memory leak.
490
- if (callbacks.length === 0) {
491
- delete this._callbacks['$' + event];
492
- }
493
-
494
- return this;
495
- };
496
-
497
- /**
498
- * Emit `event` with the given args.
499
- *
500
- * @param {String} event
501
- * @param {Mixed} ...
502
- * @return {Emitter}
503
- */
504
-
505
- Emitter.prototype.emit = function(event){
506
- this._callbacks = this._callbacks || {};
507
-
508
- var args = new Array(arguments.length - 1)
509
- , callbacks = this._callbacks['$' + event];
510
-
511
- for (var i = 1; i < arguments.length; i++) {
512
- args[i - 1] = arguments[i];
513
- }
514
-
515
- if (callbacks) {
516
- callbacks = callbacks.slice(0);
517
- for (var i = 0, len = callbacks.length; i < len; ++i) {
518
- callbacks[i].apply(this, args);
519
- }
520
- }
521
-
522
- return this;
523
- };
524
-
525
- // alias used for reserved events (protected method)
526
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
527
-
528
- /**
529
- * Return array of callbacks for `event`.
530
- *
531
- * @param {String} event
532
- * @return {Array}
533
- * @api public
534
- */
535
-
536
- Emitter.prototype.listeners = function(event){
537
- this._callbacks = this._callbacks || {};
538
- return this._callbacks['$' + event] || [];
539
- };
540
-
541
- /**
542
- * Check if this emitter has `event` handlers.
543
- *
544
- * @param {String} event
545
- * @return {Boolean}
546
- * @api public
547
- */
548
-
549
- Emitter.prototype.hasListeners = function(event){
550
- return !! this.listeners(event).length;
551
- };
552
-
553
- const globalThisShim = (() => {
554
- if (typeof self !== "undefined") {
555
- return self;
556
- }
557
- else if (typeof window !== "undefined") {
558
- return window;
559
- }
560
- else {
561
- return Function("return this")();
562
- }
563
- })();
564
-
565
- function pick(obj, ...attr) {
566
- return attr.reduce((acc, k) => {
567
- if (obj.hasOwnProperty(k)) {
568
- acc[k] = obj[k];
569
- }
570
- return acc;
571
- }, {});
572
- }
573
- // Keep a reference to the real timeout functions so they can be used when overridden
574
- const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
575
- const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
576
- function installTimerFunctions(obj, opts) {
577
- if (opts.useNativeTimers) {
578
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
579
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
580
- }
581
- else {
582
- obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
583
- obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
584
- }
585
- }
586
- // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
587
- const BASE64_OVERHEAD = 1.33;
588
- // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
589
- function byteLength(obj) {
590
- if (typeof obj === "string") {
591
- return utf8Length(obj);
592
- }
593
- // arraybuffer or blob
594
- return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
595
- }
596
- function utf8Length(str) {
597
- let c = 0, length = 0;
598
- for (let i = 0, l = str.length; i < l; i++) {
599
- c = str.charCodeAt(i);
600
- if (c < 0x80) {
601
- length += 1;
602
- }
603
- else if (c < 0x800) {
604
- length += 2;
605
- }
606
- else if (c < 0xd800 || c >= 0xe000) {
607
- length += 3;
608
- }
609
- else {
610
- i++;
611
- length += 4;
612
- }
613
- }
614
- return length;
615
- }
616
-
617
- // imported from https://github.com/galkn/querystring
618
- /**
619
- * Compiles a querystring
620
- * Returns string representation of the object
621
- *
622
- * @param {Object}
623
- * @api private
624
- */
625
- function encode$1(obj) {
626
- let str = '';
627
- for (let i in obj) {
628
- if (obj.hasOwnProperty(i)) {
629
- if (str.length)
630
- str += '&';
631
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
632
- }
633
- }
634
- return str;
635
- }
636
- /**
637
- * Parses a simple querystring into an object
638
- *
639
- * @param {String} qs
640
- * @api private
641
- */
642
- function decode(qs) {
643
- let qry = {};
644
- let pairs = qs.split('&');
645
- for (let i = 0, l = pairs.length; i < l; i++) {
646
- let pair = pairs[i].split('=');
647
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
648
- }
649
- return qry;
650
- }
651
-
652
- class TransportError extends Error {
653
- constructor(reason, description, context) {
654
- super(reason);
655
- this.description = description;
656
- this.context = context;
657
- this.type = "TransportError";
658
- }
659
- }
660
- class Transport extends Emitter {
661
- /**
662
- * Transport abstract constructor.
663
- *
664
- * @param {Object} opts - options
665
- * @protected
666
- */
667
- constructor(opts) {
668
- super();
669
- this.writable = false;
670
- installTimerFunctions(this, opts);
671
- this.opts = opts;
672
- this.query = opts.query;
673
- this.socket = opts.socket;
674
- }
675
- /**
676
- * Emits an error.
677
- *
678
- * @param {String} reason
679
- * @param description
680
- * @param context - the error context
681
- * @return {Transport} for chaining
682
- * @protected
683
- */
684
- onError(reason, description, context) {
685
- super.emitReserved("error", new TransportError(reason, description, context));
686
- return this;
687
- }
688
- /**
689
- * Opens the transport.
690
- */
691
- open() {
692
- this.readyState = "opening";
693
- this.doOpen();
694
- return this;
695
- }
696
- /**
697
- * Closes the transport.
698
- */
699
- close() {
700
- if (this.readyState === "opening" || this.readyState === "open") {
701
- this.doClose();
702
- this.onClose();
703
- }
704
- return this;
705
- }
706
- /**
707
- * Sends multiple packets.
708
- *
709
- * @param {Array} packets
710
- */
711
- send(packets) {
712
- if (this.readyState === "open") {
713
- this.write(packets);
714
- }
715
- }
716
- /**
717
- * Called upon open
718
- *
719
- * @protected
720
- */
721
- onOpen() {
722
- this.readyState = "open";
723
- this.writable = true;
724
- super.emitReserved("open");
725
- }
726
- /**
727
- * Called with data.
728
- *
729
- * @param {String} data
730
- * @protected
731
- */
732
- onData(data) {
733
- const packet = decodePacket(data, this.socket.binaryType);
734
- this.onPacket(packet);
735
- }
736
- /**
737
- * Called with a decoded packet.
738
- *
739
- * @protected
740
- */
741
- onPacket(packet) {
742
- super.emitReserved("packet", packet);
743
- }
744
- /**
745
- * Called upon close.
746
- *
747
- * @protected
748
- */
749
- onClose(details) {
750
- this.readyState = "closed";
751
- super.emitReserved("close", details);
752
- }
753
- /**
754
- * Pauses the transport, in order not to lose packets during an upgrade.
755
- *
756
- * @param onPause
757
- */
758
- pause(onPause) { }
759
- createUri(schema, query = {}) {
760
- return (schema +
761
- "://" +
762
- this._hostname() +
763
- this._port() +
764
- this.opts.path +
765
- this._query(query));
766
- }
767
- _hostname() {
768
- const hostname = this.opts.hostname;
769
- return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
770
- }
771
- _port() {
772
- if (this.opts.port &&
773
- ((this.opts.secure && Number(this.opts.port !== 443)) ||
774
- (!this.opts.secure && Number(this.opts.port) !== 80))) {
775
- return ":" + this.opts.port;
776
- }
777
- else {
778
- return "";
779
- }
780
- }
781
- _query(query) {
782
- const encodedQuery = encode$1(query);
783
- return encodedQuery.length ? "?" + encodedQuery : "";
784
- }
785
- }
786
-
787
- // imported from https://github.com/unshiftio/yeast
788
- const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};
789
- let seed = 0, i = 0, prev;
790
- /**
791
- * Return a string representing the specified number.
792
- *
793
- * @param {Number} num The number to convert.
794
- * @returns {String} The string representation of the number.
795
- * @api public
796
- */
797
- function encode(num) {
798
- let encoded = '';
799
- do {
800
- encoded = alphabet[num % length] + encoded;
801
- num = Math.floor(num / length);
802
- } while (num > 0);
803
- return encoded;
804
- }
805
- /**
806
- * Yeast: A tiny growing id generator.
807
- *
808
- * @returns {String} A unique id.
809
- * @api public
810
- */
811
- function yeast() {
812
- const now = encode(+new Date());
813
- if (now !== prev)
814
- return seed = 0, prev = now;
815
- return now + '.' + encode(seed++);
816
- }
817
- //
818
- // Map each character to its index.
819
- //
820
- for (; i < length; i++)
821
- map[alphabet[i]] = i;
822
-
823
- // imported from https://github.com/component/has-cors
824
- let value = false;
825
- try {
826
- value = typeof XMLHttpRequest !== 'undefined' &&
827
- 'withCredentials' in new XMLHttpRequest();
828
- }
829
- catch (err) {
830
- // if XMLHttp support is disabled in IE then it will throw
831
- // when trying to create
832
- }
833
- const hasCORS = value;
834
-
835
- // browser shim for xmlhttprequest module
836
- function XHR(opts) {
837
- const xdomain = opts.xdomain;
838
- // XMLHttpRequest can be disabled on IE
839
- try {
840
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
841
- return new XMLHttpRequest();
842
- }
843
- }
844
- catch (e) { }
845
- if (!xdomain) {
846
- try {
847
- return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
848
- }
849
- catch (e) { }
850
- }
851
- }
852
- function createCookieJar() { }
853
-
854
- function empty() { }
855
- const hasXHR2 = (function () {
856
- const xhr = new XHR({
857
- xdomain: false,
858
- });
859
- return null != xhr.responseType;
860
- })();
861
- class Polling extends Transport {
862
- /**
863
- * XHR Polling constructor.
864
- *
865
- * @param {Object} opts
866
- * @package
867
- */
868
- constructor(opts) {
869
- super(opts);
870
- this.polling = false;
871
- if (typeof location !== "undefined") {
872
- const isSSL = "https:" === location.protocol;
873
- let port = location.port;
874
- // some user agents have empty `location.port`
875
- if (!port) {
876
- port = isSSL ? "443" : "80";
877
- }
878
- this.xd =
879
- (typeof location !== "undefined" &&
880
- opts.hostname !== location.hostname) ||
881
- port !== opts.port;
882
- }
883
- /**
884
- * XHR supports binary
885
- */
886
- const forceBase64 = opts && opts.forceBase64;
887
- this.supportsBinary = hasXHR2 && !forceBase64;
888
- if (this.opts.withCredentials) {
889
- this.cookieJar = createCookieJar();
890
- }
891
- }
892
- get name() {
893
- return "polling";
894
- }
895
- /**
896
- * Opens the socket (triggers polling). We write a PING message to determine
897
- * when the transport is open.
898
- *
899
- * @protected
900
- */
901
- doOpen() {
902
- this.poll();
903
- }
904
- /**
905
- * Pauses polling.
906
- *
907
- * @param {Function} onPause - callback upon buffers are flushed and transport is paused
908
- * @package
909
- */
910
- pause(onPause) {
911
- this.readyState = "pausing";
912
- const pause = () => {
913
- this.readyState = "paused";
914
- onPause();
915
- };
916
- if (this.polling || !this.writable) {
917
- let total = 0;
918
- if (this.polling) {
919
- total++;
920
- this.once("pollComplete", function () {
921
- --total || pause();
922
- });
923
- }
924
- if (!this.writable) {
925
- total++;
926
- this.once("drain", function () {
927
- --total || pause();
928
- });
929
- }
930
- }
931
- else {
932
- pause();
933
- }
934
- }
935
- /**
936
- * Starts polling cycle.
937
- *
938
- * @private
939
- */
940
- poll() {
941
- this.polling = true;
942
- this.doPoll();
943
- this.emitReserved("poll");
944
- }
945
- /**
946
- * Overloads onData to detect payloads.
947
- *
948
- * @protected
949
- */
950
- onData(data) {
951
- const callback = (packet) => {
952
- // if its the first message we consider the transport open
953
- if ("opening" === this.readyState && packet.type === "open") {
954
- this.onOpen();
955
- }
956
- // if its a close packet, we close the ongoing requests
957
- if ("close" === packet.type) {
958
- this.onClose({ description: "transport closed by the server" });
959
- return false;
960
- }
961
- // otherwise bypass onData and handle the message
962
- this.onPacket(packet);
963
- };
964
- // decode payload
965
- decodePayload(data, this.socket.binaryType).forEach(callback);
966
- // if an event did not trigger closing
967
- if ("closed" !== this.readyState) {
968
- // if we got data we're not polling
969
- this.polling = false;
970
- this.emitReserved("pollComplete");
971
- if ("open" === this.readyState) {
972
- this.poll();
973
- }
974
- }
975
- }
976
- /**
977
- * For polling, send a close packet.
978
- *
979
- * @protected
980
- */
981
- doClose() {
982
- const close = () => {
983
- this.write([{ type: "close" }]);
984
- };
985
- if ("open" === this.readyState) {
986
- close();
987
- }
988
- else {
989
- // in case we're trying to close while
990
- // handshaking is in progress (GH-164)
991
- this.once("open", close);
992
- }
993
- }
994
- /**
995
- * Writes a packets payload.
996
- *
997
- * @param {Array} packets - data packets
998
- * @protected
999
- */
1000
- write(packets) {
1001
- this.writable = false;
1002
- encodePayload(packets, (data) => {
1003
- this.doWrite(data, () => {
1004
- this.writable = true;
1005
- this.emitReserved("drain");
1006
- });
1007
- });
1008
- }
1009
- /**
1010
- * Generates uri for connection.
1011
- *
1012
- * @private
1013
- */
1014
- uri() {
1015
- const schema = this.opts.secure ? "https" : "http";
1016
- const query = this.query || {};
1017
- // cache busting is forced
1018
- if (false !== this.opts.timestampRequests) {
1019
- query[this.opts.timestampParam] = yeast();
1020
- }
1021
- if (!this.supportsBinary && !query.sid) {
1022
- query.b64 = 1;
1023
- }
1024
- return this.createUri(schema, query);
1025
- }
1026
- /**
1027
- * Creates a request.
1028
- *
1029
- * @param {String} method
1030
- * @private
1031
- */
1032
- request(opts = {}) {
1033
- Object.assign(opts, { xd: this.xd, cookieJar: this.cookieJar }, this.opts);
1034
- return new Request(this.uri(), opts);
1035
- }
1036
- /**
1037
- * Sends data.
1038
- *
1039
- * @param {String} data to send.
1040
- * @param {Function} called upon flush.
1041
- * @private
1042
- */
1043
- doWrite(data, fn) {
1044
- const req = this.request({
1045
- method: "POST",
1046
- data: data,
1047
- });
1048
- req.on("success", fn);
1049
- req.on("error", (xhrStatus, context) => {
1050
- this.onError("xhr post error", xhrStatus, context);
1051
- });
1052
- }
1053
- /**
1054
- * Starts a poll cycle.
1055
- *
1056
- * @private
1057
- */
1058
- doPoll() {
1059
- const req = this.request();
1060
- req.on("data", this.onData.bind(this));
1061
- req.on("error", (xhrStatus, context) => {
1062
- this.onError("xhr poll error", xhrStatus, context);
1063
- });
1064
- this.pollXhr = req;
1065
- }
1066
- }
1067
- class Request extends Emitter {
1068
- /**
1069
- * Request constructor
1070
- *
1071
- * @param {Object} options
1072
- * @package
1073
- */
1074
- constructor(uri, opts) {
1075
- super();
1076
- installTimerFunctions(this, opts);
1077
- this.opts = opts;
1078
- this.method = opts.method || "GET";
1079
- this.uri = uri;
1080
- this.data = undefined !== opts.data ? opts.data : null;
1081
- this.create();
1082
- }
1083
- /**
1084
- * Creates the XHR object and sends the request.
1085
- *
1086
- * @private
1087
- */
1088
- create() {
1089
- var _a;
1090
- const opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
1091
- opts.xdomain = !!this.opts.xd;
1092
- const xhr = (this.xhr = new XHR(opts));
1093
- try {
1094
- xhr.open(this.method, this.uri, true);
1095
- try {
1096
- if (this.opts.extraHeaders) {
1097
- xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
1098
- for (let i in this.opts.extraHeaders) {
1099
- if (this.opts.extraHeaders.hasOwnProperty(i)) {
1100
- xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
1101
- }
1102
- }
1103
- }
1104
- }
1105
- catch (e) { }
1106
- if ("POST" === this.method) {
1107
- try {
1108
- xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
1109
- }
1110
- catch (e) { }
1111
- }
1112
- try {
1113
- xhr.setRequestHeader("Accept", "*/*");
1114
- }
1115
- catch (e) { }
1116
- (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
1117
- // ie6 check
1118
- if ("withCredentials" in xhr) {
1119
- xhr.withCredentials = this.opts.withCredentials;
1120
- }
1121
- if (this.opts.requestTimeout) {
1122
- xhr.timeout = this.opts.requestTimeout;
1123
- }
1124
- xhr.onreadystatechange = () => {
1125
- var _a;
1126
- if (xhr.readyState === 3) {
1127
- (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr);
1128
- }
1129
- if (4 !== xhr.readyState)
1130
- return;
1131
- if (200 === xhr.status || 1223 === xhr.status) {
1132
- this.onLoad();
1133
- }
1134
- else {
1135
- // make sure the `error` event handler that's user-set
1136
- // does not throw in the same tick and gets caught here
1137
- this.setTimeoutFn(() => {
1138
- this.onError(typeof xhr.status === "number" ? xhr.status : 0);
1139
- }, 0);
1140
- }
1141
- };
1142
- xhr.send(this.data);
1143
- }
1144
- catch (e) {
1145
- // Need to defer since .create() is called directly from the constructor
1146
- // and thus the 'error' event can only be only bound *after* this exception
1147
- // occurs. Therefore, also, we cannot throw here at all.
1148
- this.setTimeoutFn(() => {
1149
- this.onError(e);
1150
- }, 0);
1151
- return;
1152
- }
1153
- if (typeof document !== "undefined") {
1154
- this.index = Request.requestsCount++;
1155
- Request.requests[this.index] = this;
1156
- }
1157
- }
1158
- /**
1159
- * Called upon error.
1160
- *
1161
- * @private
1162
- */
1163
- onError(err) {
1164
- this.emitReserved("error", err, this.xhr);
1165
- this.cleanup(true);
1166
- }
1167
- /**
1168
- * Cleans up house.
1169
- *
1170
- * @private
1171
- */
1172
- cleanup(fromError) {
1173
- if ("undefined" === typeof this.xhr || null === this.xhr) {
1174
- return;
1175
- }
1176
- this.xhr.onreadystatechange = empty;
1177
- if (fromError) {
1178
- try {
1179
- this.xhr.abort();
1180
- }
1181
- catch (e) { }
1182
- }
1183
- if (typeof document !== "undefined") {
1184
- delete Request.requests[this.index];
1185
- }
1186
- this.xhr = null;
1187
- }
1188
- /**
1189
- * Called upon load.
1190
- *
1191
- * @private
1192
- */
1193
- onLoad() {
1194
- const data = this.xhr.responseText;
1195
- if (data !== null) {
1196
- this.emitReserved("data", data);
1197
- this.emitReserved("success");
1198
- this.cleanup();
1199
- }
1200
- }
1201
- /**
1202
- * Aborts the request.
1203
- *
1204
- * @package
1205
- */
1206
- abort() {
1207
- this.cleanup();
1208
- }
1209
- }
1210
- Request.requestsCount = 0;
1211
- Request.requests = {};
1212
- /**
1213
- * Aborts pending requests when unloading the window. This is needed to prevent
1214
- * memory leaks (e.g. when using IE) and to ensure that no spurious error is
1215
- * emitted.
1216
- */
1217
- if (typeof document !== "undefined") {
1218
- // @ts-ignore
1219
- if (typeof attachEvent === "function") {
1220
- // @ts-ignore
1221
- attachEvent("onunload", unloadHandler);
1222
- }
1223
- else if (typeof addEventListener === "function") {
1224
- const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
1225
- addEventListener(terminationEvent, unloadHandler, false);
1226
- }
1227
- }
1228
- function unloadHandler() {
1229
- for (let i in Request.requests) {
1230
- if (Request.requests.hasOwnProperty(i)) {
1231
- Request.requests[i].abort();
1232
- }
1233
- }
1234
- }
1235
-
1236
- const nextTick = (() => {
1237
- const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
1238
- if (isPromiseAvailable) {
1239
- return (cb) => Promise.resolve().then(cb);
1240
- }
1241
- else {
1242
- return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
1243
- }
1244
- })();
1245
- const WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1246
- const defaultBinaryType = "arraybuffer";
1247
-
1248
- // detect ReactNative environment
1249
- const isReactNative = typeof navigator !== "undefined" &&
1250
- typeof navigator.product === "string" &&
1251
- navigator.product.toLowerCase() === "reactnative";
1252
- class WS extends Transport {
1253
- /**
1254
- * WebSocket transport constructor.
1255
- *
1256
- * @param {Object} opts - connection options
1257
- * @protected
1258
- */
1259
- constructor(opts) {
1260
- super(opts);
1261
- this.supportsBinary = !opts.forceBase64;
1262
- }
1263
- get name() {
1264
- return "websocket";
1265
- }
1266
- doOpen() {
1267
- if (!this.check()) {
1268
- // let probe timeout
1269
- return;
1270
- }
1271
- const uri = this.uri();
1272
- const protocols = this.opts.protocols;
1273
- // React Native only supports the 'headers' option, and will print a warning if anything else is passed
1274
- const opts = isReactNative
1275
- ? {}
1276
- : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1277
- if (this.opts.extraHeaders) {
1278
- opts.headers = this.opts.extraHeaders;
1279
- }
1280
- try {
1281
- this.ws =
1282
- !isReactNative
1283
- ? protocols
1284
- ? new WebSocket(uri, protocols)
1285
- : new WebSocket(uri)
1286
- : new WebSocket(uri, protocols, opts);
1287
- }
1288
- catch (err) {
1289
- return this.emitReserved("error", err);
1290
- }
1291
- this.ws.binaryType = this.socket.binaryType;
1292
- this.addEventListeners();
1293
- }
1294
- /**
1295
- * Adds event listeners to the socket
1296
- *
1297
- * @private
1298
- */
1299
- addEventListeners() {
1300
- this.ws.onopen = () => {
1301
- if (this.opts.autoUnref) {
1302
- this.ws._socket.unref();
1303
- }
1304
- this.onOpen();
1305
- };
1306
- this.ws.onclose = (closeEvent) => this.onClose({
1307
- description: "websocket connection closed",
1308
- context: closeEvent,
1309
- });
1310
- this.ws.onmessage = (ev) => this.onData(ev.data);
1311
- this.ws.onerror = (e) => this.onError("websocket error", e);
1312
- }
1313
- write(packets) {
1314
- this.writable = false;
1315
- // encodePacket efficient as it uses WS framing
1316
- // no need for encodePayload
1317
- for (let i = 0; i < packets.length; i++) {
1318
- const packet = packets[i];
1319
- const lastPacket = i === packets.length - 1;
1320
- encodePacket(packet, this.supportsBinary, (data) => {
1321
- // Sometimes the websocket has already been closed but the browser didn't
1322
- // have a chance of informing us about it yet, in that case send will
1323
- // throw an error
1324
- try {
1325
- {
1326
- // TypeError is thrown when passing the second argument on Safari
1327
- this.ws.send(data);
1328
- }
1329
- }
1330
- catch (e) {
1331
- }
1332
- if (lastPacket) {
1333
- // fake drain
1334
- // defer to next tick to allow Socket to clear writeBuffer
1335
- nextTick(() => {
1336
- this.writable = true;
1337
- this.emitReserved("drain");
1338
- }, this.setTimeoutFn);
1339
- }
1340
- });
1341
- }
1342
- }
1343
- doClose() {
1344
- if (typeof this.ws !== "undefined") {
1345
- this.ws.close();
1346
- this.ws = null;
1347
- }
1348
- }
1349
- /**
1350
- * Generates uri for connection.
1351
- *
1352
- * @private
1353
- */
1354
- uri() {
1355
- const schema = this.opts.secure ? "wss" : "ws";
1356
- const query = this.query || {};
1357
- // append timestamp to URI
1358
- if (this.opts.timestampRequests) {
1359
- query[this.opts.timestampParam] = yeast();
1360
- }
1361
- // communicate binary support capabilities
1362
- if (!this.supportsBinary) {
1363
- query.b64 = 1;
1364
- }
1365
- return this.createUri(schema, query);
1366
- }
1367
- /**
1368
- * Feature detection for WebSocket.
1369
- *
1370
- * @return {Boolean} whether this transport is available.
1371
- * @private
1372
- */
1373
- check() {
1374
- return !!WebSocket;
1375
- }
1376
- }
1377
-
1378
- class WT extends Transport {
1379
- get name() {
1380
- return "webtransport";
1381
- }
1382
- doOpen() {
1383
- // @ts-ignore
1384
- if (typeof WebTransport !== "function") {
1385
- return;
1386
- }
1387
- // @ts-ignore
1388
- this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1389
- this.transport.closed
1390
- .then(() => {
1391
- this.onClose();
1392
- })
1393
- .catch((err) => {
1394
- this.onError("webtransport error", err);
1395
- });
1396
- // note: we could have used async/await, but that would require some additional polyfills
1397
- this.transport.ready.then(() => {
1398
- this.transport.createBidirectionalStream().then((stream) => {
1399
- const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1400
- const reader = stream.readable.pipeThrough(decoderStream).getReader();
1401
- const encoderStream = createPacketEncoderStream();
1402
- encoderStream.readable.pipeTo(stream.writable);
1403
- this.writer = encoderStream.writable.getWriter();
1404
- const read = () => {
1405
- reader
1406
- .read()
1407
- .then(({ done, value }) => {
1408
- if (done) {
1409
- return;
1410
- }
1411
- this.onPacket(value);
1412
- read();
1413
- })
1414
- .catch((err) => {
1415
- });
1416
- };
1417
- read();
1418
- const packet = { type: "open" };
1419
- if (this.query.sid) {
1420
- packet.data = `{"sid":"${this.query.sid}"}`;
1421
- }
1422
- this.writer.write(packet).then(() => this.onOpen());
1423
- });
1424
- });
1425
- }
1426
- write(packets) {
1427
- this.writable = false;
1428
- for (let i = 0; i < packets.length; i++) {
1429
- const packet = packets[i];
1430
- const lastPacket = i === packets.length - 1;
1431
- this.writer.write(packet).then(() => {
1432
- if (lastPacket) {
1433
- nextTick(() => {
1434
- this.writable = true;
1435
- this.emitReserved("drain");
1436
- }, this.setTimeoutFn);
1437
- }
1438
- });
1439
- }
1440
- }
1441
- doClose() {
1442
- var _a;
1443
- (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close();
1444
- }
1445
- }
1446
-
1447
- const transports = {
1448
- websocket: WS,
1449
- webtransport: WT,
1450
- polling: Polling,
1451
- };
1452
-
1453
- // imported from https://github.com/galkn/parseuri
1454
- /**
1455
- * Parses a URI
1456
- *
1457
- * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
1458
- *
1459
- * See:
1460
- * - https://developer.mozilla.org/en-US/docs/Web/API/URL
1461
- * - https://caniuse.com/url
1462
- * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
1463
- *
1464
- * History of the parse() method:
1465
- * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
1466
- * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
1467
- * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
1468
- *
1469
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
1470
- * @api private
1471
- */
1472
- const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1473
- const parts = [
1474
- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
1475
- ];
1476
- function parse(str) {
1477
- if (str.length > 2000) {
1478
- throw "URI too long";
1479
- }
1480
- const src = str, b = str.indexOf('['), e = str.indexOf(']');
1481
- if (b != -1 && e != -1) {
1482
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
1483
- }
1484
- let m = re.exec(str || ''), uri = {}, i = 14;
1485
- while (i--) {
1486
- uri[parts[i]] = m[i] || '';
1487
- }
1488
- if (b != -1 && e != -1) {
1489
- uri.source = src;
1490
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
1491
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
1492
- uri.ipv6uri = true;
1493
- }
1494
- uri.pathNames = pathNames(uri, uri['path']);
1495
- uri.queryKey = queryKey(uri, uri['query']);
1496
- return uri;
1497
- }
1498
- function pathNames(obj, path) {
1499
- const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
1500
- if (path.slice(0, 1) == '/' || path.length === 0) {
1501
- names.splice(0, 1);
1502
- }
1503
- if (path.slice(-1) == '/') {
1504
- names.splice(names.length - 1, 1);
1505
- }
1506
- return names;
1507
- }
1508
- function queryKey(uri, query) {
1509
- const data = {};
1510
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
1511
- if ($1) {
1512
- data[$1] = $2;
1513
- }
1514
- });
1515
- return data;
1516
- }
1517
-
1518
- class Socket$1 extends Emitter {
1519
- /**
1520
- * Socket constructor.
1521
- *
1522
- * @param {String|Object} uri - uri or options
1523
- * @param {Object} opts - options
1524
- */
1525
- constructor(uri, opts = {}) {
1526
- super();
1527
- this.binaryType = defaultBinaryType;
1528
- this.writeBuffer = [];
1529
- if (uri && "object" === typeof uri) {
1530
- opts = uri;
1531
- uri = null;
1532
- }
1533
- if (uri) {
1534
- uri = parse(uri);
1535
- opts.hostname = uri.host;
1536
- opts.secure = uri.protocol === "https" || uri.protocol === "wss";
1537
- opts.port = uri.port;
1538
- if (uri.query)
1539
- opts.query = uri.query;
1540
- }
1541
- else if (opts.host) {
1542
- opts.hostname = parse(opts.host).host;
1543
- }
1544
- installTimerFunctions(this, opts);
1545
- this.secure =
1546
- null != opts.secure
1547
- ? opts.secure
1548
- : typeof location !== "undefined" && "https:" === location.protocol;
1549
- if (opts.hostname && !opts.port) {
1550
- // if no port is specified manually, use the protocol default
1551
- opts.port = this.secure ? "443" : "80";
1552
- }
1553
- this.hostname =
1554
- opts.hostname ||
1555
- (typeof location !== "undefined" ? location.hostname : "localhost");
1556
- this.port =
1557
- opts.port ||
1558
- (typeof location !== "undefined" && location.port
1559
- ? location.port
1560
- : this.secure
1561
- ? "443"
1562
- : "80");
1563
- this.transports = opts.transports || [
1564
- "polling",
1565
- "websocket",
1566
- "webtransport",
1567
- ];
1568
- this.writeBuffer = [];
1569
- this.prevBufferLen = 0;
1570
- this.opts = Object.assign({
1571
- path: "/engine.io",
1572
- agent: false,
1573
- withCredentials: false,
1574
- upgrade: true,
1575
- timestampParam: "t",
1576
- rememberUpgrade: false,
1577
- addTrailingSlash: true,
1578
- rejectUnauthorized: true,
1579
- perMessageDeflate: {
1580
- threshold: 1024,
1581
- },
1582
- transportOptions: {},
1583
- closeOnBeforeunload: false,
1584
- }, opts);
1585
- this.opts.path =
1586
- this.opts.path.replace(/\/$/, "") +
1587
- (this.opts.addTrailingSlash ? "/" : "");
1588
- if (typeof this.opts.query === "string") {
1589
- this.opts.query = decode(this.opts.query);
1590
- }
1591
- // set on handshake
1592
- this.id = null;
1593
- this.upgrades = null;
1594
- this.pingInterval = null;
1595
- this.pingTimeout = null;
1596
- // set on heartbeat
1597
- this.pingTimeoutTimer = null;
1598
- if (typeof addEventListener === "function") {
1599
- if (this.opts.closeOnBeforeunload) {
1600
- // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
1601
- // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
1602
- // closed/reloaded)
1603
- this.beforeunloadEventListener = () => {
1604
- if (this.transport) {
1605
- // silently close the transport
1606
- this.transport.removeAllListeners();
1607
- this.transport.close();
1608
- }
1609
- };
1610
- addEventListener("beforeunload", this.beforeunloadEventListener, false);
1611
- }
1612
- if (this.hostname !== "localhost") {
1613
- this.offlineEventListener = () => {
1614
- this.onClose("transport close", {
1615
- description: "network connection lost",
1616
- });
1617
- };
1618
- addEventListener("offline", this.offlineEventListener, false);
1619
- }
1620
- }
1621
- this.open();
1622
- }
1623
- /**
1624
- * Creates transport of the given type.
1625
- *
1626
- * @param {String} name - transport name
1627
- * @return {Transport}
1628
- * @private
1629
- */
1630
- createTransport(name) {
1631
- const query = Object.assign({}, this.opts.query);
1632
- // append engine.io protocol identifier
1633
- query.EIO = protocol$1;
1634
- // transport name
1635
- query.transport = name;
1636
- // session id if we already have one
1637
- if (this.id)
1638
- query.sid = this.id;
1639
- const opts = Object.assign({}, this.opts, {
1640
- query,
1641
- socket: this,
1642
- hostname: this.hostname,
1643
- secure: this.secure,
1644
- port: this.port,
1645
- }, this.opts.transportOptions[name]);
1646
- return new transports[name](opts);
1647
- }
1648
- /**
1649
- * Initializes transport to use and starts probe.
1650
- *
1651
- * @private
1652
- */
1653
- open() {
1654
- let transport;
1655
- if (this.opts.rememberUpgrade &&
1656
- Socket$1.priorWebsocketSuccess &&
1657
- this.transports.indexOf("websocket") !== -1) {
1658
- transport = "websocket";
1659
- }
1660
- else if (0 === this.transports.length) {
1661
- // Emit error on next tick so it can be listened to
1662
- this.setTimeoutFn(() => {
1663
- this.emitReserved("error", "No transports available");
1664
- }, 0);
1665
- return;
1666
- }
1667
- else {
1668
- transport = this.transports[0];
1669
- }
1670
- this.readyState = "opening";
1671
- // Retry with the next transport if the transport is disabled (jsonp: false)
1672
- try {
1673
- transport = this.createTransport(transport);
1674
- }
1675
- catch (e) {
1676
- this.transports.shift();
1677
- this.open();
1678
- return;
1679
- }
1680
- transport.open();
1681
- this.setTransport(transport);
1682
- }
1683
- /**
1684
- * Sets the current transport. Disables the existing one (if any).
1685
- *
1686
- * @private
1687
- */
1688
- setTransport(transport) {
1689
- if (this.transport) {
1690
- this.transport.removeAllListeners();
1691
- }
1692
- // set up transport
1693
- this.transport = transport;
1694
- // set up transport listeners
1695
- transport
1696
- .on("drain", this.onDrain.bind(this))
1697
- .on("packet", this.onPacket.bind(this))
1698
- .on("error", this.onError.bind(this))
1699
- .on("close", (reason) => this.onClose("transport close", reason));
1700
- }
1701
- /**
1702
- * Probes a transport.
1703
- *
1704
- * @param {String} name - transport name
1705
- * @private
1706
- */
1707
- probe(name) {
1708
- let transport = this.createTransport(name);
1709
- let failed = false;
1710
- Socket$1.priorWebsocketSuccess = false;
1711
- const onTransportOpen = () => {
1712
- if (failed)
1713
- return;
1714
- transport.send([{ type: "ping", data: "probe" }]);
1715
- transport.once("packet", (msg) => {
1716
- if (failed)
1717
- return;
1718
- if ("pong" === msg.type && "probe" === msg.data) {
1719
- this.upgrading = true;
1720
- this.emitReserved("upgrading", transport);
1721
- if (!transport)
1722
- return;
1723
- Socket$1.priorWebsocketSuccess = "websocket" === transport.name;
1724
- this.transport.pause(() => {
1725
- if (failed)
1726
- return;
1727
- if ("closed" === this.readyState)
1728
- return;
1729
- cleanup();
1730
- this.setTransport(transport);
1731
- transport.send([{ type: "upgrade" }]);
1732
- this.emitReserved("upgrade", transport);
1733
- transport = null;
1734
- this.upgrading = false;
1735
- this.flush();
1736
- });
1737
- }
1738
- else {
1739
- const err = new Error("probe error");
1740
- // @ts-ignore
1741
- err.transport = transport.name;
1742
- this.emitReserved("upgradeError", err);
1743
- }
1744
- });
1745
- };
1746
- function freezeTransport() {
1747
- if (failed)
1748
- return;
1749
- // Any callback called by transport should be ignored since now
1750
- failed = true;
1751
- cleanup();
1752
- transport.close();
1753
- transport = null;
1754
- }
1755
- // Handle any error that happens while probing
1756
- const onerror = (err) => {
1757
- const error = new Error("probe error: " + err);
1758
- // @ts-ignore
1759
- error.transport = transport.name;
1760
- freezeTransport();
1761
- this.emitReserved("upgradeError", error);
1762
- };
1763
- function onTransportClose() {
1764
- onerror("transport closed");
1765
- }
1766
- // When the socket is closed while we're probing
1767
- function onclose() {
1768
- onerror("socket closed");
1769
- }
1770
- // When the socket is upgraded while we're probing
1771
- function onupgrade(to) {
1772
- if (transport && to.name !== transport.name) {
1773
- freezeTransport();
1774
- }
1775
- }
1776
- // Remove all listeners on the transport and on self
1777
- const cleanup = () => {
1778
- transport.removeListener("open", onTransportOpen);
1779
- transport.removeListener("error", onerror);
1780
- transport.removeListener("close", onTransportClose);
1781
- this.off("close", onclose);
1782
- this.off("upgrading", onupgrade);
1783
- };
1784
- transport.once("open", onTransportOpen);
1785
- transport.once("error", onerror);
1786
- transport.once("close", onTransportClose);
1787
- this.once("close", onclose);
1788
- this.once("upgrading", onupgrade);
1789
- if (this.upgrades.indexOf("webtransport") !== -1 &&
1790
- name !== "webtransport") {
1791
- // favor WebTransport
1792
- this.setTimeoutFn(() => {
1793
- if (!failed) {
1794
- transport.open();
1795
- }
1796
- }, 200);
1797
- }
1798
- else {
1799
- transport.open();
1800
- }
1801
- }
1802
- /**
1803
- * Called when connection is deemed open.
1804
- *
1805
- * @private
1806
- */
1807
- onOpen() {
1808
- this.readyState = "open";
1809
- Socket$1.priorWebsocketSuccess = "websocket" === this.transport.name;
1810
- this.emitReserved("open");
1811
- this.flush();
1812
- // we check for `readyState` in case an `open`
1813
- // listener already closed the socket
1814
- if ("open" === this.readyState && this.opts.upgrade) {
1815
- let i = 0;
1816
- const l = this.upgrades.length;
1817
- for (; i < l; i++) {
1818
- this.probe(this.upgrades[i]);
1819
- }
1820
- }
1821
- }
1822
- /**
1823
- * Handles a packet.
1824
- *
1825
- * @private
1826
- */
1827
- onPacket(packet) {
1828
- if ("opening" === this.readyState ||
1829
- "open" === this.readyState ||
1830
- "closing" === this.readyState) {
1831
- this.emitReserved("packet", packet);
1832
- // Socket is live - any packet counts
1833
- this.emitReserved("heartbeat");
1834
- this.resetPingTimeout();
1835
- switch (packet.type) {
1836
- case "open":
1837
- this.onHandshake(JSON.parse(packet.data));
1838
- break;
1839
- case "ping":
1840
- this.sendPacket("pong");
1841
- this.emitReserved("ping");
1842
- this.emitReserved("pong");
1843
- break;
1844
- case "error":
1845
- const err = new Error("server error");
1846
- // @ts-ignore
1847
- err.code = packet.data;
1848
- this.onError(err);
1849
- break;
1850
- case "message":
1851
- this.emitReserved("data", packet.data);
1852
- this.emitReserved("message", packet.data);
1853
- break;
1854
- }
1855
- }
1856
- }
1857
- /**
1858
- * Called upon handshake completion.
1859
- *
1860
- * @param {Object} data - handshake obj
1861
- * @private
1862
- */
1863
- onHandshake(data) {
1864
- this.emitReserved("handshake", data);
1865
- this.id = data.sid;
1866
- this.transport.query.sid = data.sid;
1867
- this.upgrades = this.filterUpgrades(data.upgrades);
1868
- this.pingInterval = data.pingInterval;
1869
- this.pingTimeout = data.pingTimeout;
1870
- this.maxPayload = data.maxPayload;
1871
- this.onOpen();
1872
- // In case open handler closes socket
1873
- if ("closed" === this.readyState)
1874
- return;
1875
- this.resetPingTimeout();
1876
- }
1877
- /**
1878
- * Sets and resets ping timeout timer based on server pings.
1879
- *
1880
- * @private
1881
- */
1882
- resetPingTimeout() {
1883
- this.clearTimeoutFn(this.pingTimeoutTimer);
1884
- this.pingTimeoutTimer = this.setTimeoutFn(() => {
1885
- this.onClose("ping timeout");
1886
- }, this.pingInterval + this.pingTimeout);
1887
- if (this.opts.autoUnref) {
1888
- this.pingTimeoutTimer.unref();
1889
- }
1890
- }
1891
- /**
1892
- * Called on `drain` event
1893
- *
1894
- * @private
1895
- */
1896
- onDrain() {
1897
- this.writeBuffer.splice(0, this.prevBufferLen);
1898
- // setting prevBufferLen = 0 is very important
1899
- // for example, when upgrading, upgrade packet is sent over,
1900
- // and a nonzero prevBufferLen could cause problems on `drain`
1901
- this.prevBufferLen = 0;
1902
- if (0 === this.writeBuffer.length) {
1903
- this.emitReserved("drain");
1904
- }
1905
- else {
1906
- this.flush();
1907
- }
1908
- }
1909
- /**
1910
- * Flush write buffers.
1911
- *
1912
- * @private
1913
- */
1914
- flush() {
1915
- if ("closed" !== this.readyState &&
1916
- this.transport.writable &&
1917
- !this.upgrading &&
1918
- this.writeBuffer.length) {
1919
- const packets = this.getWritablePackets();
1920
- this.transport.send(packets);
1921
- // keep track of current length of writeBuffer
1922
- // splice writeBuffer and callbackBuffer on `drain`
1923
- this.prevBufferLen = packets.length;
1924
- this.emitReserved("flush");
1925
- }
1926
- }
1927
- /**
1928
- * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
1929
- * long-polling)
1930
- *
1931
- * @private
1932
- */
1933
- getWritablePackets() {
1934
- const shouldCheckPayloadSize = this.maxPayload &&
1935
- this.transport.name === "polling" &&
1936
- this.writeBuffer.length > 1;
1937
- if (!shouldCheckPayloadSize) {
1938
- return this.writeBuffer;
1939
- }
1940
- let payloadSize = 1; // first packet type
1941
- for (let i = 0; i < this.writeBuffer.length; i++) {
1942
- const data = this.writeBuffer[i].data;
1943
- if (data) {
1944
- payloadSize += byteLength(data);
1945
- }
1946
- if (i > 0 && payloadSize > this.maxPayload) {
1947
- return this.writeBuffer.slice(0, i);
1948
- }
1949
- payloadSize += 2; // separator + packet type
1950
- }
1951
- return this.writeBuffer;
1952
- }
1953
- /**
1954
- * Sends a message.
1955
- *
1956
- * @param {String} msg - message.
1957
- * @param {Object} options.
1958
- * @param {Function} callback function.
1959
- * @return {Socket} for chaining.
1960
- */
1961
- write(msg, options, fn) {
1962
- this.sendPacket("message", msg, options, fn);
1963
- return this;
1964
- }
1965
- send(msg, options, fn) {
1966
- this.sendPacket("message", msg, options, fn);
1967
- return this;
1968
- }
1969
- /**
1970
- * Sends a packet.
1971
- *
1972
- * @param {String} type: packet type.
1973
- * @param {String} data.
1974
- * @param {Object} options.
1975
- * @param {Function} fn - callback function.
1976
- * @private
1977
- */
1978
- sendPacket(type, data, options, fn) {
1979
- if ("function" === typeof data) {
1980
- fn = data;
1981
- data = undefined;
1982
- }
1983
- if ("function" === typeof options) {
1984
- fn = options;
1985
- options = null;
1986
- }
1987
- if ("closing" === this.readyState || "closed" === this.readyState) {
1988
- return;
1989
- }
1990
- options = options || {};
1991
- options.compress = false !== options.compress;
1992
- const packet = {
1993
- type: type,
1994
- data: data,
1995
- options: options,
1996
- };
1997
- this.emitReserved("packetCreate", packet);
1998
- this.writeBuffer.push(packet);
1999
- if (fn)
2000
- this.once("flush", fn);
2001
- this.flush();
2002
- }
2003
- /**
2004
- * Closes the connection.
2005
- */
2006
- close() {
2007
- const close = () => {
2008
- this.onClose("forced close");
2009
- this.transport.close();
2010
- };
2011
- const cleanupAndClose = () => {
2012
- this.off("upgrade", cleanupAndClose);
2013
- this.off("upgradeError", cleanupAndClose);
2014
- close();
2015
- };
2016
- const waitForUpgrade = () => {
2017
- // wait for upgrade to finish since we can't send packets while pausing a transport
2018
- this.once("upgrade", cleanupAndClose);
2019
- this.once("upgradeError", cleanupAndClose);
2020
- };
2021
- if ("opening" === this.readyState || "open" === this.readyState) {
2022
- this.readyState = "closing";
2023
- if (this.writeBuffer.length) {
2024
- this.once("drain", () => {
2025
- if (this.upgrading) {
2026
- waitForUpgrade();
2027
- }
2028
- else {
2029
- close();
2030
- }
2031
- });
2032
- }
2033
- else if (this.upgrading) {
2034
- waitForUpgrade();
2035
- }
2036
- else {
2037
- close();
2038
- }
2039
- }
2040
- return this;
2041
- }
2042
- /**
2043
- * Called upon transport error
2044
- *
2045
- * @private
2046
- */
2047
- onError(err) {
2048
- Socket$1.priorWebsocketSuccess = false;
2049
- this.emitReserved("error", err);
2050
- this.onClose("transport error", err);
2051
- }
2052
- /**
2053
- * Called upon transport close.
2054
- *
2055
- * @private
2056
- */
2057
- onClose(reason, description) {
2058
- if ("opening" === this.readyState ||
2059
- "open" === this.readyState ||
2060
- "closing" === this.readyState) {
2061
- // clear timers
2062
- this.clearTimeoutFn(this.pingTimeoutTimer);
2063
- // stop event from firing again for transport
2064
- this.transport.removeAllListeners("close");
2065
- // ensure transport won't stay open
2066
- this.transport.close();
2067
- // ignore further transport communication
2068
- this.transport.removeAllListeners();
2069
- if (typeof removeEventListener === "function") {
2070
- removeEventListener("beforeunload", this.beforeunloadEventListener, false);
2071
- removeEventListener("offline", this.offlineEventListener, false);
2072
- }
2073
- // set ready state
2074
- this.readyState = "closed";
2075
- // clear session id
2076
- this.id = null;
2077
- // emit close event
2078
- this.emitReserved("close", reason, description);
2079
- // clean buffers after, so users can still
2080
- // grab the buffers on `close` event
2081
- this.writeBuffer = [];
2082
- this.prevBufferLen = 0;
2083
- }
2084
- }
2085
- /**
2086
- * Filters upgrades, returning only those matching client transports.
2087
- *
2088
- * @param {Array} upgrades - server upgrades
2089
- * @private
2090
- */
2091
- filterUpgrades(upgrades) {
2092
- const filteredUpgrades = [];
2093
- let i = 0;
2094
- const j = upgrades.length;
2095
- for (; i < j; i++) {
2096
- if (~this.transports.indexOf(upgrades[i]))
2097
- filteredUpgrades.push(upgrades[i]);
2098
- }
2099
- return filteredUpgrades;
2100
- }
2101
- }
2102
- Socket$1.protocol = protocol$1;
2103
-
2104
- /**
2105
- * URL parser.
2106
- *
2107
- * @param uri - url
2108
- * @param path - the request path of the connection
2109
- * @param loc - An object meant to mimic window.location.
2110
- * Defaults to window.location.
2111
- * @public
2112
- */
2113
- function url(uri, path = "", loc) {
2114
- let obj = uri;
2115
- // default to window.location
2116
- loc = loc || (typeof location !== "undefined" && location);
2117
- if (null == uri)
2118
- uri = loc.protocol + "//" + loc.host;
2119
- // relative path support
2120
- if (typeof uri === "string") {
2121
- if ("/" === uri.charAt(0)) {
2122
- if ("/" === uri.charAt(1)) {
2123
- uri = loc.protocol + uri;
2124
- }
2125
- else {
2126
- uri = loc.host + uri;
2127
- }
2128
- }
2129
- if (!/^(https?|wss?):\/\//.test(uri)) {
2130
- if ("undefined" !== typeof loc) {
2131
- uri = loc.protocol + "//" + uri;
2132
- }
2133
- else {
2134
- uri = "https://" + uri;
2135
- }
2136
- }
2137
- // parse
2138
- obj = parse(uri);
2139
- }
2140
- // make sure we treat `localhost:80` and `localhost` equally
2141
- if (!obj.port) {
2142
- if (/^(http|ws)$/.test(obj.protocol)) {
2143
- obj.port = "80";
2144
- }
2145
- else if (/^(http|ws)s$/.test(obj.protocol)) {
2146
- obj.port = "443";
2147
- }
2148
- }
2149
- obj.path = obj.path || "/";
2150
- const ipv6 = obj.host.indexOf(":") !== -1;
2151
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
2152
- // define unique id
2153
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
2154
- // define href
2155
- obj.href =
2156
- obj.protocol +
2157
- "://" +
2158
- host +
2159
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
2160
- return obj;
2161
- }
2162
-
2163
- const withNativeArrayBuffer = typeof ArrayBuffer === "function";
2164
- const isView = (obj) => {
2165
- return typeof ArrayBuffer.isView === "function"
2166
- ? ArrayBuffer.isView(obj)
2167
- : obj.buffer instanceof ArrayBuffer;
2168
- };
2169
- const toString = Object.prototype.toString;
2170
- const withNativeBlob = typeof Blob === "function" ||
2171
- (typeof Blob !== "undefined" &&
2172
- toString.call(Blob) === "[object BlobConstructor]");
2173
- const withNativeFile = typeof File === "function" ||
2174
- (typeof File !== "undefined" &&
2175
- toString.call(File) === "[object FileConstructor]");
2176
- /**
2177
- * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
2178
- *
2179
- * @private
2180
- */
2181
- function isBinary(obj) {
2182
- return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
2183
- (withNativeBlob && obj instanceof Blob) ||
2184
- (withNativeFile && obj instanceof File));
2185
- }
2186
- function hasBinary(obj, toJSON) {
2187
- if (!obj || typeof obj !== "object") {
2188
- return false;
2189
- }
2190
- if (Array.isArray(obj)) {
2191
- for (let i = 0, l = obj.length; i < l; i++) {
2192
- if (hasBinary(obj[i])) {
2193
- return true;
2194
- }
2195
- }
2196
- return false;
2197
- }
2198
- if (isBinary(obj)) {
2199
- return true;
2200
- }
2201
- if (obj.toJSON &&
2202
- typeof obj.toJSON === "function" &&
2203
- arguments.length === 1) {
2204
- return hasBinary(obj.toJSON(), true);
2205
- }
2206
- for (const key in obj) {
2207
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
2208
- return true;
2209
- }
2210
- }
2211
- return false;
2212
- }
2213
-
2214
- /**
2215
- * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
2216
- *
2217
- * @param {Object} packet - socket.io event packet
2218
- * @return {Object} with deconstructed packet and list of buffers
2219
- * @public
2220
- */
2221
- function deconstructPacket(packet) {
2222
- const buffers = [];
2223
- const packetData = packet.data;
2224
- const pack = packet;
2225
- pack.data = _deconstructPacket(packetData, buffers);
2226
- pack.attachments = buffers.length; // number of binary 'attachments'
2227
- return { packet: pack, buffers: buffers };
2228
- }
2229
- function _deconstructPacket(data, buffers) {
2230
- if (!data)
2231
- return data;
2232
- if (isBinary(data)) {
2233
- const placeholder = { _placeholder: true, num: buffers.length };
2234
- buffers.push(data);
2235
- return placeholder;
2236
- }
2237
- else if (Array.isArray(data)) {
2238
- const newData = new Array(data.length);
2239
- for (let i = 0; i < data.length; i++) {
2240
- newData[i] = _deconstructPacket(data[i], buffers);
2241
- }
2242
- return newData;
2243
- }
2244
- else if (typeof data === "object" && !(data instanceof Date)) {
2245
- const newData = {};
2246
- for (const key in data) {
2247
- if (Object.prototype.hasOwnProperty.call(data, key)) {
2248
- newData[key] = _deconstructPacket(data[key], buffers);
2249
- }
2250
- }
2251
- return newData;
2252
- }
2253
- return data;
2254
- }
2255
- /**
2256
- * Reconstructs a binary packet from its placeholder packet and buffers
2257
- *
2258
- * @param {Object} packet - event packet with placeholders
2259
- * @param {Array} buffers - binary buffers to put in placeholder positions
2260
- * @return {Object} reconstructed packet
2261
- * @public
2262
- */
2263
- function reconstructPacket(packet, buffers) {
2264
- packet.data = _reconstructPacket(packet.data, buffers);
2265
- delete packet.attachments; // no longer useful
2266
- return packet;
2267
- }
2268
- function _reconstructPacket(data, buffers) {
2269
- if (!data)
2270
- return data;
2271
- if (data && data._placeholder === true) {
2272
- const isIndexValid = typeof data.num === "number" &&
2273
- data.num >= 0 &&
2274
- data.num < buffers.length;
2275
- if (isIndexValid) {
2276
- return buffers[data.num]; // appropriate buffer (should be natural order anyway)
2277
- }
2278
- else {
2279
- throw new Error("illegal attachments");
2280
- }
2281
- }
2282
- else if (Array.isArray(data)) {
2283
- for (let i = 0; i < data.length; i++) {
2284
- data[i] = _reconstructPacket(data[i], buffers);
2285
- }
2286
- }
2287
- else if (typeof data === "object") {
2288
- for (const key in data) {
2289
- if (Object.prototype.hasOwnProperty.call(data, key)) {
2290
- data[key] = _reconstructPacket(data[key], buffers);
2291
- }
2292
- }
2293
- }
2294
- return data;
2295
- }
2296
-
2297
- /**
2298
- * These strings must not be used as event names, as they have a special meaning.
2299
- */
2300
- const RESERVED_EVENTS$1 = [
2301
- "connect",
2302
- "connect_error",
2303
- "disconnect",
2304
- "disconnecting",
2305
- "newListener",
2306
- "removeListener", // used by the Node.js EventEmitter
2307
- ];
2308
- /**
2309
- * Protocol version.
2310
- *
2311
- * @public
2312
- */
2313
- const protocol = 5;
2314
- var PacketType;
2315
- (function (PacketType) {
2316
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
2317
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
2318
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
2319
- PacketType[PacketType["ACK"] = 3] = "ACK";
2320
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
2321
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
2322
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
2323
- })(PacketType || (PacketType = {}));
2324
- /**
2325
- * A socket.io Encoder instance
2326
- */
2327
- class Encoder {
2328
- /**
2329
- * Encoder constructor
2330
- *
2331
- * @param {function} replacer - custom replacer to pass down to JSON.parse
2332
- */
2333
- constructor(replacer) {
2334
- this.replacer = replacer;
2335
- }
2336
- /**
2337
- * Encode a packet as a single string if non-binary, or as a
2338
- * buffer sequence, depending on packet type.
2339
- *
2340
- * @param {Object} obj - packet object
2341
- */
2342
- encode(obj) {
2343
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
2344
- if (hasBinary(obj)) {
2345
- return this.encodeAsBinary({
2346
- type: obj.type === PacketType.EVENT
2347
- ? PacketType.BINARY_EVENT
2348
- : PacketType.BINARY_ACK,
2349
- nsp: obj.nsp,
2350
- data: obj.data,
2351
- id: obj.id,
2352
- });
2353
- }
2354
- }
2355
- return [this.encodeAsString(obj)];
2356
- }
2357
- /**
2358
- * Encode packet as string.
2359
- */
2360
- encodeAsString(obj) {
2361
- // first is type
2362
- let str = "" + obj.type;
2363
- // attachments if we have them
2364
- if (obj.type === PacketType.BINARY_EVENT ||
2365
- obj.type === PacketType.BINARY_ACK) {
2366
- str += obj.attachments + "-";
2367
- }
2368
- // if we have a namespace other than `/`
2369
- // we append it followed by a comma `,`
2370
- if (obj.nsp && "/" !== obj.nsp) {
2371
- str += obj.nsp + ",";
2372
- }
2373
- // immediately followed by the id
2374
- if (null != obj.id) {
2375
- str += obj.id;
2376
- }
2377
- // json data
2378
- if (null != obj.data) {
2379
- str += JSON.stringify(obj.data, this.replacer);
2380
- }
2381
- return str;
2382
- }
2383
- /**
2384
- * Encode packet as 'buffer sequence' by removing blobs, and
2385
- * deconstructing packet into object with placeholders and
2386
- * a list of buffers.
2387
- */
2388
- encodeAsBinary(obj) {
2389
- const deconstruction = deconstructPacket(obj);
2390
- const pack = this.encodeAsString(deconstruction.packet);
2391
- const buffers = deconstruction.buffers;
2392
- buffers.unshift(pack); // add packet info to beginning of data list
2393
- return buffers; // write all the buffers
2394
- }
2395
- }
2396
- // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
2397
- function isObject(value) {
2398
- return Object.prototype.toString.call(value) === "[object Object]";
2399
- }
2400
- /**
2401
- * A socket.io Decoder instance
2402
- *
2403
- * @return {Object} decoder
2404
- */
2405
- class Decoder extends Emitter {
2406
- /**
2407
- * Decoder constructor
2408
- *
2409
- * @param {function} reviver - custom reviver to pass down to JSON.stringify
2410
- */
2411
- constructor(reviver) {
2412
- super();
2413
- this.reviver = reviver;
2414
- }
2415
- /**
2416
- * Decodes an encoded packet string into packet JSON.
2417
- *
2418
- * @param {String} obj - encoded packet
2419
- */
2420
- add(obj) {
2421
- let packet;
2422
- if (typeof obj === "string") {
2423
- if (this.reconstructor) {
2424
- throw new Error("got plaintext data when reconstructing a packet");
2425
- }
2426
- packet = this.decodeString(obj);
2427
- const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2428
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2429
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2430
- // binary packet's json
2431
- this.reconstructor = new BinaryReconstructor(packet);
2432
- // no attachments, labeled binary but no binary data to follow
2433
- if (packet.attachments === 0) {
2434
- super.emitReserved("decoded", packet);
2435
- }
2436
- }
2437
- else {
2438
- // non-binary full packet
2439
- super.emitReserved("decoded", packet);
2440
- }
2441
- }
2442
- else if (isBinary(obj) || obj.base64) {
2443
- // raw binary data
2444
- if (!this.reconstructor) {
2445
- throw new Error("got binary data when not reconstructing a packet");
2446
- }
2447
- else {
2448
- packet = this.reconstructor.takeBinaryData(obj);
2449
- if (packet) {
2450
- // received final buffer
2451
- this.reconstructor = null;
2452
- super.emitReserved("decoded", packet);
2453
- }
2454
- }
2455
- }
2456
- else {
2457
- throw new Error("Unknown type: " + obj);
2458
- }
2459
- }
2460
- /**
2461
- * Decode a packet String (JSON data)
2462
- *
2463
- * @param {String} str
2464
- * @return {Object} packet
2465
- */
2466
- decodeString(str) {
2467
- let i = 0;
2468
- // look up type
2469
- const p = {
2470
- type: Number(str.charAt(0)),
2471
- };
2472
- if (PacketType[p.type] === undefined) {
2473
- throw new Error("unknown packet type " + p.type);
2474
- }
2475
- // look up attachments if type binary
2476
- if (p.type === PacketType.BINARY_EVENT ||
2477
- p.type === PacketType.BINARY_ACK) {
2478
- const start = i + 1;
2479
- while (str.charAt(++i) !== "-" && i != str.length) { }
2480
- const buf = str.substring(start, i);
2481
- if (buf != Number(buf) || str.charAt(i) !== "-") {
2482
- throw new Error("Illegal attachments");
2483
- }
2484
- p.attachments = Number(buf);
2485
- }
2486
- // look up namespace (if any)
2487
- if ("/" === str.charAt(i + 1)) {
2488
- const start = i + 1;
2489
- while (++i) {
2490
- const c = str.charAt(i);
2491
- if ("," === c)
2492
- break;
2493
- if (i === str.length)
2494
- break;
2495
- }
2496
- p.nsp = str.substring(start, i);
2497
- }
2498
- else {
2499
- p.nsp = "/";
2500
- }
2501
- // look up id
2502
- const next = str.charAt(i + 1);
2503
- if ("" !== next && Number(next) == next) {
2504
- const start = i + 1;
2505
- while (++i) {
2506
- const c = str.charAt(i);
2507
- if (null == c || Number(c) != c) {
2508
- --i;
2509
- break;
2510
- }
2511
- if (i === str.length)
2512
- break;
2513
- }
2514
- p.id = Number(str.substring(start, i + 1));
2515
- }
2516
- // look up json data
2517
- if (str.charAt(++i)) {
2518
- const payload = this.tryParse(str.substr(i));
2519
- if (Decoder.isPayloadValid(p.type, payload)) {
2520
- p.data = payload;
2521
- }
2522
- else {
2523
- throw new Error("invalid payload");
2524
- }
2525
- }
2526
- return p;
2527
- }
2528
- tryParse(str) {
2529
- try {
2530
- return JSON.parse(str, this.reviver);
2531
- }
2532
- catch (e) {
2533
- return false;
2534
- }
2535
- }
2536
- static isPayloadValid(type, payload) {
2537
- switch (type) {
2538
- case PacketType.CONNECT:
2539
- return isObject(payload);
2540
- case PacketType.DISCONNECT:
2541
- return payload === undefined;
2542
- case PacketType.CONNECT_ERROR:
2543
- return typeof payload === "string" || isObject(payload);
2544
- case PacketType.EVENT:
2545
- case PacketType.BINARY_EVENT:
2546
- return (Array.isArray(payload) &&
2547
- (typeof payload[0] === "number" ||
2548
- (typeof payload[0] === "string" &&
2549
- RESERVED_EVENTS$1.indexOf(payload[0]) === -1)));
2550
- case PacketType.ACK:
2551
- case PacketType.BINARY_ACK:
2552
- return Array.isArray(payload);
2553
- }
2554
- }
2555
- /**
2556
- * Deallocates a parser's resources
2557
- */
2558
- destroy() {
2559
- if (this.reconstructor) {
2560
- this.reconstructor.finishedReconstruction();
2561
- this.reconstructor = null;
2562
- }
2563
- }
2564
- }
2565
- /**
2566
- * A manager of a binary event's 'buffer sequence'. Should
2567
- * be constructed whenever a packet of type BINARY_EVENT is
2568
- * decoded.
2569
- *
2570
- * @param {Object} packet
2571
- * @return {BinaryReconstructor} initialized reconstructor
2572
- */
2573
- class BinaryReconstructor {
2574
- constructor(packet) {
2575
- this.packet = packet;
2576
- this.buffers = [];
2577
- this.reconPack = packet;
2578
- }
2579
- /**
2580
- * Method to be called when binary data received from connection
2581
- * after a BINARY_EVENT packet.
2582
- *
2583
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
2584
- * @return {null | Object} returns null if more binary data is expected or
2585
- * a reconstructed packet object if all buffers have been received.
2586
- */
2587
- takeBinaryData(binData) {
2588
- this.buffers.push(binData);
2589
- if (this.buffers.length === this.reconPack.attachments) {
2590
- // done with buffer list
2591
- const packet = reconstructPacket(this.reconPack, this.buffers);
2592
- this.finishedReconstruction();
2593
- return packet;
2594
- }
2595
- return null;
2596
- }
2597
- /**
2598
- * Cleans up binary packet reconstruction variables.
2599
- */
2600
- finishedReconstruction() {
2601
- this.reconPack = null;
2602
- this.buffers = [];
2603
- }
2604
- }
2605
-
2606
- const parser = /*#__PURE__*/Object.freeze({
2607
- __proto__: null,
2608
- protocol: protocol,
2609
- get PacketType () { return PacketType; },
2610
- Encoder: Encoder,
2611
- Decoder: Decoder
2612
- });
2613
-
2614
- function on(obj, ev, fn) {
2615
- obj.on(ev, fn);
2616
- return function subDestroy() {
2617
- obj.off(ev, fn);
2618
- };
2619
- }
2620
-
2621
- /**
2622
- * Internal events.
2623
- * These events can't be emitted by the user.
2624
- */
2625
- const RESERVED_EVENTS = Object.freeze({
2626
- connect: 1,
2627
- connect_error: 1,
2628
- disconnect: 1,
2629
- disconnecting: 1,
2630
- // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
2631
- newListener: 1,
2632
- removeListener: 1,
2633
- });
2634
- /**
2635
- * A Socket is the fundamental class for interacting with the server.
2636
- *
2637
- * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
2638
- *
2639
- * @example
2640
- * const socket = io();
2641
- *
2642
- * socket.on("connect", () => {
2643
- * console.log("connected");
2644
- * });
2645
- *
2646
- * // send an event to the server
2647
- * socket.emit("foo", "bar");
2648
- *
2649
- * socket.on("foobar", () => {
2650
- * // an event was received from the server
2651
- * });
2652
- *
2653
- * // upon disconnection
2654
- * socket.on("disconnect", (reason) => {
2655
- * console.log(`disconnected due to ${reason}`);
2656
- * });
2657
- */
2658
- class Socket extends Emitter {
2659
- /**
2660
- * `Socket` constructor.
2661
- */
2662
- constructor(io, nsp, opts) {
2663
- super();
2664
- /**
2665
- * Whether the socket is currently connected to the server.
2666
- *
2667
- * @example
2668
- * const socket = io();
2669
- *
2670
- * socket.on("connect", () => {
2671
- * console.log(socket.connected); // true
2672
- * });
2673
- *
2674
- * socket.on("disconnect", () => {
2675
- * console.log(socket.connected); // false
2676
- * });
2677
- */
2678
- this.connected = false;
2679
- /**
2680
- * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
2681
- * be transmitted by the server.
2682
- */
2683
- this.recovered = false;
2684
- /**
2685
- * Buffer for packets received before the CONNECT packet
2686
- */
2687
- this.receiveBuffer = [];
2688
- /**
2689
- * Buffer for packets that will be sent once the socket is connected
2690
- */
2691
- this.sendBuffer = [];
2692
- /**
2693
- * The queue of packets to be sent with retry in case of failure.
2694
- *
2695
- * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
2696
- * @private
2697
- */
2698
- this._queue = [];
2699
- /**
2700
- * A sequence to generate the ID of the {@link QueuedPacket}.
2701
- * @private
2702
- */
2703
- this._queueSeq = 0;
2704
- this.ids = 0;
2705
- this.acks = {};
2706
- this.flags = {};
2707
- this.io = io;
2708
- this.nsp = nsp;
2709
- if (opts && opts.auth) {
2710
- this.auth = opts.auth;
2711
- }
2712
- this._opts = Object.assign({}, opts);
2713
- if (this.io._autoConnect)
2714
- this.open();
2715
- }
2716
- /**
2717
- * Whether the socket is currently disconnected
2718
- *
2719
- * @example
2720
- * const socket = io();
2721
- *
2722
- * socket.on("connect", () => {
2723
- * console.log(socket.disconnected); // false
2724
- * });
2725
- *
2726
- * socket.on("disconnect", () => {
2727
- * console.log(socket.disconnected); // true
2728
- * });
2729
- */
2730
- get disconnected() {
2731
- return !this.connected;
2732
- }
2733
- /**
2734
- * Subscribe to open, close and packet events
2735
- *
2736
- * @private
2737
- */
2738
- subEvents() {
2739
- if (this.subs)
2740
- return;
2741
- const io = this.io;
2742
- this.subs = [
2743
- on(io, "open", this.onopen.bind(this)),
2744
- on(io, "packet", this.onpacket.bind(this)),
2745
- on(io, "error", this.onerror.bind(this)),
2746
- on(io, "close", this.onclose.bind(this)),
2747
- ];
2748
- }
2749
- /**
2750
- * Whether the Socket will try to reconnect when its Manager connects or reconnects.
2751
- *
2752
- * @example
2753
- * const socket = io();
2754
- *
2755
- * console.log(socket.active); // true
2756
- *
2757
- * socket.on("disconnect", (reason) => {
2758
- * if (reason === "io server disconnect") {
2759
- * // the disconnection was initiated by the server, you need to manually reconnect
2760
- * console.log(socket.active); // false
2761
- * }
2762
- * // else the socket will automatically try to reconnect
2763
- * console.log(socket.active); // true
2764
- * });
2765
- */
2766
- get active() {
2767
- return !!this.subs;
2768
- }
2769
- /**
2770
- * "Opens" the socket.
2771
- *
2772
- * @example
2773
- * const socket = io({
2774
- * autoConnect: false
2775
- * });
2776
- *
2777
- * socket.connect();
2778
- */
2779
- connect() {
2780
- if (this.connected)
2781
- return this;
2782
- this.subEvents();
2783
- if (!this.io["_reconnecting"])
2784
- this.io.open(); // ensure open
2785
- if ("open" === this.io._readyState)
2786
- this.onopen();
2787
- return this;
2788
- }
2789
- /**
2790
- * Alias for {@link connect()}.
2791
- */
2792
- open() {
2793
- return this.connect();
2794
- }
2795
- /**
2796
- * Sends a `message` event.
2797
- *
2798
- * This method mimics the WebSocket.send() method.
2799
- *
2800
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
2801
- *
2802
- * @example
2803
- * socket.send("hello");
2804
- *
2805
- * // this is equivalent to
2806
- * socket.emit("message", "hello");
2807
- *
2808
- * @return self
2809
- */
2810
- send(...args) {
2811
- args.unshift("message");
2812
- this.emit.apply(this, args);
2813
- return this;
2814
- }
2815
- /**
2816
- * Override `emit`.
2817
- * If the event is in `events`, it's emitted normally.
2818
- *
2819
- * @example
2820
- * socket.emit("hello", "world");
2821
- *
2822
- * // all serializable datastructures are supported (no need to call JSON.stringify)
2823
- * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
2824
- *
2825
- * // with an acknowledgement from the server
2826
- * socket.emit("hello", "world", (val) => {
2827
- * // ...
2828
- * });
2829
- *
2830
- * @return self
2831
- */
2832
- emit(ev, ...args) {
2833
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
2834
- throw new Error('"' + ev.toString() + '" is a reserved event name');
2835
- }
2836
- args.unshift(ev);
2837
- if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
2838
- this._addToQueue(args);
2839
- return this;
2840
- }
2841
- const packet = {
2842
- type: PacketType.EVENT,
2843
- data: args,
2844
- };
2845
- packet.options = {};
2846
- packet.options.compress = this.flags.compress !== false;
2847
- // event ack callback
2848
- if ("function" === typeof args[args.length - 1]) {
2849
- const id = this.ids++;
2850
- const ack = args.pop();
2851
- this._registerAckCallback(id, ack);
2852
- packet.id = id;
2853
- }
2854
- const isTransportWritable = this.io.engine &&
2855
- this.io.engine.transport &&
2856
- this.io.engine.transport.writable;
2857
- const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);
2858
- if (discardPacket) ;
2859
- else if (this.connected) {
2860
- this.notifyOutgoingListeners(packet);
2861
- this.packet(packet);
2862
- }
2863
- else {
2864
- this.sendBuffer.push(packet);
2865
- }
2866
- this.flags = {};
2867
- return this;
2868
- }
2869
- /**
2870
- * @private
2871
- */
2872
- _registerAckCallback(id, ack) {
2873
- var _a;
2874
- const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
2875
- if (timeout === undefined) {
2876
- this.acks[id] = ack;
2877
- return;
2878
- }
2879
- // @ts-ignore
2880
- const timer = this.io.setTimeoutFn(() => {
2881
- delete this.acks[id];
2882
- for (let i = 0; i < this.sendBuffer.length; i++) {
2883
- if (this.sendBuffer[i].id === id) {
2884
- this.sendBuffer.splice(i, 1);
2885
- }
2886
- }
2887
- ack.call(this, new Error("operation has timed out"));
2888
- }, timeout);
2889
- this.acks[id] = (...args) => {
2890
- // @ts-ignore
2891
- this.io.clearTimeoutFn(timer);
2892
- ack.apply(this, [null, ...args]);
2893
- };
2894
- }
2895
- /**
2896
- * Emits an event and waits for an acknowledgement
2897
- *
2898
- * @example
2899
- * // without timeout
2900
- * const response = await socket.emitWithAck("hello", "world");
2901
- *
2902
- * // with a specific timeout
2903
- * try {
2904
- * const response = await socket.timeout(1000).emitWithAck("hello", "world");
2905
- * } catch (err) {
2906
- * // the server did not acknowledge the event in the given delay
2907
- * }
2908
- *
2909
- * @return a Promise that will be fulfilled when the server acknowledges the event
2910
- */
2911
- emitWithAck(ev, ...args) {
2912
- // the timeout flag is optional
2913
- const withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined;
2914
- return new Promise((resolve, reject) => {
2915
- args.push((arg1, arg2) => {
2916
- if (withErr) {
2917
- return arg1 ? reject(arg1) : resolve(arg2);
2918
- }
2919
- else {
2920
- return resolve(arg1);
2921
- }
2922
- });
2923
- this.emit(ev, ...args);
2924
- });
2925
- }
2926
- /**
2927
- * Add the packet to the queue.
2928
- * @param args
2929
- * @private
2930
- */
2931
- _addToQueue(args) {
2932
- let ack;
2933
- if (typeof args[args.length - 1] === "function") {
2934
- ack = args.pop();
2935
- }
2936
- const packet = {
2937
- id: this._queueSeq++,
2938
- tryCount: 0,
2939
- pending: false,
2940
- args,
2941
- flags: Object.assign({ fromQueue: true }, this.flags),
2942
- };
2943
- args.push((err, ...responseArgs) => {
2944
- if (packet !== this._queue[0]) {
2945
- // the packet has already been acknowledged
2946
- return;
2947
- }
2948
- const hasError = err !== null;
2949
- if (hasError) {
2950
- if (packet.tryCount > this._opts.retries) {
2951
- this._queue.shift();
2952
- if (ack) {
2953
- ack(err);
2954
- }
2955
- }
2956
- }
2957
- else {
2958
- this._queue.shift();
2959
- if (ack) {
2960
- ack(null, ...responseArgs);
2961
- }
2962
- }
2963
- packet.pending = false;
2964
- return this._drainQueue();
2965
- });
2966
- this._queue.push(packet);
2967
- this._drainQueue();
2968
- }
2969
- /**
2970
- * Send the first packet of the queue, and wait for an acknowledgement from the server.
2971
- * @param force - whether to resend a packet that has not been acknowledged yet
2972
- *
2973
- * @private
2974
- */
2975
- _drainQueue(force = false) {
2976
- if (!this.connected || this._queue.length === 0) {
2977
- return;
2978
- }
2979
- const packet = this._queue[0];
2980
- if (packet.pending && !force) {
2981
- return;
2982
- }
2983
- packet.pending = true;
2984
- packet.tryCount++;
2985
- this.flags = packet.flags;
2986
- this.emit.apply(this, packet.args);
2987
- }
2988
- /**
2989
- * Sends a packet.
2990
- *
2991
- * @param packet
2992
- * @private
2993
- */
2994
- packet(packet) {
2995
- packet.nsp = this.nsp;
2996
- this.io._packet(packet);
2997
- }
2998
- /**
2999
- * Called upon engine `open`.
3000
- *
3001
- * @private
3002
- */
3003
- onopen() {
3004
- if (typeof this.auth == "function") {
3005
- this.auth((data) => {
3006
- this._sendConnectPacket(data);
3007
- });
3008
- }
3009
- else {
3010
- this._sendConnectPacket(this.auth);
3011
- }
3012
- }
3013
- /**
3014
- * Sends a CONNECT packet to initiate the Socket.IO session.
3015
- *
3016
- * @param data
3017
- * @private
3018
- */
3019
- _sendConnectPacket(data) {
3020
- this.packet({
3021
- type: PacketType.CONNECT,
3022
- data: this._pid
3023
- ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
3024
- : data,
3025
- });
3026
- }
3027
- /**
3028
- * Called upon engine or manager `error`.
3029
- *
3030
- * @param err
3031
- * @private
3032
- */
3033
- onerror(err) {
3034
- if (!this.connected) {
3035
- this.emitReserved("connect_error", err);
3036
- }
3037
- }
3038
- /**
3039
- * Called upon engine `close`.
3040
- *
3041
- * @param reason
3042
- * @param description
3043
- * @private
3044
- */
3045
- onclose(reason, description) {
3046
- this.connected = false;
3047
- delete this.id;
3048
- this.emitReserved("disconnect", reason, description);
3049
- }
3050
- /**
3051
- * Called with socket packet.
3052
- *
3053
- * @param packet
3054
- * @private
3055
- */
3056
- onpacket(packet) {
3057
- const sameNamespace = packet.nsp === this.nsp;
3058
- if (!sameNamespace)
3059
- return;
3060
- switch (packet.type) {
3061
- case PacketType.CONNECT:
3062
- if (packet.data && packet.data.sid) {
3063
- this.onconnect(packet.data.sid, packet.data.pid);
3064
- }
3065
- else {
3066
- this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
3067
- }
3068
- break;
3069
- case PacketType.EVENT:
3070
- case PacketType.BINARY_EVENT:
3071
- this.onevent(packet);
3072
- break;
3073
- case PacketType.ACK:
3074
- case PacketType.BINARY_ACK:
3075
- this.onack(packet);
3076
- break;
3077
- case PacketType.DISCONNECT:
3078
- this.ondisconnect();
3079
- break;
3080
- case PacketType.CONNECT_ERROR:
3081
- this.destroy();
3082
- const err = new Error(packet.data.message);
3083
- // @ts-ignore
3084
- err.data = packet.data.data;
3085
- this.emitReserved("connect_error", err);
3086
- break;
3087
- }
3088
- }
3089
- /**
3090
- * Called upon a server event.
3091
- *
3092
- * @param packet
3093
- * @private
3094
- */
3095
- onevent(packet) {
3096
- const args = packet.data || [];
3097
- if (null != packet.id) {
3098
- args.push(this.ack(packet.id));
3099
- }
3100
- if (this.connected) {
3101
- this.emitEvent(args);
3102
- }
3103
- else {
3104
- this.receiveBuffer.push(Object.freeze(args));
3105
- }
3106
- }
3107
- emitEvent(args) {
3108
- if (this._anyListeners && this._anyListeners.length) {
3109
- const listeners = this._anyListeners.slice();
3110
- for (const listener of listeners) {
3111
- listener.apply(this, args);
3112
- }
3113
- }
3114
- super.emit.apply(this, args);
3115
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
3116
- this._lastOffset = args[args.length - 1];
3117
- }
3118
- }
3119
- /**
3120
- * Produces an ack callback to emit with an event.
3121
- *
3122
- * @private
3123
- */
3124
- ack(id) {
3125
- const self = this;
3126
- let sent = false;
3127
- return function (...args) {
3128
- // prevent double callbacks
3129
- if (sent)
3130
- return;
3131
- sent = true;
3132
- self.packet({
3133
- type: PacketType.ACK,
3134
- id: id,
3135
- data: args,
3136
- });
3137
- };
3138
- }
3139
- /**
3140
- * Called upon a server acknowlegement.
3141
- *
3142
- * @param packet
3143
- * @private
3144
- */
3145
- onack(packet) {
3146
- const ack = this.acks[packet.id];
3147
- if ("function" === typeof ack) {
3148
- ack.apply(this, packet.data);
3149
- delete this.acks[packet.id];
3150
- }
3151
- }
3152
- /**
3153
- * Called upon server connect.
3154
- *
3155
- * @private
3156
- */
3157
- onconnect(id, pid) {
3158
- this.id = id;
3159
- this.recovered = pid && this._pid === pid;
3160
- this._pid = pid; // defined only if connection state recovery is enabled
3161
- this.connected = true;
3162
- this.emitBuffered();
3163
- this.emitReserved("connect");
3164
- this._drainQueue(true);
3165
- }
3166
- /**
3167
- * Emit buffered events (received and emitted).
3168
- *
3169
- * @private
3170
- */
3171
- emitBuffered() {
3172
- this.receiveBuffer.forEach((args) => this.emitEvent(args));
3173
- this.receiveBuffer = [];
3174
- this.sendBuffer.forEach((packet) => {
3175
- this.notifyOutgoingListeners(packet);
3176
- this.packet(packet);
3177
- });
3178
- this.sendBuffer = [];
3179
- }
3180
- /**
3181
- * Called upon server disconnect.
3182
- *
3183
- * @private
3184
- */
3185
- ondisconnect() {
3186
- this.destroy();
3187
- this.onclose("io server disconnect");
3188
- }
3189
- /**
3190
- * Called upon forced client/server side disconnections,
3191
- * this method ensures the manager stops tracking us and
3192
- * that reconnections don't get triggered for this.
3193
- *
3194
- * @private
3195
- */
3196
- destroy() {
3197
- if (this.subs) {
3198
- // clean subscriptions to avoid reconnections
3199
- this.subs.forEach((subDestroy) => subDestroy());
3200
- this.subs = undefined;
3201
- }
3202
- this.io["_destroy"](this);
3203
- }
3204
- /**
3205
- * Disconnects the socket manually. In that case, the socket will not try to reconnect.
3206
- *
3207
- * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
3208
- *
3209
- * @example
3210
- * const socket = io();
3211
- *
3212
- * socket.on("disconnect", (reason) => {
3213
- * // console.log(reason); prints "io client disconnect"
3214
- * });
3215
- *
3216
- * socket.disconnect();
3217
- *
3218
- * @return self
3219
- */
3220
- disconnect() {
3221
- if (this.connected) {
3222
- this.packet({ type: PacketType.DISCONNECT });
3223
- }
3224
- // remove socket from pool
3225
- this.destroy();
3226
- if (this.connected) {
3227
- // fire events
3228
- this.onclose("io client disconnect");
3229
- }
3230
- return this;
3231
- }
3232
- /**
3233
- * Alias for {@link disconnect()}.
3234
- *
3235
- * @return self
3236
- */
3237
- close() {
3238
- return this.disconnect();
3239
- }
3240
- /**
3241
- * Sets the compress flag.
3242
- *
3243
- * @example
3244
- * socket.compress(false).emit("hello");
3245
- *
3246
- * @param compress - if `true`, compresses the sending data
3247
- * @return self
3248
- */
3249
- compress(compress) {
3250
- this.flags.compress = compress;
3251
- return this;
3252
- }
3253
- /**
3254
- * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
3255
- * ready to send messages.
3256
- *
3257
- * @example
3258
- * socket.volatile.emit("hello"); // the server may or may not receive it
3259
- *
3260
- * @returns self
3261
- */
3262
- get volatile() {
3263
- this.flags.volatile = true;
3264
- return this;
3265
- }
3266
- /**
3267
- * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
3268
- * given number of milliseconds have elapsed without an acknowledgement from the server:
3269
- *
3270
- * @example
3271
- * socket.timeout(5000).emit("my-event", (err) => {
3272
- * if (err) {
3273
- * // the server did not acknowledge the event in the given delay
3274
- * }
3275
- * });
3276
- *
3277
- * @returns self
3278
- */
3279
- timeout(timeout) {
3280
- this.flags.timeout = timeout;
3281
- return this;
3282
- }
3283
- /**
3284
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3285
- * callback.
3286
- *
3287
- * @example
3288
- * socket.onAny((event, ...args) => {
3289
- * console.log(`got ${event}`);
3290
- * });
3291
- *
3292
- * @param listener
3293
- */
3294
- onAny(listener) {
3295
- this._anyListeners = this._anyListeners || [];
3296
- this._anyListeners.push(listener);
3297
- return this;
3298
- }
3299
- /**
3300
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3301
- * callback. The listener is added to the beginning of the listeners array.
3302
- *
3303
- * @example
3304
- * socket.prependAny((event, ...args) => {
3305
- * console.log(`got event ${event}`);
3306
- * });
3307
- *
3308
- * @param listener
3309
- */
3310
- prependAny(listener) {
3311
- this._anyListeners = this._anyListeners || [];
3312
- this._anyListeners.unshift(listener);
3313
- return this;
3314
- }
3315
- /**
3316
- * Removes the listener that will be fired when any event is emitted.
3317
- *
3318
- * @example
3319
- * const catchAllListener = (event, ...args) => {
3320
- * console.log(`got event ${event}`);
3321
- * }
3322
- *
3323
- * socket.onAny(catchAllListener);
3324
- *
3325
- * // remove a specific listener
3326
- * socket.offAny(catchAllListener);
3327
- *
3328
- * // or remove all listeners
3329
- * socket.offAny();
3330
- *
3331
- * @param listener
3332
- */
3333
- offAny(listener) {
3334
- if (!this._anyListeners) {
3335
- return this;
3336
- }
3337
- if (listener) {
3338
- const listeners = this._anyListeners;
3339
- for (let i = 0; i < listeners.length; i++) {
3340
- if (listener === listeners[i]) {
3341
- listeners.splice(i, 1);
3342
- return this;
3343
- }
3344
- }
3345
- }
3346
- else {
3347
- this._anyListeners = [];
3348
- }
3349
- return this;
3350
- }
3351
- /**
3352
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3353
- * e.g. to remove listeners.
3354
- */
3355
- listenersAny() {
3356
- return this._anyListeners || [];
3357
- }
3358
- /**
3359
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3360
- * callback.
3361
- *
3362
- * Note: acknowledgements sent to the server are not included.
3363
- *
3364
- * @example
3365
- * socket.onAnyOutgoing((event, ...args) => {
3366
- * console.log(`sent event ${event}`);
3367
- * });
3368
- *
3369
- * @param listener
3370
- */
3371
- onAnyOutgoing(listener) {
3372
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3373
- this._anyOutgoingListeners.push(listener);
3374
- return this;
3375
- }
3376
- /**
3377
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3378
- * callback. The listener is added to the beginning of the listeners array.
3379
- *
3380
- * Note: acknowledgements sent to the server are not included.
3381
- *
3382
- * @example
3383
- * socket.prependAnyOutgoing((event, ...args) => {
3384
- * console.log(`sent event ${event}`);
3385
- * });
3386
- *
3387
- * @param listener
3388
- */
3389
- prependAnyOutgoing(listener) {
3390
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3391
- this._anyOutgoingListeners.unshift(listener);
3392
- return this;
3393
- }
3394
- /**
3395
- * Removes the listener that will be fired when any event is emitted.
3396
- *
3397
- * @example
3398
- * const catchAllListener = (event, ...args) => {
3399
- * console.log(`sent event ${event}`);
3400
- * }
3401
- *
3402
- * socket.onAnyOutgoing(catchAllListener);
3403
- *
3404
- * // remove a specific listener
3405
- * socket.offAnyOutgoing(catchAllListener);
3406
- *
3407
- * // or remove all listeners
3408
- * socket.offAnyOutgoing();
3409
- *
3410
- * @param [listener] - the catch-all listener (optional)
3411
- */
3412
- offAnyOutgoing(listener) {
3413
- if (!this._anyOutgoingListeners) {
3414
- return this;
3415
- }
3416
- if (listener) {
3417
- const listeners = this._anyOutgoingListeners;
3418
- for (let i = 0; i < listeners.length; i++) {
3419
- if (listener === listeners[i]) {
3420
- listeners.splice(i, 1);
3421
- return this;
3422
- }
3423
- }
3424
- }
3425
- else {
3426
- this._anyOutgoingListeners = [];
3427
- }
3428
- return this;
3429
- }
3430
- /**
3431
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3432
- * e.g. to remove listeners.
3433
- */
3434
- listenersAnyOutgoing() {
3435
- return this._anyOutgoingListeners || [];
3436
- }
3437
- /**
3438
- * Notify the listeners for each packet sent
3439
- *
3440
- * @param packet
3441
- *
3442
- * @private
3443
- */
3444
- notifyOutgoingListeners(packet) {
3445
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
3446
- const listeners = this._anyOutgoingListeners.slice();
3447
- for (const listener of listeners) {
3448
- listener.apply(this, packet.data);
3449
- }
3450
- }
3451
- }
3452
- }
3453
-
3454
- /**
3455
- * Initialize backoff timer with `opts`.
3456
- *
3457
- * - `min` initial timeout in milliseconds [100]
3458
- * - `max` max timeout [10000]
3459
- * - `jitter` [0]
3460
- * - `factor` [2]
3461
- *
3462
- * @param {Object} opts
3463
- * @api public
3464
- */
3465
- function Backoff(opts) {
3466
- opts = opts || {};
3467
- this.ms = opts.min || 100;
3468
- this.max = opts.max || 10000;
3469
- this.factor = opts.factor || 2;
3470
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3471
- this.attempts = 0;
3472
- }
3473
- /**
3474
- * Return the backoff duration.
3475
- *
3476
- * @return {Number}
3477
- * @api public
3478
- */
3479
- Backoff.prototype.duration = function () {
3480
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
3481
- if (this.jitter) {
3482
- var rand = Math.random();
3483
- var deviation = Math.floor(rand * this.jitter * ms);
3484
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3485
- }
3486
- return Math.min(ms, this.max) | 0;
3487
- };
3488
- /**
3489
- * Reset the number of attempts.
3490
- *
3491
- * @api public
3492
- */
3493
- Backoff.prototype.reset = function () {
3494
- this.attempts = 0;
3495
- };
3496
- /**
3497
- * Set the minimum duration
3498
- *
3499
- * @api public
3500
- */
3501
- Backoff.prototype.setMin = function (min) {
3502
- this.ms = min;
3503
- };
3504
- /**
3505
- * Set the maximum duration
3506
- *
3507
- * @api public
3508
- */
3509
- Backoff.prototype.setMax = function (max) {
3510
- this.max = max;
3511
- };
3512
- /**
3513
- * Set the jitter
3514
- *
3515
- * @api public
3516
- */
3517
- Backoff.prototype.setJitter = function (jitter) {
3518
- this.jitter = jitter;
3519
- };
3520
-
3521
- class Manager extends Emitter {
3522
- constructor(uri, opts) {
3523
- var _a;
3524
- super();
3525
- this.nsps = {};
3526
- this.subs = [];
3527
- if (uri && "object" === typeof uri) {
3528
- opts = uri;
3529
- uri = undefined;
3530
- }
3531
- opts = opts || {};
3532
- opts.path = opts.path || "/socket.io";
3533
- this.opts = opts;
3534
- installTimerFunctions(this, opts);
3535
- this.reconnection(opts.reconnection !== false);
3536
- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3537
- this.reconnectionDelay(opts.reconnectionDelay || 1000);
3538
- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
3539
- this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3540
- this.backoff = new Backoff({
3541
- min: this.reconnectionDelay(),
3542
- max: this.reconnectionDelayMax(),
3543
- jitter: this.randomizationFactor(),
3544
- });
3545
- this.timeout(null == opts.timeout ? 20000 : opts.timeout);
3546
- this._readyState = "closed";
3547
- this.uri = uri;
3548
- const _parser = opts.parser || parser;
3549
- this.encoder = new _parser.Encoder();
3550
- this.decoder = new _parser.Decoder();
3551
- this._autoConnect = opts.autoConnect !== false;
3552
- if (this._autoConnect)
3553
- this.open();
3554
- }
3555
- reconnection(v) {
3556
- if (!arguments.length)
3557
- return this._reconnection;
3558
- this._reconnection = !!v;
3559
- return this;
3560
- }
3561
- reconnectionAttempts(v) {
3562
- if (v === undefined)
3563
- return this._reconnectionAttempts;
3564
- this._reconnectionAttempts = v;
3565
- return this;
3566
- }
3567
- reconnectionDelay(v) {
3568
- var _a;
3569
- if (v === undefined)
3570
- return this._reconnectionDelay;
3571
- this._reconnectionDelay = v;
3572
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3573
- return this;
3574
- }
3575
- randomizationFactor(v) {
3576
- var _a;
3577
- if (v === undefined)
3578
- return this._randomizationFactor;
3579
- this._randomizationFactor = v;
3580
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3581
- return this;
3582
- }
3583
- reconnectionDelayMax(v) {
3584
- var _a;
3585
- if (v === undefined)
3586
- return this._reconnectionDelayMax;
3587
- this._reconnectionDelayMax = v;
3588
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3589
- return this;
3590
- }
3591
- timeout(v) {
3592
- if (!arguments.length)
3593
- return this._timeout;
3594
- this._timeout = v;
3595
- return this;
3596
- }
3597
- /**
3598
- * Starts trying to reconnect if reconnection is enabled and we have not
3599
- * started reconnecting yet
3600
- *
3601
- * @private
3602
- */
3603
- maybeReconnectOnOpen() {
3604
- // Only try to reconnect if it's the first time we're connecting
3605
- if (!this._reconnecting &&
3606
- this._reconnection &&
3607
- this.backoff.attempts === 0) {
3608
- // keeps reconnection from firing twice for the same reconnection loop
3609
- this.reconnect();
3610
- }
3611
- }
3612
- /**
3613
- * Sets the current transport `socket`.
3614
- *
3615
- * @param {Function} fn - optional, callback
3616
- * @return self
3617
- * @public
3618
- */
3619
- open(fn) {
3620
- if (~this._readyState.indexOf("open"))
3621
- return this;
3622
- this.engine = new Socket$1(this.uri, this.opts);
3623
- const socket = this.engine;
3624
- const self = this;
3625
- this._readyState = "opening";
3626
- this.skipReconnect = false;
3627
- // emit `open`
3628
- const openSubDestroy = on(socket, "open", function () {
3629
- self.onopen();
3630
- fn && fn();
3631
- });
3632
- const onError = (err) => {
3633
- this.cleanup();
3634
- this._readyState = "closed";
3635
- this.emitReserved("error", err);
3636
- if (fn) {
3637
- fn(err);
3638
- }
3639
- else {
3640
- // Only do this if there is no fn to handle the error
3641
- this.maybeReconnectOnOpen();
3642
- }
3643
- };
3644
- // emit `error`
3645
- const errorSub = on(socket, "error", onError);
3646
- if (false !== this._timeout) {
3647
- const timeout = this._timeout;
3648
- // set timer
3649
- const timer = this.setTimeoutFn(() => {
3650
- openSubDestroy();
3651
- onError(new Error("timeout"));
3652
- socket.close();
3653
- }, timeout);
3654
- if (this.opts.autoUnref) {
3655
- timer.unref();
3656
- }
3657
- this.subs.push(() => {
3658
- this.clearTimeoutFn(timer);
3659
- });
3660
- }
3661
- this.subs.push(openSubDestroy);
3662
- this.subs.push(errorSub);
3663
- return this;
3664
- }
3665
- /**
3666
- * Alias for open()
3667
- *
3668
- * @return self
3669
- * @public
3670
- */
3671
- connect(fn) {
3672
- return this.open(fn);
3673
- }
3674
- /**
3675
- * Called upon transport open.
3676
- *
3677
- * @private
3678
- */
3679
- onopen() {
3680
- // clear old subs
3681
- this.cleanup();
3682
- // mark as open
3683
- this._readyState = "open";
3684
- this.emitReserved("open");
3685
- // add new subs
3686
- const socket = this.engine;
3687
- this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this)));
3688
- }
3689
- /**
3690
- * Called upon a ping.
3691
- *
3692
- * @private
3693
- */
3694
- onping() {
3695
- this.emitReserved("ping");
3696
- }
3697
- /**
3698
- * Called with data.
3699
- *
3700
- * @private
3701
- */
3702
- ondata(data) {
3703
- try {
3704
- this.decoder.add(data);
3705
- }
3706
- catch (e) {
3707
- this.onclose("parse error", e);
3708
- }
3709
- }
3710
- /**
3711
- * Called when parser fully decodes a packet.
3712
- *
3713
- * @private
3714
- */
3715
- ondecoded(packet) {
3716
- // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
3717
- nextTick(() => {
3718
- this.emitReserved("packet", packet);
3719
- }, this.setTimeoutFn);
3720
- }
3721
- /**
3722
- * Called upon socket error.
3723
- *
3724
- * @private
3725
- */
3726
- onerror(err) {
3727
- this.emitReserved("error", err);
3728
- }
3729
- /**
3730
- * Creates a new socket for the given `nsp`.
3731
- *
3732
- * @return {Socket}
3733
- * @public
3734
- */
3735
- socket(nsp, opts) {
3736
- let socket = this.nsps[nsp];
3737
- if (!socket) {
3738
- socket = new Socket(this, nsp, opts);
3739
- this.nsps[nsp] = socket;
3740
- }
3741
- else if (this._autoConnect && !socket.active) {
3742
- socket.connect();
3743
- }
3744
- return socket;
3745
- }
3746
- /**
3747
- * Called upon a socket close.
3748
- *
3749
- * @param socket
3750
- * @private
3751
- */
3752
- _destroy(socket) {
3753
- const nsps = Object.keys(this.nsps);
3754
- for (const nsp of nsps) {
3755
- const socket = this.nsps[nsp];
3756
- if (socket.active) {
3757
- return;
3758
- }
3759
- }
3760
- this._close();
3761
- }
3762
- /**
3763
- * Writes a packet.
3764
- *
3765
- * @param packet
3766
- * @private
3767
- */
3768
- _packet(packet) {
3769
- const encodedPackets = this.encoder.encode(packet);
3770
- for (let i = 0; i < encodedPackets.length; i++) {
3771
- this.engine.write(encodedPackets[i], packet.options);
3772
- }
3773
- }
3774
- /**
3775
- * Clean up transport subscriptions and packet buffer.
3776
- *
3777
- * @private
3778
- */
3779
- cleanup() {
3780
- this.subs.forEach((subDestroy) => subDestroy());
3781
- this.subs.length = 0;
3782
- this.decoder.destroy();
3783
- }
3784
- /**
3785
- * Close the current socket.
3786
- *
3787
- * @private
3788
- */
3789
- _close() {
3790
- this.skipReconnect = true;
3791
- this._reconnecting = false;
3792
- this.onclose("forced close");
3793
- if (this.engine)
3794
- this.engine.close();
3795
- }
3796
- /**
3797
- * Alias for close()
3798
- *
3799
- * @private
3800
- */
3801
- disconnect() {
3802
- return this._close();
3803
- }
3804
- /**
3805
- * Called upon engine close.
3806
- *
3807
- * @private
3808
- */
3809
- onclose(reason, description) {
3810
- this.cleanup();
3811
- this.backoff.reset();
3812
- this._readyState = "closed";
3813
- this.emitReserved("close", reason, description);
3814
- if (this._reconnection && !this.skipReconnect) {
3815
- this.reconnect();
3816
- }
3817
- }
3818
- /**
3819
- * Attempt a reconnection.
3820
- *
3821
- * @private
3822
- */
3823
- reconnect() {
3824
- if (this._reconnecting || this.skipReconnect)
3825
- return this;
3826
- const self = this;
3827
- if (this.backoff.attempts >= this._reconnectionAttempts) {
3828
- this.backoff.reset();
3829
- this.emitReserved("reconnect_failed");
3830
- this._reconnecting = false;
3831
- }
3832
- else {
3833
- const delay = this.backoff.duration();
3834
- this._reconnecting = true;
3835
- const timer = this.setTimeoutFn(() => {
3836
- if (self.skipReconnect)
3837
- return;
3838
- this.emitReserved("reconnect_attempt", self.backoff.attempts);
3839
- // check again for the case socket closed in above events
3840
- if (self.skipReconnect)
3841
- return;
3842
- self.open((err) => {
3843
- if (err) {
3844
- self._reconnecting = false;
3845
- self.reconnect();
3846
- this.emitReserved("reconnect_error", err);
3847
- }
3848
- else {
3849
- self.onreconnect();
3850
- }
3851
- });
3852
- }, delay);
3853
- if (this.opts.autoUnref) {
3854
- timer.unref();
3855
- }
3856
- this.subs.push(() => {
3857
- this.clearTimeoutFn(timer);
3858
- });
3859
- }
3860
- }
3861
- /**
3862
- * Called upon successful reconnect.
3863
- *
3864
- * @private
3865
- */
3866
- onreconnect() {
3867
- const attempt = this.backoff.attempts;
3868
- this._reconnecting = false;
3869
- this.backoff.reset();
3870
- this.emitReserved("reconnect", attempt);
3871
- }
3872
- }
3873
-
3874
- /**
3875
- * Managers cache.
3876
- */
3877
- const cache = {};
3878
- function lookup(uri, opts) {
3879
- if (typeof uri === "object") {
3880
- opts = uri;
3881
- uri = undefined;
3882
- }
3883
- opts = opts || {};
3884
- const parsed = url(uri, opts.path || "/socket.io");
3885
- const source = parsed.source;
3886
- const id = parsed.id;
3887
- const path = parsed.path;
3888
- const sameNamespace = cache[id] && path in cache[id]["nsps"];
3889
- const newConnection = opts.forceNew ||
3890
- opts["force new connection"] ||
3891
- false === opts.multiplex ||
3892
- sameNamespace;
3893
- let io;
3894
- if (newConnection) {
3895
- io = new Manager(source, opts);
3896
- }
3897
- else {
3898
- if (!cache[id]) {
3899
- cache[id] = new Manager(source, opts);
3900
- }
3901
- io = cache[id];
3902
- }
3903
- if (parsed.query && !opts.query) {
3904
- opts.query = parsed.queryKey;
3905
- }
3906
- return io.socket(parsed.path, opts);
3907
- }
3908
- // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
3909
- // namespace (e.g. `io.connect(...)`), for backward compatibility
3910
- Object.assign(lookup, {
3911
- Manager,
3912
- Socket,
3913
- io: lookup,
3914
- connect: lookup,
3915
- });
3916
-
3917
61
  const initializeSession = async ({ baseUrl, body, headers, }) => {
3918
62
  var _a;
3919
63
  const url = new URL(`${baseUrl}/widgets/session/initialize`);
@@ -4166,7 +310,7 @@ const NutsInboxWidget = class {
4166
310
  }
4167
311
  setupSocket() {
4168
312
  if (this.token) {
4169
- this.socketRef = lookup(this.socketUrl, {
313
+ this.socketRef = socket_ioClient.io(this.socketUrl, {
4170
314
  reconnection: true,
4171
315
  reconnectionDelayMax: 10000,
4172
316
  transports: ['websocket'],
@@ -4223,7 +367,7 @@ const NutsInboxWidget = class {
4223
367
  return (index.h("div", { onClick: this.togglePopover, class: "BellIcon" }, index.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "32", height: "32", fill: "currentColor", class: "bi bi-bell", viewBox: "0 0 16 16" }, ' ', index.h("path", { d: "M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z" }), ' '), this.unseenCount > 0 ? (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", class: "nc-bell-button-dot css-0 css-1eg2znq" }, index.h("rect", { x: "1.5", y: "1.5", width: "13", height: "13", rx: "6.5", fill: "url(#paint0_linear_1722_2699)", stroke: "#1E1E26", "stroke-width": "3" }), index.h("defs", null, index.h("linearGradient", { id: "paint0_linear_1722_2699", x1: "8", y1: "13", x2: "8", y2: "3", gradientUnits: "userSpaceOnUse" }, index.h("stop", { "stop-color": "#FF512F" }), index.h("stop", { offset: "1", "stop-color": "#DD2476" }))))) : ('')));
4224
368
  }
4225
369
  render() {
4226
- return (index.h("div", { key: '8aaf695a90d66cdfe70898bdd4719146eb068040', ref: this.assignRefToStylingContainer, class: "Wrapper" }, index.h("div", { key: 'cf368ca584705447a2e996a2ae9eddf8a6b49d1a', ref: this.assignRefToBell, class: "BellIconWrapper" }, !this.isLoading && this.renderBellIcon()), this.popoverVisible && (index.h("nuts-popover", { key: '23c169106c9bb0760b0018d0d316a2ca8a4f6d86', "notification-action": this.notificationAction, sessionId: this.sessionId, admin: this.admin, "unseen-count": this.unseenCount, token: this.token, "backend-url": this.backendUrl, "operator-id": this.operatorId, "user-id": this.userId, language: this.language, "client-styling": this.clientStyling, "translation-url": this.translationUrl }))));
370
+ return (index.h("div", { key: 'bb43fa770a88fc3ba23d1b84a0a6a368e1ea477b', ref: this.assignRefToStylingContainer, class: "Wrapper" }, index.h("div", { key: '24f98cb04a9026d5c2d1c11145c322893a2093c1', ref: this.assignRefToBell, class: "BellIconWrapper" }, !this.isLoading && this.renderBellIcon()), this.popoverVisible && (index.h("nuts-popover", { key: 'ab978988c295abfcb753de8551e5e35d267cce12', "notification-action": this.notificationAction, sessionId: this.sessionId, admin: this.admin, "unseen-count": this.unseenCount, token: this.token, "backend-url": this.backendUrl, "operator-id": this.operatorId, "user-id": this.userId, language: this.language, "client-styling": this.clientStyling, "translation-url": this.translationUrl }))));
4227
371
  }
4228
372
  get el() { return index.getElement(this); }
4229
373
  static get watchers() { return {