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