@heyputer/puter.js 2.0.0 → 2.0.1

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