@depup/primus 8.0.9-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +36 -0
  3. package/changes.json +30 -0
  4. package/dist/primus.js +3663 -0
  5. package/errors.js +51 -0
  6. package/index.js +1153 -0
  7. package/middleware/access-control.js +20 -0
  8. package/middleware/authorization.js +57 -0
  9. package/middleware/error.js +41 -0
  10. package/middleware/forwarded.js +18 -0
  11. package/middleware/no-cache.js +25 -0
  12. package/middleware/primus.js +47 -0
  13. package/middleware/spec.js +36 -0
  14. package/middleware/xss.js +28 -0
  15. package/package.json +140 -0
  16. package/parsers/binary.js +54 -0
  17. package/parsers/ejson.js +41 -0
  18. package/parsers/json.js +35 -0
  19. package/parsers/msgpack.js +55 -0
  20. package/parsers.json +12 -0
  21. package/primus.js +1158 -0
  22. package/spark.js +515 -0
  23. package/transformer.js +237 -0
  24. package/transformers/browserchannel/client.js +92 -0
  25. package/transformers/browserchannel/index.js +19 -0
  26. package/transformers/browserchannel/server.js +64 -0
  27. package/transformers/engine.io/README.md +34 -0
  28. package/transformers/engine.io/client.js +111 -0
  29. package/transformers/engine.io/index.js +15 -0
  30. package/transformers/engine.io/library.js +2273 -0
  31. package/transformers/engine.io/server.js +63 -0
  32. package/transformers/faye/client.js +103 -0
  33. package/transformers/faye/index.js +12 -0
  34. package/transformers/faye/server.js +85 -0
  35. package/transformers/sockjs/README.md +31 -0
  36. package/transformers/sockjs/client.js +86 -0
  37. package/transformers/sockjs/index.js +15 -0
  38. package/transformers/sockjs/library.js +4201 -0
  39. package/transformers/sockjs/server.js +108 -0
  40. package/transformers/uws/index.js +12 -0
  41. package/transformers/uws/server.js +131 -0
  42. package/transformers/websockets/client.js +112 -0
  43. package/transformers/websockets/index.js +12 -0
  44. package/transformers/websockets/server.js +77 -0
  45. package/transformers.json +26 -0
