engine.io.js 72 KB

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