uniapp,h5

engine.io.js 94KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968
  1. /*!
  2. * Engine.IO v6.6.1
  3. * (c) 2014-2024 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 _arrayLikeToArray(r, a) {
  12. (null == a || a > r.length) && (a = r.length);
  13. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  14. return n;
  15. }
  16. function _arrayWithoutHoles(r) {
  17. if (Array.isArray(r)) return _arrayLikeToArray(r);
  18. }
  19. function _construct(t, e, r) {
  20. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  21. var o = [null];
  22. o.push.apply(o, e);
  23. var p = new (t.bind.apply(t, o))();
  24. return r && _setPrototypeOf(p, r.prototype), p;
  25. }
  26. function _defineProperties(e, r) {
  27. for (var t = 0; t < r.length; t++) {
  28. var o = r[t];
  29. o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
  30. }
  31. }
  32. function _createClass(e, r, t) {
  33. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  34. writable: !1
  35. }), e;
  36. }
  37. function _extends() {
  38. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  39. for (var e = 1; e < arguments.length; e++) {
  40. var t = arguments[e];
  41. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  42. }
  43. return n;
  44. }, _extends.apply(null, arguments);
  45. }
  46. function _getPrototypeOf(t) {
  47. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  48. return t.__proto__ || Object.getPrototypeOf(t);
  49. }, _getPrototypeOf(t);
  50. }
  51. function _inheritsLoose(t, o) {
  52. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  53. }
  54. function _isNativeFunction(t) {
  55. try {
  56. return -1 !== Function.toString.call(t).indexOf("[native code]");
  57. } catch (n) {
  58. return "function" == typeof t;
  59. }
  60. }
  61. function _isNativeReflectConstruct() {
  62. try {
  63. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  64. } catch (t) {}
  65. return (_isNativeReflectConstruct = function () {
  66. return !!t;
  67. })();
  68. }
  69. function _iterableToArray(r) {
  70. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  71. }
  72. function _nonIterableSpread() {
  73. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  74. }
  75. function _setPrototypeOf(t, e) {
  76. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  77. return t.__proto__ = e, t;
  78. }, _setPrototypeOf(t, e);
  79. }
  80. function _toConsumableArray(r) {
  81. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  82. }
  83. function _toPrimitive(t, r) {
  84. if ("object" != typeof t || !t) return t;
  85. var e = t[Symbol.toPrimitive];
  86. if (void 0 !== e) {
  87. var i = e.call(t, r || "default");
  88. if ("object" != typeof i) return i;
  89. throw new TypeError("@@toPrimitive must return a primitive value.");
  90. }
  91. return ("string" === r ? String : Number)(t);
  92. }
  93. function _toPropertyKey(t) {
  94. var i = _toPrimitive(t, "string");
  95. return "symbol" == typeof i ? i : i + "";
  96. }
  97. function _typeof(o) {
  98. "@babel/helpers - typeof";
  99. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  100. return typeof o;
  101. } : function (o) {
  102. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  103. }, _typeof(o);
  104. }
  105. function _unsupportedIterableToArray(r, a) {
  106. if (r) {
  107. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  108. var t = {}.toString.call(r).slice(8, -1);
  109. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  110. }
  111. }
  112. function _wrapNativeSuper(t) {
  113. var r = "function" == typeof Map ? new Map() : void 0;
  114. return _wrapNativeSuper = function (t) {
  115. if (null === t || !_isNativeFunction(t)) return t;
  116. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  117. if (void 0 !== r) {
  118. if (r.has(t)) return r.get(t);
  119. r.set(t, Wrapper);
  120. }
  121. function Wrapper() {
  122. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  123. }
  124. return Wrapper.prototype = Object.create(t.prototype, {
  125. constructor: {
  126. value: Wrapper,
  127. enumerable: !1,
  128. writable: !0,
  129. configurable: !0
  130. }
  131. }), _setPrototypeOf(Wrapper, t);
  132. }, _wrapNativeSuper(t);
  133. }
  134. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  135. PACKET_TYPES["open"] = "0";
  136. PACKET_TYPES["close"] = "1";
  137. PACKET_TYPES["ping"] = "2";
  138. PACKET_TYPES["pong"] = "3";
  139. PACKET_TYPES["message"] = "4";
  140. PACKET_TYPES["upgrade"] = "5";
  141. PACKET_TYPES["noop"] = "6";
  142. var PACKET_TYPES_REVERSE = Object.create(null);
  143. Object.keys(PACKET_TYPES).forEach(function (key) {
  144. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  145. });
  146. var ERROR_PACKET = {
  147. type: "error",
  148. data: "parser error"
  149. };
  150. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  151. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  152. // ArrayBuffer.isView method is not defined in IE10
  153. var isView = function isView(obj) {
  154. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  155. };
  156. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  157. var type = _ref.type,
  158. data = _ref.data;
  159. if (withNativeBlob && data instanceof Blob) {
  160. if (supportsBinary) {
  161. return callback(data);
  162. } else {
  163. return encodeBlobAsBase64(data, callback);
  164. }
  165. } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) {
  166. if (supportsBinary) {
  167. return callback(data);
  168. } else {
  169. return encodeBlobAsBase64(new Blob([data]), callback);
  170. }
  171. }
  172. // plain string
  173. return callback(PACKET_TYPES[type] + (data || ""));
  174. };
  175. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  176. var fileReader = new FileReader();
  177. fileReader.onload = function () {
  178. var content = fileReader.result.split(",")[1];
  179. callback("b" + (content || ""));
  180. };
  181. return fileReader.readAsDataURL(data);
  182. };
  183. function toArray(data) {
  184. if (data instanceof Uint8Array) {
  185. return data;
  186. } else if (data instanceof ArrayBuffer) {
  187. return new Uint8Array(data);
  188. } else {
  189. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  190. }
  191. }
  192. var TEXT_ENCODER;
  193. function encodePacketToBinary(packet, callback) {
  194. if (withNativeBlob && packet.data instanceof Blob) {
  195. return packet.data.arrayBuffer().then(toArray).then(callback);
  196. } else if (withNativeArrayBuffer$1 && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
  197. return callback(toArray(packet.data));
  198. }
  199. encodePacket(packet, false, function (encoded) {
  200. if (!TEXT_ENCODER) {
  201. TEXT_ENCODER = new TextEncoder();
  202. }
  203. callback(TEXT_ENCODER.encode(encoded));
  204. });
  205. }
  206. // imported from https://github.com/socketio/base64-arraybuffer
  207. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  208. // Use a lookup table to find the index.
  209. var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  210. for (var i = 0; i < chars.length; i++) {
  211. lookup[chars.charCodeAt(i)] = i;
  212. }
  213. var decode$1 = function decode(base64) {
  214. var bufferLength = base64.length * 0.75,
  215. len = base64.length,
  216. i,
  217. p = 0,
  218. encoded1,
  219. encoded2,
  220. encoded3,
  221. encoded4;
  222. if (base64[base64.length - 1] === '=') {
  223. bufferLength--;
  224. if (base64[base64.length - 2] === '=') {
  225. bufferLength--;
  226. }
  227. }
  228. var arraybuffer = new ArrayBuffer(bufferLength),
  229. bytes = new Uint8Array(arraybuffer);
  230. for (i = 0; i < len; i += 4) {
  231. encoded1 = lookup[base64.charCodeAt(i)];
  232. encoded2 = lookup[base64.charCodeAt(i + 1)];
  233. encoded3 = lookup[base64.charCodeAt(i + 2)];
  234. encoded4 = lookup[base64.charCodeAt(i + 3)];
  235. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  236. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  237. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  238. }
  239. return arraybuffer;
  240. };
  241. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  242. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  243. if (typeof encodedPacket !== "string") {
  244. return {
  245. type: "message",
  246. data: mapBinary(encodedPacket, binaryType)
  247. };
  248. }
  249. var type = encodedPacket.charAt(0);
  250. if (type === "b") {
  251. return {
  252. type: "message",
  253. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  254. };
  255. }
  256. var packetType = PACKET_TYPES_REVERSE[type];
  257. if (!packetType) {
  258. return ERROR_PACKET;
  259. }
  260. return encodedPacket.length > 1 ? {
  261. type: PACKET_TYPES_REVERSE[type],
  262. data: encodedPacket.substring(1)
  263. } : {
  264. type: PACKET_TYPES_REVERSE[type]
  265. };
  266. };
  267. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  268. if (withNativeArrayBuffer) {
  269. var decoded = decode$1(data);
  270. return mapBinary(decoded, binaryType);
  271. } else {
  272. return {
  273. base64: true,
  274. data: data
  275. }; // fallback for old browsers
  276. }
  277. };
  278. var mapBinary = function mapBinary(data, binaryType) {
  279. switch (binaryType) {
  280. case "blob":
  281. if (data instanceof Blob) {
  282. // from WebSocket + binaryType "blob"
  283. return data;
  284. } else {
  285. // from HTTP long-polling or WebTransport
  286. return new Blob([data]);
  287. }
  288. case "arraybuffer":
  289. default:
  290. if (data instanceof ArrayBuffer) {
  291. // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
  292. return data;
  293. } else {
  294. // from WebTransport (Uint8Array)
  295. return data.buffer;
  296. }
  297. }
  298. };
  299. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  300. var encodePayload = function encodePayload(packets, callback) {
  301. // some packets may be added to the array while encoding, so the initial length must be saved
  302. var length = packets.length;
  303. var encodedPackets = new Array(length);
  304. var count = 0;
  305. packets.forEach(function (packet, i) {
  306. // force base64 encoding for binary packets
  307. encodePacket(packet, false, function (encodedPacket) {
  308. encodedPackets[i] = encodedPacket;
  309. if (++count === length) {
  310. callback(encodedPackets.join(SEPARATOR));
  311. }
  312. });
  313. });
  314. };
  315. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  316. var encodedPackets = encodedPayload.split(SEPARATOR);
  317. var packets = [];
  318. for (var i = 0; i < encodedPackets.length; i++) {
  319. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  320. packets.push(decodedPacket);
  321. if (decodedPacket.type === "error") {
  322. break;
  323. }
  324. }
  325. return packets;
  326. };
  327. function createPacketEncoderStream() {
  328. return new TransformStream({
  329. transform: function transform(packet, controller) {
  330. encodePacketToBinary(packet, function (encodedPacket) {
  331. var payloadLength = encodedPacket.length;
  332. var header;
  333. // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
  334. if (payloadLength < 126) {
  335. header = new Uint8Array(1);
  336. new DataView(header.buffer).setUint8(0, payloadLength);
  337. } else if (payloadLength < 65536) {
  338. header = new Uint8Array(3);
  339. var view = new DataView(header.buffer);
  340. view.setUint8(0, 126);
  341. view.setUint16(1, payloadLength);
  342. } else {
  343. header = new Uint8Array(9);
  344. var _view = new DataView(header.buffer);
  345. _view.setUint8(0, 127);
  346. _view.setBigUint64(1, BigInt(payloadLength));
  347. }
  348. // first bit indicates whether the payload is plain text (0) or binary (1)
  349. if (packet.data && typeof packet.data !== "string") {
  350. header[0] |= 0x80;
  351. }
  352. controller.enqueue(header);
  353. controller.enqueue(encodedPacket);
  354. });
  355. }
  356. });
  357. }
  358. var TEXT_DECODER;
  359. function totalLength(chunks) {
  360. return chunks.reduce(function (acc, chunk) {
  361. return acc + chunk.length;
  362. }, 0);
  363. }
  364. function concatChunks(chunks, size) {
  365. if (chunks[0].length === size) {
  366. return chunks.shift();
  367. }
  368. var buffer = new Uint8Array(size);
  369. var j = 0;
  370. for (var i = 0; i < size; i++) {
  371. buffer[i] = chunks[0][j++];
  372. if (j === chunks[0].length) {
  373. chunks.shift();
  374. j = 0;
  375. }
  376. }
  377. if (chunks.length && j < chunks[0].length) {
  378. chunks[0] = chunks[0].slice(j);
  379. }
  380. return buffer;
  381. }
  382. function createPacketDecoderStream(maxPayload, binaryType) {
  383. if (!TEXT_DECODER) {
  384. TEXT_DECODER = new TextDecoder();
  385. }
  386. var chunks = [];
  387. var state = 0 /* State.READ_HEADER */;
  388. var expectedLength = -1;
  389. var isBinary = false;
  390. return new TransformStream({
  391. transform: function transform(chunk, controller) {
  392. chunks.push(chunk);
  393. while (true) {
  394. if (state === 0 /* State.READ_HEADER */) {
  395. if (totalLength(chunks) < 1) {
  396. break;
  397. }
  398. var header = concatChunks(chunks, 1);
  399. isBinary = (header[0] & 0x80) === 0x80;
  400. expectedLength = header[0] & 0x7f;
  401. if (expectedLength < 126) {
  402. state = 3 /* State.READ_PAYLOAD */;
  403. } else if (expectedLength === 126) {
  404. state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
  405. } else {
  406. state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
  407. }
  408. } else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
  409. if (totalLength(chunks) < 2) {
  410. break;
  411. }
  412. var headerArray = concatChunks(chunks, 2);
  413. expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
  414. state = 3 /* State.READ_PAYLOAD */;
  415. } else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
  416. if (totalLength(chunks) < 8) {
  417. break;
  418. }
  419. var _headerArray = concatChunks(chunks, 8);
  420. var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length);
  421. var n = view.getUint32(0);
  422. if (n > Math.pow(2, 53 - 32) - 1) {
  423. // the maximum safe integer in JavaScript is 2^53 - 1
  424. controller.enqueue(ERROR_PACKET);
  425. break;
  426. }
  427. expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
  428. state = 3 /* State.READ_PAYLOAD */;
  429. } else {
  430. if (totalLength(chunks) < expectedLength) {
  431. break;
  432. }
  433. var data = concatChunks(chunks, expectedLength);
  434. controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
  435. state = 0 /* State.READ_HEADER */;
  436. }
  437. if (expectedLength === 0 || expectedLength > maxPayload) {
  438. controller.enqueue(ERROR_PACKET);
  439. break;
  440. }
  441. }
  442. }
  443. });
  444. }
  445. var protocol = 4;
  446. /**
  447. * Initialize a new `Emitter`.
  448. *
  449. * @api public
  450. */
  451. function Emitter(obj) {
  452. if (obj) return mixin(obj);
  453. }
  454. /**
  455. * Mixin the emitter properties.
  456. *
  457. * @param {Object} obj
  458. * @return {Object}
  459. * @api private
  460. */
  461. function mixin(obj) {
  462. for (var key in Emitter.prototype) {
  463. obj[key] = Emitter.prototype[key];
  464. }
  465. return obj;
  466. }
  467. /**
  468. * Listen on the given `event` with `fn`.
  469. *
  470. * @param {String} event
  471. * @param {Function} fn
  472. * @return {Emitter}
  473. * @api public
  474. */
  475. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  476. this._callbacks = this._callbacks || {};
  477. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  478. return this;
  479. };
  480. /**
  481. * Adds an `event` listener that will be invoked a single
  482. * time then automatically removed.
  483. *
  484. * @param {String} event
  485. * @param {Function} fn
  486. * @return {Emitter}
  487. * @api public
  488. */
  489. Emitter.prototype.once = function (event, fn) {
  490. function on() {
  491. this.off(event, on);
  492. fn.apply(this, arguments);
  493. }
  494. on.fn = fn;
  495. this.on(event, on);
  496. return this;
  497. };
  498. /**
  499. * Remove the given callback for `event` or all
  500. * registered callbacks.
  501. *
  502. * @param {String} event
  503. * @param {Function} fn
  504. * @return {Emitter}
  505. * @api public
  506. */
  507. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  508. this._callbacks = this._callbacks || {};
  509. // all
  510. if (0 == arguments.length) {
  511. this._callbacks = {};
  512. return this;
  513. }
  514. // specific event
  515. var callbacks = this._callbacks['$' + event];
  516. if (!callbacks) return this;
  517. // remove all handlers
  518. if (1 == arguments.length) {
  519. delete this._callbacks['$' + event];
  520. return this;
  521. }
  522. // remove specific handler
  523. var cb;
  524. for (var i = 0; i < callbacks.length; i++) {
  525. cb = callbacks[i];
  526. if (cb === fn || cb.fn === fn) {
  527. callbacks.splice(i, 1);
  528. break;
  529. }
  530. }
  531. // Remove event specific arrays for event types that no
  532. // one is subscribed for to avoid memory leak.
  533. if (callbacks.length === 0) {
  534. delete this._callbacks['$' + event];
  535. }
  536. return this;
  537. };
  538. /**
  539. * Emit `event` with the given args.
  540. *
  541. * @param {String} event
  542. * @param {Mixed} ...
  543. * @return {Emitter}
  544. */
  545. Emitter.prototype.emit = function (event) {
  546. this._callbacks = this._callbacks || {};
  547. var args = new Array(arguments.length - 1),
  548. callbacks = this._callbacks['$' + event];
  549. for (var i = 1; i < arguments.length; i++) {
  550. args[i - 1] = arguments[i];
  551. }
  552. if (callbacks) {
  553. callbacks = callbacks.slice(0);
  554. for (var i = 0, len = callbacks.length; i < len; ++i) {
  555. callbacks[i].apply(this, args);
  556. }
  557. }
  558. return this;
  559. };
  560. // alias used for reserved events (protected method)
  561. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  562. /**
  563. * Return array of callbacks for `event`.
  564. *
  565. * @param {String} event
  566. * @return {Array}
  567. * @api public
  568. */
  569. Emitter.prototype.listeners = function (event) {
  570. this._callbacks = this._callbacks || {};
  571. return this._callbacks['$' + event] || [];
  572. };
  573. /**
  574. * Check if this emitter has `event` handlers.
  575. *
  576. * @param {String} event
  577. * @return {Boolean}
  578. * @api public
  579. */
  580. Emitter.prototype.hasListeners = function (event) {
  581. return !!this.listeners(event).length;
  582. };
  583. var nextTick = function () {
  584. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  585. if (isPromiseAvailable) {
  586. return function (cb) {
  587. return Promise.resolve().then(cb);
  588. };
  589. } else {
  590. return function (cb, setTimeoutFn) {
  591. return setTimeoutFn(cb, 0);
  592. };
  593. }
  594. }();
  595. var globalThisShim = function () {
  596. if (typeof self !== "undefined") {
  597. return self;
  598. } else if (typeof window !== "undefined") {
  599. return window;
  600. } else {
  601. return Function("return this")();
  602. }
  603. }();
  604. var defaultBinaryType = "arraybuffer";
  605. function createCookieJar() {}
  606. function pick(obj) {
  607. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  608. attr[_key - 1] = arguments[_key];
  609. }
  610. return attr.reduce(function (acc, k) {
  611. if (obj.hasOwnProperty(k)) {
  612. acc[k] = obj[k];
  613. }
  614. return acc;
  615. }, {});
  616. }
  617. // Keep a reference to the real timeout functions so they can be used when overridden
  618. var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
  619. var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
  620. function installTimerFunctions(obj, opts) {
  621. if (opts.useNativeTimers) {
  622. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
  623. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
  624. } else {
  625. obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
  626. obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
  627. }
  628. }
  629. // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  630. var BASE64_OVERHEAD = 1.33;
  631. // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  632. function byteLength(obj) {
  633. if (typeof obj === "string") {
  634. return utf8Length(obj);
  635. }
  636. // arraybuffer or blob
  637. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  638. }
  639. function utf8Length(str) {
  640. var c = 0,
  641. length = 0;
  642. for (var i = 0, l = str.length; i < l; i++) {
  643. c = str.charCodeAt(i);
  644. if (c < 0x80) {
  645. length += 1;
  646. } else if (c < 0x800) {
  647. length += 2;
  648. } else if (c < 0xd800 || c >= 0xe000) {
  649. length += 3;
  650. } else {
  651. i++;
  652. length += 4;
  653. }
  654. }
  655. return length;
  656. }
  657. /**
  658. * Generates a random 8-characters string.
  659. */
  660. function randomString() {
  661. return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
  662. }
  663. // imported from https://github.com/galkn/querystring
  664. /**
  665. * Compiles a querystring
  666. * Returns string representation of the object
  667. *
  668. * @param {Object}
  669. * @api private
  670. */
  671. function encode(obj) {
  672. var str = '';
  673. for (var i in obj) {
  674. if (obj.hasOwnProperty(i)) {
  675. if (str.length) str += '&';
  676. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  677. }
  678. }
  679. return str;
  680. }
  681. /**
  682. * Parses a simple querystring into an object
  683. *
  684. * @param {String} qs
  685. * @api private
  686. */
  687. function decode(qs) {
  688. var qry = {};
  689. var pairs = qs.split('&');
  690. for (var i = 0, l = pairs.length; i < l; i++) {
  691. var pair = pairs[i].split('=');
  692. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  693. }
  694. return qry;
  695. }
  696. function getDefaultExportFromCjs (x) {
  697. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  698. }
  699. var browser = {exports: {}};
  700. var ms;
  701. var hasRequiredMs;
  702. function requireMs() {
  703. if (hasRequiredMs) return ms;
  704. hasRequiredMs = 1;
  705. var s = 1000;
  706. var m = s * 60;
  707. var h = m * 60;
  708. var d = h * 24;
  709. var w = d * 7;
  710. var y = d * 365.25;
  711. /**
  712. * Parse or format the given `val`.
  713. *
  714. * Options:
  715. *
  716. * - `long` verbose formatting [false]
  717. *
  718. * @param {String|Number} val
  719. * @param {Object} [options]
  720. * @throws {Error} throw an error if val is not a non-empty string or a number
  721. * @return {String|Number}
  722. * @api public
  723. */
  724. ms = function ms(val, options) {
  725. options = options || {};
  726. var type = _typeof(val);
  727. if (type === 'string' && val.length > 0) {
  728. return parse(val);
  729. } else if (type === 'number' && isFinite(val)) {
  730. return options["long"] ? fmtLong(val) : fmtShort(val);
  731. }
  732. throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
  733. };
  734. /**
  735. * Parse the given `str` and return milliseconds.
  736. *
  737. * @param {String} str
  738. * @return {Number}
  739. * @api private
  740. */
  741. function parse(str) {
  742. str = String(str);
  743. if (str.length > 100) {
  744. return;
  745. }
  746. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
  747. if (!match) {
  748. return;
  749. }
  750. var n = parseFloat(match[1]);
  751. var type = (match[2] || 'ms').toLowerCase();
  752. switch (type) {
  753. case 'years':
  754. case 'year':
  755. case 'yrs':
  756. case 'yr':
  757. case 'y':
  758. return n * y;
  759. case 'weeks':
  760. case 'week':
  761. case 'w':
  762. return n * w;
  763. case 'days':
  764. case 'day':
  765. case 'd':
  766. return n * d;
  767. case 'hours':
  768. case 'hour':
  769. case 'hrs':
  770. case 'hr':
  771. case 'h':
  772. return n * h;
  773. case 'minutes':
  774. case 'minute':
  775. case 'mins':
  776. case 'min':
  777. case 'm':
  778. return n * m;
  779. case 'seconds':
  780. case 'second':
  781. case 'secs':
  782. case 'sec':
  783. case 's':
  784. return n * s;
  785. case 'milliseconds':
  786. case 'millisecond':
  787. case 'msecs':
  788. case 'msec':
  789. case 'ms':
  790. return n;
  791. default:
  792. return undefined;
  793. }
  794. }
  795. /**
  796. * Short format for `ms`.
  797. *
  798. * @param {Number} ms
  799. * @return {String}
  800. * @api private
  801. */
  802. function fmtShort(ms) {
  803. var msAbs = Math.abs(ms);
  804. if (msAbs >= d) {
  805. return Math.round(ms / d) + 'd';
  806. }
  807. if (msAbs >= h) {
  808. return Math.round(ms / h) + 'h';
  809. }
  810. if (msAbs >= m) {
  811. return Math.round(ms / m) + 'm';
  812. }
  813. if (msAbs >= s) {
  814. return Math.round(ms / s) + 's';
  815. }
  816. return ms + 'ms';
  817. }
  818. /**
  819. * Long format for `ms`.
  820. *
  821. * @param {Number} ms
  822. * @return {String}
  823. * @api private
  824. */
  825. function fmtLong(ms) {
  826. var msAbs = Math.abs(ms);
  827. if (msAbs >= d) {
  828. return plural(ms, msAbs, d, 'day');
  829. }
  830. if (msAbs >= h) {
  831. return plural(ms, msAbs, h, 'hour');
  832. }
  833. if (msAbs >= m) {
  834. return plural(ms, msAbs, m, 'minute');
  835. }
  836. if (msAbs >= s) {
  837. return plural(ms, msAbs, s, 'second');
  838. }
  839. return ms + ' ms';
  840. }
  841. /**
  842. * Pluralization helper.
  843. */
  844. function plural(ms, msAbs, n, name) {
  845. var isPlural = msAbs >= n * 1.5;
  846. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  847. }
  848. return ms;
  849. }
  850. /**
  851. * This is the common logic for both the Node.js and web browser
  852. * implementations of `debug()`.
  853. */
  854. function setup(env) {
  855. createDebug.debug = createDebug;
  856. createDebug["default"] = createDebug;
  857. createDebug.coerce = coerce;
  858. createDebug.disable = disable;
  859. createDebug.enable = enable;
  860. createDebug.enabled = enabled;
  861. createDebug.humanize = requireMs();
  862. createDebug.destroy = destroy;
  863. Object.keys(env).forEach(function (key) {
  864. createDebug[key] = env[key];
  865. });
  866. /**
  867. * The currently active debug mode names, and names to skip.
  868. */
  869. createDebug.names = [];
  870. createDebug.skips = [];
  871. /**
  872. * Map of special "%n" handling functions, for the debug "format" argument.
  873. *
  874. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  875. */
  876. createDebug.formatters = {};
  877. /**
  878. * Selects a color for a debug namespace
  879. * @param {String} namespace The namespace string for the debug instance to be colored
  880. * @return {Number|String} An ANSI color code for the given namespace
  881. * @api private
  882. */
  883. function selectColor(namespace) {
  884. var hash = 0;
  885. for (var i = 0; i < namespace.length; i++) {
  886. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  887. hash |= 0; // Convert to 32bit integer
  888. }
  889. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  890. }
  891. createDebug.selectColor = selectColor;
  892. /**
  893. * Create a debugger with the given `namespace`.
  894. *
  895. * @param {String} namespace
  896. * @return {Function}
  897. * @api public
  898. */
  899. function createDebug(namespace) {
  900. var prevTime;
  901. var enableOverride = null;
  902. var namespacesCache;
  903. var enabledCache;
  904. function debug() {
  905. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  906. args[_key] = arguments[_key];
  907. }
  908. // Disabled?
  909. if (!debug.enabled) {
  910. return;
  911. }
  912. var self = debug;
  913. // Set `diff` timestamp
  914. var curr = Number(new Date());
  915. var ms = curr - (prevTime || curr);
  916. self.diff = ms;
  917. self.prev = prevTime;
  918. self.curr = curr;
  919. prevTime = curr;
  920. args[0] = createDebug.coerce(args[0]);
  921. if (typeof args[0] !== 'string') {
  922. // Anything else let's inspect with %O
  923. args.unshift('%O');
  924. }
  925. // Apply any `formatters` transformations
  926. var index = 0;
  927. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  928. // If we encounter an escaped % then don't increase the array index
  929. if (match === '%%') {
  930. return '%';
  931. }
  932. index++;
  933. var formatter = createDebug.formatters[format];
  934. if (typeof formatter === 'function') {
  935. var val = args[index];
  936. match = formatter.call(self, val);
  937. // Now we need to remove `args[index]` since it's inlined in the `format`
  938. args.splice(index, 1);
  939. index--;
  940. }
  941. return match;
  942. });
  943. // Apply env-specific formatting (colors, etc.)
  944. createDebug.formatArgs.call(self, args);
  945. var logFn = self.log || createDebug.log;
  946. logFn.apply(self, args);
  947. }
  948. debug.namespace = namespace;
  949. debug.useColors = createDebug.useColors();
  950. debug.color = createDebug.selectColor(namespace);
  951. debug.extend = extend;
  952. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  953. Object.defineProperty(debug, 'enabled', {
  954. enumerable: true,
  955. configurable: false,
  956. get: function get() {
  957. if (enableOverride !== null) {
  958. return enableOverride;
  959. }
  960. if (namespacesCache !== createDebug.namespaces) {
  961. namespacesCache = createDebug.namespaces;
  962. enabledCache = createDebug.enabled(namespace);
  963. }
  964. return enabledCache;
  965. },
  966. set: function set(v) {
  967. enableOverride = v;
  968. }
  969. });
  970. // Env-specific initialization logic for debug instances
  971. if (typeof createDebug.init === 'function') {
  972. createDebug.init(debug);
  973. }
  974. return debug;
  975. }
  976. function extend(namespace, delimiter) {
  977. var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  978. newDebug.log = this.log;
  979. return newDebug;
  980. }
  981. /**
  982. * Enables a debug mode by namespaces. This can include modes
  983. * separated by a colon and wildcards.
  984. *
  985. * @param {String} namespaces
  986. * @api public
  987. */
  988. function enable(namespaces) {
  989. createDebug.save(namespaces);
  990. createDebug.namespaces = namespaces;
  991. createDebug.names = [];
  992. createDebug.skips = [];
  993. var i;
  994. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  995. var len = split.length;
  996. for (i = 0; i < len; i++) {
  997. if (!split[i]) {
  998. // ignore empty strings
  999. continue;
  1000. }
  1001. namespaces = split[i].replace(/\*/g, '.*?');
  1002. if (namespaces[0] === '-') {
  1003. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  1004. } else {
  1005. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * Disable debug output.
  1011. *
  1012. * @return {String} namespaces
  1013. * @api public
  1014. */
  1015. function disable() {
  1016. var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
  1017. return '-' + namespace;
  1018. }))).join(',');
  1019. createDebug.enable('');
  1020. return namespaces;
  1021. }
  1022. /**
  1023. * Returns true if the given mode name is enabled, false otherwise.
  1024. *
  1025. * @param {String} name
  1026. * @return {Boolean}
  1027. * @api public
  1028. */
  1029. function enabled(name) {
  1030. if (name[name.length - 1] === '*') {
  1031. return true;
  1032. }
  1033. var i;
  1034. var len;
  1035. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  1036. if (createDebug.skips[i].test(name)) {
  1037. return false;
  1038. }
  1039. }
  1040. for (i = 0, len = createDebug.names.length; i < len; i++) {
  1041. if (createDebug.names[i].test(name)) {
  1042. return true;
  1043. }
  1044. }
  1045. return false;
  1046. }
  1047. /**
  1048. * Convert regexp to namespace
  1049. *
  1050. * @param {RegExp} regxep
  1051. * @return {String} namespace
  1052. * @api private
  1053. */
  1054. function toNamespace(regexp) {
  1055. return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
  1056. }
  1057. /**
  1058. * Coerce `val`.
  1059. *
  1060. * @param {Mixed} val
  1061. * @return {Mixed}
  1062. * @api private
  1063. */
  1064. function coerce(val) {
  1065. if (val instanceof Error) {
  1066. return val.stack || val.message;
  1067. }
  1068. return val;
  1069. }
  1070. /**
  1071. * XXX DO NOT USE. This is a temporary stub function.
  1072. * XXX It WILL be removed in the next major release.
  1073. */
  1074. function destroy() {
  1075. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1076. }
  1077. createDebug.enable(createDebug.load());
  1078. return createDebug;
  1079. }
  1080. var common = setup;
  1081. /* eslint-env browser */
  1082. browser.exports;
  1083. (function (module, exports) {
  1084. /**
  1085. * This is the web browser implementation of `debug()`.
  1086. */
  1087. exports.formatArgs = formatArgs;
  1088. exports.save = save;
  1089. exports.load = load;
  1090. exports.useColors = useColors;
  1091. exports.storage = localstorage();
  1092. exports.destroy = function () {
  1093. var warned = false;
  1094. return function () {
  1095. if (!warned) {
  1096. warned = true;
  1097. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1098. }
  1099. };
  1100. }();
  1101. /**
  1102. * Colors.
  1103. */
  1104. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  1105. /**
  1106. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1107. * and the Firebug extension (any Firefox version) are known
  1108. * to support "%c" CSS customizations.
  1109. *
  1110. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1111. */
  1112. // eslint-disable-next-line complexity
  1113. function useColors() {
  1114. // NB: In an Electron preload script, document will be defined but not fully
  1115. // initialized. Since we know we're in Chrome, we'll just detect this case
  1116. // explicitly
  1117. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  1118. return true;
  1119. }
  1120. // Internet Explorer and Edge do not support colors.
  1121. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  1122. return false;
  1123. }
  1124. // Is webkit? http://stackoverflow.com/a/16459606/376773
  1125. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  1126. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
  1127. // Is firebug? http://stackoverflow.com/a/398120/376773
  1128. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
  1129. // Is firefox >= v31?
  1130. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1131. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
  1132. // Double check webkit in userAgent just in case we are in a worker
  1133. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  1134. }
  1135. /**
  1136. * Colorize log arguments if enabled.
  1137. *
  1138. * @api public
  1139. */
  1140. function formatArgs(args) {
  1141. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  1142. if (!this.useColors) {
  1143. return;
  1144. }
  1145. var c = 'color: ' + this.color;
  1146. args.splice(1, 0, c, 'color: inherit');
  1147. // The final "%c" is somewhat tricky, because there could be other
  1148. // arguments passed either before or after the %c, so we need to
  1149. // figure out the correct index to insert the CSS into
  1150. var index = 0;
  1151. var lastC = 0;
  1152. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  1153. if (match === '%%') {
  1154. return;
  1155. }
  1156. index++;
  1157. if (match === '%c') {
  1158. // We only are interested in the *last* %c
  1159. // (the user may have provided their own)
  1160. lastC = index;
  1161. }
  1162. });
  1163. args.splice(lastC, 0, c);
  1164. }
  1165. /**
  1166. * Invokes `console.debug()` when available.
  1167. * No-op when `console.debug` is not a "function".
  1168. * If `console.debug` is not available, falls back
  1169. * to `console.log`.
  1170. *
  1171. * @api public
  1172. */
  1173. exports.log = console.debug || console.log || function () {};
  1174. /**
  1175. * Save `namespaces`.
  1176. *
  1177. * @param {String} namespaces
  1178. * @api private
  1179. */
  1180. function save(namespaces) {
  1181. try {
  1182. if (namespaces) {
  1183. exports.storage.setItem('debug', namespaces);
  1184. } else {
  1185. exports.storage.removeItem('debug');
  1186. }
  1187. } catch (error) {
  1188. // Swallow
  1189. // XXX (@Qix-) should we be logging these?
  1190. }
  1191. }
  1192. /**
  1193. * Load `namespaces`.
  1194. *
  1195. * @return {String} returns the previously persisted debug modes
  1196. * @api private
  1197. */
  1198. function load() {
  1199. var r;
  1200. try {
  1201. r = exports.storage.getItem('debug');
  1202. } catch (error) {
  1203. // Swallow
  1204. // XXX (@Qix-) should we be logging these?
  1205. }
  1206. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  1207. if (!r && typeof process !== 'undefined' && 'env' in process) {
  1208. r = process.env.DEBUG;
  1209. }
  1210. return r;
  1211. }
  1212. /**
  1213. * Localstorage attempts to return the localstorage.
  1214. *
  1215. * This is necessary because safari throws
  1216. * when a user disables cookies/localstorage
  1217. * and you attempt to access it.
  1218. *
  1219. * @return {LocalStorage}
  1220. * @api private
  1221. */
  1222. function localstorage() {
  1223. try {
  1224. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  1225. // The Browser also has localStorage in the global context.
  1226. return localStorage;
  1227. } catch (error) {
  1228. // Swallow
  1229. // XXX (@Qix-) should we be logging these?
  1230. }
  1231. }
  1232. module.exports = common(exports);
  1233. var formatters = module.exports.formatters;
  1234. /**
  1235. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1236. */
  1237. formatters.j = function (v) {
  1238. try {
  1239. return JSON.stringify(v);
  1240. } catch (error) {
  1241. return '[UnexpectedJSONParseError]: ' + error.message;
  1242. }
  1243. };
  1244. })(browser, browser.exports);
  1245. var browserExports = browser.exports;
  1246. var debugModule = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
  1247. var debug$5 = debugModule("engine.io-client:transport"); // debug()
  1248. var TransportError = /*#__PURE__*/function (_Error) {
  1249. function TransportError(reason, description, context) {
  1250. var _this;
  1251. _this = _Error.call(this, reason) || this;
  1252. _this.description = description;
  1253. _this.context = context;
  1254. _this.type = "TransportError";
  1255. return _this;
  1256. }
  1257. _inheritsLoose(TransportError, _Error);
  1258. return TransportError;
  1259. }( /*#__PURE__*/_wrapNativeSuper(Error));
  1260. var Transport = /*#__PURE__*/function (_Emitter) {
  1261. /**
  1262. * Transport abstract constructor.
  1263. *
  1264. * @param {Object} opts - options
  1265. * @protected
  1266. */
  1267. function Transport(opts) {
  1268. var _this2;
  1269. _this2 = _Emitter.call(this) || this;
  1270. _this2.writable = false;
  1271. installTimerFunctions(_this2, opts);
  1272. _this2.opts = opts;
  1273. _this2.query = opts.query;
  1274. _this2.socket = opts.socket;
  1275. _this2.supportsBinary = !opts.forceBase64;
  1276. return _this2;
  1277. }
  1278. /**
  1279. * Emits an error.
  1280. *
  1281. * @param {String} reason
  1282. * @param description
  1283. * @param context - the error context
  1284. * @return {Transport} for chaining
  1285. * @protected
  1286. */
  1287. _inheritsLoose(Transport, _Emitter);
  1288. var _proto = Transport.prototype;
  1289. _proto.onError = function onError(reason, description, context) {
  1290. _Emitter.prototype.emitReserved.call(this, "error", new TransportError(reason, description, context));
  1291. return this;
  1292. }
  1293. /**
  1294. * Opens the transport.
  1295. */;
  1296. _proto.open = function open() {
  1297. this.readyState = "opening";
  1298. this.doOpen();
  1299. return this;
  1300. }
  1301. /**
  1302. * Closes the transport.
  1303. */;
  1304. _proto.close = function close() {
  1305. if (this.readyState === "opening" || this.readyState === "open") {
  1306. this.doClose();
  1307. this.onClose();
  1308. }
  1309. return this;
  1310. }
  1311. /**
  1312. * Sends multiple packets.
  1313. *
  1314. * @param {Array} packets
  1315. */;
  1316. _proto.send = function send(packets) {
  1317. if (this.readyState === "open") {
  1318. this.write(packets);
  1319. } else {
  1320. // this might happen if the transport was silently closed in the beforeunload event handler
  1321. debug$5("transport is not open, discarding packets");
  1322. }
  1323. }
  1324. /**
  1325. * Called upon open
  1326. *
  1327. * @protected
  1328. */;
  1329. _proto.onOpen = function onOpen() {
  1330. this.readyState = "open";
  1331. this.writable = true;
  1332. _Emitter.prototype.emitReserved.call(this, "open");
  1333. }
  1334. /**
  1335. * Called with data.
  1336. *
  1337. * @param {String} data
  1338. * @protected
  1339. */;
  1340. _proto.onData = function onData(data) {
  1341. var packet = decodePacket(data, this.socket.binaryType);
  1342. this.onPacket(packet);
  1343. }
  1344. /**
  1345. * Called with a decoded packet.
  1346. *
  1347. * @protected
  1348. */;
  1349. _proto.onPacket = function onPacket(packet) {
  1350. _Emitter.prototype.emitReserved.call(this, "packet", packet);
  1351. }
  1352. /**
  1353. * Called upon close.
  1354. *
  1355. * @protected
  1356. */;
  1357. _proto.onClose = function onClose(details) {
  1358. this.readyState = "closed";
  1359. _Emitter.prototype.emitReserved.call(this, "close", details);
  1360. }
  1361. /**
  1362. * Pauses the transport, in order not to lose packets during an upgrade.
  1363. *
  1364. * @param onPause
  1365. */;
  1366. _proto.pause = function pause(onPause) {};
  1367. _proto.createUri = function createUri(schema) {
  1368. var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1369. return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
  1370. };
  1371. _proto._hostname = function _hostname() {
  1372. var hostname = this.opts.hostname;
  1373. return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
  1374. };
  1375. _proto._port = function _port() {
  1376. if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
  1377. return ":" + this.opts.port;
  1378. } else {
  1379. return "";
  1380. }
  1381. };
  1382. _proto._query = function _query(query) {
  1383. var encodedQuery = encode(query);
  1384. return encodedQuery.length ? "?" + encodedQuery : "";
  1385. };
  1386. return Transport;
  1387. }(Emitter);
  1388. var debug$4 = debugModule("engine.io-client:polling"); // debug()
  1389. var Polling = /*#__PURE__*/function (_Transport) {
  1390. function Polling() {
  1391. var _this;
  1392. _this = _Transport.apply(this, arguments) || this;
  1393. _this._polling = false;
  1394. return _this;
  1395. }
  1396. _inheritsLoose(Polling, _Transport);
  1397. var _proto = Polling.prototype;
  1398. /**
  1399. * Opens the socket (triggers polling). We write a PING message to determine
  1400. * when the transport is open.
  1401. *
  1402. * @protected
  1403. */
  1404. _proto.doOpen = function doOpen() {
  1405. this._poll();
  1406. }
  1407. /**
  1408. * Pauses polling.
  1409. *
  1410. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  1411. * @package
  1412. */;
  1413. _proto.pause = function pause(onPause) {
  1414. var _this2 = this;
  1415. this.readyState = "pausing";
  1416. var pause = function pause() {
  1417. debug$4("paused");
  1418. _this2.readyState = "paused";
  1419. onPause();
  1420. };
  1421. if (this._polling || !this.writable) {
  1422. var total = 0;
  1423. if (this._polling) {
  1424. debug$4("we are currently polling - waiting to pause");
  1425. total++;
  1426. this.once("pollComplete", function () {
  1427. debug$4("pre-pause polling complete");
  1428. --total || pause();
  1429. });
  1430. }
  1431. if (!this.writable) {
  1432. debug$4("we are currently writing - waiting to pause");
  1433. total++;
  1434. this.once("drain", function () {
  1435. debug$4("pre-pause writing complete");
  1436. --total || pause();
  1437. });
  1438. }
  1439. } else {
  1440. pause();
  1441. }
  1442. }
  1443. /**
  1444. * Starts polling cycle.
  1445. *
  1446. * @private
  1447. */;
  1448. _proto._poll = function _poll() {
  1449. debug$4("polling");
  1450. this._polling = true;
  1451. this.doPoll();
  1452. this.emitReserved("poll");
  1453. }
  1454. /**
  1455. * Overloads onData to detect payloads.
  1456. *
  1457. * @protected
  1458. */;
  1459. _proto.onData = function onData(data) {
  1460. var _this3 = this;
  1461. debug$4("polling got data %s", data);
  1462. var callback = function callback(packet) {
  1463. // if its the first message we consider the transport open
  1464. if ("opening" === _this3.readyState && packet.type === "open") {
  1465. _this3.onOpen();
  1466. }
  1467. // if its a close packet, we close the ongoing requests
  1468. if ("close" === packet.type) {
  1469. _this3.onClose({
  1470. description: "transport closed by the server"
  1471. });
  1472. return false;
  1473. }
  1474. // otherwise bypass onData and handle the message
  1475. _this3.onPacket(packet);
  1476. };
  1477. // decode payload
  1478. decodePayload(data, this.socket.binaryType).forEach(callback);
  1479. // if an event did not trigger closing
  1480. if ("closed" !== this.readyState) {
  1481. // if we got data we're not polling
  1482. this._polling = false;
  1483. this.emitReserved("pollComplete");
  1484. if ("open" === this.readyState) {
  1485. this._poll();
  1486. } else {
  1487. debug$4('ignoring poll - transport state "%s"', this.readyState);
  1488. }
  1489. }
  1490. }
  1491. /**
  1492. * For polling, send a close packet.
  1493. *
  1494. * @protected
  1495. */;
  1496. _proto.doClose = function doClose() {
  1497. var _this4 = this;
  1498. var close = function close() {
  1499. debug$4("writing close packet");
  1500. _this4.write([{
  1501. type: "close"
  1502. }]);
  1503. };
  1504. if ("open" === this.readyState) {
  1505. debug$4("transport open - closing");
  1506. close();
  1507. } else {
  1508. // in case we're trying to close while
  1509. // handshaking is in progress (GH-164)
  1510. debug$4("transport not open - deferring close");
  1511. this.once("open", close);
  1512. }
  1513. }
  1514. /**
  1515. * Writes a packets payload.
  1516. *
  1517. * @param {Array} packets - data packets
  1518. * @protected
  1519. */;
  1520. _proto.write = function write(packets) {
  1521. var _this5 = this;
  1522. this.writable = false;
  1523. encodePayload(packets, function (data) {
  1524. _this5.doWrite(data, function () {
  1525. _this5.writable = true;
  1526. _this5.emitReserved("drain");
  1527. });
  1528. });
  1529. }
  1530. /**
  1531. * Generates uri for connection.
  1532. *
  1533. * @private
  1534. */;
  1535. _proto.uri = function uri() {
  1536. var schema = this.opts.secure ? "https" : "http";
  1537. var query = this.query || {};
  1538. // cache busting is forced
  1539. if (false !== this.opts.timestampRequests) {
  1540. query[this.opts.timestampParam] = randomString();
  1541. }
  1542. if (!this.supportsBinary && !query.sid) {
  1543. query.b64 = 1;
  1544. }
  1545. return this.createUri(schema, query);
  1546. };
  1547. return _createClass(Polling, [{
  1548. key: "name",
  1549. get: function get() {
  1550. return "polling";
  1551. }
  1552. }]);
  1553. }(Transport);
  1554. // imported from https://github.com/component/has-cors
  1555. var value = false;
  1556. try {
  1557. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  1558. } catch (err) {
  1559. // if XMLHttp support is disabled in IE then it will throw
  1560. // when trying to create
  1561. }
  1562. var hasCORS = value;
  1563. var debug$3 = debugModule("engine.io-client:polling"); // debug()
  1564. function empty() {}
  1565. var BaseXHR = /*#__PURE__*/function (_Polling) {
  1566. /**
  1567. * XHR Polling constructor.
  1568. *
  1569. * @param {Object} opts
  1570. * @package
  1571. */
  1572. function BaseXHR(opts) {
  1573. var _this;
  1574. _this = _Polling.call(this, opts) || this;
  1575. if (typeof location !== "undefined") {
  1576. var isSSL = "https:" === location.protocol;
  1577. var port = location.port;
  1578. // some user agents have empty `location.port`
  1579. if (!port) {
  1580. port = isSSL ? "443" : "80";
  1581. }
  1582. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  1583. }
  1584. return _this;
  1585. }
  1586. /**
  1587. * Sends data.
  1588. *
  1589. * @param {String} data to send.
  1590. * @param {Function} called upon flush.
  1591. * @private
  1592. */
  1593. _inheritsLoose(BaseXHR, _Polling);
  1594. var _proto = BaseXHR.prototype;
  1595. _proto.doWrite = function doWrite(data, fn) {
  1596. var _this2 = this;
  1597. var req = this.request({
  1598. method: "POST",
  1599. data: data
  1600. });
  1601. req.on("success", fn);
  1602. req.on("error", function (xhrStatus, context) {
  1603. _this2.onError("xhr post error", xhrStatus, context);
  1604. });
  1605. }
  1606. /**
  1607. * Starts a poll cycle.
  1608. *
  1609. * @private
  1610. */;
  1611. _proto.doPoll = function doPoll() {
  1612. var _this3 = this;
  1613. debug$3("xhr poll");
  1614. var req = this.request();
  1615. req.on("data", this.onData.bind(this));
  1616. req.on("error", function (xhrStatus, context) {
  1617. _this3.onError("xhr poll error", xhrStatus, context);
  1618. });
  1619. this.pollXhr = req;
  1620. };
  1621. return BaseXHR;
  1622. }(Polling);
  1623. var Request = /*#__PURE__*/function (_Emitter) {
  1624. /**
  1625. * Request constructor
  1626. *
  1627. * @param {Object} options
  1628. * @package
  1629. */
  1630. function Request(createRequest, uri, opts) {
  1631. var _this4;
  1632. _this4 = _Emitter.call(this) || this;
  1633. _this4.createRequest = createRequest;
  1634. installTimerFunctions(_this4, opts);
  1635. _this4._opts = opts;
  1636. _this4._method = opts.method || "GET";
  1637. _this4._uri = uri;
  1638. _this4._data = undefined !== opts.data ? opts.data : null;
  1639. _this4._create();
  1640. return _this4;
  1641. }
  1642. /**
  1643. * Creates the XHR object and sends the request.
  1644. *
  1645. * @private
  1646. */
  1647. _inheritsLoose(Request, _Emitter);
  1648. var _proto2 = Request.prototype;
  1649. _proto2._create = function _create() {
  1650. var _this5 = this;
  1651. var _a;
  1652. var opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1653. opts.xdomain = !!this._opts.xd;
  1654. var xhr = this._xhr = this.createRequest(opts);
  1655. try {
  1656. debug$3("xhr open %s: %s", this._method, this._uri);
  1657. xhr.open(this._method, this._uri, true);
  1658. try {
  1659. if (this._opts.extraHeaders) {
  1660. // @ts-ignore
  1661. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1662. for (var i in this._opts.extraHeaders) {
  1663. if (this._opts.extraHeaders.hasOwnProperty(i)) {
  1664. xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
  1665. }
  1666. }
  1667. }
  1668. } catch (e) {}
  1669. if ("POST" === this._method) {
  1670. try {
  1671. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1672. } catch (e) {}
  1673. }
  1674. try {
  1675. xhr.setRequestHeader("Accept", "*/*");
  1676. } catch (e) {}
  1677. (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  1678. // ie6 check
  1679. if ("withCredentials" in xhr) {
  1680. xhr.withCredentials = this._opts.withCredentials;
  1681. }
  1682. if (this._opts.requestTimeout) {
  1683. xhr.timeout = this._opts.requestTimeout;
  1684. }
  1685. xhr.onreadystatechange = function () {
  1686. var _a;
  1687. if (xhr.readyState === 3) {
  1688. (_a = _this5._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
  1689. // @ts-ignore
  1690. xhr.getResponseHeader("set-cookie"));
  1691. }
  1692. if (4 !== xhr.readyState) return;
  1693. if (200 === xhr.status || 1223 === xhr.status) {
  1694. _this5._onLoad();
  1695. } else {
  1696. // make sure the `error` event handler that's user-set
  1697. // does not throw in the same tick and gets caught here
  1698. _this5.setTimeoutFn(function () {
  1699. _this5._onError(typeof xhr.status === "number" ? xhr.status : 0);
  1700. }, 0);
  1701. }
  1702. };
  1703. debug$3("xhr data %s", this._data);
  1704. xhr.send(this._data);
  1705. } catch (e) {
  1706. // Need to defer since .create() is called directly from the constructor
  1707. // and thus the 'error' event can only be only bound *after* this exception
  1708. // occurs. Therefore, also, we cannot throw here at all.
  1709. this.setTimeoutFn(function () {
  1710. _this5._onError(e);
  1711. }, 0);
  1712. return;
  1713. }
  1714. if (typeof document !== "undefined") {
  1715. this._index = Request.requestsCount++;
  1716. Request.requests[this._index] = this;
  1717. }
  1718. }
  1719. /**
  1720. * Called upon error.
  1721. *
  1722. * @private
  1723. */;
  1724. _proto2._onError = function _onError(err) {
  1725. this.emitReserved("error", err, this._xhr);
  1726. this._cleanup(true);
  1727. }
  1728. /**
  1729. * Cleans up house.
  1730. *
  1731. * @private
  1732. */;
  1733. _proto2._cleanup = function _cleanup(fromError) {
  1734. if ("undefined" === typeof this._xhr || null === this._xhr) {
  1735. return;
  1736. }
  1737. this._xhr.onreadystatechange = empty;
  1738. if (fromError) {
  1739. try {
  1740. this._xhr.abort();
  1741. } catch (e) {}
  1742. }
  1743. if (typeof document !== "undefined") {
  1744. delete Request.requests[this._index];
  1745. }
  1746. this._xhr = null;
  1747. }
  1748. /**
  1749. * Called upon load.
  1750. *
  1751. * @private
  1752. */;
  1753. _proto2._onLoad = function _onLoad() {
  1754. var data = this._xhr.responseText;
  1755. if (data !== null) {
  1756. this.emitReserved("data", data);
  1757. this.emitReserved("success");
  1758. this._cleanup();
  1759. }
  1760. }
  1761. /**
  1762. * Aborts the request.
  1763. *
  1764. * @package
  1765. */;
  1766. _proto2.abort = function abort() {
  1767. this._cleanup();
  1768. };
  1769. return Request;
  1770. }(Emitter);
  1771. Request.requestsCount = 0;
  1772. Request.requests = {};
  1773. /**
  1774. * Aborts pending requests when unloading the window. This is needed to prevent
  1775. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1776. * emitted.
  1777. */
  1778. if (typeof document !== "undefined") {
  1779. // @ts-ignore
  1780. if (typeof attachEvent === "function") {
  1781. // @ts-ignore
  1782. attachEvent("onunload", unloadHandler);
  1783. } else if (typeof addEventListener === "function") {
  1784. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1785. addEventListener(terminationEvent, unloadHandler, false);
  1786. }
  1787. }
  1788. function unloadHandler() {
  1789. for (var i in Request.requests) {
  1790. if (Request.requests.hasOwnProperty(i)) {
  1791. Request.requests[i].abort();
  1792. }
  1793. }
  1794. }
  1795. var hasXHR2 = function () {
  1796. var xhr = newRequest({
  1797. xdomain: false
  1798. });
  1799. return xhr && xhr.responseType !== null;
  1800. }();
  1801. /**
  1802. * HTTP long-polling based on the built-in `XMLHttpRequest` object.
  1803. *
  1804. * Usage: browser
  1805. *
  1806. * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  1807. */
  1808. var XHR = /*#__PURE__*/function (_BaseXHR) {
  1809. function XHR(opts) {
  1810. var _this6;
  1811. _this6 = _BaseXHR.call(this, opts) || this;
  1812. var forceBase64 = opts && opts.forceBase64;
  1813. _this6.supportsBinary = hasXHR2 && !forceBase64;
  1814. return _this6;
  1815. }
  1816. _inheritsLoose(XHR, _BaseXHR);
  1817. var _proto3 = XHR.prototype;
  1818. _proto3.request = function request() {
  1819. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1820. _extends(opts, {
  1821. xd: this.xd
  1822. }, this.opts);
  1823. return new Request(newRequest, this.uri(), opts);
  1824. };
  1825. return XHR;
  1826. }(BaseXHR);
  1827. function newRequest(opts) {
  1828. var xdomain = opts.xdomain;
  1829. // XMLHttpRequest can be disabled on IE
  1830. try {
  1831. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  1832. return new XMLHttpRequest();
  1833. }
  1834. } catch (e) {}
  1835. if (!xdomain) {
  1836. try {
  1837. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  1838. } catch (e) {}
  1839. }
  1840. }
  1841. var debug$2 = debugModule("engine.io-client:websocket"); // debug()
  1842. // detect ReactNative environment
  1843. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1844. var BaseWS = /*#__PURE__*/function (_Transport) {
  1845. function BaseWS() {
  1846. return _Transport.apply(this, arguments) || this;
  1847. }
  1848. _inheritsLoose(BaseWS, _Transport);
  1849. var _proto = BaseWS.prototype;
  1850. _proto.doOpen = function doOpen() {
  1851. var uri = this.uri();
  1852. var protocols = this.opts.protocols;
  1853. // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1854. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1855. if (this.opts.extraHeaders) {
  1856. opts.headers = this.opts.extraHeaders;
  1857. }
  1858. try {
  1859. this.ws = this.createSocket(uri, protocols, opts);
  1860. } catch (err) {
  1861. return this.emitReserved("error", err);
  1862. }
  1863. this.ws.binaryType = this.socket.binaryType;
  1864. this.addEventListeners();
  1865. }
  1866. /**
  1867. * Adds event listeners to the socket
  1868. *
  1869. * @private
  1870. */;
  1871. _proto.addEventListeners = function addEventListeners() {
  1872. var _this = this;
  1873. this.ws.onopen = function () {
  1874. if (_this.opts.autoUnref) {
  1875. _this.ws._socket.unref();
  1876. }
  1877. _this.onOpen();
  1878. };
  1879. this.ws.onclose = function (closeEvent) {
  1880. return _this.onClose({
  1881. description: "websocket connection closed",
  1882. context: closeEvent
  1883. });
  1884. };
  1885. this.ws.onmessage = function (ev) {
  1886. return _this.onData(ev.data);
  1887. };
  1888. this.ws.onerror = function (e) {
  1889. return _this.onError("websocket error", e);
  1890. };
  1891. };
  1892. _proto.write = function write(packets) {
  1893. var _this2 = this;
  1894. this.writable = false;
  1895. // encodePacket efficient as it uses WS framing
  1896. // no need for encodePayload
  1897. var _loop = function _loop() {
  1898. var packet = packets[i];
  1899. var lastPacket = i === packets.length - 1;
  1900. encodePacket(packet, _this2.supportsBinary, function (data) {
  1901. // Sometimes the websocket has already been closed but the browser didn't
  1902. // have a chance of informing us about it yet, in that case send will
  1903. // throw an error
  1904. try {
  1905. _this2.doWrite(packet, data);
  1906. } catch (e) {
  1907. debug$2("websocket closed before onclose event");
  1908. }
  1909. if (lastPacket) {
  1910. // fake drain
  1911. // defer to next tick to allow Socket to clear writeBuffer
  1912. nextTick(function () {
  1913. _this2.writable = true;
  1914. _this2.emitReserved("drain");
  1915. }, _this2.setTimeoutFn);
  1916. }
  1917. });
  1918. };
  1919. for (var i = 0; i < packets.length; i++) {
  1920. _loop();
  1921. }
  1922. };
  1923. _proto.doClose = function doClose() {
  1924. if (typeof this.ws !== "undefined") {
  1925. this.ws.close();
  1926. this.ws = null;
  1927. }
  1928. }
  1929. /**
  1930. * Generates uri for connection.
  1931. *
  1932. * @private
  1933. */;
  1934. _proto.uri = function uri() {
  1935. var schema = this.opts.secure ? "wss" : "ws";
  1936. var query = this.query || {};
  1937. // append timestamp to URI
  1938. if (this.opts.timestampRequests) {
  1939. query[this.opts.timestampParam] = randomString();
  1940. }
  1941. // communicate binary support capabilities
  1942. if (!this.supportsBinary) {
  1943. query.b64 = 1;
  1944. }
  1945. return this.createUri(schema, query);
  1946. };
  1947. return _createClass(BaseWS, [{
  1948. key: "name",
  1949. get: function get() {
  1950. return "websocket";
  1951. }
  1952. }]);
  1953. }(Transport);
  1954. var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  1955. /**
  1956. * WebSocket transport based on the built-in `WebSocket` object.
  1957. *
  1958. * Usage: browser, Node.js (since v21), Deno, Bun
  1959. *
  1960. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
  1961. * @see https://caniuse.com/mdn-api_websocket
  1962. * @see https://nodejs.org/api/globals.html#websocket
  1963. */
  1964. var WS = /*#__PURE__*/function (_BaseWS) {
  1965. function WS() {
  1966. return _BaseWS.apply(this, arguments) || this;
  1967. }
  1968. _inheritsLoose(WS, _BaseWS);
  1969. var _proto2 = WS.prototype;
  1970. _proto2.createSocket = function createSocket(uri, protocols, opts) {
  1971. return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
  1972. };
  1973. _proto2.doWrite = function doWrite(_packet, data) {
  1974. this.ws.send(data);
  1975. };
  1976. return WS;
  1977. }(BaseWS);
  1978. var debug$1 = debugModule("engine.io-client:webtransport"); // debug()
  1979. /**
  1980. * WebTransport transport based on the built-in `WebTransport` object.
  1981. *
  1982. * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
  1983. *
  1984. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
  1985. * @see https://caniuse.com/webtransport
  1986. */
  1987. var WT = /*#__PURE__*/function (_Transport) {
  1988. function WT() {
  1989. return _Transport.apply(this, arguments) || this;
  1990. }
  1991. _inheritsLoose(WT, _Transport);
  1992. var _proto = WT.prototype;
  1993. _proto.doOpen = function doOpen() {
  1994. var _this = this;
  1995. try {
  1996. // @ts-ignore
  1997. this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  1998. } catch (err) {
  1999. return this.emitReserved("error", err);
  2000. }
  2001. this._transport.closed.then(function () {
  2002. debug$1("transport closed gracefully");
  2003. _this.onClose();
  2004. })["catch"](function (err) {
  2005. debug$1("transport closed due to %s", err);
  2006. _this.onError("webtransport error", err);
  2007. });
  2008. // note: we could have used async/await, but that would require some additional polyfills
  2009. this._transport.ready.then(function () {
  2010. _this._transport.createBidirectionalStream().then(function (stream) {
  2011. var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType);
  2012. var reader = stream.readable.pipeThrough(decoderStream).getReader();
  2013. var encoderStream = createPacketEncoderStream();
  2014. encoderStream.readable.pipeTo(stream.writable);
  2015. _this._writer = encoderStream.writable.getWriter();
  2016. var read = function read() {
  2017. reader.read().then(function (_ref) {
  2018. var done = _ref.done,
  2019. value = _ref.value;
  2020. if (done) {
  2021. debug$1("session is closed");
  2022. return;
  2023. }
  2024. debug$1("received chunk: %o", value);
  2025. _this.onPacket(value);
  2026. read();
  2027. })["catch"](function (err) {
  2028. debug$1("an error occurred while reading: %s", err);
  2029. });
  2030. };
  2031. read();
  2032. var packet = {
  2033. type: "open"
  2034. };
  2035. if (_this.query.sid) {
  2036. packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}");
  2037. }
  2038. _this._writer.write(packet).then(function () {
  2039. return _this.onOpen();
  2040. });
  2041. });
  2042. });
  2043. };
  2044. _proto.write = function write(packets) {
  2045. var _this2 = this;
  2046. this.writable = false;
  2047. var _loop = function _loop() {
  2048. var packet = packets[i];
  2049. var lastPacket = i === packets.length - 1;
  2050. _this2._writer.write(packet).then(function () {
  2051. if (lastPacket) {
  2052. nextTick(function () {
  2053. _this2.writable = true;
  2054. _this2.emitReserved("drain");
  2055. }, _this2.setTimeoutFn);
  2056. }
  2057. });
  2058. };
  2059. for (var i = 0; i < packets.length; i++) {
  2060. _loop();
  2061. }
  2062. };
  2063. _proto.doClose = function doClose() {
  2064. var _a;
  2065. (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
  2066. };
  2067. return _createClass(WT, [{
  2068. key: "name",
  2069. get: function get() {
  2070. return "webtransport";
  2071. }
  2072. }]);
  2073. }(Transport);
  2074. var transports = {
  2075. websocket: WS,
  2076. webtransport: WT,
  2077. polling: XHR
  2078. };
  2079. // imported from https://github.com/galkn/parseuri
  2080. /**
  2081. * Parses a URI
  2082. *
  2083. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  2084. *
  2085. * See:
  2086. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  2087. * - https://caniuse.com/url
  2088. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  2089. *
  2090. * History of the parse() method:
  2091. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  2092. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  2093. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  2094. *
  2095. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  2096. * @api private
  2097. */
  2098. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  2099. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  2100. function parse(str) {
  2101. if (str.length > 8000) {
  2102. throw "URI too long";
  2103. }
  2104. var src = str,
  2105. b = str.indexOf('['),
  2106. e = str.indexOf(']');
  2107. if (b != -1 && e != -1) {
  2108. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  2109. }
  2110. var m = re.exec(str || ''),
  2111. uri = {},
  2112. i = 14;
  2113. while (i--) {
  2114. uri[parts[i]] = m[i] || '';
  2115. }
  2116. if (b != -1 && e != -1) {
  2117. uri.source = src;
  2118. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  2119. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  2120. uri.ipv6uri = true;
  2121. }
  2122. uri.pathNames = pathNames(uri, uri['path']);
  2123. uri.queryKey = queryKey(uri, uri['query']);
  2124. return uri;
  2125. }
  2126. function pathNames(obj, path) {
  2127. var regx = /\/{2,9}/g,
  2128. names = path.replace(regx, "/").split("/");
  2129. if (path.slice(0, 1) == '/' || path.length === 0) {
  2130. names.splice(0, 1);
  2131. }
  2132. if (path.slice(-1) == '/') {
  2133. names.splice(names.length - 1, 1);
  2134. }
  2135. return names;
  2136. }
  2137. function queryKey(uri, query) {
  2138. var data = {};
  2139. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  2140. if ($1) {
  2141. data[$1] = $2;
  2142. }
  2143. });
  2144. return data;
  2145. }
  2146. var debug = debugModule("engine.io-client:socket"); // debug()
  2147. var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
  2148. var OFFLINE_EVENT_LISTENERS = [];
  2149. if (withEventListeners) {
  2150. // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
  2151. // script, so we create one single event listener here which will forward the event to the socket instances
  2152. addEventListener("offline", function () {
  2153. debug("closing %d connection(s) because the network was lost", OFFLINE_EVENT_LISTENERS.length);
  2154. OFFLINE_EVENT_LISTENERS.forEach(function (listener) {
  2155. return listener();
  2156. });
  2157. }, false);
  2158. }
  2159. /**
  2160. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2161. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2162. *
  2163. * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
  2164. * successfully establishes the connection.
  2165. *
  2166. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2167. *
  2168. * @example
  2169. * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
  2170. *
  2171. * const socket = new SocketWithoutUpgrade({
  2172. * transports: [WebSocket]
  2173. * });
  2174. *
  2175. * socket.on("open", () => {
  2176. * socket.send("hello");
  2177. * });
  2178. *
  2179. * @see SocketWithUpgrade
  2180. * @see Socket
  2181. */
  2182. var SocketWithoutUpgrade = /*#__PURE__*/function (_Emitter) {
  2183. /**
  2184. * Socket constructor.
  2185. *
  2186. * @param {String|Object} uri - uri or options
  2187. * @param {Object} opts - options
  2188. */
  2189. function SocketWithoutUpgrade(uri, opts) {
  2190. var _this;
  2191. _this = _Emitter.call(this) || this;
  2192. _this.binaryType = defaultBinaryType;
  2193. _this.writeBuffer = [];
  2194. _this._prevBufferLen = 0;
  2195. _this._pingInterval = -1;
  2196. _this._pingTimeout = -1;
  2197. _this._maxPayload = -1;
  2198. /**
  2199. * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
  2200. * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
  2201. */
  2202. _this._pingTimeoutTime = Infinity;
  2203. if (uri && "object" === _typeof(uri)) {
  2204. opts = uri;
  2205. uri = null;
  2206. }
  2207. if (uri) {
  2208. var parsedUri = parse(uri);
  2209. opts.hostname = parsedUri.host;
  2210. opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
  2211. opts.port = parsedUri.port;
  2212. if (parsedUri.query) opts.query = parsedUri.query;
  2213. } else if (opts.host) {
  2214. opts.hostname = parse(opts.host).host;
  2215. }
  2216. installTimerFunctions(_this, opts);
  2217. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  2218. if (opts.hostname && !opts.port) {
  2219. // if no port is specified manually, use the protocol default
  2220. opts.port = _this.secure ? "443" : "80";
  2221. }
  2222. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  2223. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  2224. _this.transports = [];
  2225. _this._transportsByName = {};
  2226. opts.transports.forEach(function (t) {
  2227. var transportName = t.prototype.name;
  2228. _this.transports.push(transportName);
  2229. _this._transportsByName[transportName] = t;
  2230. });
  2231. _this.opts = _extends({
  2232. path: "/engine.io",
  2233. agent: false,
  2234. withCredentials: false,
  2235. upgrade: true,
  2236. timestampParam: "t",
  2237. rememberUpgrade: false,
  2238. addTrailingSlash: true,
  2239. rejectUnauthorized: true,
  2240. perMessageDeflate: {
  2241. threshold: 1024
  2242. },
  2243. transportOptions: {},
  2244. closeOnBeforeunload: false
  2245. }, opts);
  2246. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  2247. if (typeof _this.opts.query === "string") {
  2248. _this.opts.query = decode(_this.opts.query);
  2249. }
  2250. if (withEventListeners) {
  2251. if (_this.opts.closeOnBeforeunload) {
  2252. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  2253. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  2254. // closed/reloaded)
  2255. _this._beforeunloadEventListener = function () {
  2256. if (_this.transport) {
  2257. // silently close the transport
  2258. _this.transport.removeAllListeners();
  2259. _this.transport.close();
  2260. }
  2261. };
  2262. addEventListener("beforeunload", _this._beforeunloadEventListener, false);
  2263. }
  2264. if (_this.hostname !== "localhost") {
  2265. debug("adding listener for the 'offline' event");
  2266. _this._offlineEventListener = function () {
  2267. _this._onClose("transport close", {
  2268. description: "network connection lost"
  2269. });
  2270. };
  2271. OFFLINE_EVENT_LISTENERS.push(_this._offlineEventListener);
  2272. }
  2273. }
  2274. if (_this.opts.withCredentials) {
  2275. _this._cookieJar = createCookieJar();
  2276. }
  2277. _this._open();
  2278. return _this;
  2279. }
  2280. /**
  2281. * Creates transport of the given type.
  2282. *
  2283. * @param {String} name - transport name
  2284. * @return {Transport}
  2285. * @private
  2286. */
  2287. _inheritsLoose(SocketWithoutUpgrade, _Emitter);
  2288. var _proto = SocketWithoutUpgrade.prototype;
  2289. _proto.createTransport = function createTransport(name) {
  2290. debug('creating transport "%s"', name);
  2291. var query = _extends({}, this.opts.query);
  2292. // append engine.io protocol identifier
  2293. query.EIO = protocol;
  2294. // transport name
  2295. query.transport = name;
  2296. // session id if we already have one
  2297. if (this.id) query.sid = this.id;
  2298. var opts = _extends({}, this.opts, {
  2299. query: query,
  2300. socket: this,
  2301. hostname: this.hostname,
  2302. secure: this.secure,
  2303. port: this.port
  2304. }, this.opts.transportOptions[name]);
  2305. debug("options: %j", opts);
  2306. return new this._transportsByName[name](opts);
  2307. }
  2308. /**
  2309. * Initializes transport to use and starts probe.
  2310. *
  2311. * @private
  2312. */;
  2313. _proto._open = function _open() {
  2314. var _this2 = this;
  2315. if (this.transports.length === 0) {
  2316. // Emit error on next tick so it can be listened to
  2317. this.setTimeoutFn(function () {
  2318. _this2.emitReserved("error", "No transports available");
  2319. }, 0);
  2320. return;
  2321. }
  2322. var transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
  2323. this.readyState = "opening";
  2324. var transport = this.createTransport(transportName);
  2325. transport.open();
  2326. this.setTransport(transport);
  2327. }
  2328. /**
  2329. * Sets the current transport. Disables the existing one (if any).
  2330. *
  2331. * @private
  2332. */;
  2333. _proto.setTransport = function setTransport(transport) {
  2334. var _this3 = this;
  2335. debug("setting transport %s", transport.name);
  2336. if (this.transport) {
  2337. debug("clearing existing transport %s", this.transport.name);
  2338. this.transport.removeAllListeners();
  2339. }
  2340. // set up transport
  2341. this.transport = transport;
  2342. // set up transport listeners
  2343. transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", function (reason) {
  2344. return _this3._onClose("transport close", reason);
  2345. });
  2346. }
  2347. /**
  2348. * Called when connection is deemed open.
  2349. *
  2350. * @private
  2351. */;
  2352. _proto.onOpen = function onOpen() {
  2353. debug("socket open");
  2354. this.readyState = "open";
  2355. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
  2356. this.emitReserved("open");
  2357. this.flush();
  2358. }
  2359. /**
  2360. * Handles a packet.
  2361. *
  2362. * @private
  2363. */;
  2364. _proto._onPacket = function _onPacket(packet) {
  2365. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2366. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  2367. this.emitReserved("packet", packet);
  2368. // Socket is live - any packet counts
  2369. this.emitReserved("heartbeat");
  2370. switch (packet.type) {
  2371. case "open":
  2372. this.onHandshake(JSON.parse(packet.data));
  2373. break;
  2374. case "ping":
  2375. this._sendPacket("pong");
  2376. this.emitReserved("ping");
  2377. this.emitReserved("pong");
  2378. this._resetPingTimeout();
  2379. break;
  2380. case "error":
  2381. var err = new Error("server error");
  2382. // @ts-ignore
  2383. err.code = packet.data;
  2384. this._onError(err);
  2385. break;
  2386. case "message":
  2387. this.emitReserved("data", packet.data);
  2388. this.emitReserved("message", packet.data);
  2389. break;
  2390. }
  2391. } else {
  2392. debug('packet received with socket readyState "%s"', this.readyState);
  2393. }
  2394. }
  2395. /**
  2396. * Called upon handshake completion.
  2397. *
  2398. * @param {Object} data - handshake obj
  2399. * @private
  2400. */;
  2401. _proto.onHandshake = function onHandshake(data) {
  2402. this.emitReserved("handshake", data);
  2403. this.id = data.sid;
  2404. this.transport.query.sid = data.sid;
  2405. this._pingInterval = data.pingInterval;
  2406. this._pingTimeout = data.pingTimeout;
  2407. this._maxPayload = data.maxPayload;
  2408. this.onOpen();
  2409. // In case open handler closes socket
  2410. if ("closed" === this.readyState) return;
  2411. this._resetPingTimeout();
  2412. }
  2413. /**
  2414. * Sets and resets ping timeout timer based on server pings.
  2415. *
  2416. * @private
  2417. */;
  2418. _proto._resetPingTimeout = function _resetPingTimeout() {
  2419. var _this4 = this;
  2420. this.clearTimeoutFn(this._pingTimeoutTimer);
  2421. var delay = this._pingInterval + this._pingTimeout;
  2422. this._pingTimeoutTime = Date.now() + delay;
  2423. this._pingTimeoutTimer = this.setTimeoutFn(function () {
  2424. _this4._onClose("ping timeout");
  2425. }, delay);
  2426. if (this.opts.autoUnref) {
  2427. this._pingTimeoutTimer.unref();
  2428. }
  2429. }
  2430. /**
  2431. * Called on `drain` event
  2432. *
  2433. * @private
  2434. */;
  2435. _proto._onDrain = function _onDrain() {
  2436. this.writeBuffer.splice(0, this._prevBufferLen);
  2437. // setting prevBufferLen = 0 is very important
  2438. // for example, when upgrading, upgrade packet is sent over,
  2439. // and a nonzero prevBufferLen could cause problems on `drain`
  2440. this._prevBufferLen = 0;
  2441. if (0 === this.writeBuffer.length) {
  2442. this.emitReserved("drain");
  2443. } else {
  2444. this.flush();
  2445. }
  2446. }
  2447. /**
  2448. * Flush write buffers.
  2449. *
  2450. * @private
  2451. */;
  2452. _proto.flush = function flush() {
  2453. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  2454. var packets = this._getWritablePackets();
  2455. debug("flushing %d packets in socket", packets.length);
  2456. this.transport.send(packets);
  2457. // keep track of current length of writeBuffer
  2458. // splice writeBuffer and callbackBuffer on `drain`
  2459. this._prevBufferLen = packets.length;
  2460. this.emitReserved("flush");
  2461. }
  2462. }
  2463. /**
  2464. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  2465. * long-polling)
  2466. *
  2467. * @private
  2468. */;
  2469. _proto._getWritablePackets = function _getWritablePackets() {
  2470. var shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  2471. if (!shouldCheckPayloadSize) {
  2472. return this.writeBuffer;
  2473. }
  2474. var payloadSize = 1; // first packet type
  2475. for (var i = 0; i < this.writeBuffer.length; i++) {
  2476. var data = this.writeBuffer[i].data;
  2477. if (data) {
  2478. payloadSize += byteLength(data);
  2479. }
  2480. if (i > 0 && payloadSize > this._maxPayload) {
  2481. debug("only send %d out of %d packets", i, this.writeBuffer.length);
  2482. return this.writeBuffer.slice(0, i);
  2483. }
  2484. payloadSize += 2; // separator + packet type
  2485. }
  2486. debug("payload size is %d (max: %d)", payloadSize, this._maxPayload);
  2487. return this.writeBuffer;
  2488. }
  2489. /**
  2490. * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
  2491. *
  2492. * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
  2493. * `write()` method then the message would not be buffered by the Socket.IO client.
  2494. *
  2495. * @return {boolean}
  2496. * @private
  2497. */
  2498. /* private */;
  2499. _proto._hasPingExpired = function _hasPingExpired() {
  2500. var _this5 = this;
  2501. if (!this._pingTimeoutTime) return true;
  2502. var hasExpired = Date.now() > this._pingTimeoutTime;
  2503. if (hasExpired) {
  2504. debug("throttled timer detected, scheduling connection close");
  2505. this._pingTimeoutTime = 0;
  2506. nextTick(function () {
  2507. _this5._onClose("ping timeout");
  2508. }, this.setTimeoutFn);
  2509. }
  2510. return hasExpired;
  2511. }
  2512. /**
  2513. * Sends a message.
  2514. *
  2515. * @param {String} msg - message.
  2516. * @param {Object} options.
  2517. * @param {Function} fn - callback function.
  2518. * @return {Socket} for chaining.
  2519. */;
  2520. _proto.write = function write(msg, options, fn) {
  2521. this._sendPacket("message", msg, options, fn);
  2522. return this;
  2523. }
  2524. /**
  2525. * Sends a message. Alias of {@link Socket#write}.
  2526. *
  2527. * @param {String} msg - message.
  2528. * @param {Object} options.
  2529. * @param {Function} fn - callback function.
  2530. * @return {Socket} for chaining.
  2531. */;
  2532. _proto.send = function send(msg, options, fn) {
  2533. this._sendPacket("message", msg, options, fn);
  2534. return this;
  2535. }
  2536. /**
  2537. * Sends a packet.
  2538. *
  2539. * @param {String} type: packet type.
  2540. * @param {String} data.
  2541. * @param {Object} options.
  2542. * @param {Function} fn - callback function.
  2543. * @private
  2544. */;
  2545. _proto._sendPacket = function _sendPacket(type, data, options, fn) {
  2546. if ("function" === typeof data) {
  2547. fn = data;
  2548. data = undefined;
  2549. }
  2550. if ("function" === typeof options) {
  2551. fn = options;
  2552. options = null;
  2553. }
  2554. if ("closing" === this.readyState || "closed" === this.readyState) {
  2555. return;
  2556. }
  2557. options = options || {};
  2558. options.compress = false !== options.compress;
  2559. var packet = {
  2560. type: type,
  2561. data: data,
  2562. options: options
  2563. };
  2564. this.emitReserved("packetCreate", packet);
  2565. this.writeBuffer.push(packet);
  2566. if (fn) this.once("flush", fn);
  2567. this.flush();
  2568. }
  2569. /**
  2570. * Closes the connection.
  2571. */;
  2572. _proto.close = function close() {
  2573. var _this6 = this;
  2574. var close = function close() {
  2575. _this6._onClose("forced close");
  2576. debug("socket closing - telling transport to close");
  2577. _this6.transport.close();
  2578. };
  2579. var cleanupAndClose = function cleanupAndClose() {
  2580. _this6.off("upgrade", cleanupAndClose);
  2581. _this6.off("upgradeError", cleanupAndClose);
  2582. close();
  2583. };
  2584. var waitForUpgrade = function waitForUpgrade() {
  2585. // wait for upgrade to finish since we can't send packets while pausing a transport
  2586. _this6.once("upgrade", cleanupAndClose);
  2587. _this6.once("upgradeError", cleanupAndClose);
  2588. };
  2589. if ("opening" === this.readyState || "open" === this.readyState) {
  2590. this.readyState = "closing";
  2591. if (this.writeBuffer.length) {
  2592. this.once("drain", function () {
  2593. if (_this6.upgrading) {
  2594. waitForUpgrade();
  2595. } else {
  2596. close();
  2597. }
  2598. });
  2599. } else if (this.upgrading) {
  2600. waitForUpgrade();
  2601. } else {
  2602. close();
  2603. }
  2604. }
  2605. return this;
  2606. }
  2607. /**
  2608. * Called upon transport error
  2609. *
  2610. * @private
  2611. */;
  2612. _proto._onError = function _onError(err) {
  2613. debug("socket error %j", err);
  2614. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2615. if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
  2616. debug("trying next transport");
  2617. this.transports.shift();
  2618. return this._open();
  2619. }
  2620. this.emitReserved("error", err);
  2621. this._onClose("transport error", err);
  2622. }
  2623. /**
  2624. * Called upon transport close.
  2625. *
  2626. * @private
  2627. */;
  2628. _proto._onClose = function _onClose(reason, description) {
  2629. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2630. debug('socket close with reason: "%s"', reason);
  2631. // clear timers
  2632. this.clearTimeoutFn(this._pingTimeoutTimer);
  2633. // stop event from firing again for transport
  2634. this.transport.removeAllListeners("close");
  2635. // ensure transport won't stay open
  2636. this.transport.close();
  2637. // ignore further transport communication
  2638. this.transport.removeAllListeners();
  2639. if (withEventListeners) {
  2640. if (this._beforeunloadEventListener) {
  2641. removeEventListener("beforeunload", this._beforeunloadEventListener, false);
  2642. }
  2643. if (this._offlineEventListener) {
  2644. var i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
  2645. if (i !== -1) {
  2646. debug("removing listener for the 'offline' event");
  2647. OFFLINE_EVENT_LISTENERS.splice(i, 1);
  2648. }
  2649. }
  2650. }
  2651. // set ready state
  2652. this.readyState = "closed";
  2653. // clear session id
  2654. this.id = null;
  2655. // emit close event
  2656. this.emitReserved("close", reason, description);
  2657. // clean buffers after, so users can still
  2658. // grab the buffers on `close` event
  2659. this.writeBuffer = [];
  2660. this._prevBufferLen = 0;
  2661. }
  2662. };
  2663. return SocketWithoutUpgrade;
  2664. }(Emitter);
  2665. SocketWithoutUpgrade.protocol = protocol;
  2666. /**
  2667. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2668. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2669. *
  2670. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2671. * low-level transport, it will try to upgrade to a better transport.
  2672. *
  2673. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2674. *
  2675. * @example
  2676. * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
  2677. *
  2678. * const socket = new SocketWithUpgrade({
  2679. * transports: [WebSocket]
  2680. * });
  2681. *
  2682. * socket.on("open", () => {
  2683. * socket.send("hello");
  2684. * });
  2685. *
  2686. * @see SocketWithoutUpgrade
  2687. * @see Socket
  2688. */
  2689. var SocketWithUpgrade = /*#__PURE__*/function (_SocketWithoutUpgrade) {
  2690. function SocketWithUpgrade() {
  2691. var _this7;
  2692. _this7 = _SocketWithoutUpgrade.apply(this, arguments) || this;
  2693. _this7._upgrades = [];
  2694. return _this7;
  2695. }
  2696. _inheritsLoose(SocketWithUpgrade, _SocketWithoutUpgrade);
  2697. var _proto2 = SocketWithUpgrade.prototype;
  2698. _proto2.onOpen = function onOpen() {
  2699. _SocketWithoutUpgrade.prototype.onOpen.call(this);
  2700. if ("open" === this.readyState && this.opts.upgrade) {
  2701. debug("starting upgrade probes");
  2702. for (var i = 0; i < this._upgrades.length; i++) {
  2703. this._probe(this._upgrades[i]);
  2704. }
  2705. }
  2706. }
  2707. /**
  2708. * Probes a transport.
  2709. *
  2710. * @param {String} name - transport name
  2711. * @private
  2712. */;
  2713. _proto2._probe = function _probe(name) {
  2714. var _this8 = this;
  2715. debug('probing transport "%s"', name);
  2716. var transport = this.createTransport(name);
  2717. var failed = false;
  2718. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2719. var onTransportOpen = function onTransportOpen() {
  2720. if (failed) return;
  2721. debug('probe transport "%s" opened', name);
  2722. transport.send([{
  2723. type: "ping",
  2724. data: "probe"
  2725. }]);
  2726. transport.once("packet", function (msg) {
  2727. if (failed) return;
  2728. if ("pong" === msg.type && "probe" === msg.data) {
  2729. debug('probe transport "%s" pong', name);
  2730. _this8.upgrading = true;
  2731. _this8.emitReserved("upgrading", transport);
  2732. if (!transport) return;
  2733. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
  2734. debug('pausing current transport "%s"', _this8.transport.name);
  2735. _this8.transport.pause(function () {
  2736. if (failed) return;
  2737. if ("closed" === _this8.readyState) return;
  2738. debug("changing transport and sending upgrade packet");
  2739. cleanup();
  2740. _this8.setTransport(transport);
  2741. transport.send([{
  2742. type: "upgrade"
  2743. }]);
  2744. _this8.emitReserved("upgrade", transport);
  2745. transport = null;
  2746. _this8.upgrading = false;
  2747. _this8.flush();
  2748. });
  2749. } else {
  2750. debug('probe transport "%s" failed', name);
  2751. var err = new Error("probe error");
  2752. // @ts-ignore
  2753. err.transport = transport.name;
  2754. _this8.emitReserved("upgradeError", err);
  2755. }
  2756. });
  2757. };
  2758. function freezeTransport() {
  2759. if (failed) return;
  2760. // Any callback called by transport should be ignored since now
  2761. failed = true;
  2762. cleanup();
  2763. transport.close();
  2764. transport = null;
  2765. }
  2766. // Handle any error that happens while probing
  2767. var onerror = function onerror(err) {
  2768. var error = new Error("probe error: " + err);
  2769. // @ts-ignore
  2770. error.transport = transport.name;
  2771. freezeTransport();
  2772. debug('probe transport "%s" failed because of error: %s', name, err);
  2773. _this8.emitReserved("upgradeError", error);
  2774. };
  2775. function onTransportClose() {
  2776. onerror("transport closed");
  2777. }
  2778. // When the socket is closed while we're probing
  2779. function onclose() {
  2780. onerror("socket closed");
  2781. }
  2782. // When the socket is upgraded while we're probing
  2783. function onupgrade(to) {
  2784. if (transport && to.name !== transport.name) {
  2785. debug('"%s" works - aborting "%s"', to.name, transport.name);
  2786. freezeTransport();
  2787. }
  2788. }
  2789. // Remove all listeners on the transport and on self
  2790. var cleanup = function cleanup() {
  2791. transport.removeListener("open", onTransportOpen);
  2792. transport.removeListener("error", onerror);
  2793. transport.removeListener("close", onTransportClose);
  2794. _this8.off("close", onclose);
  2795. _this8.off("upgrading", onupgrade);
  2796. };
  2797. transport.once("open", onTransportOpen);
  2798. transport.once("error", onerror);
  2799. transport.once("close", onTransportClose);
  2800. this.once("close", onclose);
  2801. this.once("upgrading", onupgrade);
  2802. if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
  2803. // favor WebTransport
  2804. this.setTimeoutFn(function () {
  2805. if (!failed) {
  2806. transport.open();
  2807. }
  2808. }, 200);
  2809. } else {
  2810. transport.open();
  2811. }
  2812. };
  2813. _proto2.onHandshake = function onHandshake(data) {
  2814. this._upgrades = this._filterUpgrades(data.upgrades);
  2815. _SocketWithoutUpgrade.prototype.onHandshake.call(this, data);
  2816. }
  2817. /**
  2818. * Filters upgrades, returning only those matching client transports.
  2819. *
  2820. * @param {Array} upgrades - server upgrades
  2821. * @private
  2822. */;
  2823. _proto2._filterUpgrades = function _filterUpgrades(upgrades) {
  2824. var filteredUpgrades = [];
  2825. for (var i = 0; i < upgrades.length; i++) {
  2826. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2827. }
  2828. return filteredUpgrades;
  2829. };
  2830. return SocketWithUpgrade;
  2831. }(SocketWithoutUpgrade);
  2832. /**
  2833. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2834. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2835. *
  2836. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2837. * low-level transport, it will try to upgrade to a better transport.
  2838. *
  2839. * @example
  2840. * import { Socket } from "engine.io-client";
  2841. *
  2842. * const socket = new Socket();
  2843. *
  2844. * socket.on("open", () => {
  2845. * socket.send("hello");
  2846. * });
  2847. *
  2848. * @see SocketWithoutUpgrade
  2849. * @see SocketWithUpgrade
  2850. */
  2851. var Socket = /*#__PURE__*/function (_SocketWithUpgrade) {
  2852. function Socket(uri) {
  2853. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2854. var o = _typeof(uri) === "object" ? uri : opts;
  2855. if (!o.transports || o.transports && typeof o.transports[0] === "string") {
  2856. o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map(function (transportName) {
  2857. return transports[transportName];
  2858. }).filter(function (t) {
  2859. return !!t;
  2860. });
  2861. }
  2862. return _SocketWithUpgrade.call(this, uri, o) || this;
  2863. }
  2864. _inheritsLoose(Socket, _SocketWithUpgrade);
  2865. return Socket;
  2866. }(SocketWithUpgrade);
  2867. var browserEntrypoint = (function (uri, opts) {
  2868. return new Socket(uri, opts);
  2869. });
  2870. return browserEntrypoint;
  2871. }));
  2872. //# sourceMappingURL=engine.io.js.map