socket.io.js 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240
  1. /*!
  2. * Socket.IO v4.4.1
  3. * (c) 2014-2022 Guillermo Rauch
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory());
  10. })(this, (function () { 'use strict';
  11. function _typeof(obj) {
  12. "@babel/helpers - typeof";
  13. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  14. _typeof = function (obj) {
  15. return typeof obj;
  16. };
  17. } else {
  18. _typeof = function (obj) {
  19. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  20. };
  21. }
  22. return _typeof(obj);
  23. }
  24. function _classCallCheck(instance, Constructor) {
  25. if (!(instance instanceof Constructor)) {
  26. throw new TypeError("Cannot call a class as a function");
  27. }
  28. }
  29. function _defineProperties(target, props) {
  30. for (var i = 0; i < props.length; i++) {
  31. var descriptor = props[i];
  32. descriptor.enumerable = descriptor.enumerable || false;
  33. descriptor.configurable = true;
  34. if ("value" in descriptor) descriptor.writable = true;
  35. Object.defineProperty(target, descriptor.key, descriptor);
  36. }
  37. }
  38. function _createClass(Constructor, protoProps, staticProps) {
  39. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  40. if (staticProps) _defineProperties(Constructor, staticProps);
  41. return Constructor;
  42. }
  43. function _extends() {
  44. _extends = Object.assign || function (target) {
  45. for (var i = 1; i < arguments.length; i++) {
  46. var source = arguments[i];
  47. for (var key in source) {
  48. if (Object.prototype.hasOwnProperty.call(source, key)) {
  49. target[key] = source[key];
  50. }
  51. }
  52. }
  53. return target;
  54. };
  55. return _extends.apply(this, arguments);
  56. }
  57. function _inherits(subClass, superClass) {
  58. if (typeof superClass !== "function" && superClass !== null) {
  59. throw new TypeError("Super expression must either be null or a function");
  60. }
  61. subClass.prototype = Object.create(superClass && superClass.prototype, {
  62. constructor: {
  63. value: subClass,
  64. writable: true,
  65. configurable: true
  66. }
  67. });
  68. if (superClass) _setPrototypeOf(subClass, superClass);
  69. }
  70. function _getPrototypeOf(o) {
  71. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  72. return o.__proto__ || Object.getPrototypeOf(o);
  73. };
  74. return _getPrototypeOf(o);
  75. }
  76. function _setPrototypeOf(o, p) {
  77. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  78. o.__proto__ = p;
  79. return o;
  80. };
  81. return _setPrototypeOf(o, p);
  82. }
  83. function _isNativeReflectConstruct() {
  84. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  85. if (Reflect.construct.sham) return false;
  86. if (typeof Proxy === "function") return true;
  87. try {
  88. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  89. return true;
  90. } catch (e) {
  91. return false;
  92. }
  93. }
  94. function _assertThisInitialized(self) {
  95. if (self === void 0) {
  96. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  97. }
  98. return self;
  99. }
  100. function _possibleConstructorReturn(self, call) {
  101. if (call && (typeof call === "object" || typeof call === "function")) {
  102. return call;
  103. } else if (call !== void 0) {
  104. throw new TypeError("Derived constructors may only return object or undefined");
  105. }
  106. return _assertThisInitialized(self);
  107. }
  108. function _createSuper(Derived) {
  109. var hasNativeReflectConstruct = _isNativeReflectConstruct();
  110. return function _createSuperInternal() {
  111. var Super = _getPrototypeOf(Derived),
  112. result;
  113. if (hasNativeReflectConstruct) {
  114. var NewTarget = _getPrototypeOf(this).constructor;
  115. result = Reflect.construct(Super, arguments, NewTarget);
  116. } else {
  117. result = Super.apply(this, arguments);
  118. }
  119. return _possibleConstructorReturn(this, result);
  120. };
  121. }
  122. function _superPropBase(object, property) {
  123. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  124. object = _getPrototypeOf(object);
  125. if (object === null) break;
  126. }
  127. return object;
  128. }
  129. function _get(target, property, receiver) {
  130. if (typeof Reflect !== "undefined" && Reflect.get) {
  131. _get = Reflect.get;
  132. } else {
  133. _get = function _get(target, property, receiver) {
  134. var base = _superPropBase(target, property);
  135. if (!base) return;
  136. var desc = Object.getOwnPropertyDescriptor(base, property);
  137. if (desc.get) {
  138. return desc.get.call(receiver);
  139. }
  140. return desc.value;
  141. };
  142. }
  143. return _get(target, property, receiver || target);
  144. }
  145. function _unsupportedIterableToArray(o, minLen) {
  146. if (!o) return;
  147. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  148. var n = Object.prototype.toString.call(o).slice(8, -1);
  149. if (n === "Object" && o.constructor) n = o.constructor.name;
  150. if (n === "Map" || n === "Set") return Array.from(o);
  151. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  152. }
  153. function _arrayLikeToArray(arr, len) {
  154. if (len == null || len > arr.length) len = arr.length;
  155. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  156. return arr2;
  157. }
  158. function _createForOfIteratorHelper(o, allowArrayLike) {
  159. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  160. if (!it) {
  161. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  162. if (it) o = it;
  163. var i = 0;
  164. var F = function () {};
  165. return {
  166. s: F,
  167. n: function () {
  168. if (i >= o.length) return {
  169. done: true
  170. };
  171. return {
  172. done: false,
  173. value: o[i++]
  174. };
  175. },
  176. e: function (e) {
  177. throw e;
  178. },
  179. f: F
  180. };
  181. }
  182. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  183. }
  184. var normalCompletion = true,
  185. didErr = false,
  186. err;
  187. return {
  188. s: function () {
  189. it = it.call(o);
  190. },
  191. n: function () {
  192. var step = it.next();
  193. normalCompletion = step.done;
  194. return step;
  195. },
  196. e: function (e) {
  197. didErr = true;
  198. err = e;
  199. },
  200. f: function () {
  201. try {
  202. if (!normalCompletion && it.return != null) it.return();
  203. } finally {
  204. if (didErr) throw err;
  205. }
  206. }
  207. };
  208. }
  209. /**
  210. * Parses an URI
  211. *
  212. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  213. * @api private
  214. */
  215. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  216. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  217. var parseuri = function parseuri(str) {
  218. var src = str,
  219. b = str.indexOf('['),
  220. e = str.indexOf(']');
  221. if (b != -1 && e != -1) {
  222. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  223. }
  224. var m = re.exec(str || ''),
  225. uri = {},
  226. i = 14;
  227. while (i--) {
  228. uri[parts[i]] = m[i] || '';
  229. }
  230. if (b != -1 && e != -1) {
  231. uri.source = src;
  232. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  233. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  234. uri.ipv6uri = true;
  235. }
  236. uri.pathNames = pathNames(uri, uri['path']);
  237. uri.queryKey = queryKey(uri, uri['query']);
  238. return uri;
  239. };
  240. function pathNames(obj, path) {
  241. var regx = /\/{2,9}/g,
  242. names = path.replace(regx, "/").split("/");
  243. if (path.substr(0, 1) == '/' || path.length === 0) {
  244. names.splice(0, 1);
  245. }
  246. if (path.substr(path.length - 1, 1) == '/') {
  247. names.splice(names.length - 1, 1);
  248. }
  249. return names;
  250. }
  251. function queryKey(uri, query) {
  252. var data = {};
  253. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  254. if ($1) {
  255. data[$1] = $2;
  256. }
  257. });
  258. return data;
  259. }
  260. /**
  261. * URL parser.
  262. *
  263. * @param uri - url
  264. * @param path - the request path of the connection
  265. * @param loc - An object meant to mimic window.location.
  266. * Defaults to window.location.
  267. * @public
  268. */
  269. function url(uri) {
  270. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  271. var loc = arguments.length > 2 ? arguments[2] : undefined;
  272. var obj = uri; // default to window.location
  273. loc = loc || typeof location !== "undefined" && location;
  274. if (null == uri) uri = loc.protocol + "//" + loc.host; // relative path support
  275. if (typeof uri === "string") {
  276. if ("/" === uri.charAt(0)) {
  277. if ("/" === uri.charAt(1)) {
  278. uri = loc.protocol + uri;
  279. } else {
  280. uri = loc.host + uri;
  281. }
  282. }
  283. if (!/^(https?|wss?):\/\//.test(uri)) {
  284. if ("undefined" !== typeof loc) {
  285. uri = loc.protocol + "//" + uri;
  286. } else {
  287. uri = "https://" + uri;
  288. }
  289. } // parse
  290. obj = parseuri(uri);
  291. } // make sure we treat `localhost:80` and `localhost` equally
  292. if (!obj.port) {
  293. if (/^(http|ws)$/.test(obj.protocol)) {
  294. obj.port = "80";
  295. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  296. obj.port = "443";
  297. }
  298. }
  299. obj.path = obj.path || "/";
  300. var ipv6 = obj.host.indexOf(":") !== -1;
  301. var host = ipv6 ? "[" + obj.host + "]" : obj.host; // define unique id
  302. obj.id = obj.protocol + "://" + host + ":" + obj.port + path; // define href
  303. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  304. return obj;
  305. }
  306. var hasCors = {exports: {}};
  307. /**
  308. * Module exports.
  309. *
  310. * Logic borrowed from Modernizr:
  311. *
  312. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  313. */
  314. try {
  315. hasCors.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  316. } catch (err) {
  317. // if XMLHttp support is disabled in IE then it will throw
  318. // when trying to create
  319. hasCors.exports = false;
  320. }
  321. var hasCORS = hasCors.exports;
  322. var globalThis = (function () {
  323. if (typeof self !== "undefined") {
  324. return self;
  325. } else if (typeof window !== "undefined") {
  326. return window;
  327. } else {
  328. return Function("return this")();
  329. }
  330. })();
  331. // browser shim for xmlhttprequest module
  332. function XMLHttpRequest$1 (opts) {
  333. var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE
  334. try {
  335. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  336. return new XMLHttpRequest();
  337. }
  338. } catch (e) {}
  339. if (!xdomain) {
  340. try {
  341. return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  342. } catch (e) {}
  343. }
  344. }
  345. function pick(obj) {
  346. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  347. attr[_key - 1] = arguments[_key];
  348. }
  349. return attr.reduce(function (acc, k) {
  350. if (obj.hasOwnProperty(k)) {
  351. acc[k] = obj[k];
  352. }
  353. return acc;
  354. }, {});
  355. } // Keep a reference to the real timeout functions so they can be used when overridden
  356. var NATIVE_SET_TIMEOUT = setTimeout;
  357. var NATIVE_CLEAR_TIMEOUT = clearTimeout;
  358. function installTimerFunctions(obj, opts) {
  359. if (opts.useNativeTimers) {
  360. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);
  361. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);
  362. } else {
  363. obj.setTimeoutFn = setTimeout.bind(globalThis);
  364. obj.clearTimeoutFn = clearTimeout.bind(globalThis);
  365. }
  366. }
  367. /**
  368. * Expose `Emitter`.
  369. */
  370. var Emitter_1 = Emitter;
  371. /**
  372. * Initialize a new `Emitter`.
  373. *
  374. * @api public
  375. */
  376. function Emitter(obj) {
  377. if (obj) return mixin(obj);
  378. }
  379. /**
  380. * Mixin the emitter properties.
  381. *
  382. * @param {Object} obj
  383. * @return {Object}
  384. * @api private
  385. */
  386. function mixin(obj) {
  387. for (var key in Emitter.prototype) {
  388. obj[key] = Emitter.prototype[key];
  389. }
  390. return obj;
  391. }
  392. /**
  393. * Listen on the given `event` with `fn`.
  394. *
  395. * @param {String} event
  396. * @param {Function} fn
  397. * @return {Emitter}
  398. * @api public
  399. */
  400. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  401. this._callbacks = this._callbacks || {};
  402. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  403. return this;
  404. };
  405. /**
  406. * Adds an `event` listener that will be invoked a single
  407. * time then automatically removed.
  408. *
  409. * @param {String} event
  410. * @param {Function} fn
  411. * @return {Emitter}
  412. * @api public
  413. */
  414. Emitter.prototype.once = function (event, fn) {
  415. function on() {
  416. this.off(event, on);
  417. fn.apply(this, arguments);
  418. }
  419. on.fn = fn;
  420. this.on(event, on);
  421. return this;
  422. };
  423. /**
  424. * Remove the given callback for `event` or all
  425. * registered callbacks.
  426. *
  427. * @param {String} event
  428. * @param {Function} fn
  429. * @return {Emitter}
  430. * @api public
  431. */
  432. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  433. this._callbacks = this._callbacks || {}; // all
  434. if (0 == arguments.length) {
  435. this._callbacks = {};
  436. return this;
  437. } // specific event
  438. var callbacks = this._callbacks['$' + event];
  439. if (!callbacks) return this; // remove all handlers
  440. if (1 == arguments.length) {
  441. delete this._callbacks['$' + event];
  442. return this;
  443. } // remove specific handler
  444. var cb;
  445. for (var i = 0; i < callbacks.length; i++) {
  446. cb = callbacks[i];
  447. if (cb === fn || cb.fn === fn) {
  448. callbacks.splice(i, 1);
  449. break;
  450. }
  451. } // Remove event specific arrays for event types that no
  452. // one is subscribed for to avoid memory leak.
  453. if (callbacks.length === 0) {
  454. delete this._callbacks['$' + event];
  455. }
  456. return this;
  457. };
  458. /**
  459. * Emit `event` with the given args.
  460. *
  461. * @param {String} event
  462. * @param {Mixed} ...
  463. * @return {Emitter}
  464. */
  465. Emitter.prototype.emit = function (event) {
  466. this._callbacks = this._callbacks || {};
  467. var args = new Array(arguments.length - 1),
  468. callbacks = this._callbacks['$' + event];
  469. for (var i = 1; i < arguments.length; i++) {
  470. args[i - 1] = arguments[i];
  471. }
  472. if (callbacks) {
  473. callbacks = callbacks.slice(0);
  474. for (var i = 0, len = callbacks.length; i < len; ++i) {
  475. callbacks[i].apply(this, args);
  476. }
  477. }
  478. return this;
  479. }; // alias used for reserved events (protected method)
  480. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  481. /**
  482. * Return array of callbacks for `event`.
  483. *
  484. * @param {String} event
  485. * @return {Array}
  486. * @api public
  487. */
  488. Emitter.prototype.listeners = function (event) {
  489. this._callbacks = this._callbacks || {};
  490. return this._callbacks['$' + event] || [];
  491. };
  492. /**
  493. * Check if this emitter has `event` handlers.
  494. *
  495. * @param {String} event
  496. * @return {Boolean}
  497. * @api public
  498. */
  499. Emitter.prototype.hasListeners = function (event) {
  500. return !!this.listeners(event).length;
  501. };
  502. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  503. PACKET_TYPES["open"] = "0";
  504. PACKET_TYPES["close"] = "1";
  505. PACKET_TYPES["ping"] = "2";
  506. PACKET_TYPES["pong"] = "3";
  507. PACKET_TYPES["message"] = "4";
  508. PACKET_TYPES["upgrade"] = "5";
  509. PACKET_TYPES["noop"] = "6";
  510. var PACKET_TYPES_REVERSE = Object.create(null);
  511. Object.keys(PACKET_TYPES).forEach(function (key) {
  512. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  513. });
  514. var ERROR_PACKET = {
  515. type: "error",
  516. data: "parser error"
  517. };
  518. var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  519. var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10
  520. var isView$1 = function isView(obj) {
  521. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  522. };
  523. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  524. var type = _ref.type,
  525. data = _ref.data;
  526. if (withNativeBlob$1 && data instanceof Blob) {
  527. if (supportsBinary) {
  528. return callback(data);
  529. } else {
  530. return encodeBlobAsBase64(data, callback);
  531. }
  532. } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
  533. if (supportsBinary) {
  534. return callback(data);
  535. } else {
  536. return encodeBlobAsBase64(new Blob([data]), callback);
  537. }
  538. } // plain string
  539. return callback(PACKET_TYPES[type] + (data || ""));
  540. };
  541. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  542. var fileReader = new FileReader();
  543. fileReader.onload = function () {
  544. var content = fileReader.result.split(",")[1];
  545. callback("b" + content);
  546. };
  547. return fileReader.readAsDataURL(data);
  548. };
  549. /*
  550. * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
  551. * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
  552. * Released under MIT License
  553. */
  554. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
  555. var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  556. for (var i$1 = 0; i$1 < chars.length; i$1++) {
  557. lookup$1[chars.charCodeAt(i$1)] = i$1;
  558. }
  559. var decode$1 = function decode(base64) {
  560. var bufferLength = base64.length * 0.75,
  561. len = base64.length,
  562. i,
  563. p = 0,
  564. encoded1,
  565. encoded2,
  566. encoded3,
  567. encoded4;
  568. if (base64[base64.length - 1] === '=') {
  569. bufferLength--;
  570. if (base64[base64.length - 2] === '=') {
  571. bufferLength--;
  572. }
  573. }
  574. var arraybuffer = new ArrayBuffer(bufferLength),
  575. bytes = new Uint8Array(arraybuffer);
  576. for (i = 0; i < len; i += 4) {
  577. encoded1 = lookup$1[base64.charCodeAt(i)];
  578. encoded2 = lookup$1[base64.charCodeAt(i + 1)];
  579. encoded3 = lookup$1[base64.charCodeAt(i + 2)];
  580. encoded4 = lookup$1[base64.charCodeAt(i + 3)];
  581. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  582. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  583. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  584. }
  585. return arraybuffer;
  586. };
  587. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  588. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  589. if (typeof encodedPacket !== "string") {
  590. return {
  591. type: "message",
  592. data: mapBinary(encodedPacket, binaryType)
  593. };
  594. }
  595. var type = encodedPacket.charAt(0);
  596. if (type === "b") {
  597. return {
  598. type: "message",
  599. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  600. };
  601. }
  602. var packetType = PACKET_TYPES_REVERSE[type];
  603. if (!packetType) {
  604. return ERROR_PACKET;
  605. }
  606. return encodedPacket.length > 1 ? {
  607. type: PACKET_TYPES_REVERSE[type],
  608. data: encodedPacket.substring(1)
  609. } : {
  610. type: PACKET_TYPES_REVERSE[type]
  611. };
  612. };
  613. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  614. if (withNativeArrayBuffer$1) {
  615. var decoded = decode$1(data);
  616. return mapBinary(decoded, binaryType);
  617. } else {
  618. return {
  619. base64: true,
  620. data: data
  621. }; // fallback for old browsers
  622. }
  623. };
  624. var mapBinary = function mapBinary(data, binaryType) {
  625. switch (binaryType) {
  626. case "blob":
  627. return data instanceof ArrayBuffer ? new Blob([data]) : data;
  628. case "arraybuffer":
  629. default:
  630. return data;
  631. // assuming the data is already an ArrayBuffer
  632. }
  633. };
  634. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  635. var encodePayload = function encodePayload(packets, callback) {
  636. // some packets may be added to the array while encoding, so the initial length must be saved
  637. var length = packets.length;
  638. var encodedPackets = new Array(length);
  639. var count = 0;
  640. packets.forEach(function (packet, i) {
  641. // force base64 encoding for binary packets
  642. encodePacket(packet, false, function (encodedPacket) {
  643. encodedPackets[i] = encodedPacket;
  644. if (++count === length) {
  645. callback(encodedPackets.join(SEPARATOR));
  646. }
  647. });
  648. });
  649. };
  650. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  651. var encodedPackets = encodedPayload.split(SEPARATOR);
  652. var packets = [];
  653. for (var i = 0; i < encodedPackets.length; i++) {
  654. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  655. packets.push(decodedPacket);
  656. if (decodedPacket.type === "error") {
  657. break;
  658. }
  659. }
  660. return packets;
  661. };
  662. var protocol$1 = 4;
  663. var Transport = /*#__PURE__*/function (_Emitter) {
  664. _inherits(Transport, _Emitter);
  665. var _super = _createSuper(Transport);
  666. /**
  667. * Transport abstract constructor.
  668. *
  669. * @param {Object} options.
  670. * @api private
  671. */
  672. function Transport(opts) {
  673. var _this;
  674. _classCallCheck(this, Transport);
  675. _this = _super.call(this);
  676. _this.writable = false;
  677. installTimerFunctions(_assertThisInitialized(_this), opts);
  678. _this.opts = opts;
  679. _this.query = opts.query;
  680. _this.readyState = "";
  681. _this.socket = opts.socket;
  682. return _this;
  683. }
  684. /**
  685. * Emits an error.
  686. *
  687. * @param {String} str
  688. * @return {Transport} for chaining
  689. * @api protected
  690. */
  691. _createClass(Transport, [{
  692. key: "onError",
  693. value: function onError(msg, desc) {
  694. var err = new Error(msg); // @ts-ignore
  695. err.type = "TransportError"; // @ts-ignore
  696. err.description = desc;
  697. _get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "error", err);
  698. return this;
  699. }
  700. /**
  701. * Opens the transport.
  702. *
  703. * @api public
  704. */
  705. }, {
  706. key: "open",
  707. value: function open() {
  708. if ("closed" === this.readyState || "" === this.readyState) {
  709. this.readyState = "opening";
  710. this.doOpen();
  711. }
  712. return this;
  713. }
  714. /**
  715. * Closes the transport.
  716. *
  717. * @api public
  718. */
  719. }, {
  720. key: "close",
  721. value: function close() {
  722. if ("opening" === this.readyState || "open" === this.readyState) {
  723. this.doClose();
  724. this.onClose();
  725. }
  726. return this;
  727. }
  728. /**
  729. * Sends multiple packets.
  730. *
  731. * @param {Array} packets
  732. * @api public
  733. */
  734. }, {
  735. key: "send",
  736. value: function send(packets) {
  737. if ("open" === this.readyState) {
  738. this.write(packets);
  739. }
  740. }
  741. /**
  742. * Called upon open
  743. *
  744. * @api protected
  745. */
  746. }, {
  747. key: "onOpen",
  748. value: function onOpen() {
  749. this.readyState = "open";
  750. this.writable = true;
  751. _get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "open");
  752. }
  753. /**
  754. * Called with data.
  755. *
  756. * @param {String} data
  757. * @api protected
  758. */
  759. }, {
  760. key: "onData",
  761. value: function onData(data) {
  762. var packet = decodePacket(data, this.socket.binaryType);
  763. this.onPacket(packet);
  764. }
  765. /**
  766. * Called with a decoded packet.
  767. *
  768. * @api protected
  769. */
  770. }, {
  771. key: "onPacket",
  772. value: function onPacket(packet) {
  773. _get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "packet", packet);
  774. }
  775. /**
  776. * Called upon close.
  777. *
  778. * @api protected
  779. */
  780. }, {
  781. key: "onClose",
  782. value: function onClose() {
  783. this.readyState = "closed";
  784. _get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "close");
  785. }
  786. }]);
  787. return Transport;
  788. }(Emitter_1);
  789. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
  790. length = 64,
  791. map = {},
  792. seed = 0,
  793. i = 0,
  794. prev;
  795. /**
  796. * Return a string representing the specified number.
  797. *
  798. * @param {Number} num The number to convert.
  799. * @returns {String} The string representation of the number.
  800. * @api public
  801. */
  802. function encode(num) {
  803. var encoded = '';
  804. do {
  805. encoded = alphabet[num % length] + encoded;
  806. num = Math.floor(num / length);
  807. } while (num > 0);
  808. return encoded;
  809. }
  810. /**
  811. * Return the integer value specified by the given string.
  812. *
  813. * @param {String} str The string to convert.
  814. * @returns {Number} The integer value represented by the string.
  815. * @api public
  816. */
  817. function decode(str) {
  818. var decoded = 0;
  819. for (i = 0; i < str.length; i++) {
  820. decoded = decoded * length + map[str.charAt(i)];
  821. }
  822. return decoded;
  823. }
  824. /**
  825. * Yeast: A tiny growing id generator.
  826. *
  827. * @returns {String} A unique id.
  828. * @api public
  829. */
  830. function yeast() {
  831. var now = encode(+new Date());
  832. if (now !== prev) return seed = 0, prev = now;
  833. return now + '.' + encode(seed++);
  834. } //
  835. // Map each character to its index.
  836. //
  837. for (; i < length; i++) {
  838. map[alphabet[i]] = i;
  839. } //
  840. // Expose the `yeast`, `encode` and `decode` functions.
  841. //
  842. yeast.encode = encode;
  843. yeast.decode = decode;
  844. var yeast_1 = yeast;
  845. var parseqs = {};
  846. /**
  847. * Compiles a querystring
  848. * Returns string representation of the object
  849. *
  850. * @param {Object}
  851. * @api private
  852. */
  853. parseqs.encode = function (obj) {
  854. var str = '';
  855. for (var i in obj) {
  856. if (obj.hasOwnProperty(i)) {
  857. if (str.length) str += '&';
  858. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  859. }
  860. }
  861. return str;
  862. };
  863. /**
  864. * Parses a simple querystring into an object
  865. *
  866. * @param {String} qs
  867. * @api private
  868. */
  869. parseqs.decode = function (qs) {
  870. var qry = {};
  871. var pairs = qs.split('&');
  872. for (var i = 0, l = pairs.length; i < l; i++) {
  873. var pair = pairs[i].split('=');
  874. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  875. }
  876. return qry;
  877. };
  878. var Polling = /*#__PURE__*/function (_Transport) {
  879. _inherits(Polling, _Transport);
  880. var _super = _createSuper(Polling);
  881. function Polling() {
  882. var _this;
  883. _classCallCheck(this, Polling);
  884. _this = _super.apply(this, arguments);
  885. _this.polling = false;
  886. return _this;
  887. }
  888. /**
  889. * Transport name.
  890. */
  891. _createClass(Polling, [{
  892. key: "name",
  893. get: function get() {
  894. return "polling";
  895. }
  896. /**
  897. * Opens the socket (triggers polling). We write a PING message to determine
  898. * when the transport is open.
  899. *
  900. * @api private
  901. */
  902. }, {
  903. key: "doOpen",
  904. value: function doOpen() {
  905. this.poll();
  906. }
  907. /**
  908. * Pauses polling.
  909. *
  910. * @param {Function} callback upon buffers are flushed and transport is paused
  911. * @api private
  912. */
  913. }, {
  914. key: "pause",
  915. value: function pause(onPause) {
  916. var _this2 = this;
  917. this.readyState = "pausing";
  918. var pause = function pause() {
  919. _this2.readyState = "paused";
  920. onPause();
  921. };
  922. if (this.polling || !this.writable) {
  923. var total = 0;
  924. if (this.polling) {
  925. total++;
  926. this.once("pollComplete", function () {
  927. --total || pause();
  928. });
  929. }
  930. if (!this.writable) {
  931. total++;
  932. this.once("drain", function () {
  933. --total || pause();
  934. });
  935. }
  936. } else {
  937. pause();
  938. }
  939. }
  940. /**
  941. * Starts polling cycle.
  942. *
  943. * @api public
  944. */
  945. }, {
  946. key: "poll",
  947. value: function poll() {
  948. this.polling = true;
  949. this.doPoll();
  950. this.emit("poll");
  951. }
  952. /**
  953. * Overloads onData to detect payloads.
  954. *
  955. * @api private
  956. */
  957. }, {
  958. key: "onData",
  959. value: function onData(data) {
  960. var _this3 = this;
  961. var callback = function callback(packet) {
  962. // if its the first message we consider the transport open
  963. if ("opening" === _this3.readyState && packet.type === "open") {
  964. _this3.onOpen();
  965. } // if its a close packet, we close the ongoing requests
  966. if ("close" === packet.type) {
  967. _this3.onClose();
  968. return false;
  969. } // otherwise bypass onData and handle the message
  970. _this3.onPacket(packet);
  971. }; // decode payload
  972. decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing
  973. if ("closed" !== this.readyState) {
  974. // if we got data we're not polling
  975. this.polling = false;
  976. this.emit("pollComplete");
  977. if ("open" === this.readyState) {
  978. this.poll();
  979. }
  980. }
  981. }
  982. /**
  983. * For polling, send a close packet.
  984. *
  985. * @api private
  986. */
  987. }, {
  988. key: "doClose",
  989. value: function doClose() {
  990. var _this4 = this;
  991. var close = function close() {
  992. _this4.write([{
  993. type: "close"
  994. }]);
  995. };
  996. if ("open" === this.readyState) {
  997. close();
  998. } else {
  999. // in case we're trying to close while
  1000. // handshaking is in progress (GH-164)
  1001. this.once("open", close);
  1002. }
  1003. }
  1004. /**
  1005. * Writes a packets payload.
  1006. *
  1007. * @param {Array} data packets
  1008. * @param {Function} drain callback
  1009. * @api private
  1010. */
  1011. }, {
  1012. key: "write",
  1013. value: function write(packets) {
  1014. var _this5 = this;
  1015. this.writable = false;
  1016. encodePayload(packets, function (data) {
  1017. _this5.doWrite(data, function () {
  1018. _this5.writable = true;
  1019. _this5.emit("drain");
  1020. });
  1021. });
  1022. }
  1023. /**
  1024. * Generates uri for connection.
  1025. *
  1026. * @api private
  1027. */
  1028. }, {
  1029. key: "uri",
  1030. value: function uri() {
  1031. var query = this.query || {};
  1032. var schema = this.opts.secure ? "https" : "http";
  1033. var port = ""; // cache busting is forced
  1034. if (false !== this.opts.timestampRequests) {
  1035. query[this.opts.timestampParam] = yeast_1();
  1036. }
  1037. if (!this.supportsBinary && !query.sid) {
  1038. query.b64 = 1;
  1039. } // avoid port if default for schema
  1040. if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) {
  1041. port = ":" + this.opts.port;
  1042. }
  1043. var encodedQuery = parseqs.encode(query);
  1044. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1045. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1046. }
  1047. }]);
  1048. return Polling;
  1049. }(Transport);
  1050. /**
  1051. * Empty function
  1052. */
  1053. function empty() {}
  1054. var hasXHR2 = function () {
  1055. var xhr = new XMLHttpRequest$1({
  1056. xdomain: false
  1057. });
  1058. return null != xhr.responseType;
  1059. }();
  1060. var XHR = /*#__PURE__*/function (_Polling) {
  1061. _inherits(XHR, _Polling);
  1062. var _super = _createSuper(XHR);
  1063. /**
  1064. * XHR Polling constructor.
  1065. *
  1066. * @param {Object} opts
  1067. * @api public
  1068. */
  1069. function XHR(opts) {
  1070. var _this;
  1071. _classCallCheck(this, XHR);
  1072. _this = _super.call(this, opts);
  1073. if (typeof location !== "undefined") {
  1074. var isSSL = "https:" === location.protocol;
  1075. var port = location.port; // some user agents have empty `location.port`
  1076. if (!port) {
  1077. port = isSSL ? "443" : "80";
  1078. }
  1079. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  1080. _this.xs = opts.secure !== isSSL;
  1081. }
  1082. /**
  1083. * XHR supports binary
  1084. */
  1085. var forceBase64 = opts && opts.forceBase64;
  1086. _this.supportsBinary = hasXHR2 && !forceBase64;
  1087. return _this;
  1088. }
  1089. /**
  1090. * Creates a request.
  1091. *
  1092. * @param {String} method
  1093. * @api private
  1094. */
  1095. _createClass(XHR, [{
  1096. key: "request",
  1097. value: function request() {
  1098. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1099. _extends(opts, {
  1100. xd: this.xd,
  1101. xs: this.xs
  1102. }, this.opts);
  1103. return new Request(this.uri(), opts);
  1104. }
  1105. /**
  1106. * Sends data.
  1107. *
  1108. * @param {String} data to send.
  1109. * @param {Function} called upon flush.
  1110. * @api private
  1111. */
  1112. }, {
  1113. key: "doWrite",
  1114. value: function doWrite(data, fn) {
  1115. var _this2 = this;
  1116. var req = this.request({
  1117. method: "POST",
  1118. data: data
  1119. });
  1120. req.on("success", fn);
  1121. req.on("error", function (err) {
  1122. _this2.onError("xhr post error", err);
  1123. });
  1124. }
  1125. /**
  1126. * Starts a poll cycle.
  1127. *
  1128. * @api private
  1129. */
  1130. }, {
  1131. key: "doPoll",
  1132. value: function doPoll() {
  1133. var _this3 = this;
  1134. var req = this.request();
  1135. req.on("data", this.onData.bind(this));
  1136. req.on("error", function (err) {
  1137. _this3.onError("xhr poll error", err);
  1138. });
  1139. this.pollXhr = req;
  1140. }
  1141. }]);
  1142. return XHR;
  1143. }(Polling);
  1144. var Request = /*#__PURE__*/function (_Emitter) {
  1145. _inherits(Request, _Emitter);
  1146. var _super2 = _createSuper(Request);
  1147. /**
  1148. * Request constructor
  1149. *
  1150. * @param {Object} options
  1151. * @api public
  1152. */
  1153. function Request(uri, opts) {
  1154. var _this4;
  1155. _classCallCheck(this, Request);
  1156. _this4 = _super2.call(this);
  1157. installTimerFunctions(_assertThisInitialized(_this4), opts);
  1158. _this4.opts = opts;
  1159. _this4.method = opts.method || "GET";
  1160. _this4.uri = uri;
  1161. _this4.async = false !== opts.async;
  1162. _this4.data = undefined !== opts.data ? opts.data : null;
  1163. _this4.create();
  1164. return _this4;
  1165. }
  1166. /**
  1167. * Creates the XHR object and sends the request.
  1168. *
  1169. * @api private
  1170. */
  1171. _createClass(Request, [{
  1172. key: "create",
  1173. value: function create() {
  1174. var _this5 = this;
  1175. var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1176. opts.xdomain = !!this.opts.xd;
  1177. opts.xscheme = !!this.opts.xs;
  1178. var xhr = this.xhr = new XMLHttpRequest$1(opts);
  1179. try {
  1180. xhr.open(this.method, this.uri, this.async);
  1181. try {
  1182. if (this.opts.extraHeaders) {
  1183. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1184. for (var i in this.opts.extraHeaders) {
  1185. if (this.opts.extraHeaders.hasOwnProperty(i)) {
  1186. xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
  1187. }
  1188. }
  1189. }
  1190. } catch (e) {}
  1191. if ("POST" === this.method) {
  1192. try {
  1193. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1194. } catch (e) {}
  1195. }
  1196. try {
  1197. xhr.setRequestHeader("Accept", "*/*");
  1198. } catch (e) {} // ie6 check
  1199. if ("withCredentials" in xhr) {
  1200. xhr.withCredentials = this.opts.withCredentials;
  1201. }
  1202. if (this.opts.requestTimeout) {
  1203. xhr.timeout = this.opts.requestTimeout;
  1204. }
  1205. xhr.onreadystatechange = function () {
  1206. if (4 !== xhr.readyState) return;
  1207. if (200 === xhr.status || 1223 === xhr.status) {
  1208. _this5.onLoad();
  1209. } else {
  1210. // make sure the `error` event handler that's user-set
  1211. // does not throw in the same tick and gets caught here
  1212. _this5.setTimeoutFn(function () {
  1213. _this5.onError(typeof xhr.status === "number" ? xhr.status : 0);
  1214. }, 0);
  1215. }
  1216. };
  1217. xhr.send(this.data);
  1218. } catch (e) {
  1219. // Need to defer since .create() is called directly from the constructor
  1220. // and thus the 'error' event can only be only bound *after* this exception
  1221. // occurs. Therefore, also, we cannot throw here at all.
  1222. this.setTimeoutFn(function () {
  1223. _this5.onError(e);
  1224. }, 0);
  1225. return;
  1226. }
  1227. if (typeof document !== "undefined") {
  1228. this.index = Request.requestsCount++;
  1229. Request.requests[this.index] = this;
  1230. }
  1231. }
  1232. /**
  1233. * Called upon successful response.
  1234. *
  1235. * @api private
  1236. */
  1237. }, {
  1238. key: "onSuccess",
  1239. value: function onSuccess() {
  1240. this.emit("success");
  1241. this.cleanup();
  1242. }
  1243. /**
  1244. * Called if we have data.
  1245. *
  1246. * @api private
  1247. */
  1248. }, {
  1249. key: "onData",
  1250. value: function onData(data) {
  1251. this.emit("data", data);
  1252. this.onSuccess();
  1253. }
  1254. /**
  1255. * Called upon error.
  1256. *
  1257. * @api private
  1258. */
  1259. }, {
  1260. key: "onError",
  1261. value: function onError(err) {
  1262. this.emit("error", err);
  1263. this.cleanup(true);
  1264. }
  1265. /**
  1266. * Cleans up house.
  1267. *
  1268. * @api private
  1269. */
  1270. }, {
  1271. key: "cleanup",
  1272. value: function cleanup(fromError) {
  1273. if ("undefined" === typeof this.xhr || null === this.xhr) {
  1274. return;
  1275. }
  1276. this.xhr.onreadystatechange = empty;
  1277. if (fromError) {
  1278. try {
  1279. this.xhr.abort();
  1280. } catch (e) {}
  1281. }
  1282. if (typeof document !== "undefined") {
  1283. delete Request.requests[this.index];
  1284. }
  1285. this.xhr = null;
  1286. }
  1287. /**
  1288. * Called upon load.
  1289. *
  1290. * @api private
  1291. */
  1292. }, {
  1293. key: "onLoad",
  1294. value: function onLoad() {
  1295. var data = this.xhr.responseText;
  1296. if (data !== null) {
  1297. this.onData(data);
  1298. }
  1299. }
  1300. /**
  1301. * Aborts the request.
  1302. *
  1303. * @api public
  1304. */
  1305. }, {
  1306. key: "abort",
  1307. value: function abort() {
  1308. this.cleanup();
  1309. }
  1310. }]);
  1311. return Request;
  1312. }(Emitter_1);
  1313. Request.requestsCount = 0;
  1314. Request.requests = {};
  1315. /**
  1316. * Aborts pending requests when unloading the window. This is needed to prevent
  1317. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1318. * emitted.
  1319. */
  1320. if (typeof document !== "undefined") {
  1321. // @ts-ignore
  1322. if (typeof attachEvent === "function") {
  1323. // @ts-ignore
  1324. attachEvent("onunload", unloadHandler);
  1325. } else if (typeof addEventListener === "function") {
  1326. var terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload";
  1327. addEventListener(terminationEvent, unloadHandler, false);
  1328. }
  1329. }
  1330. function unloadHandler() {
  1331. for (var i in Request.requests) {
  1332. if (Request.requests.hasOwnProperty(i)) {
  1333. Request.requests[i].abort();
  1334. }
  1335. }
  1336. }
  1337. var nextTick = function () {
  1338. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  1339. if (isPromiseAvailable) {
  1340. return function (cb) {
  1341. return Promise.resolve().then(cb);
  1342. };
  1343. } else {
  1344. return function (cb, setTimeoutFn) {
  1345. return setTimeoutFn(cb, 0);
  1346. };
  1347. }
  1348. }();
  1349. var WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;
  1350. var usingBrowserWebSocket = true;
  1351. var defaultBinaryType = "arraybuffer";
  1352. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1353. var WS = /*#__PURE__*/function (_Transport) {
  1354. _inherits(WS, _Transport);
  1355. var _super = _createSuper(WS);
  1356. /**
  1357. * WebSocket transport constructor.
  1358. *
  1359. * @api {Object} connection options
  1360. * @api public
  1361. */
  1362. function WS(opts) {
  1363. var _this;
  1364. _classCallCheck(this, WS);
  1365. _this = _super.call(this, opts);
  1366. _this.supportsBinary = !opts.forceBase64;
  1367. return _this;
  1368. }
  1369. /**
  1370. * Transport name.
  1371. *
  1372. * @api public
  1373. */
  1374. _createClass(WS, [{
  1375. key: "name",
  1376. get: function get() {
  1377. return "websocket";
  1378. }
  1379. /**
  1380. * Opens socket.
  1381. *
  1382. * @api private
  1383. */
  1384. }, {
  1385. key: "doOpen",
  1386. value: function doOpen() {
  1387. if (!this.check()) {
  1388. // let probe timeout
  1389. return;
  1390. }
  1391. var uri = this.uri();
  1392. var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1393. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1394. if (this.opts.extraHeaders) {
  1395. opts.headers = this.opts.extraHeaders;
  1396. }
  1397. try {
  1398. this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  1399. } catch (err) {
  1400. return this.emit("error", err);
  1401. }
  1402. this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
  1403. this.addEventListeners();
  1404. }
  1405. /**
  1406. * Adds event listeners to the socket
  1407. *
  1408. * @api private
  1409. */
  1410. }, {
  1411. key: "addEventListeners",
  1412. value: function addEventListeners() {
  1413. var _this2 = this;
  1414. this.ws.onopen = function () {
  1415. if (_this2.opts.autoUnref) {
  1416. _this2.ws._socket.unref();
  1417. }
  1418. _this2.onOpen();
  1419. };
  1420. this.ws.onclose = this.onClose.bind(this);
  1421. this.ws.onmessage = function (ev) {
  1422. return _this2.onData(ev.data);
  1423. };
  1424. this.ws.onerror = function (e) {
  1425. return _this2.onError("websocket error", e);
  1426. };
  1427. }
  1428. /**
  1429. * Writes data to socket.
  1430. *
  1431. * @param {Array} array of packets.
  1432. * @api private
  1433. */
  1434. }, {
  1435. key: "write",
  1436. value: function write(packets) {
  1437. var _this3 = this;
  1438. this.writable = false; // encodePacket efficient as it uses WS framing
  1439. // no need for encodePayload
  1440. var _loop = function _loop(i) {
  1441. var packet = packets[i];
  1442. var lastPacket = i === packets.length - 1;
  1443. encodePacket(packet, _this3.supportsBinary, function (data) {
  1444. // always create a new object (GH-437)
  1445. var opts = {};
  1446. // have a chance of informing us about it yet, in that case send will
  1447. // throw an error
  1448. try {
  1449. if (usingBrowserWebSocket) {
  1450. // TypeError is thrown when passing the second argument on Safari
  1451. _this3.ws.send(data);
  1452. }
  1453. } catch (e) {}
  1454. if (lastPacket) {
  1455. // fake drain
  1456. // defer to next tick to allow Socket to clear writeBuffer
  1457. nextTick(function () {
  1458. _this3.writable = true;
  1459. _this3.emit("drain");
  1460. }, _this3.setTimeoutFn);
  1461. }
  1462. });
  1463. };
  1464. for (var i = 0; i < packets.length; i++) {
  1465. _loop(i);
  1466. }
  1467. }
  1468. /**
  1469. * Closes socket.
  1470. *
  1471. * @api private
  1472. */
  1473. }, {
  1474. key: "doClose",
  1475. value: function doClose() {
  1476. if (typeof this.ws !== "undefined") {
  1477. this.ws.close();
  1478. this.ws = null;
  1479. }
  1480. }
  1481. /**
  1482. * Generates uri for connection.
  1483. *
  1484. * @api private
  1485. */
  1486. }, {
  1487. key: "uri",
  1488. value: function uri() {
  1489. var query = this.query || {};
  1490. var schema = this.opts.secure ? "wss" : "ws";
  1491. var port = ""; // avoid port if default for schema
  1492. if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) {
  1493. port = ":" + this.opts.port;
  1494. } // append timestamp to URI
  1495. if (this.opts.timestampRequests) {
  1496. query[this.opts.timestampParam] = yeast_1();
  1497. } // communicate binary support capabilities
  1498. if (!this.supportsBinary) {
  1499. query.b64 = 1;
  1500. }
  1501. var encodedQuery = parseqs.encode(query);
  1502. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1503. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1504. }
  1505. /**
  1506. * Feature detection for WebSocket.
  1507. *
  1508. * @return {Boolean} whether this transport is available.
  1509. * @api public
  1510. */
  1511. }, {
  1512. key: "check",
  1513. value: function check() {
  1514. return !!WebSocket && !("__initialize" in WebSocket && this.name === WS.prototype.name);
  1515. }
  1516. }]);
  1517. return WS;
  1518. }(Transport);
  1519. var transports = {
  1520. websocket: WS,
  1521. polling: XHR
  1522. };
  1523. var Socket$1 = /*#__PURE__*/function (_Emitter) {
  1524. _inherits(Socket, _Emitter);
  1525. var _super = _createSuper(Socket);
  1526. /**
  1527. * Socket constructor.
  1528. *
  1529. * @param {String|Object} uri or options
  1530. * @param {Object} opts - options
  1531. * @api public
  1532. */
  1533. function Socket(uri) {
  1534. var _this;
  1535. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1536. _classCallCheck(this, Socket);
  1537. _this = _super.call(this);
  1538. if (uri && "object" === _typeof(uri)) {
  1539. opts = uri;
  1540. uri = null;
  1541. }
  1542. if (uri) {
  1543. uri = parseuri(uri);
  1544. opts.hostname = uri.host;
  1545. opts.secure = uri.protocol === "https" || uri.protocol === "wss";
  1546. opts.port = uri.port;
  1547. if (uri.query) opts.query = uri.query;
  1548. } else if (opts.host) {
  1549. opts.hostname = parseuri(opts.host).host;
  1550. }
  1551. installTimerFunctions(_assertThisInitialized(_this), opts);
  1552. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  1553. if (opts.hostname && !opts.port) {
  1554. // if no port is specified manually, use the protocol default
  1555. opts.port = _this.secure ? "443" : "80";
  1556. }
  1557. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  1558. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  1559. _this.transports = opts.transports || ["polling", "websocket"];
  1560. _this.readyState = "";
  1561. _this.writeBuffer = [];
  1562. _this.prevBufferLen = 0;
  1563. _this.opts = _extends({
  1564. path: "/engine.io",
  1565. agent: false,
  1566. withCredentials: false,
  1567. upgrade: true,
  1568. timestampParam: "t",
  1569. rememberUpgrade: false,
  1570. rejectUnauthorized: true,
  1571. perMessageDeflate: {
  1572. threshold: 1024
  1573. },
  1574. transportOptions: {},
  1575. closeOnBeforeunload: true
  1576. }, opts);
  1577. _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
  1578. if (typeof _this.opts.query === "string") {
  1579. _this.opts.query = parseqs.decode(_this.opts.query);
  1580. } // set on handshake
  1581. _this.id = null;
  1582. _this.upgrades = null;
  1583. _this.pingInterval = null;
  1584. _this.pingTimeout = null; // set on heartbeat
  1585. _this.pingTimeoutTimer = null;
  1586. if (typeof addEventListener === "function") {
  1587. if (_this.opts.closeOnBeforeunload) {
  1588. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  1589. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  1590. // closed/reloaded)
  1591. addEventListener("beforeunload", function () {
  1592. if (_this.transport) {
  1593. // silently close the transport
  1594. _this.transport.removeAllListeners();
  1595. _this.transport.close();
  1596. }
  1597. }, false);
  1598. }
  1599. if (_this.hostname !== "localhost") {
  1600. _this.offlineEventListener = function () {
  1601. _this.onClose("transport close");
  1602. };
  1603. addEventListener("offline", _this.offlineEventListener, false);
  1604. }
  1605. }
  1606. _this.open();
  1607. return _this;
  1608. }
  1609. /**
  1610. * Creates transport of the given type.
  1611. *
  1612. * @param {String} transport name
  1613. * @return {Transport}
  1614. * @api private
  1615. */
  1616. _createClass(Socket, [{
  1617. key: "createTransport",
  1618. value: function createTransport(name) {
  1619. var query = clone(this.opts.query); // append engine.io protocol identifier
  1620. query.EIO = protocol$1; // transport name
  1621. query.transport = name; // session id if we already have one
  1622. if (this.id) query.sid = this.id;
  1623. var opts = _extends({}, this.opts.transportOptions[name], this.opts, {
  1624. query: query,
  1625. socket: this,
  1626. hostname: this.hostname,
  1627. secure: this.secure,
  1628. port: this.port
  1629. });
  1630. return new transports[name](opts);
  1631. }
  1632. /**
  1633. * Initializes transport to use and starts probe.
  1634. *
  1635. * @api private
  1636. */
  1637. }, {
  1638. key: "open",
  1639. value: function open() {
  1640. var _this2 = this;
  1641. var transport;
  1642. if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
  1643. transport = "websocket";
  1644. } else if (0 === this.transports.length) {
  1645. // Emit error on next tick so it can be listened to
  1646. this.setTimeoutFn(function () {
  1647. _this2.emitReserved("error", "No transports available");
  1648. }, 0);
  1649. return;
  1650. } else {
  1651. transport = this.transports[0];
  1652. }
  1653. this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false)
  1654. try {
  1655. transport = this.createTransport(transport);
  1656. } catch (e) {
  1657. this.transports.shift();
  1658. this.open();
  1659. return;
  1660. }
  1661. transport.open();
  1662. this.setTransport(transport);
  1663. }
  1664. /**
  1665. * Sets the current transport. Disables the existing one (if any).
  1666. *
  1667. * @api private
  1668. */
  1669. }, {
  1670. key: "setTransport",
  1671. value: function setTransport(transport) {
  1672. var _this3 = this;
  1673. if (this.transport) {
  1674. this.transport.removeAllListeners();
  1675. } // set up transport
  1676. this.transport = transport; // set up transport listeners
  1677. transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function () {
  1678. _this3.onClose("transport close");
  1679. });
  1680. }
  1681. /**
  1682. * Probes a transport.
  1683. *
  1684. * @param {String} transport name
  1685. * @api private
  1686. */
  1687. }, {
  1688. key: "probe",
  1689. value: function probe(name) {
  1690. var _this4 = this;
  1691. var transport = this.createTransport(name);
  1692. var failed = false;
  1693. Socket.priorWebsocketSuccess = false;
  1694. var onTransportOpen = function onTransportOpen() {
  1695. if (failed) return;
  1696. transport.send([{
  1697. type: "ping",
  1698. data: "probe"
  1699. }]);
  1700. transport.once("packet", function (msg) {
  1701. if (failed) return;
  1702. if ("pong" === msg.type && "probe" === msg.data) {
  1703. _this4.upgrading = true;
  1704. _this4.emitReserved("upgrading", transport);
  1705. if (!transport) return;
  1706. Socket.priorWebsocketSuccess = "websocket" === transport.name;
  1707. _this4.transport.pause(function () {
  1708. if (failed) return;
  1709. if ("closed" === _this4.readyState) return;
  1710. cleanup();
  1711. _this4.setTransport(transport);
  1712. transport.send([{
  1713. type: "upgrade"
  1714. }]);
  1715. _this4.emitReserved("upgrade", transport);
  1716. transport = null;
  1717. _this4.upgrading = false;
  1718. _this4.flush();
  1719. });
  1720. } else {
  1721. var err = new Error("probe error"); // @ts-ignore
  1722. err.transport = transport.name;
  1723. _this4.emitReserved("upgradeError", err);
  1724. }
  1725. });
  1726. };
  1727. function freezeTransport() {
  1728. if (failed) return; // Any callback called by transport should be ignored since now
  1729. failed = true;
  1730. cleanup();
  1731. transport.close();
  1732. transport = null;
  1733. } // Handle any error that happens while probing
  1734. var onerror = function onerror(err) {
  1735. var error = new Error("probe error: " + err); // @ts-ignore
  1736. error.transport = transport.name;
  1737. freezeTransport();
  1738. _this4.emitReserved("upgradeError", error);
  1739. };
  1740. function onTransportClose() {
  1741. onerror("transport closed");
  1742. } // When the socket is closed while we're probing
  1743. function onclose() {
  1744. onerror("socket closed");
  1745. } // When the socket is upgraded while we're probing
  1746. function onupgrade(to) {
  1747. if (transport && to.name !== transport.name) {
  1748. freezeTransport();
  1749. }
  1750. } // Remove all listeners on the transport and on self
  1751. var cleanup = function cleanup() {
  1752. transport.removeListener("open", onTransportOpen);
  1753. transport.removeListener("error", onerror);
  1754. transport.removeListener("close", onTransportClose);
  1755. _this4.off("close", onclose);
  1756. _this4.off("upgrading", onupgrade);
  1757. };
  1758. transport.once("open", onTransportOpen);
  1759. transport.once("error", onerror);
  1760. transport.once("close", onTransportClose);
  1761. this.once("close", onclose);
  1762. this.once("upgrading", onupgrade);
  1763. transport.open();
  1764. }
  1765. /**
  1766. * Called when connection is deemed open.
  1767. *
  1768. * @api private
  1769. */
  1770. }, {
  1771. key: "onOpen",
  1772. value: function onOpen() {
  1773. this.readyState = "open";
  1774. Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
  1775. this.emitReserved("open");
  1776. this.flush(); // we check for `readyState` in case an `open`
  1777. // listener already closed the socket
  1778. if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) {
  1779. var i = 0;
  1780. var l = this.upgrades.length;
  1781. for (; i < l; i++) {
  1782. this.probe(this.upgrades[i]);
  1783. }
  1784. }
  1785. }
  1786. /**
  1787. * Handles a packet.
  1788. *
  1789. * @api private
  1790. */
  1791. }, {
  1792. key: "onPacket",
  1793. value: function onPacket(packet) {
  1794. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1795. this.emitReserved("packet", packet); // Socket is live - any packet counts
  1796. this.emitReserved("heartbeat");
  1797. switch (packet.type) {
  1798. case "open":
  1799. this.onHandshake(JSON.parse(packet.data));
  1800. break;
  1801. case "ping":
  1802. this.resetPingTimeout();
  1803. this.sendPacket("pong");
  1804. this.emitReserved("ping");
  1805. this.emitReserved("pong");
  1806. break;
  1807. case "error":
  1808. var err = new Error("server error"); // @ts-ignore
  1809. err.code = packet.data;
  1810. this.onError(err);
  1811. break;
  1812. case "message":
  1813. this.emitReserved("data", packet.data);
  1814. this.emitReserved("message", packet.data);
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. /**
  1820. * Called upon handshake completion.
  1821. *
  1822. * @param {Object} data - handshake obj
  1823. * @api private
  1824. */
  1825. }, {
  1826. key: "onHandshake",
  1827. value: function onHandshake(data) {
  1828. this.emitReserved("handshake", data);
  1829. this.id = data.sid;
  1830. this.transport.query.sid = data.sid;
  1831. this.upgrades = this.filterUpgrades(data.upgrades);
  1832. this.pingInterval = data.pingInterval;
  1833. this.pingTimeout = data.pingTimeout;
  1834. this.onOpen(); // In case open handler closes socket
  1835. if ("closed" === this.readyState) return;
  1836. this.resetPingTimeout();
  1837. }
  1838. /**
  1839. * Sets and resets ping timeout timer based on server pings.
  1840. *
  1841. * @api private
  1842. */
  1843. }, {
  1844. key: "resetPingTimeout",
  1845. value: function resetPingTimeout() {
  1846. var _this5 = this;
  1847. this.clearTimeoutFn(this.pingTimeoutTimer);
  1848. this.pingTimeoutTimer = this.setTimeoutFn(function () {
  1849. _this5.onClose("ping timeout");
  1850. }, this.pingInterval + this.pingTimeout);
  1851. if (this.opts.autoUnref) {
  1852. this.pingTimeoutTimer.unref();
  1853. }
  1854. }
  1855. /**
  1856. * Called on `drain` event
  1857. *
  1858. * @api private
  1859. */
  1860. }, {
  1861. key: "onDrain",
  1862. value: function onDrain() {
  1863. this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important
  1864. // for example, when upgrading, upgrade packet is sent over,
  1865. // and a nonzero prevBufferLen could cause problems on `drain`
  1866. this.prevBufferLen = 0;
  1867. if (0 === this.writeBuffer.length) {
  1868. this.emitReserved("drain");
  1869. } else {
  1870. this.flush();
  1871. }
  1872. }
  1873. /**
  1874. * Flush write buffers.
  1875. *
  1876. * @api private
  1877. */
  1878. }, {
  1879. key: "flush",
  1880. value: function flush() {
  1881. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  1882. this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer
  1883. // splice writeBuffer and callbackBuffer on `drain`
  1884. this.prevBufferLen = this.writeBuffer.length;
  1885. this.emitReserved("flush");
  1886. }
  1887. }
  1888. /**
  1889. * Sends a message.
  1890. *
  1891. * @param {String} message.
  1892. * @param {Function} callback function.
  1893. * @param {Object} options.
  1894. * @return {Socket} for chaining.
  1895. * @api public
  1896. */
  1897. }, {
  1898. key: "write",
  1899. value: function write(msg, options, fn) {
  1900. this.sendPacket("message", msg, options, fn);
  1901. return this;
  1902. }
  1903. }, {
  1904. key: "send",
  1905. value: function send(msg, options, fn) {
  1906. this.sendPacket("message", msg, options, fn);
  1907. return this;
  1908. }
  1909. /**
  1910. * Sends a packet.
  1911. *
  1912. * @param {String} packet type.
  1913. * @param {String} data.
  1914. * @param {Object} options.
  1915. * @param {Function} callback function.
  1916. * @api private
  1917. */
  1918. }, {
  1919. key: "sendPacket",
  1920. value: function sendPacket(type, data, options, fn) {
  1921. if ("function" === typeof data) {
  1922. fn = data;
  1923. data = undefined;
  1924. }
  1925. if ("function" === typeof options) {
  1926. fn = options;
  1927. options = null;
  1928. }
  1929. if ("closing" === this.readyState || "closed" === this.readyState) {
  1930. return;
  1931. }
  1932. options = options || {};
  1933. options.compress = false !== options.compress;
  1934. var packet = {
  1935. type: type,
  1936. data: data,
  1937. options: options
  1938. };
  1939. this.emitReserved("packetCreate", packet);
  1940. this.writeBuffer.push(packet);
  1941. if (fn) this.once("flush", fn);
  1942. this.flush();
  1943. }
  1944. /**
  1945. * Closes the connection.
  1946. *
  1947. * @api public
  1948. */
  1949. }, {
  1950. key: "close",
  1951. value: function close() {
  1952. var _this6 = this;
  1953. var close = function close() {
  1954. _this6.onClose("forced close");
  1955. _this6.transport.close();
  1956. };
  1957. var cleanupAndClose = function cleanupAndClose() {
  1958. _this6.off("upgrade", cleanupAndClose);
  1959. _this6.off("upgradeError", cleanupAndClose);
  1960. close();
  1961. };
  1962. var waitForUpgrade = function waitForUpgrade() {
  1963. // wait for upgrade to finish since we can't send packets while pausing a transport
  1964. _this6.once("upgrade", cleanupAndClose);
  1965. _this6.once("upgradeError", cleanupAndClose);
  1966. };
  1967. if ("opening" === this.readyState || "open" === this.readyState) {
  1968. this.readyState = "closing";
  1969. if (this.writeBuffer.length) {
  1970. this.once("drain", function () {
  1971. if (_this6.upgrading) {
  1972. waitForUpgrade();
  1973. } else {
  1974. close();
  1975. }
  1976. });
  1977. } else if (this.upgrading) {
  1978. waitForUpgrade();
  1979. } else {
  1980. close();
  1981. }
  1982. }
  1983. return this;
  1984. }
  1985. /**
  1986. * Called upon transport error
  1987. *
  1988. * @api private
  1989. */
  1990. }, {
  1991. key: "onError",
  1992. value: function onError(err) {
  1993. Socket.priorWebsocketSuccess = false;
  1994. this.emitReserved("error", err);
  1995. this.onClose("transport error", err);
  1996. }
  1997. /**
  1998. * Called upon transport close.
  1999. *
  2000. * @api private
  2001. */
  2002. }, {
  2003. key: "onClose",
  2004. value: function onClose(reason, desc) {
  2005. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2006. // clear timers
  2007. this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport
  2008. this.transport.removeAllListeners("close"); // ensure transport won't stay open
  2009. this.transport.close(); // ignore further transport communication
  2010. this.transport.removeAllListeners();
  2011. if (typeof removeEventListener === "function") {
  2012. removeEventListener("offline", this.offlineEventListener, false);
  2013. } // set ready state
  2014. this.readyState = "closed"; // clear session id
  2015. this.id = null; // emit close event
  2016. this.emitReserved("close", reason, desc); // clean buffers after, so users can still
  2017. // grab the buffers on `close` event
  2018. this.writeBuffer = [];
  2019. this.prevBufferLen = 0;
  2020. }
  2021. }
  2022. /**
  2023. * Filters upgrades, returning only those matching client transports.
  2024. *
  2025. * @param {Array} server upgrades
  2026. * @api private
  2027. *
  2028. */
  2029. }, {
  2030. key: "filterUpgrades",
  2031. value: function filterUpgrades(upgrades) {
  2032. var filteredUpgrades = [];
  2033. var i = 0;
  2034. var j = upgrades.length;
  2035. for (; i < j; i++) {
  2036. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2037. }
  2038. return filteredUpgrades;
  2039. }
  2040. }]);
  2041. return Socket;
  2042. }(Emitter_1);
  2043. Socket$1.protocol = protocol$1;
  2044. function clone(obj) {
  2045. var o = {};
  2046. for (var i in obj) {
  2047. if (obj.hasOwnProperty(i)) {
  2048. o[i] = obj[i];
  2049. }
  2050. }
  2051. return o;
  2052. }
  2053. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2054. var isView = function isView(obj) {
  2055. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2056. };
  2057. var toString = Object.prototype.toString;
  2058. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2059. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2060. /**
  2061. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2062. *
  2063. * @private
  2064. */
  2065. function isBinary(obj) {
  2066. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2067. }
  2068. function hasBinary(obj, toJSON) {
  2069. if (!obj || _typeof(obj) !== "object") {
  2070. return false;
  2071. }
  2072. if (Array.isArray(obj)) {
  2073. for (var i = 0, l = obj.length; i < l; i++) {
  2074. if (hasBinary(obj[i])) {
  2075. return true;
  2076. }
  2077. }
  2078. return false;
  2079. }
  2080. if (isBinary(obj)) {
  2081. return true;
  2082. }
  2083. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2084. return hasBinary(obj.toJSON(), true);
  2085. }
  2086. for (var key in obj) {
  2087. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2088. return true;
  2089. }
  2090. }
  2091. return false;
  2092. }
  2093. /**
  2094. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  2095. *
  2096. * @param {Object} packet - socket.io event packet
  2097. * @return {Object} with deconstructed packet and list of buffers
  2098. * @public
  2099. */
  2100. function deconstructPacket(packet) {
  2101. var buffers = [];
  2102. var packetData = packet.data;
  2103. var pack = packet;
  2104. pack.data = _deconstructPacket(packetData, buffers);
  2105. pack.attachments = buffers.length; // number of binary 'attachments'
  2106. return {
  2107. packet: pack,
  2108. buffers: buffers
  2109. };
  2110. }
  2111. function _deconstructPacket(data, buffers) {
  2112. if (!data) return data;
  2113. if (isBinary(data)) {
  2114. var placeholder = {
  2115. _placeholder: true,
  2116. num: buffers.length
  2117. };
  2118. buffers.push(data);
  2119. return placeholder;
  2120. } else if (Array.isArray(data)) {
  2121. var newData = new Array(data.length);
  2122. for (var i = 0; i < data.length; i++) {
  2123. newData[i] = _deconstructPacket(data[i], buffers);
  2124. }
  2125. return newData;
  2126. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  2127. var _newData = {};
  2128. for (var key in data) {
  2129. if (data.hasOwnProperty(key)) {
  2130. _newData[key] = _deconstructPacket(data[key], buffers);
  2131. }
  2132. }
  2133. return _newData;
  2134. }
  2135. return data;
  2136. }
  2137. /**
  2138. * Reconstructs a binary packet from its placeholder packet and buffers
  2139. *
  2140. * @param {Object} packet - event packet with placeholders
  2141. * @param {Array} buffers - binary buffers to put in placeholder positions
  2142. * @return {Object} reconstructed packet
  2143. * @public
  2144. */
  2145. function reconstructPacket(packet, buffers) {
  2146. packet.data = _reconstructPacket(packet.data, buffers);
  2147. packet.attachments = undefined; // no longer useful
  2148. return packet;
  2149. }
  2150. function _reconstructPacket(data, buffers) {
  2151. if (!data) return data;
  2152. if (data && data._placeholder) {
  2153. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  2154. } else if (Array.isArray(data)) {
  2155. for (var i = 0; i < data.length; i++) {
  2156. data[i] = _reconstructPacket(data[i], buffers);
  2157. }
  2158. } else if (_typeof(data) === "object") {
  2159. for (var key in data) {
  2160. if (data.hasOwnProperty(key)) {
  2161. data[key] = _reconstructPacket(data[key], buffers);
  2162. }
  2163. }
  2164. }
  2165. return data;
  2166. }
  2167. /**
  2168. * Protocol version.
  2169. *
  2170. * @public
  2171. */
  2172. var protocol = 5;
  2173. var PacketType;
  2174. (function (PacketType) {
  2175. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  2176. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  2177. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  2178. PacketType[PacketType["ACK"] = 3] = "ACK";
  2179. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  2180. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  2181. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  2182. })(PacketType || (PacketType = {}));
  2183. /**
  2184. * A socket.io Encoder instance
  2185. */
  2186. var Encoder = /*#__PURE__*/function () {
  2187. function Encoder() {
  2188. _classCallCheck(this, Encoder);
  2189. }
  2190. _createClass(Encoder, [{
  2191. key: "encode",
  2192. value:
  2193. /**
  2194. * Encode a packet as a single string if non-binary, or as a
  2195. * buffer sequence, depending on packet type.
  2196. *
  2197. * @param {Object} obj - packet object
  2198. */
  2199. function encode(obj) {
  2200. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  2201. if (hasBinary(obj)) {
  2202. obj.type = obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK;
  2203. return this.encodeAsBinary(obj);
  2204. }
  2205. }
  2206. return [this.encodeAsString(obj)];
  2207. }
  2208. /**
  2209. * Encode packet as string.
  2210. */
  2211. }, {
  2212. key: "encodeAsString",
  2213. value: function encodeAsString(obj) {
  2214. // first is type
  2215. var str = "" + obj.type; // attachments if we have them
  2216. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  2217. str += obj.attachments + "-";
  2218. } // if we have a namespace other than `/`
  2219. // we append it followed by a comma `,`
  2220. if (obj.nsp && "/" !== obj.nsp) {
  2221. str += obj.nsp + ",";
  2222. } // immediately followed by the id
  2223. if (null != obj.id) {
  2224. str += obj.id;
  2225. } // json data
  2226. if (null != obj.data) {
  2227. str += JSON.stringify(obj.data);
  2228. }
  2229. return str;
  2230. }
  2231. /**
  2232. * Encode packet as 'buffer sequence' by removing blobs, and
  2233. * deconstructing packet into object with placeholders and
  2234. * a list of buffers.
  2235. */
  2236. }, {
  2237. key: "encodeAsBinary",
  2238. value: function encodeAsBinary(obj) {
  2239. var deconstruction = deconstructPacket(obj);
  2240. var pack = this.encodeAsString(deconstruction.packet);
  2241. var buffers = deconstruction.buffers;
  2242. buffers.unshift(pack); // add packet info to beginning of data list
  2243. return buffers; // write all the buffers
  2244. }
  2245. }]);
  2246. return Encoder;
  2247. }();
  2248. /**
  2249. * A socket.io Decoder instance
  2250. *
  2251. * @return {Object} decoder
  2252. */
  2253. var Decoder = /*#__PURE__*/function (_Emitter) {
  2254. _inherits(Decoder, _Emitter);
  2255. var _super = _createSuper(Decoder);
  2256. function Decoder() {
  2257. _classCallCheck(this, Decoder);
  2258. return _super.call(this);
  2259. }
  2260. /**
  2261. * Decodes an encoded packet string into packet JSON.
  2262. *
  2263. * @param {String} obj - encoded packet
  2264. */
  2265. _createClass(Decoder, [{
  2266. key: "add",
  2267. value: function add(obj) {
  2268. var packet;
  2269. if (typeof obj === "string") {
  2270. packet = this.decodeString(obj);
  2271. if (packet.type === PacketType.BINARY_EVENT || packet.type === PacketType.BINARY_ACK) {
  2272. // binary packet's json
  2273. this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow
  2274. if (packet.attachments === 0) {
  2275. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2276. }
  2277. } else {
  2278. // non-binary full packet
  2279. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2280. }
  2281. } else if (isBinary(obj) || obj.base64) {
  2282. // raw binary data
  2283. if (!this.reconstructor) {
  2284. throw new Error("got binary data when not reconstructing a packet");
  2285. } else {
  2286. packet = this.reconstructor.takeBinaryData(obj);
  2287. if (packet) {
  2288. // received final buffer
  2289. this.reconstructor = null;
  2290. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2291. }
  2292. }
  2293. } else {
  2294. throw new Error("Unknown type: " + obj);
  2295. }
  2296. }
  2297. /**
  2298. * Decode a packet String (JSON data)
  2299. *
  2300. * @param {String} str
  2301. * @return {Object} packet
  2302. */
  2303. }, {
  2304. key: "decodeString",
  2305. value: function decodeString(str) {
  2306. var i = 0; // look up type
  2307. var p = {
  2308. type: Number(str.charAt(0))
  2309. };
  2310. if (PacketType[p.type] === undefined) {
  2311. throw new Error("unknown packet type " + p.type);
  2312. } // look up attachments if type binary
  2313. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  2314. var start = i + 1;
  2315. while (str.charAt(++i) !== "-" && i != str.length) {}
  2316. var buf = str.substring(start, i);
  2317. if (buf != Number(buf) || str.charAt(i) !== "-") {
  2318. throw new Error("Illegal attachments");
  2319. }
  2320. p.attachments = Number(buf);
  2321. } // look up namespace (if any)
  2322. if ("/" === str.charAt(i + 1)) {
  2323. var _start = i + 1;
  2324. while (++i) {
  2325. var c = str.charAt(i);
  2326. if ("," === c) break;
  2327. if (i === str.length) break;
  2328. }
  2329. p.nsp = str.substring(_start, i);
  2330. } else {
  2331. p.nsp = "/";
  2332. } // look up id
  2333. var next = str.charAt(i + 1);
  2334. if ("" !== next && Number(next) == next) {
  2335. var _start2 = i + 1;
  2336. while (++i) {
  2337. var _c = str.charAt(i);
  2338. if (null == _c || Number(_c) != _c) {
  2339. --i;
  2340. break;
  2341. }
  2342. if (i === str.length) break;
  2343. }
  2344. p.id = Number(str.substring(_start2, i + 1));
  2345. } // look up json data
  2346. if (str.charAt(++i)) {
  2347. var payload = tryParse(str.substr(i));
  2348. if (Decoder.isPayloadValid(p.type, payload)) {
  2349. p.data = payload;
  2350. } else {
  2351. throw new Error("invalid payload");
  2352. }
  2353. }
  2354. return p;
  2355. }
  2356. }, {
  2357. key: "destroy",
  2358. value:
  2359. /**
  2360. * Deallocates a parser's resources
  2361. */
  2362. function destroy() {
  2363. if (this.reconstructor) {
  2364. this.reconstructor.finishedReconstruction();
  2365. }
  2366. }
  2367. }], [{
  2368. key: "isPayloadValid",
  2369. value: function isPayloadValid(type, payload) {
  2370. switch (type) {
  2371. case PacketType.CONNECT:
  2372. return _typeof(payload) === "object";
  2373. case PacketType.DISCONNECT:
  2374. return payload === undefined;
  2375. case PacketType.CONNECT_ERROR:
  2376. return typeof payload === "string" || _typeof(payload) === "object";
  2377. case PacketType.EVENT:
  2378. case PacketType.BINARY_EVENT:
  2379. return Array.isArray(payload) && payload.length > 0;
  2380. case PacketType.ACK:
  2381. case PacketType.BINARY_ACK:
  2382. return Array.isArray(payload);
  2383. }
  2384. }
  2385. }]);
  2386. return Decoder;
  2387. }(Emitter_1);
  2388. function tryParse(str) {
  2389. try {
  2390. return JSON.parse(str);
  2391. } catch (e) {
  2392. return false;
  2393. }
  2394. }
  2395. /**
  2396. * A manager of a binary event's 'buffer sequence'. Should
  2397. * be constructed whenever a packet of type BINARY_EVENT is
  2398. * decoded.
  2399. *
  2400. * @param {Object} packet
  2401. * @return {BinaryReconstructor} initialized reconstructor
  2402. */
  2403. var BinaryReconstructor = /*#__PURE__*/function () {
  2404. function BinaryReconstructor(packet) {
  2405. _classCallCheck(this, BinaryReconstructor);
  2406. this.packet = packet;
  2407. this.buffers = [];
  2408. this.reconPack = packet;
  2409. }
  2410. /**
  2411. * Method to be called when binary data received from connection
  2412. * after a BINARY_EVENT packet.
  2413. *
  2414. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  2415. * @return {null | Object} returns null if more binary data is expected or
  2416. * a reconstructed packet object if all buffers have been received.
  2417. */
  2418. _createClass(BinaryReconstructor, [{
  2419. key: "takeBinaryData",
  2420. value: function takeBinaryData(binData) {
  2421. this.buffers.push(binData);
  2422. if (this.buffers.length === this.reconPack.attachments) {
  2423. // done with buffer list
  2424. var packet = reconstructPacket(this.reconPack, this.buffers);
  2425. this.finishedReconstruction();
  2426. return packet;
  2427. }
  2428. return null;
  2429. }
  2430. /**
  2431. * Cleans up binary packet reconstruction variables.
  2432. */
  2433. }, {
  2434. key: "finishedReconstruction",
  2435. value: function finishedReconstruction() {
  2436. this.reconPack = null;
  2437. this.buffers = [];
  2438. }
  2439. }]);
  2440. return BinaryReconstructor;
  2441. }();
  2442. var parser = /*#__PURE__*/Object.freeze({
  2443. __proto__: null,
  2444. protocol: protocol,
  2445. get PacketType () { return PacketType; },
  2446. Encoder: Encoder,
  2447. Decoder: Decoder
  2448. });
  2449. function on(obj, ev, fn) {
  2450. obj.on(ev, fn);
  2451. return function subDestroy() {
  2452. obj.off(ev, fn);
  2453. };
  2454. }
  2455. /**
  2456. * Internal events.
  2457. * These events can't be emitted by the user.
  2458. */
  2459. var RESERVED_EVENTS = Object.freeze({
  2460. connect: 1,
  2461. connect_error: 1,
  2462. disconnect: 1,
  2463. disconnecting: 1,
  2464. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  2465. newListener: 1,
  2466. removeListener: 1
  2467. });
  2468. var Socket = /*#__PURE__*/function (_Emitter) {
  2469. _inherits(Socket, _Emitter);
  2470. var _super = _createSuper(Socket);
  2471. /**
  2472. * `Socket` constructor.
  2473. *
  2474. * @public
  2475. */
  2476. function Socket(io, nsp, opts) {
  2477. var _this;
  2478. _classCallCheck(this, Socket);
  2479. _this = _super.call(this);
  2480. _this.connected = false;
  2481. _this.disconnected = true;
  2482. _this.receiveBuffer = [];
  2483. _this.sendBuffer = [];
  2484. _this.ids = 0;
  2485. _this.acks = {};
  2486. _this.flags = {};
  2487. _this.io = io;
  2488. _this.nsp = nsp;
  2489. if (opts && opts.auth) {
  2490. _this.auth = opts.auth;
  2491. }
  2492. if (_this.io._autoConnect) _this.open();
  2493. return _this;
  2494. }
  2495. /**
  2496. * Subscribe to open, close and packet events
  2497. *
  2498. * @private
  2499. */
  2500. _createClass(Socket, [{
  2501. key: "subEvents",
  2502. value: function subEvents() {
  2503. if (this.subs) return;
  2504. var io = this.io;
  2505. this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))];
  2506. }
  2507. /**
  2508. * Whether the Socket will try to reconnect when its Manager connects or reconnects
  2509. */
  2510. }, {
  2511. key: "active",
  2512. get: function get() {
  2513. return !!this.subs;
  2514. }
  2515. /**
  2516. * "Opens" the socket.
  2517. *
  2518. * @public
  2519. */
  2520. }, {
  2521. key: "connect",
  2522. value: function connect() {
  2523. if (this.connected) return this;
  2524. this.subEvents();
  2525. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  2526. if ("open" === this.io._readyState) this.onopen();
  2527. return this;
  2528. }
  2529. /**
  2530. * Alias for connect()
  2531. */
  2532. }, {
  2533. key: "open",
  2534. value: function open() {
  2535. return this.connect();
  2536. }
  2537. /**
  2538. * Sends a `message` event.
  2539. *
  2540. * @return self
  2541. * @public
  2542. */
  2543. }, {
  2544. key: "send",
  2545. value: function send() {
  2546. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2547. args[_key] = arguments[_key];
  2548. }
  2549. args.unshift("message");
  2550. this.emit.apply(this, args);
  2551. return this;
  2552. }
  2553. /**
  2554. * Override `emit`.
  2555. * If the event is in `events`, it's emitted normally.
  2556. *
  2557. * @return self
  2558. * @public
  2559. */
  2560. }, {
  2561. key: "emit",
  2562. value: function emit(ev) {
  2563. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  2564. throw new Error('"' + ev + '" is a reserved event name');
  2565. }
  2566. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  2567. args[_key2 - 1] = arguments[_key2];
  2568. }
  2569. args.unshift(ev);
  2570. var packet = {
  2571. type: PacketType.EVENT,
  2572. data: args
  2573. };
  2574. packet.options = {};
  2575. packet.options.compress = this.flags.compress !== false; // event ack callback
  2576. if ("function" === typeof args[args.length - 1]) {
  2577. var id = this.ids++;
  2578. var ack = args.pop();
  2579. this._registerAckCallback(id, ack);
  2580. packet.id = id;
  2581. }
  2582. var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable;
  2583. var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected);
  2584. if (discardPacket) ; else if (this.connected) {
  2585. this.packet(packet);
  2586. } else {
  2587. this.sendBuffer.push(packet);
  2588. }
  2589. this.flags = {};
  2590. return this;
  2591. }
  2592. /**
  2593. * @private
  2594. */
  2595. }, {
  2596. key: "_registerAckCallback",
  2597. value: function _registerAckCallback(id, ack) {
  2598. var _this2 = this;
  2599. var timeout = this.flags.timeout;
  2600. if (timeout === undefined) {
  2601. this.acks[id] = ack;
  2602. return;
  2603. } // @ts-ignore
  2604. var timer = this.io.setTimeoutFn(function () {
  2605. delete _this2.acks[id];
  2606. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  2607. if (_this2.sendBuffer[i].id === id) {
  2608. _this2.sendBuffer.splice(i, 1);
  2609. }
  2610. }
  2611. ack.call(_this2, new Error("operation has timed out"));
  2612. }, timeout);
  2613. this.acks[id] = function () {
  2614. // @ts-ignore
  2615. _this2.io.clearTimeoutFn(timer);
  2616. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  2617. args[_key3] = arguments[_key3];
  2618. }
  2619. ack.apply(_this2, [null].concat(args));
  2620. };
  2621. }
  2622. /**
  2623. * Sends a packet.
  2624. *
  2625. * @param packet
  2626. * @private
  2627. */
  2628. }, {
  2629. key: "packet",
  2630. value: function packet(_packet) {
  2631. _packet.nsp = this.nsp;
  2632. this.io._packet(_packet);
  2633. }
  2634. /**
  2635. * Called upon engine `open`.
  2636. *
  2637. * @private
  2638. */
  2639. }, {
  2640. key: "onopen",
  2641. value: function onopen() {
  2642. var _this3 = this;
  2643. if (typeof this.auth == "function") {
  2644. this.auth(function (data) {
  2645. _this3.packet({
  2646. type: PacketType.CONNECT,
  2647. data: data
  2648. });
  2649. });
  2650. } else {
  2651. this.packet({
  2652. type: PacketType.CONNECT,
  2653. data: this.auth
  2654. });
  2655. }
  2656. }
  2657. /**
  2658. * Called upon engine or manager `error`.
  2659. *
  2660. * @param err
  2661. * @private
  2662. */
  2663. }, {
  2664. key: "onerror",
  2665. value: function onerror(err) {
  2666. if (!this.connected) {
  2667. this.emitReserved("connect_error", err);
  2668. }
  2669. }
  2670. /**
  2671. * Called upon engine `close`.
  2672. *
  2673. * @param reason
  2674. * @private
  2675. */
  2676. }, {
  2677. key: "onclose",
  2678. value: function onclose(reason) {
  2679. this.connected = false;
  2680. this.disconnected = true;
  2681. delete this.id;
  2682. this.emitReserved("disconnect", reason);
  2683. }
  2684. /**
  2685. * Called with socket packet.
  2686. *
  2687. * @param packet
  2688. * @private
  2689. */
  2690. }, {
  2691. key: "onpacket",
  2692. value: function onpacket(packet) {
  2693. var sameNamespace = packet.nsp === this.nsp;
  2694. if (!sameNamespace) return;
  2695. switch (packet.type) {
  2696. case PacketType.CONNECT:
  2697. if (packet.data && packet.data.sid) {
  2698. var id = packet.data.sid;
  2699. this.onconnect(id);
  2700. } else {
  2701. this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
  2702. }
  2703. break;
  2704. case PacketType.EVENT:
  2705. this.onevent(packet);
  2706. break;
  2707. case PacketType.BINARY_EVENT:
  2708. this.onevent(packet);
  2709. break;
  2710. case PacketType.ACK:
  2711. this.onack(packet);
  2712. break;
  2713. case PacketType.BINARY_ACK:
  2714. this.onack(packet);
  2715. break;
  2716. case PacketType.DISCONNECT:
  2717. this.ondisconnect();
  2718. break;
  2719. case PacketType.CONNECT_ERROR:
  2720. this.destroy();
  2721. var err = new Error(packet.data.message); // @ts-ignore
  2722. err.data = packet.data.data;
  2723. this.emitReserved("connect_error", err);
  2724. break;
  2725. }
  2726. }
  2727. /**
  2728. * Called upon a server event.
  2729. *
  2730. * @param packet
  2731. * @private
  2732. */
  2733. }, {
  2734. key: "onevent",
  2735. value: function onevent(packet) {
  2736. var args = packet.data || [];
  2737. if (null != packet.id) {
  2738. args.push(this.ack(packet.id));
  2739. }
  2740. if (this.connected) {
  2741. this.emitEvent(args);
  2742. } else {
  2743. this.receiveBuffer.push(Object.freeze(args));
  2744. }
  2745. }
  2746. }, {
  2747. key: "emitEvent",
  2748. value: function emitEvent(args) {
  2749. if (this._anyListeners && this._anyListeners.length) {
  2750. var listeners = this._anyListeners.slice();
  2751. var _iterator = _createForOfIteratorHelper(listeners),
  2752. _step;
  2753. try {
  2754. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  2755. var listener = _step.value;
  2756. listener.apply(this, args);
  2757. }
  2758. } catch (err) {
  2759. _iterator.e(err);
  2760. } finally {
  2761. _iterator.f();
  2762. }
  2763. }
  2764. _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args);
  2765. }
  2766. /**
  2767. * Produces an ack callback to emit with an event.
  2768. *
  2769. * @private
  2770. */
  2771. }, {
  2772. key: "ack",
  2773. value: function ack(id) {
  2774. var self = this;
  2775. var sent = false;
  2776. return function () {
  2777. // prevent double callbacks
  2778. if (sent) return;
  2779. sent = true;
  2780. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  2781. args[_key4] = arguments[_key4];
  2782. }
  2783. self.packet({
  2784. type: PacketType.ACK,
  2785. id: id,
  2786. data: args
  2787. });
  2788. };
  2789. }
  2790. /**
  2791. * Called upon a server acknowlegement.
  2792. *
  2793. * @param packet
  2794. * @private
  2795. */
  2796. }, {
  2797. key: "onack",
  2798. value: function onack(packet) {
  2799. var ack = this.acks[packet.id];
  2800. if ("function" === typeof ack) {
  2801. ack.apply(this, packet.data);
  2802. delete this.acks[packet.id];
  2803. }
  2804. }
  2805. /**
  2806. * Called upon server connect.
  2807. *
  2808. * @private
  2809. */
  2810. }, {
  2811. key: "onconnect",
  2812. value: function onconnect(id) {
  2813. this.id = id;
  2814. this.connected = true;
  2815. this.disconnected = false;
  2816. this.emitBuffered();
  2817. this.emitReserved("connect");
  2818. }
  2819. /**
  2820. * Emit buffered events (received and emitted).
  2821. *
  2822. * @private
  2823. */
  2824. }, {
  2825. key: "emitBuffered",
  2826. value: function emitBuffered() {
  2827. var _this4 = this;
  2828. this.receiveBuffer.forEach(function (args) {
  2829. return _this4.emitEvent(args);
  2830. });
  2831. this.receiveBuffer = [];
  2832. this.sendBuffer.forEach(function (packet) {
  2833. return _this4.packet(packet);
  2834. });
  2835. this.sendBuffer = [];
  2836. }
  2837. /**
  2838. * Called upon server disconnect.
  2839. *
  2840. * @private
  2841. */
  2842. }, {
  2843. key: "ondisconnect",
  2844. value: function ondisconnect() {
  2845. this.destroy();
  2846. this.onclose("io server disconnect");
  2847. }
  2848. /**
  2849. * Called upon forced client/server side disconnections,
  2850. * this method ensures the manager stops tracking us and
  2851. * that reconnections don't get triggered for this.
  2852. *
  2853. * @private
  2854. */
  2855. }, {
  2856. key: "destroy",
  2857. value: function destroy() {
  2858. if (this.subs) {
  2859. // clean subscriptions to avoid reconnections
  2860. this.subs.forEach(function (subDestroy) {
  2861. return subDestroy();
  2862. });
  2863. this.subs = undefined;
  2864. }
  2865. this.io["_destroy"](this);
  2866. }
  2867. /**
  2868. * Disconnects the socket manually.
  2869. *
  2870. * @return self
  2871. * @public
  2872. */
  2873. }, {
  2874. key: "disconnect",
  2875. value: function disconnect() {
  2876. if (this.connected) {
  2877. this.packet({
  2878. type: PacketType.DISCONNECT
  2879. });
  2880. } // remove socket from pool
  2881. this.destroy();
  2882. if (this.connected) {
  2883. // fire events
  2884. this.onclose("io client disconnect");
  2885. }
  2886. return this;
  2887. }
  2888. /**
  2889. * Alias for disconnect()
  2890. *
  2891. * @return self
  2892. * @public
  2893. */
  2894. }, {
  2895. key: "close",
  2896. value: function close() {
  2897. return this.disconnect();
  2898. }
  2899. /**
  2900. * Sets the compress flag.
  2901. *
  2902. * @param compress - if `true`, compresses the sending data
  2903. * @return self
  2904. * @public
  2905. */
  2906. }, {
  2907. key: "compress",
  2908. value: function compress(_compress) {
  2909. this.flags.compress = _compress;
  2910. return this;
  2911. }
  2912. /**
  2913. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  2914. * ready to send messages.
  2915. *
  2916. * @returns self
  2917. * @public
  2918. */
  2919. }, {
  2920. key: "volatile",
  2921. get: function get() {
  2922. this.flags["volatile"] = true;
  2923. return this;
  2924. }
  2925. /**
  2926. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  2927. * given number of milliseconds have elapsed without an acknowledgement from the server:
  2928. *
  2929. * ```
  2930. * socket.timeout(5000).emit("my-event", (err) => {
  2931. * if (err) {
  2932. * // the server did not acknowledge the event in the given delay
  2933. * }
  2934. * });
  2935. * ```
  2936. *
  2937. * @returns self
  2938. * @public
  2939. */
  2940. }, {
  2941. key: "timeout",
  2942. value: function timeout(_timeout) {
  2943. this.flags.timeout = _timeout;
  2944. return this;
  2945. }
  2946. /**
  2947. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  2948. * callback.
  2949. *
  2950. * @param listener
  2951. * @public
  2952. */
  2953. }, {
  2954. key: "onAny",
  2955. value: function onAny(listener) {
  2956. this._anyListeners = this._anyListeners || [];
  2957. this._anyListeners.push(listener);
  2958. return this;
  2959. }
  2960. /**
  2961. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  2962. * callback. The listener is added to the beginning of the listeners array.
  2963. *
  2964. * @param listener
  2965. * @public
  2966. */
  2967. }, {
  2968. key: "prependAny",
  2969. value: function prependAny(listener) {
  2970. this._anyListeners = this._anyListeners || [];
  2971. this._anyListeners.unshift(listener);
  2972. return this;
  2973. }
  2974. /**
  2975. * Removes the listener that will be fired when any event is emitted.
  2976. *
  2977. * @param listener
  2978. * @public
  2979. */
  2980. }, {
  2981. key: "offAny",
  2982. value: function offAny(listener) {
  2983. if (!this._anyListeners) {
  2984. return this;
  2985. }
  2986. if (listener) {
  2987. var listeners = this._anyListeners;
  2988. for (var i = 0; i < listeners.length; i++) {
  2989. if (listener === listeners[i]) {
  2990. listeners.splice(i, 1);
  2991. return this;
  2992. }
  2993. }
  2994. } else {
  2995. this._anyListeners = [];
  2996. }
  2997. return this;
  2998. }
  2999. /**
  3000. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3001. * e.g. to remove listeners.
  3002. *
  3003. * @public
  3004. */
  3005. }, {
  3006. key: "listenersAny",
  3007. value: function listenersAny() {
  3008. return this._anyListeners || [];
  3009. }
  3010. }]);
  3011. return Socket;
  3012. }(Emitter_1);
  3013. /**
  3014. * Expose `Backoff`.
  3015. */
  3016. var backo2 = Backoff;
  3017. /**
  3018. * Initialize backoff timer with `opts`.
  3019. *
  3020. * - `min` initial timeout in milliseconds [100]
  3021. * - `max` max timeout [10000]
  3022. * - `jitter` [0]
  3023. * - `factor` [2]
  3024. *
  3025. * @param {Object} opts
  3026. * @api public
  3027. */
  3028. function Backoff(opts) {
  3029. opts = opts || {};
  3030. this.ms = opts.min || 100;
  3031. this.max = opts.max || 10000;
  3032. this.factor = opts.factor || 2;
  3033. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  3034. this.attempts = 0;
  3035. }
  3036. /**
  3037. * Return the backoff duration.
  3038. *
  3039. * @return {Number}
  3040. * @api public
  3041. */
  3042. Backoff.prototype.duration = function () {
  3043. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  3044. if (this.jitter) {
  3045. var rand = Math.random();
  3046. var deviation = Math.floor(rand * this.jitter * ms);
  3047. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  3048. }
  3049. return Math.min(ms, this.max) | 0;
  3050. };
  3051. /**
  3052. * Reset the number of attempts.
  3053. *
  3054. * @api public
  3055. */
  3056. Backoff.prototype.reset = function () {
  3057. this.attempts = 0;
  3058. };
  3059. /**
  3060. * Set the minimum duration
  3061. *
  3062. * @api public
  3063. */
  3064. Backoff.prototype.setMin = function (min) {
  3065. this.ms = min;
  3066. };
  3067. /**
  3068. * Set the maximum duration
  3069. *
  3070. * @api public
  3071. */
  3072. Backoff.prototype.setMax = function (max) {
  3073. this.max = max;
  3074. };
  3075. /**
  3076. * Set the jitter
  3077. *
  3078. * @api public
  3079. */
  3080. Backoff.prototype.setJitter = function (jitter) {
  3081. this.jitter = jitter;
  3082. };
  3083. var Manager = /*#__PURE__*/function (_Emitter) {
  3084. _inherits(Manager, _Emitter);
  3085. var _super = _createSuper(Manager);
  3086. function Manager(uri, opts) {
  3087. var _this;
  3088. _classCallCheck(this, Manager);
  3089. var _a;
  3090. _this = _super.call(this);
  3091. _this.nsps = {};
  3092. _this.subs = [];
  3093. if (uri && "object" === _typeof(uri)) {
  3094. opts = uri;
  3095. uri = undefined;
  3096. }
  3097. opts = opts || {};
  3098. opts.path = opts.path || "/socket.io";
  3099. _this.opts = opts;
  3100. installTimerFunctions(_assertThisInitialized(_this), opts);
  3101. _this.reconnection(opts.reconnection !== false);
  3102. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  3103. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  3104. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  3105. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  3106. _this.backoff = new backo2({
  3107. min: _this.reconnectionDelay(),
  3108. max: _this.reconnectionDelayMax(),
  3109. jitter: _this.randomizationFactor()
  3110. });
  3111. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  3112. _this._readyState = "closed";
  3113. _this.uri = uri;
  3114. var _parser = opts.parser || parser;
  3115. _this.encoder = new _parser.Encoder();
  3116. _this.decoder = new _parser.Decoder();
  3117. _this._autoConnect = opts.autoConnect !== false;
  3118. if (_this._autoConnect) _this.open();
  3119. return _this;
  3120. }
  3121. _createClass(Manager, [{
  3122. key: "reconnection",
  3123. value: function reconnection(v) {
  3124. if (!arguments.length) return this._reconnection;
  3125. this._reconnection = !!v;
  3126. return this;
  3127. }
  3128. }, {
  3129. key: "reconnectionAttempts",
  3130. value: function reconnectionAttempts(v) {
  3131. if (v === undefined) return this._reconnectionAttempts;
  3132. this._reconnectionAttempts = v;
  3133. return this;
  3134. }
  3135. }, {
  3136. key: "reconnectionDelay",
  3137. value: function reconnectionDelay(v) {
  3138. var _a;
  3139. if (v === undefined) return this._reconnectionDelay;
  3140. this._reconnectionDelay = v;
  3141. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  3142. return this;
  3143. }
  3144. }, {
  3145. key: "randomizationFactor",
  3146. value: function randomizationFactor(v) {
  3147. var _a;
  3148. if (v === undefined) return this._randomizationFactor;
  3149. this._randomizationFactor = v;
  3150. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  3151. return this;
  3152. }
  3153. }, {
  3154. key: "reconnectionDelayMax",
  3155. value: function reconnectionDelayMax(v) {
  3156. var _a;
  3157. if (v === undefined) return this._reconnectionDelayMax;
  3158. this._reconnectionDelayMax = v;
  3159. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  3160. return this;
  3161. }
  3162. }, {
  3163. key: "timeout",
  3164. value: function timeout(v) {
  3165. if (!arguments.length) return this._timeout;
  3166. this._timeout = v;
  3167. return this;
  3168. }
  3169. /**
  3170. * Starts trying to reconnect if reconnection is enabled and we have not
  3171. * started reconnecting yet
  3172. *
  3173. * @private
  3174. */
  3175. }, {
  3176. key: "maybeReconnectOnOpen",
  3177. value: function maybeReconnectOnOpen() {
  3178. // Only try to reconnect if it's the first time we're connecting
  3179. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  3180. // keeps reconnection from firing twice for the same reconnection loop
  3181. this.reconnect();
  3182. }
  3183. }
  3184. /**
  3185. * Sets the current transport `socket`.
  3186. *
  3187. * @param {Function} fn - optional, callback
  3188. * @return self
  3189. * @public
  3190. */
  3191. }, {
  3192. key: "open",
  3193. value: function open(fn) {
  3194. var _this2 = this;
  3195. if (~this._readyState.indexOf("open")) return this;
  3196. this.engine = new Socket$1(this.uri, this.opts);
  3197. var socket = this.engine;
  3198. var self = this;
  3199. this._readyState = "opening";
  3200. this.skipReconnect = false; // emit `open`
  3201. var openSubDestroy = on(socket, "open", function () {
  3202. self.onopen();
  3203. fn && fn();
  3204. }); // emit `error`
  3205. var errorSub = on(socket, "error", function (err) {
  3206. self.cleanup();
  3207. self._readyState = "closed";
  3208. _this2.emitReserved("error", err);
  3209. if (fn) {
  3210. fn(err);
  3211. } else {
  3212. // Only do this if there is no fn to handle the error
  3213. self.maybeReconnectOnOpen();
  3214. }
  3215. });
  3216. if (false !== this._timeout) {
  3217. var timeout = this._timeout;
  3218. if (timeout === 0) {
  3219. openSubDestroy(); // prevents a race condition with the 'open' event
  3220. } // set timer
  3221. var timer = this.setTimeoutFn(function () {
  3222. openSubDestroy();
  3223. socket.close(); // @ts-ignore
  3224. socket.emit("error", new Error("timeout"));
  3225. }, timeout);
  3226. if (this.opts.autoUnref) {
  3227. timer.unref();
  3228. }
  3229. this.subs.push(function subDestroy() {
  3230. clearTimeout(timer);
  3231. });
  3232. }
  3233. this.subs.push(openSubDestroy);
  3234. this.subs.push(errorSub);
  3235. return this;
  3236. }
  3237. /**
  3238. * Alias for open()
  3239. *
  3240. * @return self
  3241. * @public
  3242. */
  3243. }, {
  3244. key: "connect",
  3245. value: function connect(fn) {
  3246. return this.open(fn);
  3247. }
  3248. /**
  3249. * Called upon transport open.
  3250. *
  3251. * @private
  3252. */
  3253. }, {
  3254. key: "onopen",
  3255. value: function onopen() {
  3256. // clear old subs
  3257. this.cleanup(); // mark as open
  3258. this._readyState = "open";
  3259. this.emitReserved("open"); // add new subs
  3260. var socket = this.engine;
  3261. this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this)));
  3262. }
  3263. /**
  3264. * Called upon a ping.
  3265. *
  3266. * @private
  3267. */
  3268. }, {
  3269. key: "onping",
  3270. value: function onping() {
  3271. this.emitReserved("ping");
  3272. }
  3273. /**
  3274. * Called with data.
  3275. *
  3276. * @private
  3277. */
  3278. }, {
  3279. key: "ondata",
  3280. value: function ondata(data) {
  3281. this.decoder.add(data);
  3282. }
  3283. /**
  3284. * Called when parser fully decodes a packet.
  3285. *
  3286. * @private
  3287. */
  3288. }, {
  3289. key: "ondecoded",
  3290. value: function ondecoded(packet) {
  3291. this.emitReserved("packet", packet);
  3292. }
  3293. /**
  3294. * Called upon socket error.
  3295. *
  3296. * @private
  3297. */
  3298. }, {
  3299. key: "onerror",
  3300. value: function onerror(err) {
  3301. this.emitReserved("error", err);
  3302. }
  3303. /**
  3304. * Creates a new socket for the given `nsp`.
  3305. *
  3306. * @return {Socket}
  3307. * @public
  3308. */
  3309. }, {
  3310. key: "socket",
  3311. value: function socket(nsp, opts) {
  3312. var socket = this.nsps[nsp];
  3313. if (!socket) {
  3314. socket = new Socket(this, nsp, opts);
  3315. this.nsps[nsp] = socket;
  3316. }
  3317. return socket;
  3318. }
  3319. /**
  3320. * Called upon a socket close.
  3321. *
  3322. * @param socket
  3323. * @private
  3324. */
  3325. }, {
  3326. key: "_destroy",
  3327. value: function _destroy(socket) {
  3328. var nsps = Object.keys(this.nsps);
  3329. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  3330. var nsp = _nsps[_i];
  3331. var _socket = this.nsps[nsp];
  3332. if (_socket.active) {
  3333. return;
  3334. }
  3335. }
  3336. this._close();
  3337. }
  3338. /**
  3339. * Writes a packet.
  3340. *
  3341. * @param packet
  3342. * @private
  3343. */
  3344. }, {
  3345. key: "_packet",
  3346. value: function _packet(packet) {
  3347. var encodedPackets = this.encoder.encode(packet);
  3348. for (var i = 0; i < encodedPackets.length; i++) {
  3349. this.engine.write(encodedPackets[i], packet.options);
  3350. }
  3351. }
  3352. /**
  3353. * Clean up transport subscriptions and packet buffer.
  3354. *
  3355. * @private
  3356. */
  3357. }, {
  3358. key: "cleanup",
  3359. value: function cleanup() {
  3360. this.subs.forEach(function (subDestroy) {
  3361. return subDestroy();
  3362. });
  3363. this.subs.length = 0;
  3364. this.decoder.destroy();
  3365. }
  3366. /**
  3367. * Close the current socket.
  3368. *
  3369. * @private
  3370. */
  3371. }, {
  3372. key: "_close",
  3373. value: function _close() {
  3374. this.skipReconnect = true;
  3375. this._reconnecting = false;
  3376. this.onclose("forced close");
  3377. if (this.engine) this.engine.close();
  3378. }
  3379. /**
  3380. * Alias for close()
  3381. *
  3382. * @private
  3383. */
  3384. }, {
  3385. key: "disconnect",
  3386. value: function disconnect() {
  3387. return this._close();
  3388. }
  3389. /**
  3390. * Called upon engine close.
  3391. *
  3392. * @private
  3393. */
  3394. }, {
  3395. key: "onclose",
  3396. value: function onclose(reason) {
  3397. this.cleanup();
  3398. this.backoff.reset();
  3399. this._readyState = "closed";
  3400. this.emitReserved("close", reason);
  3401. if (this._reconnection && !this.skipReconnect) {
  3402. this.reconnect();
  3403. }
  3404. }
  3405. /**
  3406. * Attempt a reconnection.
  3407. *
  3408. * @private
  3409. */
  3410. }, {
  3411. key: "reconnect",
  3412. value: function reconnect() {
  3413. var _this3 = this;
  3414. if (this._reconnecting || this.skipReconnect) return this;
  3415. var self = this;
  3416. if (this.backoff.attempts >= this._reconnectionAttempts) {
  3417. this.backoff.reset();
  3418. this.emitReserved("reconnect_failed");
  3419. this._reconnecting = false;
  3420. } else {
  3421. var delay = this.backoff.duration();
  3422. this._reconnecting = true;
  3423. var timer = this.setTimeoutFn(function () {
  3424. if (self.skipReconnect) return;
  3425. _this3.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events
  3426. if (self.skipReconnect) return;
  3427. self.open(function (err) {
  3428. if (err) {
  3429. self._reconnecting = false;
  3430. self.reconnect();
  3431. _this3.emitReserved("reconnect_error", err);
  3432. } else {
  3433. self.onreconnect();
  3434. }
  3435. });
  3436. }, delay);
  3437. if (this.opts.autoUnref) {
  3438. timer.unref();
  3439. }
  3440. this.subs.push(function subDestroy() {
  3441. clearTimeout(timer);
  3442. });
  3443. }
  3444. }
  3445. /**
  3446. * Called upon successful reconnect.
  3447. *
  3448. * @private
  3449. */
  3450. }, {
  3451. key: "onreconnect",
  3452. value: function onreconnect() {
  3453. var attempt = this.backoff.attempts;
  3454. this._reconnecting = false;
  3455. this.backoff.reset();
  3456. this.emitReserved("reconnect", attempt);
  3457. }
  3458. }]);
  3459. return Manager;
  3460. }(Emitter_1);
  3461. /**
  3462. * Managers cache.
  3463. */
  3464. var cache = {};
  3465. function lookup(uri, opts) {
  3466. if (_typeof(uri) === "object") {
  3467. opts = uri;
  3468. uri = undefined;
  3469. }
  3470. opts = opts || {};
  3471. var parsed = url(uri, opts.path || "/socket.io");
  3472. var source = parsed.source;
  3473. var id = parsed.id;
  3474. var path = parsed.path;
  3475. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  3476. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  3477. var io;
  3478. if (newConnection) {
  3479. io = new Manager(source, opts);
  3480. } else {
  3481. if (!cache[id]) {
  3482. cache[id] = new Manager(source, opts);
  3483. }
  3484. io = cache[id];
  3485. }
  3486. if (parsed.query && !opts.query) {
  3487. opts.query = parsed.queryKey;
  3488. }
  3489. return io.socket(parsed.path, opts);
  3490. } // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  3491. // namespace (e.g. `io.connect(...)`), for backward compatibility
  3492. _extends(lookup, {
  3493. Manager: Manager,
  3494. Socket: Socket,
  3495. io: lookup,
  3496. connect: lookup
  3497. });
  3498. return lookup;
  3499. }));
  3500. //# sourceMappingURL=socket.io.js.map