@oox/socketio-client 1.0.0

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