@@ -0,0 +1,2273 @@
1
+ (function (f) {
2
+ var g;
3
+
4
+ if (typeof window !== 'undefined') {
5
+ g = window;
6
+ } else if (typeof self !== 'undefined') {
7
+ g = self;
8
+ }
9
+
10
+ g.eio = f();
11
+ })(function () {
12
+ var eio = (function () {
13
+ 'use strict';
14
+
15
+ function _typeof(obj) {
16
+ "@babel/helpers - typeof";
17
+
18
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
19
+ return typeof obj;
20
+ } : function (obj) {
21
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
22
+ }, _typeof(obj);
23
+ }
24
+ function _classCallCheck(instance, Constructor) {
25
+ if (!(instance instanceof Constructor)) {
26
+ throw new TypeError("Cannot call a class as a function");
27
+ }
28
+ }
29
+ function _defineProperties(target, props) {
30
+ for (var i = 0; i < props.length; i++) {
31
+ var descriptor = props[i];
32
+ descriptor.enumerable = descriptor.enumerable || false;
33
+ descriptor.configurable = true;
34
+ if ("value" in descriptor) descriptor.writable = true;
35
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
36
+ }
37
+ }
38
+ function _createClass(Constructor, protoProps, staticProps) {
39
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
40
+ if (staticProps) _defineProperties(Constructor, staticProps);
41
+ Object.defineProperty(Constructor, "prototype", {
42
+ writable: false
43
+ });
44
+ return Constructor;
45
+ }
46
+ function _extends() {
47
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
48
+ for (var i = 1; i < arguments.length; i++) {
49
+ var source = arguments[i];
50
+ for (var key in source) {
51
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
52
+ target[key] = source[key];
53
+ }
54
+ }
55
+ }
56
+ return target;
57
+ };
58
+ return _extends.apply(this, arguments);
59
+ }
60
+ function _inherits(subClass, superClass) {
61
+ if (typeof superClass !== "function" && superClass !== null) {
62
+ throw new TypeError("Super expression must either be null or a function");
63
+ }
64
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
65
+ constructor: {
66
+ value: subClass,
67
+ writable: true,
68
+ configurable: true
69
+ }
70
+ });
71
+ Object.defineProperty(subClass, "prototype", {
72
+ writable: false
73
+ });
74
+ if (superClass) _setPrototypeOf(subClass, superClass);
75
+ }
76
+ function _getPrototypeOf(o) {
77
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
78
+ return o.__proto__ || Object.getPrototypeOf(o);
79
+ };
80
+ return _getPrototypeOf(o);
81
+ }
82
+ function _setPrototypeOf(o, p) {
83
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
84
+ o.__proto__ = p;
85
+ return o;
86
+ };
87
+ return _setPrototypeOf(o, p);
88
+ }
89
+ function _isNativeReflectConstruct() {
90
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
91
+ if (Reflect.construct.sham) return false;
92
+ if (typeof Proxy === "function") return true;
93
+ try {
94
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
95
+ return true;
96
+ } catch (e) {
97
+ return false;
98
+ }
99
+ }
100
+ function _construct(Parent, args, Class) {
101
+ if (_isNativeReflectConstruct()) {
102
+ _construct = Reflect.construct.bind();
103
+ } else {
104
+ _construct = function _construct(Parent, args, Class) {
105
+ var a = [null];
106
+ a.push.apply(a, args);
107
+ var Constructor = Function.bind.apply(Parent, a);
108
+ var instance = new Constructor();
109
+ if (Class) _setPrototypeOf(instance, Class.prototype);
110
+ return instance;
111
+ };
112
+ }
113
+ return _construct.apply(null, arguments);
114
+ }
115
+ function _isNativeFunction(fn) {
116
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
117
+ }
118
+ function _wrapNativeSuper(Class) {
119
+ var _cache = typeof Map === "function" ? new Map() : undefined;
120
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
121
+ if (Class === null || !_isNativeFunction(Class)) return Class;
122
+ if (typeof Class !== "function") {
123
+ throw new TypeError("Super expression must either be null or a function");
124
+ }
125
+ if (typeof _cache !== "undefined") {
126
+ if (_cache.has(Class)) return _cache.get(Class);
127
+ _cache.set(Class, Wrapper);
128
+ }
129
+ function Wrapper() {
130
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
131
+ }
132
+ Wrapper.prototype = Object.create(Class.prototype, {
133
+ constructor: {
134
+ value: Wrapper,
135
+ enumerable: false,
136
+ writable: true,
137
+ configurable: true
138
+ }
139
+ });
140
+ return _setPrototypeOf(Wrapper, Class);
141
+ };
142
+ return _wrapNativeSuper(Class);
143
+ }
144
+ function _assertThisInitialized(self) {
145
+ if (self === void 0) {
146
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
147
+ }
148
+ return self;
149
+ }
150
+ function _possibleConstructorReturn(self, call) {
151
+ if (call && (typeof call === "object" || typeof call === "function")) {
152
+ return call;
153
+ } else if (call !== void 0) {
154
+ throw new TypeError("Derived constructors may only return object or undefined");
155
+ }
156
+ return _assertThisInitialized(self);
157
+ }
158
+ function _createSuper(Derived) {
159
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
160
+ return function _createSuperInternal() {
161
+ var Super = _getPrototypeOf(Derived),
162
+ result;
163
+ if (hasNativeReflectConstruct) {
164
+ var NewTarget = _getPrototypeOf(this).constructor;
165
+ result = Reflect.construct(Super, arguments, NewTarget);
166
+ } else {
167
+ result = Super.apply(this, arguments);
168
+ }
169
+ return _possibleConstructorReturn(this, result);
170
+ };
171
+ }
172
+ function _superPropBase(object, property) {
173
+ while (!Object.prototype.hasOwnProperty.call(object, property)) {
174
+ object = _getPrototypeOf(object);
175
+ if (object === null) break;
176
+ }
177
+ return object;
178
+ }
179
+ function _get() {
180
+ if (typeof Reflect !== "undefined" && Reflect.get) {
181
+ _get = Reflect.get.bind();
182
+ } else {
183
+ _get = function _get(target, property, receiver) {
184
+ var base = _superPropBase(target, property);
185
+ if (!base) return;
186
+ var desc = Object.getOwnPropertyDescriptor(base, property);
187
+ if (desc.get) {
188
+ return desc.get.call(arguments.length < 3 ? target : receiver);
189
+ }
190
+ return desc.value;
191
+ };
192
+ }
193
+ return _get.apply(this, arguments);
194
+ }
195
+ function _toPrimitive(input, hint) {
196
+ if (typeof input !== "object" || input === null) return input;
197
+ var prim = input[Symbol.toPrimitive];
198
+ if (prim !== undefined) {
199
+ var res = prim.call(input, hint || "default");
200
+ if (typeof res !== "object") return res;
201
+ throw new TypeError("@@toPrimitive must return a primitive value.");
202
+ }
203
+ return (hint === "string" ? String : Number)(input);
204
+ }
205
+ function _toPropertyKey(arg) {
206
+ var key = _toPrimitive(arg, "string");
207
+ return typeof key === "symbol" ? key : String(key);
208
+ }
209
+
210
+ var PACKET_TYPES = Object.create(null); // no Map = no polyfill
211
+ PACKET_TYPES["open"] = "0";
212
+ PACKET_TYPES["close"] = "1";
213
+ PACKET_TYPES["ping"] = "2";
214
+ PACKET_TYPES["pong"] = "3";
215
+ PACKET_TYPES["message"] = "4";
216
+ PACKET_TYPES["upgrade"] = "5";
217
+ PACKET_TYPES["noop"] = "6";
218
+ var PACKET_TYPES_REVERSE = Object.create(null);
219
+ Object.keys(PACKET_TYPES).forEach(function (key) {
220
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
221
+ });
222
+ var ERROR_PACKET = {
223
+ type: "error",
224
+ data: "parser error"
225
+ };
226
+
227
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
228
+ var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
229
+ // ArrayBuffer.isView method is not defined in IE10
230
+ var isView = function isView(obj) {
231
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
232
+ };
233
+ var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
234
+ var type = _ref.type,
235
+ data = _ref.data;
236
+ if (withNativeBlob && data instanceof Blob) {
237
+ if (supportsBinary) {
238
+ return callback(data);
239
+ } else {
240
+ return encodeBlobAsBase64(data, callback);
241
+ }
242
+ } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) {
243
+ if (supportsBinary) {
244
+ return callback(data);
245
+ } else {
246
+ return encodeBlobAsBase64(new Blob([data]), callback);
247
+ }
248
+ }
249
+ // plain string
250
+ return callback(PACKET_TYPES[type] + (data || ""));
251
+ };
252
+ var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
253
+ var fileReader = new FileReader();
254
+ fileReader.onload = function () {
255
+ var content = fileReader.result.split(",")[1];
256
+ callback("b" + (content || ""));
257
+ };
258
+ return fileReader.readAsDataURL(data);
259
+ };
260
+ function toArray(data) {
261
+ if (data instanceof Uint8Array) {
262
+ return data;
263
+ } else if (data instanceof ArrayBuffer) {
264
+ return new Uint8Array(data);
265
+ } else {
266
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
267
+ }
268
+ }
269
+ var TEXT_ENCODER;
270
+ function encodePacketToBinary(packet, callback) {
271
+ if (withNativeBlob && packet.data instanceof Blob) {
272
+ return packet.data.arrayBuffer().then(toArray).then(callback);
273
+ } else if (withNativeArrayBuffer$1 && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
274
+ return callback(toArray(packet.data));
275
+ }
276
+ encodePacket(packet, false, function (encoded) {
277
+ if (!TEXT_ENCODER) {
278
+ TEXT_ENCODER = new TextEncoder();
279
+ }
280
+ callback(TEXT_ENCODER.encode(encoded));
281
+ });
282
+ }
283
+
284
+ // imported from https://github.com/socketio/base64-arraybuffer
285
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
286
+ // Use a lookup table to find the index.
287
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
288
+ for (var i$1 = 0; i$1 < chars.length; i$1++) {
289
+ lookup[chars.charCodeAt(i$1)] = i$1;
290
+ }
291
+ var decode$1 = function decode(base64) {
292
+ var bufferLength = base64.length * 0.75,
293
+ len = base64.length,
294
+ i,
295
+ p = 0,
296
+ encoded1,
297
+ encoded2,
298
+ encoded3,
299
+ encoded4;
300
+ if (base64[base64.length - 1] === '=') {
301
+ bufferLength--;
302
+ if (base64[base64.length - 2] === '=') {
303
+ bufferLength--;
304
+ }
305
+ }
306
+ var arraybuffer = new ArrayBuffer(bufferLength),
307
+ bytes = new Uint8Array(arraybuffer);
308
+ for (i = 0; i < len; i += 4) {
309
+ encoded1 = lookup[base64.charCodeAt(i)];
310
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
311
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
312
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
313
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
314
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
315
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
316
+ }
317
+ return arraybuffer;
318
+ };
319
+
320
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
321
+ var decodePacket = function decodePacket(encodedPacket, binaryType) {
322
+ if (typeof encodedPacket !== "string") {
323
+ return {
324
+ type: "message",
325
+ data: mapBinary(encodedPacket, binaryType)
326
+ };
327
+ }
328
+ var type = encodedPacket.charAt(0);
329
+ if (type === "b") {
330
+ return {
331
+ type: "message",
332
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
333
+ };
334
+ }
335
+ var packetType = PACKET_TYPES_REVERSE[type];
336
+ if (!packetType) {
337
+ return ERROR_PACKET;
338
+ }
339
+ return encodedPacket.length > 1 ? {
340
+ type: PACKET_TYPES_REVERSE[type],
341
+ data: encodedPacket.substring(1)
342
+ } : {
343
+ type: PACKET_TYPES_REVERSE[type]
344
+ };
345
+ };
346
+ var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
347
+ if (withNativeArrayBuffer) {
348
+ var decoded = decode$1(data);
349
+ return mapBinary(decoded, binaryType);
350
+ } else {
351
+ return {
352
+ base64: true,
353
+ data: data
354
+ }; // fallback for old browsers
355
+ }
356
+ };
357
+
358
+ var mapBinary = function mapBinary(data, binaryType) {
359
+ switch (binaryType) {
360
+ case "blob":
361
+ if (data instanceof Blob) {
362
+ // from WebSocket + binaryType "blob"
363
+ return data;
364
+ } else {
365
+ // from HTTP long-polling or WebTransport
366
+ return new Blob([data]);
367
+ }
368
+ case "arraybuffer":
369
+ default:
370
+ if (data instanceof ArrayBuffer) {
371
+ // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
372
+ return data;
373
+ } else {
374
+ // from WebTransport (Uint8Array)
375
+ return data.buffer;
376
+ }
377
+ }
378
+ };
379
+
380
+ var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
381
+ var encodePayload = function encodePayload(packets, callback) {
382
+ // some packets may be added to the array while encoding, so the initial length must be saved
383
+ var length = packets.length;
384
+ var encodedPackets = new Array(length);
385
+ var count = 0;
386
+ packets.forEach(function (packet, i) {
387
+ // force base64 encoding for binary packets
388
+ encodePacket(packet, false, function (encodedPacket) {
389
+ encodedPackets[i] = encodedPacket;
390
+ if (++count === length) {
391
+ callback(encodedPackets.join(SEPARATOR));
392
+ }
393
+ });
394
+ });
395
+ };
396
+ var decodePayload = function decodePayload(encodedPayload, binaryType) {
397
+ var encodedPackets = encodedPayload.split(SEPARATOR);
398
+ var packets = [];
399
+ for (var i = 0; i < encodedPackets.length; i++) {
400
+ var decodedPacket = decodePacket(encodedPackets[i], binaryType);
401
+ packets.push(decodedPacket);
402
+ if (decodedPacket.type === "error") {
403
+ break;
404
+ }
405
+ }
406
+ return packets;
407
+ };
408
+ var TEXT_DECODER;
409
+ function decodePacketFromBinary(data, isBinary, binaryType) {
410
+ if (!TEXT_DECODER) {
411
+ // lazily created for compatibility with old browser platforms
412
+ TEXT_DECODER = new TextDecoder();
413
+ }
414
+ // 48 === "0".charCodeAt(0) (OPEN packet type)
415
+ // 54 === "6".charCodeAt(0) (NOOP packet type)
416
+ var isPlainBinary = isBinary || data[0] < 48 || data[0] > 54;
417
+ return decodePacket(isPlainBinary ? data : TEXT_DECODER.decode(data), binaryType);
418
+ }
419
+ var protocol = 4;
420
+
421
+ /**
422
+ * Initialize a new `Emitter`.
423
+ *
424
+ * @api public
425
+ */
426
+
427
+ function Emitter(obj) {
428
+ if (obj) return mixin(obj);
429
+ }
430
+
431
+ /**
432
+ * Mixin the emitter properties.
433
+ *
434
+ * @param {Object} obj
435
+ * @return {Object}
436
+ * @api private
437
+ */
438
+
439
+ function mixin(obj) {
440
+ for (var key in Emitter.prototype) {
441
+ obj[key] = Emitter.prototype[key];
442
+ }
443
+ return obj;
444
+ }
445
+
446
+ /**
447
+ * Listen on the given `event` with `fn`.
448
+ *
449
+ * @param {String} event
450
+ * @param {Function} fn
451
+ * @return {Emitter}
452
+ * @api public
453
+ */
454
+
455
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
456
+ this._callbacks = this._callbacks || {};
457
+ (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
458
+ return this;
459
+ };
460
+
461
+ /**
462
+ * Adds an `event` listener that will be invoked a single
463
+ * time then automatically removed.
464
+ *
465
+ * @param {String} event
466
+ * @param {Function} fn
467
+ * @return {Emitter}
468
+ * @api public
469
+ */
470
+
471
+ Emitter.prototype.once = function (event, fn) {
472
+ function on() {
473
+ this.off(event, on);
474
+ fn.apply(this, arguments);
475
+ }
476
+ on.fn = fn;
477
+ this.on(event, on);
478
+ return this;
479
+ };
480
+
481
+ /**
482
+ * Remove the given callback for `event` or all
483
+ * registered callbacks.
484
+ *
485
+ * @param {String} event
486
+ * @param {Function} fn
487
+ * @return {Emitter}
488
+ * @api public
489
+ */
490
+
491
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
492
+ this._callbacks = this._callbacks || {};
493
+
494
+ // all
495
+ if (0 == arguments.length) {
496
+ this._callbacks = {};
497
+ return this;
498
+ }
499
+
500
+ // specific event
501
+ var callbacks = this._callbacks['$' + event];
502
+ if (!callbacks) return this;
503
+
504
+ // remove all handlers
505
+ if (1 == arguments.length) {
506
+ delete this._callbacks['$' + event];
507
+ return this;
508
+ }
509
+
510
+ // remove specific handler
511
+ var cb;
512
+ for (var i = 0; i < callbacks.length; i++) {
513
+ cb = callbacks[i];
514
+ if (cb === fn || cb.fn === fn) {
515
+ callbacks.splice(i, 1);
516
+ break;
517
+ }
518
+ }
519
+
520
+ // Remove event specific arrays for event types that no
521
+ // one is subscribed for to avoid memory leak.
522
+ if (callbacks.length === 0) {
523
+ delete this._callbacks['$' + event];
524
+ }
525
+ return this;
526
+ };
527
+
528
+ /**
529
+ * Emit `event` with the given args.
530
+ *
531
+ * @param {String} event
532
+ * @param {Mixed} ...
533
+ * @return {Emitter}
534
+ */
535
+
536
+ Emitter.prototype.emit = function (event) {
537
+ this._callbacks = this._callbacks || {};
538
+ var args = new Array(arguments.length - 1),
539
+ callbacks = this._callbacks['$' + event];
540
+ for (var i = 1; i < arguments.length; i++) {
541
+ args[i - 1] = arguments[i];
542
+ }
543
+ if (callbacks) {
544
+ callbacks = callbacks.slice(0);
545
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
546
+ callbacks[i].apply(this, args);
547
+ }
548
+ }
549
+ return this;
550
+ };
551
+
552
+ // alias used for reserved events (protected method)
553
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
554
+
555
+ /**
556
+ * Return array of callbacks for `event`.
557
+ *
558
+ * @param {String} event
559
+ * @return {Array}
560
+ * @api public
561
+ */
562
+
563
+ Emitter.prototype.listeners = function (event) {
564
+ this._callbacks = this._callbacks || {};
565
+ return this._callbacks['$' + event] || [];
566
+ };
567
+
568
+ /**
569
+ * Check if this emitter has `event` handlers.
570
+ *
571
+ * @param {String} event
572
+ * @return {Boolean}
573
+ * @api public
574
+ */
575
+
576
+ Emitter.prototype.hasListeners = function (event) {
577
+ return !!this.listeners(event).length;
578
+ };
579
+
580
+ var globalThisShim = function () {
581
+ if (typeof self !== "undefined") {
582
+ return self;
583
+ } else if (typeof window !== "undefined") {
584
+ return window;
585
+ } else {
586
+ return Function("return this")();
587
+ }
588
+ }();
589
+
590
+ function pick(obj) {
591
+ for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
592
+ attr[_key - 1] = arguments[_key];
593
+ }
594
+ return attr.reduce(function (acc, k) {
595
+ if (obj.hasOwnProperty(k)) {
596
+ acc[k] = obj[k];
597
+ }
598
+ return acc;
599
+ }, {});
600
+ }
601
+ // Keep a reference to the real timeout functions so they can be used when overridden
602
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
603
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
604
+ function installTimerFunctions(obj, opts) {
605
+ if (opts.useNativeTimers) {
606
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
607
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
608
+ } else {
609
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
610
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
611
+ }
612
+ }
613
+ // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
614
+ var BASE64_OVERHEAD = 1.33;
615
+ // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
616
+ function byteLength(obj) {
617
+ if (typeof obj === "string") {
618
+ return utf8Length(obj);
619
+ }
620
+ // arraybuffer or blob
621
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
622
+ }
623
+ function utf8Length(str) {
624
+ var c = 0,
625
+ length = 0;
626
+ for (var i = 0, l = str.length; i < l; i++) {
627
+ c = str.charCodeAt(i);
628
+ if (c < 0x80) {
629
+ length += 1;
630
+ } else if (c < 0x800) {
631
+ length += 2;
632
+ } else if (c < 0xd800 || c >= 0xe000) {
633
+ length += 3;
634
+ } else {
635
+ i++;
636
+ length += 4;
637
+ }
638
+ }
639
+ return length;
640
+ }
641
+
642
+ // imported from https://github.com/galkn/querystring
643
+ /**
644
+ * Compiles a querystring
645
+ * Returns string representation of the object
646
+ *
647
+ * @param {Object}
648
+ * @api private
649
+ */
650
+ function encode$1(obj) {
651
+ var str = '';
652
+ for (var i in obj) {
653
+ if (obj.hasOwnProperty(i)) {
654
+ if (str.length) str += '&';
655
+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
656
+ }
657
+ }
658
+ return str;
659
+ }
660
+ /**
661
+ * Parses a simple querystring into an object
662
+ *
663
+ * @param {String} qs
664
+ * @api private
665
+ */
666
+ function decode(qs) {
667
+ var qry = {};
668
+ var pairs = qs.split('&');
669
+ for (var i = 0, l = pairs.length; i < l; i++) {
670
+ var pair = pairs[i].split('=');
671
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
672
+ }
673
+ return qry;
674
+ }
675
+
676
+ var TransportError = /*#__PURE__*/function (_Error) {
677
+ _inherits(TransportError, _Error);
678
+ var _super = _createSuper(TransportError);
679
+ function TransportError(reason, description, context) {
680
+ var _this;
681
+ _classCallCheck(this, TransportError);
682
+ _this = _super.call(this, reason);
683
+ _this.description = description;
684
+ _this.context = context;
685
+ _this.type = "TransportError";
686
+ return _this;
687
+ }
688
+ return _createClass(TransportError);
689
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
690
+ var Transport = /*#__PURE__*/function (_Emitter) {
691
+ _inherits(Transport, _Emitter);
692
+ var _super2 = _createSuper(Transport);
693
+ /**
694
+ * Transport abstract constructor.
695
+ *
696
+ * @param {Object} opts - options
697
+ * @protected
698
+ */
699
+ function Transport(opts) {
700
+ var _this2;
701
+ _classCallCheck(this, Transport);
702
+ _this2 = _super2.call(this);
703
+ _this2.writable = false;
704
+ installTimerFunctions(_assertThisInitialized(_this2), opts);
705
+ _this2.opts = opts;
706
+ _this2.query = opts.query;
707
+ _this2.socket = opts.socket;
708
+ return _this2;
709
+ }
710
+ /**
711
+ * Emits an error.
712
+ *
713
+ * @param {String} reason
714
+ * @param description
715
+ * @param context - the error context
716
+ * @return {Transport} for chaining
717
+ * @protected
718
+ */
719
+ _createClass(Transport, [{
720
+ key: "onError",
721
+ value: function onError(reason, description, context) {
722
+ _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
723
+ return this;
724
+ }
725
+ /**
726
+ * Opens the transport.
727
+ */
728
+ }, {
729
+ key: "open",
730
+ value: function open() {
731
+ this.readyState = "opening";
732
+ this.doOpen();
733
+ return this;
734
+ }
735
+ /**
736
+ * Closes the transport.
737
+ */
738
+ }, {
739
+ key: "close",
740
+ value: function close() {
741
+ if (this.readyState === "opening" || this.readyState === "open") {
742
+ this.doClose();
743
+ this.onClose();
744
+ }
745
+ return this;
746
+ }
747
+ /**
748
+ * Sends multiple packets.
749
+ *
750
+ * @param {Array} packets
751
+ */
752
+ }, {
753
+ key: "send",
754
+ value: function send(packets) {
755
+ if (this.readyState === "open") {
756
+ this.write(packets);
757
+ }
758
+ }
759
+ /**
760
+ * Called upon open
761
+ *
762
+ * @protected
763
+ */
764
+ }, {
765
+ key: "onOpen",
766
+ value: function onOpen() {
767
+ this.readyState = "open";
768
+ this.writable = true;
769
+ _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
770
+ }
771
+ /**
772
+ * Called with data.
773
+ *
774
+ * @param {String} data
775
+ * @protected
776
+ */
777
+ }, {
778
+ key: "onData",
779
+ value: function onData(data) {
780
+ var packet = decodePacket(data, this.socket.binaryType);
781
+ this.onPacket(packet);
782
+ }
783
+ /**
784
+ * Called with a decoded packet.
785
+ *
786
+ * @protected
787
+ */
788
+ }, {
789
+ key: "onPacket",
790
+ value: function onPacket(packet) {
791
+ _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
792
+ }
793
+ /**
794
+ * Called upon close.
795
+ *
796
+ * @protected
797
+ */
798
+ }, {
799
+ key: "onClose",
800
+ value: function onClose(details) {
801
+ this.readyState = "closed";
802
+ _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
803
+ }
804
+ /**
805
+ * Pauses the transport, in order not to lose packets during an upgrade.
806
+ *
807
+ * @param onPause
808
+ */
809
+ }, {
810
+ key: "pause",
811
+ value: function pause(onPause) {}
812
+ }, {
813
+ key: "createUri",
814
+ value: function createUri(schema) {
815
+ var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
816
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
817
+ }
818
+ }, {
819
+ key: "_hostname",
820
+ value: function _hostname() {
821
+ var hostname = this.opts.hostname;
822
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
823
+ }
824
+ }, {
825
+ key: "_port",
826
+ value: function _port() {
827
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
828
+ return ":" + this.opts.port;
829
+ } else {
830
+ return "";
831
+ }
832
+ }
833
+ }, {
834
+ key: "_query",
835
+ value: function _query(query) {
836
+ var encodedQuery = encode$1(query);
837
+ return encodedQuery.length ? "?" + encodedQuery : "";
838
+ }
839
+ }]);
840
+ return Transport;
841
+ }(Emitter);
842
+
843
+ // imported from https://github.com/unshiftio/yeast
844
+
845
+ var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
846
+ length = 64,
847
+ map = {};
848
+ var seed = 0,
849
+ i = 0,
850
+ prev;
851
+ /**
852
+ * Return a string representing the specified number.
853
+ *
854
+ * @param {Number} num The number to convert.
855
+ * @returns {String} The string representation of the number.
856
+ * @api public
857
+ */
858
+ function encode(num) {
859
+ var encoded = '';
860
+ do {
861
+ encoded = alphabet[num % length] + encoded;
862
+ num = Math.floor(num / length);
863
+ } while (num > 0);
864
+ return encoded;
865
+ }
866
+ /**
867
+ * Yeast: A tiny growing id generator.
868
+ *
869
+ * @returns {String} A unique id.
870
+ * @api public
871
+ */
872
+ function yeast() {
873
+ var now = encode(+new Date());
874
+ if (now !== prev) return seed = 0, prev = now;
875
+ return now + '.' + encode(seed++);
876
+ }
877
+ //
878
+ // Map each character to its index.
879
+ //
880
+ for (; i < length; i++) map[alphabet[i]] = i;
881
+
882
+ // imported from https://github.com/component/has-cors
883
+ var value = false;
884
+ try {
885
+ value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
886
+ } catch (err) {
887
+ // if XMLHttp support is disabled in IE then it will throw
888
+ // when trying to create
889
+ }
890
+ var hasCORS = value;
891
+
892
+ // browser shim for xmlhttprequest module
893
+ function XHR(opts) {
894
+ var xdomain = opts.xdomain;
895
+ // XMLHttpRequest can be disabled on IE
896
+ try {
897
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
898
+ return new XMLHttpRequest();
899
+ }
900
+ } catch (e) {}
901
+ if (!xdomain) {
902
+ try {
903
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
904
+ } catch (e) {}
905
+ }
906
+ }
907
+ function createCookieJar() {}
908
+
909
+ function empty() {}
910
+ var hasXHR2 = function () {
911
+ var xhr = new XHR({
912
+ xdomain: false
913
+ });
914
+ return null != xhr.responseType;
915
+ }();
916
+ var Polling = /*#__PURE__*/function (_Transport) {
917
+ _inherits(Polling, _Transport);
918
+ var _super = _createSuper(Polling);
919
+ /**
920
+ * XHR Polling constructor.
921
+ *
922
+ * @param {Object} opts
923
+ * @package
924
+ */
925
+ function Polling(opts) {
926
+ var _this;
927
+ _classCallCheck(this, Polling);
928
+ _this = _super.call(this, opts);
929
+ _this.polling = false;
930
+ if (typeof location !== "undefined") {
931
+ var isSSL = "https:" === location.protocol;
932
+ var port = location.port;
933
+ // some user agents have empty `location.port`
934
+ if (!port) {
935
+ port = isSSL ? "443" : "80";
936
+ }
937
+ _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
938
+ }
939
+ /**
940
+ * XHR supports binary
941
+ */
942
+ var forceBase64 = opts && opts.forceBase64;
943
+ _this.supportsBinary = hasXHR2 && !forceBase64;
944
+ if (_this.opts.withCredentials) {
945
+ _this.cookieJar = createCookieJar();
946
+ }
947
+ return _this;
948
+ }
949
+ _createClass(Polling, [{
950
+ key: "name",
951
+ get: function get() {
952
+ return "polling";
953
+ }
954
+ /**
955
+ * Opens the socket (triggers polling). We write a PING message to determine
956
+ * when the transport is open.
957
+ *
958
+ * @protected
959
+ */
960
+ }, {
961
+ key: "doOpen",
962
+ value: function doOpen() {
963
+ this.poll();
964
+ }
965
+ /**
966
+ * Pauses polling.
967
+ *
968
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
969
+ * @package
970
+ */
971
+ }, {
972
+ key: "pause",
973
+ value: function pause(onPause) {
974
+ var _this2 = this;
975
+ this.readyState = "pausing";
976
+ var pause = function pause() {
977
+ _this2.readyState = "paused";
978
+ onPause();
979
+ };
980
+ if (this.polling || !this.writable) {
981
+ var total = 0;
982
+ if (this.polling) {
983
+ total++;
984
+ this.once("pollComplete", function () {
985
+ --total || pause();
986
+ });
987
+ }
988
+ if (!this.writable) {
989
+ total++;
990
+ this.once("drain", function () {
991
+ --total || pause();
992
+ });
993
+ }
994
+ } else {
995
+ pause();
996
+ }
997
+ }
998
+ /**
999
+ * Starts polling cycle.
1000
+ *
1001
+ * @private
1002
+ */
1003
+ }, {
1004
+ key: "poll",
1005
+ value: function poll() {
1006
+ this.polling = true;
1007
+ this.doPoll();
1008
+ this.emitReserved("poll");
1009
+ }
1010
+ /**
1011
+ * Overloads onData to detect payloads.
1012
+ *
1013
+ * @protected
1014
+ */
1015
+ }, {
1016
+ key: "onData",
1017
+ value: function onData(data) {
1018
+ var _this3 = this;
1019
+ var callback = function callback(packet) {
1020
+ // if its the first message we consider the transport open
1021
+ if ("opening" === _this3.readyState && packet.type === "open") {
1022
+ _this3.onOpen();
1023
+ }
1024
+ // if its a close packet, we close the ongoing requests
1025
+ if ("close" === packet.type) {
1026
+ _this3.onClose({
1027
+ description: "transport closed by the server"
1028
+ });
1029
+ return false;
1030
+ }
1031
+ // otherwise bypass onData and handle the message
1032
+ _this3.onPacket(packet);
1033
+ };
1034
+ // decode payload
1035
+ decodePayload(data, this.socket.binaryType).forEach(callback);
1036
+ // if an event did not trigger closing
1037
+ if ("closed" !== this.readyState) {
1038
+ // if we got data we're not polling
1039
+ this.polling = false;
1040
+ this.emitReserved("pollComplete");
1041
+ if ("open" === this.readyState) {
1042
+ this.poll();
1043
+ }
1044
+ }
1045
+ }
1046
+ /**
1047
+ * For polling, send a close packet.
1048
+ *
1049
+ * @protected
1050
+ */
1051
+ }, {
1052
+ key: "doClose",
1053
+ value: function doClose() {
1054
+ var _this4 = this;
1055
+ var close = function close() {
1056
+ _this4.write([{
1057
+ type: "close"
1058
+ }]);
1059
+ };
1060
+ if ("open" === this.readyState) {
1061
+ close();
1062
+ } else {
1063
+ // in case we're trying to close while
1064
+ // handshaking is in progress (GH-164)
1065
+ this.once("open", close);
1066
+ }
1067
+ }
1068
+ /**
1069
+ * Writes a packets payload.
1070
+ *
1071
+ * @param {Array} packets - data packets
1072
+ * @protected
1073
+ */
1074
+ }, {
1075
+ key: "write",
1076
+ value: function write(packets) {
1077
+ var _this5 = this;
1078
+ this.writable = false;
1079
+ encodePayload(packets, function (data) {
1080
+ _this5.doWrite(data, function () {
1081
+ _this5.writable = true;
1082
+ _this5.emitReserved("drain");
1083
+ });
1084
+ });
1085
+ }
1086
+ /**
1087
+ * Generates uri for connection.
1088
+ *
1089
+ * @private
1090
+ */
1091
+ }, {
1092
+ key: "uri",
1093
+ value: function uri() {
1094
+ var schema = this.opts.secure ? "https" : "http";
1095
+ var query = this.query || {};
1096
+ // cache busting is forced
1097
+ if (false !== this.opts.timestampRequests) {
1098
+ query[this.opts.timestampParam] = yeast();
1099
+ }
1100
+ if (!this.supportsBinary && !query.sid) {
1101
+ query.b64 = 1;
1102
+ }
1103
+ return this.createUri(schema, query);
1104
+ }
1105
+ /**
1106
+ * Creates a request.
1107
+ *
1108
+ * @param {String} method
1109
+ * @private
1110
+ */
1111
+ }, {
1112
+ key: "request",
1113
+ value: function request() {
1114
+ var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1115
+ _extends(opts, {
1116
+ xd: this.xd,
1117
+ cookieJar: this.cookieJar
1118
+ }, this.opts);
1119
+ return new Request(this.uri(), opts);
1120
+ }
1121
+ /**
1122
+ * Sends data.
1123
+ *
1124
+ * @param {String} data to send.
1125
+ * @param {Function} called upon flush.
1126
+ * @private
1127
+ */
1128
+ }, {
1129
+ key: "doWrite",
1130
+ value: function doWrite(data, fn) {
1131
+ var _this6 = this;
1132
+ var req = this.request({
1133
+ method: "POST",
1134
+ data: data
1135
+ });
1136
+ req.on("success", fn);
1137
+ req.on("error", function (xhrStatus, context) {
1138
+ _this6.onError("xhr post error", xhrStatus, context);
1139
+ });
1140
+ }
1141
+ /**
1142
+ * Starts a poll cycle.
1143
+ *
1144
+ * @private
1145
+ */
1146
+ }, {
1147
+ key: "doPoll",
1148
+ value: function doPoll() {
1149
+ var _this7 = this;
1150
+ var req = this.request();
1151
+ req.on("data", this.onData.bind(this));
1152
+ req.on("error", function (xhrStatus, context) {
1153
+ _this7.onError("xhr poll error", xhrStatus, context);
1154
+ });
1155
+ this.pollXhr = req;
1156
+ }
1157
+ }]);
1158
+ return Polling;
1159
+ }(Transport);
1160
+ var Request = /*#__PURE__*/function (_Emitter) {
1161
+ _inherits(Request, _Emitter);
1162
+ var _super2 = _createSuper(Request);
1163
+ /**
1164
+ * Request constructor
1165
+ *
1166
+ * @param {Object} options
1167
+ * @package
1168
+ */
1169
+ function Request(uri, opts) {
1170
+ var _this8;
1171
+ _classCallCheck(this, Request);
1172
+ _this8 = _super2.call(this);
1173
+ installTimerFunctions(_assertThisInitialized(_this8), opts);
1174
+ _this8.opts = opts;
1175
+ _this8.method = opts.method || "GET";
1176
+ _this8.uri = uri;
1177
+ _this8.data = undefined !== opts.data ? opts.data : null;
1178
+ _this8.create();
1179
+ return _this8;
1180
+ }
1181
+ /**
1182
+ * Creates the XHR object and sends the request.
1183
+ *
1184
+ * @private
1185
+ */
1186
+ _createClass(Request, [{
1187
+ key: "create",
1188
+ value: function create() {
1189
+ var _this9 = this;
1190
+ var _a;
1191
+ var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
1192
+ opts.xdomain = !!this.opts.xd;
1193
+ var xhr = this.xhr = new XHR(opts);
1194
+ try {
1195
+ xhr.open(this.method, this.uri, true);
1196
+ try {
1197
+ if (this.opts.extraHeaders) {
1198
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
1199
+ for (var i in this.opts.extraHeaders) {
1200
+ if (this.opts.extraHeaders.hasOwnProperty(i)) {
1201
+ xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
1202
+ }
1203
+ }
1204
+ }
1205
+ } catch (e) {}
1206
+ if ("POST" === this.method) {
1207
+ try {
1208
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
1209
+ } catch (e) {}
1210
+ }
1211
+ try {
1212
+ xhr.setRequestHeader("Accept", "*/*");
1213
+ } catch (e) {}
1214
+ (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
1215
+ // ie6 check
1216
+ if ("withCredentials" in xhr) {
1217
+ xhr.withCredentials = this.opts.withCredentials;
1218
+ }
1219
+ if (this.opts.requestTimeout) {
1220
+ xhr.timeout = this.opts.requestTimeout;
1221
+ }
1222
+ xhr.onreadystatechange = function () {
1223
+ var _a;
1224
+ if (xhr.readyState === 3) {
1225
+ (_a = _this9.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr);
1226
+ }
1227
+ if (4 !== xhr.readyState) return;
1228
+ if (200 === xhr.status || 1223 === xhr.status) {
1229
+ _this9.onLoad();
1230
+ } else {
1231
+ // make sure the `error` event handler that's user-set
1232
+ // does not throw in the same tick and gets caught here
1233
+ _this9.setTimeoutFn(function () {
1234
+ _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
1235
+ }, 0);
1236
+ }
1237
+ };
1238
+ xhr.send(this.data);
1239
+ } catch (e) {
1240
+ // Need to defer since .create() is called directly from the constructor
1241
+ // and thus the 'error' event can only be only bound *after* this exception
1242
+ // occurs. Therefore, also, we cannot throw here at all.
1243
+ this.setTimeoutFn(function () {
1244
+ _this9.onError(e);
1245
+ }, 0);
1246
+ return;
1247
+ }
1248
+ if (typeof document !== "undefined") {
1249
+ this.index = Request.requestsCount++;
1250
+ Request.requests[this.index] = this;
1251
+ }
1252
+ }
1253
+ /**
1254
+ * Called upon error.
1255
+ *
1256
+ * @private
1257
+ */
1258
+ }, {
1259
+ key: "onError",
1260
+ value: function onError(err) {
1261
+ this.emitReserved("error", err, this.xhr);
1262
+ this.cleanup(true);
1263
+ }
1264
+ /**
1265
+ * Cleans up house.
1266
+ *
1267
+ * @private
1268
+ */
1269
+ }, {
1270
+ key: "cleanup",
1271
+ value: function cleanup(fromError) {
1272
+ if ("undefined" === typeof this.xhr || null === this.xhr) {
1273
+ return;
1274
+ }
1275
+ this.xhr.onreadystatechange = empty;
1276
+ if (fromError) {
1277
+ try {
1278
+ this.xhr.abort();
1279
+ } catch (e) {}
1280
+ }
1281
+ if (typeof document !== "undefined") {
1282
+ delete Request.requests[this.index];
1283
+ }
1284
+ this.xhr = null;
1285
+ }
1286
+ /**
1287
+ * Called upon load.
1288
+ *
1289
+ * @private
1290
+ */
1291
+ }, {
1292
+ key: "onLoad",
1293
+ value: function onLoad() {
1294
+ var data = this.xhr.responseText;
1295
+ if (data !== null) {
1296
+ this.emitReserved("data", data);
1297
+ this.emitReserved("success");
1298
+ this.cleanup();
1299
+ }
1300
+ }
1301
+ /**
1302
+ * Aborts the request.
1303
+ *
1304
+ * @package
1305
+ */
1306
+ }, {
1307
+ key: "abort",
1308
+ value: function abort() {
1309
+ this.cleanup();
1310
+ }
1311
+ }]);
1312
+ return Request;
1313
+ }(Emitter);
1314
+ Request.requestsCount = 0;
1315
+ Request.requests = {};
1316
+ /**
1317
+ * Aborts pending requests when unloading the window. This is needed to prevent
1318
+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is
1319
+ * emitted.
1320
+ */
1321
+ if (typeof document !== "undefined") {
1322
+ // @ts-ignore
1323
+ if (typeof attachEvent === "function") {
1324
+ // @ts-ignore
1325
+ attachEvent("onunload", unloadHandler);
1326
+ } else if (typeof addEventListener === "function") {
1327
+ var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
1328
+ addEventListener(terminationEvent, unloadHandler, false);
1329
+ }
1330
+ }
1331
+ function unloadHandler() {
1332
+ for (var i in Request.requests) {
1333
+ if (Request.requests.hasOwnProperty(i)) {
1334
+ Request.requests[i].abort();
1335
+ }
1336
+ }
1337
+ }
1338
+
1339
+ var nextTick = function () {
1340
+ var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
1341
+ if (isPromiseAvailable) {
1342
+ return function (cb) {
1343
+ return Promise.resolve().then(cb);
1344
+ };
1345
+ } else {
1346
+ return function (cb, setTimeoutFn) {
1347
+ return setTimeoutFn(cb, 0);
1348
+ };
1349
+ }
1350
+ }();
1351
+ var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1352
+ var usingBrowserWebSocket = true;
1353
+ var defaultBinaryType = "arraybuffer";
1354
+
1355
+ // detect ReactNative environment
1356
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
1357
+ var WS = /*#__PURE__*/function (_Transport) {
1358
+ _inherits(WS, _Transport);
1359
+ var _super = _createSuper(WS);
1360
+ /**
1361
+ * WebSocket transport constructor.
1362
+ *
1363
+ * @param {Object} opts - connection options
1364
+ * @protected
1365
+ */
1366
+ function WS(opts) {
1367
+ var _this;
1368
+ _classCallCheck(this, WS);
1369
+ _this = _super.call(this, opts);
1370
+ _this.supportsBinary = !opts.forceBase64;
1371
+ return _this;
1372
+ }
1373
+ _createClass(WS, [{
1374
+ key: "name",
1375
+ get: function get() {
1376
+ return "websocket";
1377
+ }
1378
+ }, {
1379
+ key: "doOpen",
1380
+ value: function doOpen() {
1381
+ if (!this.check()) {
1382
+ // let probe timeout
1383
+ return;
1384
+ }
1385
+ var uri = this.uri();
1386
+ var protocols = this.opts.protocols;
1387
+ // React Native only supports the 'headers' option, and will print a warning if anything else is passed
1388
+ var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1389
+ if (this.opts.extraHeaders) {
1390
+ opts.headers = this.opts.extraHeaders;
1391
+ }
1392
+ try {
1393
+ this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
1394
+ } catch (err) {
1395
+ return this.emitReserved("error", err);
1396
+ }
1397
+ this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
1398
+ this.addEventListeners();
1399
+ }
1400
+ /**
1401
+ * Adds event listeners to the socket
1402
+ *
1403
+ * @private
1404
+ */
1405
+ }, {
1406
+ key: "addEventListeners",
1407
+ value: function addEventListeners() {
1408
+ var _this2 = this;
1409
+ this.ws.onopen = function () {
1410
+ if (_this2.opts.autoUnref) {
1411
+ _this2.ws._socket.unref();
1412
+ }
1413
+ _this2.onOpen();
1414
+ };
1415
+ this.ws.onclose = function (closeEvent) {
1416
+ return _this2.onClose({
1417
+ description: "websocket connection closed",
1418
+ context: closeEvent
1419
+ });
1420
+ };
1421
+ this.ws.onmessage = function (ev) {
1422
+ return _this2.onData(ev.data);
1423
+ };
1424
+ this.ws.onerror = function (e) {
1425
+ return _this2.onError("websocket error", e);
1426
+ };
1427
+ }
1428
+ }, {
1429
+ key: "write",
1430
+ value: function write(packets) {
1431
+ var _this3 = this;
1432
+ this.writable = false;
1433
+ // encodePacket efficient as it uses WS framing
1434
+ // no need for encodePayload
1435
+ var _loop = function _loop() {
1436
+ var packet = packets[i];
1437
+ var lastPacket = i === packets.length - 1;
1438
+ encodePacket(packet, _this3.supportsBinary, function (data) {
1439
+ // always create a new object (GH-437)
1440
+ var opts = {};
1441
+ // Sometimes the websocket has already been closed but the browser didn't
1442
+ // have a chance of informing us about it yet, in that case send will
1443
+ // throw an error
1444
+ try {
1445
+ if (usingBrowserWebSocket) {
1446
+ // TypeError is thrown when passing the second argument on Safari
1447
+ _this3.ws.send(data);
1448
+ }
1449
+ } catch (e) {}
1450
+ if (lastPacket) {
1451
+ // fake drain
1452
+ // defer to next tick to allow Socket to clear writeBuffer
1453
+ nextTick(function () {
1454
+ _this3.writable = true;
1455
+ _this3.emitReserved("drain");
1456
+ }, _this3.setTimeoutFn);
1457
+ }
1458
+ });
1459
+ };
1460
+ for (var i = 0; i < packets.length; i++) {
1461
+ _loop();
1462
+ }
1463
+ }
1464
+ }, {
1465
+ key: "doClose",
1466
+ value: function doClose() {
1467
+ if (typeof this.ws !== "undefined") {
1468
+ this.ws.close();
1469
+ this.ws = null;
1470
+ }
1471
+ }
1472
+ /**
1473
+ * Generates uri for connection.
1474
+ *
1475
+ * @private
1476
+ */
1477
+ }, {
1478
+ key: "uri",
1479
+ value: function uri() {
1480
+ var schema = this.opts.secure ? "wss" : "ws";
1481
+ var query = this.query || {};
1482
+ // append timestamp to URI
1483
+ if (this.opts.timestampRequests) {
1484
+ query[this.opts.timestampParam] = yeast();
1485
+ }
1486
+ // communicate binary support capabilities
1487
+ if (!this.supportsBinary) {
1488
+ query.b64 = 1;
1489
+ }
1490
+ return this.createUri(schema, query);
1491
+ }
1492
+ /**
1493
+ * Feature detection for WebSocket.
1494
+ *
1495
+ * @return {Boolean} whether this transport is available.
1496
+ * @private
1497
+ */
1498
+ }, {
1499
+ key: "check",
1500
+ value: function check() {
1501
+ return !!WebSocket;
1502
+ }
1503
+ }]);
1504
+ return WS;
1505
+ }(Transport);
1506
+
1507
+ function shouldIncludeBinaryHeader(packet, encoded) {
1508
+ // 48 === "0".charCodeAt(0) (OPEN packet type)
1509
+ // 54 === "6".charCodeAt(0) (NOOP packet type)
1510
+ return packet.type === "message" && typeof packet.data !== "string" && encoded[0] >= 48 && encoded[0] <= 54;
1511
+ }
1512
+ var WT = /*#__PURE__*/function (_Transport) {
1513
+ _inherits(WT, _Transport);
1514
+ var _super = _createSuper(WT);
1515
+ function WT() {
1516
+ _classCallCheck(this, WT);
1517
+ return _super.apply(this, arguments);
1518
+ }
1519
+ _createClass(WT, [{
1520
+ key: "name",
1521
+ get: function get() {
1522
+ return "webtransport";
1523
+ }
1524
+ }, {
1525
+ key: "doOpen",
1526
+ value: function doOpen() {
1527
+ var _this = this;
1528
+ // @ts-ignore
1529
+ if (typeof WebTransport !== "function") {
1530
+ return;
1531
+ }
1532
+ // @ts-ignore
1533
+ this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1534
+ this.transport.closed.then(function () {
1535
+ _this.onClose();
1536
+ })["catch"](function (err) {
1537
+ _this.onError("webtransport error", err);
1538
+ });
1539
+ // note: we could have used async/await, but that would require some additional polyfills
1540
+ this.transport.ready.then(function () {
1541
+ _this.transport.createBidirectionalStream().then(function (stream) {
1542
+ var reader = stream.readable.getReader();
1543
+ _this.writer = stream.writable.getWriter();
1544
+ var binaryFlag;
1545
+ var read = function read() {
1546
+ reader.read().then(function (_ref) {
1547
+ var done = _ref.done,
1548
+ value = _ref.value;
1549
+ if (done) {
1550
+ return;
1551
+ }
1552
+ if (!binaryFlag && value.byteLength === 1 && value[0] === 54) {
1553
+ binaryFlag = true;
1554
+ } else {
1555
+ // TODO expose binarytype
1556
+ _this.onPacket(decodePacketFromBinary(value, binaryFlag, "arraybuffer"));
1557
+ binaryFlag = false;
1558
+ }
1559
+ read();
1560
+ })["catch"](function (err) {});
1561
+ };
1562
+ read();
1563
+ var handshake = _this.query.sid ? "0{\"sid\":\"".concat(_this.query.sid, "\"}") : "0";
1564
+ _this.writer.write(new TextEncoder().encode(handshake)).then(function () {
1565
+ return _this.onOpen();
1566
+ });
1567
+ });
1568
+ });
1569
+ }
1570
+ }, {
1571
+ key: "write",
1572
+ value: function write(packets) {
1573
+ var _this2 = this;
1574
+ this.writable = false;
1575
+ var _loop = function _loop() {
1576
+ var packet = packets[i];
1577
+ var lastPacket = i === packets.length - 1;
1578
+ encodePacketToBinary(packet, function (data) {
1579
+ if (shouldIncludeBinaryHeader(packet, data)) {
1580
+ _this2.writer.write(Uint8Array.of(54));
1581
+ }
1582
+ _this2.writer.write(data).then(function () {
1583
+ if (lastPacket) {
1584
+ nextTick(function () {
1585
+ _this2.writable = true;
1586
+ _this2.emitReserved("drain");
1587
+ }, _this2.setTimeoutFn);
1588
+ }
1589
+ });
1590
+ });
1591
+ };
1592
+ for (var i = 0; i < packets.length; i++) {
1593
+ _loop();
1594
+ }
1595
+ }
1596
+ }, {
1597
+ key: "doClose",
1598
+ value: function doClose() {
1599
+ var _a;
1600
+ (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close();
1601
+ }
1602
+ }]);
1603
+ return WT;
1604
+ }(Transport);
1605
+
1606
+ var transports = {
1607
+ websocket: WS,
1608
+ webtransport: WT,
1609
+ polling: Polling
1610
+ };
1611
+
1612
+ // imported from https://github.com/galkn/parseuri
1613
+ /**
1614
+ * Parses a URI
1615
+ *
1616
+ * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
1617
+ *
1618
+ * See:
1619
+ * - https://developer.mozilla.org/en-US/docs/Web/API/URL
1620
+ * - https://caniuse.com/url
1621
+ * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
1622
+ *
1623
+ * History of the parse() method:
1624
+ * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
1625
+ * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
1626
+ * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
1627
+ *
1628
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
1629
+ * @api private
1630
+ */
1631
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1632
+ var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
1633
+ function parse(str) {
1634
+ var src = str,
1635
+ b = str.indexOf('['),
1636
+ e = str.indexOf(']');
1637
+ if (b != -1 && e != -1) {
1638
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
1639
+ }
1640
+ var m = re.exec(str || ''),
1641
+ uri = {},
1642
+ i = 14;
1643
+ while (i--) {
1644
+ uri[parts[i]] = m[i] || '';
1645
+ }
1646
+ if (b != -1 && e != -1) {
1647
+ uri.source = src;
1648
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
1649
+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
1650
+ uri.ipv6uri = true;
1651
+ }
1652
+ uri.pathNames = pathNames(uri, uri['path']);
1653
+ uri.queryKey = queryKey(uri, uri['query']);
1654
+ return uri;
1655
+ }
1656
+ function pathNames(obj, path) {
1657
+ var regx = /\/{2,9}/g,
1658
+ names = path.replace(regx, "/").split("/");
1659
+ if (path.slice(0, 1) == '/' || path.length === 0) {
1660
+ names.splice(0, 1);
1661
+ }
1662
+ if (path.slice(-1) == '/') {
1663
+ names.splice(names.length - 1, 1);
1664
+ }
1665
+ return names;
1666
+ }
1667
+ function queryKey(uri, query) {
1668
+ var data = {};
1669
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
1670
+ if ($1) {
1671
+ data[$1] = $2;
1672
+ }
1673
+ });
1674
+ return data;
1675
+ }
1676
+
1677
+ var Socket = /*#__PURE__*/function (_Emitter) {
1678
+ _inherits(Socket, _Emitter);
1679
+ var _super = _createSuper(Socket);
1680
+ /**
1681
+ * Socket constructor.
1682
+ *
1683
+ * @param {String|Object} uri - uri or options
1684
+ * @param {Object} opts - options
1685
+ */
1686
+ function Socket(uri) {
1687
+ var _this;
1688
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1689
+ _classCallCheck(this, Socket);
1690
+ _this = _super.call(this);
1691
+ _this.writeBuffer = [];
1692
+ if (uri && "object" === _typeof(uri)) {
1693
+ opts = uri;
1694
+ uri = null;
1695
+ }
1696
+ if (uri) {
1697
+ uri = parse(uri);
1698
+ opts.hostname = uri.host;
1699
+ opts.secure = uri.protocol === "https" || uri.protocol === "wss";
1700
+ opts.port = uri.port;
1701
+ if (uri.query) opts.query = uri.query;
1702
+ } else if (opts.host) {
1703
+ opts.hostname = parse(opts.host).host;
1704
+ }
1705
+ installTimerFunctions(_assertThisInitialized(_this), opts);
1706
+ _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
1707
+ if (opts.hostname && !opts.port) {
1708
+ // if no port is specified manually, use the protocol default
1709
+ opts.port = _this.secure ? "443" : "80";
1710
+ }
1711
+ _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
1712
+ _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
1713
+ _this.transports = opts.transports || ["polling", "websocket", "webtransport"];
1714
+ _this.writeBuffer = [];
1715
+ _this.prevBufferLen = 0;
1716
+ _this.opts = _extends({
1717
+ path: "/engine.io",
1718
+ agent: false,
1719
+ withCredentials: false,
1720
+ upgrade: true,
1721
+ timestampParam: "t",
1722
+ rememberUpgrade: false,
1723
+ addTrailingSlash: true,
1724
+ rejectUnauthorized: true,
1725
+ perMessageDeflate: {
1726
+ threshold: 1024
1727
+ },
1728
+ transportOptions: {},
1729
+ closeOnBeforeunload: false
1730
+ }, opts);
1731
+ _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
1732
+ if (typeof _this.opts.query === "string") {
1733
+ _this.opts.query = decode(_this.opts.query);
1734
+ }
1735
+ // set on handshake
1736
+ _this.id = null;
1737
+ _this.upgrades = null;
1738
+ _this.pingInterval = null;
1739
+ _this.pingTimeout = null;
1740
+ // set on heartbeat
1741
+ _this.pingTimeoutTimer = null;
1742
+ if (typeof addEventListener === "function") {
1743
+ if (_this.opts.closeOnBeforeunload) {
1744
+ // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
1745
+ // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
1746
+ // closed/reloaded)
1747
+ _this.beforeunloadEventListener = function () {
1748
+ if (_this.transport) {
1749
+ // silently close the transport
1750
+ _this.transport.removeAllListeners();
1751
+ _this.transport.close();
1752
+ }
1753
+ };
1754
+ addEventListener("beforeunload", _this.beforeunloadEventListener, false);
1755
+ }
1756
+ if (_this.hostname !== "localhost") {
1757
+ _this.offlineEventListener = function () {
1758
+ _this.onClose("transport close", {
1759
+ description: "network connection lost"
1760
+ });
1761
+ };
1762
+ addEventListener("offline", _this.offlineEventListener, false);
1763
+ }
1764
+ }
1765
+ _this.open();
1766
+ return _this;
1767
+ }
1768
+ /**
1769
+ * Creates transport of the given type.
1770
+ *
1771
+ * @param {String} name - transport name
1772
+ * @return {Transport}
1773
+ * @private
1774
+ */
1775
+ _createClass(Socket, [{
1776
+ key: "createTransport",
1777
+ value: function createTransport(name) {
1778
+ var query = _extends({}, this.opts.query);
1779
+ // append engine.io protocol identifier
1780
+ query.EIO = protocol;
1781
+ // transport name
1782
+ query.transport = name;
1783
+ // session id if we already have one
1784
+ if (this.id) query.sid = this.id;
1785
+ var opts = _extends({}, this.opts, {
1786
+ query: query,
1787
+ socket: this,
1788
+ hostname: this.hostname,
1789
+ secure: this.secure,
1790
+ port: this.port
1791
+ }, this.opts.transportOptions[name]);
1792
+ return new transports[name](opts);
1793
+ }
1794
+ /**
1795
+ * Initializes transport to use and starts probe.
1796
+ *
1797
+ * @private
1798
+ */
1799
+ }, {
1800
+ key: "open",
1801
+ value: function open() {
1802
+ var _this2 = this;
1803
+ var transport;
1804
+ if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
1805
+ transport = "websocket";
1806
+ } else if (0 === this.transports.length) {
1807
+ // Emit error on next tick so it can be listened to
1808
+ this.setTimeoutFn(function () {
1809
+ _this2.emitReserved("error", "No transports available");
1810
+ }, 0);
1811
+ return;
1812
+ } else {
1813
+ transport = this.transports[0];
1814
+ }
1815
+ this.readyState = "opening";
1816
+ // Retry with the next transport if the transport is disabled (jsonp: false)
1817
+ try {
1818
+ transport = this.createTransport(transport);
1819
+ } catch (e) {
1820
+ this.transports.shift();
1821
+ this.open();
1822
+ return;
1823
+ }
1824
+ transport.open();
1825
+ this.setTransport(transport);
1826
+ }
1827
+ /**
1828
+ * Sets the current transport. Disables the existing one (if any).
1829
+ *
1830
+ * @private
1831
+ */
1832
+ }, {
1833
+ key: "setTransport",
1834
+ value: function setTransport(transport) {
1835
+ var _this3 = this;
1836
+ if (this.transport) {
1837
+ this.transport.removeAllListeners();
1838
+ }
1839
+ // set up transport
1840
+ this.transport = transport;
1841
+ // set up transport listeners
1842
+ transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
1843
+ return _this3.onClose("transport close", reason);
1844
+ });
1845
+ }
1846
+ /**
1847
+ * Probes a transport.
1848
+ *
1849
+ * @param {String} name - transport name
1850
+ * @private
1851
+ */
1852
+ }, {
1853
+ key: "probe",
1854
+ value: function probe(name) {
1855
+ var _this4 = this;
1856
+ var transport = this.createTransport(name);
1857
+ var failed = false;
1858
+ Socket.priorWebsocketSuccess = false;
1859
+ var onTransportOpen = function onTransportOpen() {
1860
+ if (failed) return;
1861
+ transport.send([{
1862
+ type: "ping",
1863
+ data: "probe"
1864
+ }]);
1865
+ transport.once("packet", function (msg) {
1866
+ if (failed) return;
1867
+ if ("pong" === msg.type && "probe" === msg.data) {
1868
+ _this4.upgrading = true;
1869
+ _this4.emitReserved("upgrading", transport);
1870
+ if (!transport) return;
1871
+ Socket.priorWebsocketSuccess = "websocket" === transport.name;
1872
+ _this4.transport.pause(function () {
1873
+ if (failed) return;
1874
+ if ("closed" === _this4.readyState) return;
1875
+ cleanup();
1876
+ _this4.setTransport(transport);
1877
+ transport.send([{
1878
+ type: "upgrade"
1879
+ }]);
1880
+ _this4.emitReserved("upgrade", transport);
1881
+ transport = null;
1882
+ _this4.upgrading = false;
1883
+ _this4.flush();
1884
+ });
1885
+ } else {
1886
+ var err = new Error("probe error");
1887
+ // @ts-ignore
1888
+ err.transport = transport.name;
1889
+ _this4.emitReserved("upgradeError", err);
1890
+ }
1891
+ });
1892
+ };
1893
+ function freezeTransport() {
1894
+ if (failed) return;
1895
+ // Any callback called by transport should be ignored since now
1896
+ failed = true;
1897
+ cleanup();
1898
+ transport.close();
1899
+ transport = null;
1900
+ }
1901
+ // Handle any error that happens while probing
1902
+ var onerror = function onerror(err) {
1903
+ var error = new Error("probe error: " + err);
1904
+ // @ts-ignore
1905
+ error.transport = transport.name;
1906
+ freezeTransport();
1907
+ _this4.emitReserved("upgradeError", error);
1908
+ };
1909
+ function onTransportClose() {
1910
+ onerror("transport closed");
1911
+ }
1912
+ // When the socket is closed while we're probing
1913
+ function onclose() {
1914
+ onerror("socket closed");
1915
+ }
1916
+ // When the socket is upgraded while we're probing
1917
+ function onupgrade(to) {
1918
+ if (transport && to.name !== transport.name) {
1919
+ freezeTransport();
1920
+ }
1921
+ }
1922
+ // Remove all listeners on the transport and on self
1923
+ var cleanup = function cleanup() {
1924
+ transport.removeListener("open", onTransportOpen);
1925
+ transport.removeListener("error", onerror);
1926
+ transport.removeListener("close", onTransportClose);
1927
+ _this4.off("close", onclose);
1928
+ _this4.off("upgrading", onupgrade);
1929
+ };
1930
+ transport.once("open", onTransportOpen);
1931
+ transport.once("error", onerror);
1932
+ transport.once("close", onTransportClose);
1933
+ this.once("close", onclose);
1934
+ this.once("upgrading", onupgrade);
1935
+ if (this.upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
1936
+ // favor WebTransport
1937
+ this.setTimeoutFn(function () {
1938
+ if (!failed) {
1939
+ transport.open();
1940
+ }
1941
+ }, 200);
1942
+ } else {
1943
+ transport.open();
1944
+ }
1945
+ }
1946
+ /**
1947
+ * Called when connection is deemed open.
1948
+ *
1949
+ * @private
1950
+ */
1951
+ }, {
1952
+ key: "onOpen",
1953
+ value: function onOpen() {
1954
+ this.readyState = "open";
1955
+ Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
1956
+ this.emitReserved("open");
1957
+ this.flush();
1958
+ // we check for `readyState` in case an `open`
1959
+ // listener already closed the socket
1960
+ if ("open" === this.readyState && this.opts.upgrade) {
1961
+ var i = 0;
1962
+ var l = this.upgrades.length;
1963
+ for (; i < l; i++) {
1964
+ this.probe(this.upgrades[i]);
1965
+ }
1966
+ }
1967
+ }
1968
+ /**
1969
+ * Handles a packet.
1970
+ *
1971
+ * @private
1972
+ */
1973
+ }, {
1974
+ key: "onPacket",
1975
+ value: function onPacket(packet) {
1976
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1977
+ this.emitReserved("packet", packet);
1978
+ // Socket is live - any packet counts
1979
+ this.emitReserved("heartbeat");
1980
+ switch (packet.type) {
1981
+ case "open":
1982
+ this.onHandshake(JSON.parse(packet.data));
1983
+ break;
1984
+ case "ping":
1985
+ this.resetPingTimeout();
1986
+ this.sendPacket("pong");
1987
+ this.emitReserved("ping");
1988
+ this.emitReserved("pong");
1989
+ break;
1990
+ case "error":
1991
+ var err = new Error("server error");
1992
+ // @ts-ignore
1993
+ err.code = packet.data;
1994
+ this.onError(err);
1995
+ break;
1996
+ case "message":
1997
+ this.emitReserved("data", packet.data);
1998
+ this.emitReserved("message", packet.data);
1999
+ break;
2000
+ }
2001
+ }
2002
+ }
2003
+ /**
2004
+ * Called upon handshake completion.
2005
+ *
2006
+ * @param {Object} data - handshake obj
2007
+ * @private
2008
+ */
2009
+ }, {
2010
+ key: "onHandshake",
2011
+ value: function onHandshake(data) {
2012
+ this.emitReserved("handshake", data);
2013
+ this.id = data.sid;
2014
+ this.transport.query.sid = data.sid;
2015
+ this.upgrades = this.filterUpgrades(data.upgrades);
2016
+ this.pingInterval = data.pingInterval;
2017
+ this.pingTimeout = data.pingTimeout;
2018
+ this.maxPayload = data.maxPayload;
2019
+ this.onOpen();
2020
+ // In case open handler closes socket
2021
+ if ("closed" === this.readyState) return;
2022
+ this.resetPingTimeout();
2023
+ }
2024
+ /**
2025
+ * Sets and resets ping timeout timer based on server pings.
2026
+ *
2027
+ * @private
2028
+ */
2029
+ }, {
2030
+ key: "resetPingTimeout",
2031
+ value: function resetPingTimeout() {
2032
+ var _this5 = this;
2033
+ this.clearTimeoutFn(this.pingTimeoutTimer);
2034
+ this.pingTimeoutTimer = this.setTimeoutFn(function () {
2035
+ _this5.onClose("ping timeout");
2036
+ }, this.pingInterval + this.pingTimeout);
2037
+ if (this.opts.autoUnref) {
2038
+ this.pingTimeoutTimer.unref();
2039
+ }
2040
+ }
2041
+ /**
2042
+ * Called on `drain` event
2043
+ *
2044
+ * @private
2045
+ */
2046
+ }, {
2047
+ key: "onDrain",
2048
+ value: function onDrain() {
2049
+ this.writeBuffer.splice(0, this.prevBufferLen);
2050
+ // setting prevBufferLen = 0 is very important
2051
+ // for example, when upgrading, upgrade packet is sent over,
2052
+ // and a nonzero prevBufferLen could cause problems on `drain`
2053
+ this.prevBufferLen = 0;
2054
+ if (0 === this.writeBuffer.length) {
2055
+ this.emitReserved("drain");
2056
+ } else {
2057
+ this.flush();
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Flush write buffers.
2062
+ *
2063
+ * @private
2064
+ */
2065
+ }, {
2066
+ key: "flush",
2067
+ value: function flush() {
2068
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
2069
+ var packets = this.getWritablePackets();
2070
+ this.transport.send(packets);
2071
+ // keep track of current length of writeBuffer
2072
+ // splice writeBuffer and callbackBuffer on `drain`
2073
+ this.prevBufferLen = packets.length;
2074
+ this.emitReserved("flush");
2075
+ }
2076
+ }
2077
+ /**
2078
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
2079
+ * long-polling)
2080
+ *
2081
+ * @private
2082
+ */
2083
+ }, {
2084
+ key: "getWritablePackets",
2085
+ value: function getWritablePackets() {
2086
+ var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
2087
+ if (!shouldCheckPayloadSize) {
2088
+ return this.writeBuffer;
2089
+ }
2090
+ var payloadSize = 1; // first packet type
2091
+ for (var i = 0; i < this.writeBuffer.length; i++) {
2092
+ var data = this.writeBuffer[i].data;
2093
+ if (data) {
2094
+ payloadSize += byteLength(data);
2095
+ }
2096
+ if (i > 0 && payloadSize > this.maxPayload) {
2097
+ return this.writeBuffer.slice(0, i);
2098
+ }
2099
+ payloadSize += 2; // separator + packet type
2100
+ }
2101
+
2102
+ return this.writeBuffer;
2103
+ }
2104
+ /**
2105
+ * Sends a message.
2106
+ *
2107
+ * @param {String} msg - message.
2108
+ * @param {Object} options.
2109
+ * @param {Function} callback function.
2110
+ * @return {Socket} for chaining.
2111
+ */
2112
+ }, {
2113
+ key: "write",
2114
+ value: function write(msg, options, fn) {
2115
+ this.sendPacket("message", msg, options, fn);
2116
+ return this;
2117
+ }
2118
+ }, {
2119
+ key: "send",
2120
+ value: function send(msg, options, fn) {
2121
+ this.sendPacket("message", msg, options, fn);
2122
+ return this;
2123
+ }
2124
+ /**
2125
+ * Sends a packet.
2126
+ *
2127
+ * @param {String} type: packet type.
2128
+ * @param {String} data.
2129
+ * @param {Object} options.
2130
+ * @param {Function} fn - callback function.
2131
+ * @private
2132
+ */
2133
+ }, {
2134
+ key: "sendPacket",
2135
+ value: function sendPacket(type, data, options, fn) {
2136
+ if ("function" === typeof data) {
2137
+ fn = data;
2138
+ data = undefined;
2139
+ }
2140
+ if ("function" === typeof options) {
2141
+ fn = options;
2142
+ options = null;
2143
+ }
2144
+ if ("closing" === this.readyState || "closed" === this.readyState) {
2145
+ return;
2146
+ }
2147
+ options = options || {};
2148
+ options.compress = false !== options.compress;
2149
+ var packet = {
2150
+ type: type,
2151
+ data: data,
2152
+ options: options
2153
+ };
2154
+ this.emitReserved("packetCreate", packet);
2155
+ this.writeBuffer.push(packet);
2156
+ if (fn) this.once("flush", fn);
2157
+ this.flush();
2158
+ }
2159
+ /**
2160
+ * Closes the connection.
2161
+ */
2162
+ }, {
2163
+ key: "close",
2164
+ value: function close() {
2165
+ var _this6 = this;
2166
+ var close = function close() {
2167
+ _this6.onClose("forced close");
2168
+ _this6.transport.close();
2169
+ };
2170
+ var cleanupAndClose = function cleanupAndClose() {
2171
+ _this6.off("upgrade", cleanupAndClose);
2172
+ _this6.off("upgradeError", cleanupAndClose);
2173
+ close();
2174
+ };
2175
+ var waitForUpgrade = function waitForUpgrade() {
2176
+ // wait for upgrade to finish since we can't send packets while pausing a transport
2177
+ _this6.once("upgrade", cleanupAndClose);
2178
+ _this6.once("upgradeError", cleanupAndClose);
2179
+ };
2180
+ if ("opening" === this.readyState || "open" === this.readyState) {
2181
+ this.readyState = "closing";
2182
+ if (this.writeBuffer.length) {
2183
+ this.once("drain", function () {
2184
+ if (_this6.upgrading) {
2185
+ waitForUpgrade();
2186
+ } else {
2187
+ close();
2188
+ }
2189
+ });
2190
+ } else if (this.upgrading) {
2191
+ waitForUpgrade();
2192
+ } else {
2193
+ close();
2194
+ }
2195
+ }
2196
+ return this;
2197
+ }
2198
+ /**
2199
+ * Called upon transport error
2200
+ *
2201
+ * @private
2202
+ */
2203
+ }, {
2204
+ key: "onError",
2205
+ value: function onError(err) {
2206
+ Socket.priorWebsocketSuccess = false;
2207
+ this.emitReserved("error", err);
2208
+ this.onClose("transport error", err);
2209
+ }
2210
+ /**
2211
+ * Called upon transport close.
2212
+ *
2213
+ * @private
2214
+ */
2215
+ }, {
2216
+ key: "onClose",
2217
+ value: function onClose(reason, description) {
2218
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2219
+ // clear timers
2220
+ this.clearTimeoutFn(this.pingTimeoutTimer);
2221
+ // stop event from firing again for transport
2222
+ this.transport.removeAllListeners("close");
2223
+ // ensure transport won't stay open
2224
+ this.transport.close();
2225
+ // ignore further transport communication
2226
+ this.transport.removeAllListeners();
2227
+ if (typeof removeEventListener === "function") {
2228
+ removeEventListener("beforeunload", this.beforeunloadEventListener, false);
2229
+ removeEventListener("offline", this.offlineEventListener, false);
2230
+ }
2231
+ // set ready state
2232
+ this.readyState = "closed";
2233
+ // clear session id
2234
+ this.id = null;
2235
+ // emit close event
2236
+ this.emitReserved("close", reason, description);
2237
+ // clean buffers after, so users can still
2238
+ // grab the buffers on `close` event
2239
+ this.writeBuffer = [];
2240
+ this.prevBufferLen = 0;
2241
+ }
2242
+ }
2243
+ /**
2244
+ * Filters upgrades, returning only those matching client transports.
2245
+ *
2246
+ * @param {Array} upgrades - server upgrades
2247
+ * @private
2248
+ */
2249
+ }, {
2250
+ key: "filterUpgrades",
2251
+ value: function filterUpgrades(upgrades) {
2252
+ var filteredUpgrades = [];
2253
+ var i = 0;
2254
+ var j = upgrades.length;
2255
+ for (; i < j; i++) {
2256
+ if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
2257
+ }
2258
+ return filteredUpgrades;
2259
+ }
2260
+ }]);
2261
+ return Socket;
2262
+ }(Emitter);
2263
+ Socket.protocol = protocol;
2264
+
2265
+ var browserEntrypoint = (function (uri, opts) {
2266
+ return new Socket(uri, opts);
2267
+ });
2268
+
2269
+ return browserEntrypoint;
2270
+
2271
+ })();
2272
+ return eio;
2273
+ });