engine.io.js 72 KB

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