engine.io.js 62 KB

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