socket.io.js 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955
  1. /*!
  2. * Socket.IO v4.8.3
  3. * (c) 2014-2025 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 _arrayLikeToArray(r, a) {
  12. (null == a || a > r.length) && (a = r.length);
  13. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  14. return n;
  15. }
  16. function _arrayWithoutHoles(r) {
  17. if (Array.isArray(r)) return _arrayLikeToArray(r);
  18. }
  19. function _construct(t, e, r) {
  20. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  21. var o = [null];
  22. o.push.apply(o, e);
  23. var p = new (t.bind.apply(t, o))();
  24. return r && _setPrototypeOf(p, r.prototype), p;
  25. }
  26. function _defineProperties(e, r) {
  27. for (var t = 0; t < r.length; t++) {
  28. var o = r[t];
  29. o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
  30. }
  31. }
  32. function _createClass(e, r, t) {
  33. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  34. writable: !1
  35. }), e;
  36. }
  37. function _createForOfIteratorHelper(r, e) {
  38. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  39. if (!t) {
  40. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
  41. t && (r = t);
  42. var n = 0,
  43. F = function () {};
  44. return {
  45. s: F,
  46. n: function () {
  47. return n >= r.length ? {
  48. done: !0
  49. } : {
  50. done: !1,
  51. value: r[n++]
  52. };
  53. },
  54. e: function (r) {
  55. throw r;
  56. },
  57. f: F
  58. };
  59. }
  60. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  61. }
  62. var o,
  63. a = !0,
  64. u = !1;
  65. return {
  66. s: function () {
  67. t = t.call(r);
  68. },
  69. n: function () {
  70. var r = t.next();
  71. return a = r.done, r;
  72. },
  73. e: function (r) {
  74. u = !0, o = r;
  75. },
  76. f: function () {
  77. try {
  78. a || null == t.return || t.return();
  79. } finally {
  80. if (u) throw o;
  81. }
  82. }
  83. };
  84. }
  85. function _extends() {
  86. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  87. for (var e = 1; e < arguments.length; e++) {
  88. var t = arguments[e];
  89. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  90. }
  91. return n;
  92. }, _extends.apply(null, arguments);
  93. }
  94. function _getPrototypeOf(t) {
  95. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  96. return t.__proto__ || Object.getPrototypeOf(t);
  97. }, _getPrototypeOf(t);
  98. }
  99. function _inheritsLoose(t, o) {
  100. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  101. }
  102. function _isNativeFunction(t) {
  103. try {
  104. return -1 !== Function.toString.call(t).indexOf("[native code]");
  105. } catch (n) {
  106. return "function" == typeof t;
  107. }
  108. }
  109. function _isNativeReflectConstruct() {
  110. try {
  111. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  112. } catch (t) {}
  113. return (_isNativeReflectConstruct = function () {
  114. return !!t;
  115. })();
  116. }
  117. function _iterableToArray(r) {
  118. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  119. }
  120. function _nonIterableSpread() {
  121. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  122. }
  123. function _setPrototypeOf(t, e) {
  124. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  125. return t.__proto__ = e, t;
  126. }, _setPrototypeOf(t, e);
  127. }
  128. function _toConsumableArray(r) {
  129. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  130. }
  131. function _toPrimitive(t, r) {
  132. if ("object" != typeof t || !t) return t;
  133. var e = t[Symbol.toPrimitive];
  134. if (void 0 !== e) {
  135. var i = e.call(t, r || "default");
  136. if ("object" != typeof i) return i;
  137. throw new TypeError("@@toPrimitive must return a primitive value.");
  138. }
  139. return ("string" === r ? String : Number)(t);
  140. }
  141. function _toPropertyKey(t) {
  142. var i = _toPrimitive(t, "string");
  143. return "symbol" == typeof i ? i : i + "";
  144. }
  145. function _typeof(o) {
  146. "@babel/helpers - typeof";
  147. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  148. return typeof o;
  149. } : function (o) {
  150. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  151. }, _typeof(o);
  152. }
  153. function _unsupportedIterableToArray(r, a) {
  154. if (r) {
  155. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  156. var t = {}.toString.call(r).slice(8, -1);
  157. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  158. }
  159. }
  160. function _wrapNativeSuper(t) {
  161. var r = "function" == typeof Map ? new Map() : void 0;
  162. return _wrapNativeSuper = function (t) {
  163. if (null === t || !_isNativeFunction(t)) return t;
  164. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  165. if (void 0 !== r) {
  166. if (r.has(t)) return r.get(t);
  167. r.set(t, Wrapper);
  168. }
  169. function Wrapper() {
  170. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  171. }
  172. return Wrapper.prototype = Object.create(t.prototype, {
  173. constructor: {
  174. value: Wrapper,
  175. enumerable: !1,
  176. writable: !0,
  177. configurable: !0
  178. }
  179. }), _setPrototypeOf(Wrapper, t);
  180. }, _wrapNativeSuper(t);
  181. }
  182. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  183. PACKET_TYPES["open"] = "0";
  184. PACKET_TYPES["close"] = "1";
  185. PACKET_TYPES["ping"] = "2";
  186. PACKET_TYPES["pong"] = "3";
  187. PACKET_TYPES["message"] = "4";
  188. PACKET_TYPES["upgrade"] = "5";
  189. PACKET_TYPES["noop"] = "6";
  190. var PACKET_TYPES_REVERSE = Object.create(null);
  191. Object.keys(PACKET_TYPES).forEach(function (key) {
  192. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  193. });
  194. var ERROR_PACKET = {
  195. type: "error",
  196. data: "parser error"
  197. };
  198. var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  199. var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
  200. // ArrayBuffer.isView method is not defined in IE10
  201. var isView$1 = function isView(obj) {
  202. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  203. };
  204. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  205. var type = _ref.type,
  206. data = _ref.data;
  207. if (withNativeBlob$1 && data instanceof Blob) {
  208. if (supportsBinary) {
  209. return callback(data);
  210. } else {
  211. return encodeBlobAsBase64(data, callback);
  212. }
  213. } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
  214. if (supportsBinary) {
  215. return callback(data);
  216. } else {
  217. return encodeBlobAsBase64(new Blob([data]), callback);
  218. }
  219. }
  220. // plain string
  221. return callback(PACKET_TYPES[type] + (data || ""));
  222. };
  223. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  224. var fileReader = new FileReader();
  225. fileReader.onload = function () {
  226. var content = fileReader.result.split(",")[1];
  227. callback("b" + (content || ""));
  228. };
  229. return fileReader.readAsDataURL(data);
  230. };
  231. function toArray(data) {
  232. if (data instanceof Uint8Array) {
  233. return data;
  234. } else if (data instanceof ArrayBuffer) {
  235. return new Uint8Array(data);
  236. } else {
  237. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  238. }
  239. }
  240. var TEXT_ENCODER;
  241. function encodePacketToBinary(packet, callback) {
  242. if (withNativeBlob$1 && packet.data instanceof Blob) {
  243. return packet.data.arrayBuffer().then(toArray).then(callback);
  244. } else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
  245. return callback(toArray(packet.data));
  246. }
  247. encodePacket(packet, false, function (encoded) {
  248. if (!TEXT_ENCODER) {
  249. TEXT_ENCODER = new TextEncoder();
  250. }
  251. callback(TEXT_ENCODER.encode(encoded));
  252. });
  253. }
  254. // imported from https://github.com/socketio/base64-arraybuffer
  255. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  256. // Use a lookup table to find the index.
  257. var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  258. for (var i = 0; i < chars.length; i++) {
  259. lookup$1[chars.charCodeAt(i)] = i;
  260. }
  261. var decode$1 = function decode(base64) {
  262. var bufferLength = base64.length * 0.75,
  263. len = base64.length,
  264. i,
  265. p = 0,
  266. encoded1,
  267. encoded2,
  268. encoded3,
  269. encoded4;
  270. if (base64[base64.length - 1] === '=') {
  271. bufferLength--;
  272. if (base64[base64.length - 2] === '=') {
  273. bufferLength--;
  274. }
  275. }
  276. var arraybuffer = new ArrayBuffer(bufferLength),
  277. bytes = new Uint8Array(arraybuffer);
  278. for (i = 0; i < len; i += 4) {
  279. encoded1 = lookup$1[base64.charCodeAt(i)];
  280. encoded2 = lookup$1[base64.charCodeAt(i + 1)];
  281. encoded3 = lookup$1[base64.charCodeAt(i + 2)];
  282. encoded4 = lookup$1[base64.charCodeAt(i + 3)];
  283. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  284. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  285. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  286. }
  287. return arraybuffer;
  288. };
  289. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  290. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  291. if (typeof encodedPacket !== "string") {
  292. return {
  293. type: "message",
  294. data: mapBinary(encodedPacket, binaryType)
  295. };
  296. }
  297. var type = encodedPacket.charAt(0);
  298. if (type === "b") {
  299. return {
  300. type: "message",
  301. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  302. };
  303. }
  304. var packetType = PACKET_TYPES_REVERSE[type];
  305. if (!packetType) {
  306. return ERROR_PACKET;
  307. }
  308. return encodedPacket.length > 1 ? {
  309. type: PACKET_TYPES_REVERSE[type],
  310. data: encodedPacket.substring(1)
  311. } : {
  312. type: PACKET_TYPES_REVERSE[type]
  313. };
  314. };
  315. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  316. if (withNativeArrayBuffer$1) {
  317. var decoded = decode$1(data);
  318. return mapBinary(decoded, binaryType);
  319. } else {
  320. return {
  321. base64: true,
  322. data: data
  323. }; // fallback for old browsers
  324. }
  325. };
  326. var mapBinary = function mapBinary(data, binaryType) {
  327. switch (binaryType) {
  328. case "blob":
  329. if (data instanceof Blob) {
  330. // from WebSocket + binaryType "blob"
  331. return data;
  332. } else {
  333. // from HTTP long-polling or WebTransport
  334. return new Blob([data]);
  335. }
  336. case "arraybuffer":
  337. default:
  338. if (data instanceof ArrayBuffer) {
  339. // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
  340. return data;
  341. } else {
  342. // from WebTransport (Uint8Array)
  343. return data.buffer;
  344. }
  345. }
  346. };
  347. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  348. var encodePayload = function encodePayload(packets, callback) {
  349. // some packets may be added to the array while encoding, so the initial length must be saved
  350. var length = packets.length;
  351. var encodedPackets = new Array(length);
  352. var count = 0;
  353. packets.forEach(function (packet, i) {
  354. // force base64 encoding for binary packets
  355. encodePacket(packet, false, function (encodedPacket) {
  356. encodedPackets[i] = encodedPacket;
  357. if (++count === length) {
  358. callback(encodedPackets.join(SEPARATOR));
  359. }
  360. });
  361. });
  362. };
  363. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  364. var encodedPackets = encodedPayload.split(SEPARATOR);
  365. var packets = [];
  366. for (var i = 0; i < encodedPackets.length; i++) {
  367. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  368. packets.push(decodedPacket);
  369. if (decodedPacket.type === "error") {
  370. break;
  371. }
  372. }
  373. return packets;
  374. };
  375. function createPacketEncoderStream() {
  376. return new TransformStream({
  377. transform: function transform(packet, controller) {
  378. encodePacketToBinary(packet, function (encodedPacket) {
  379. var payloadLength = encodedPacket.length;
  380. var header;
  381. // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
  382. if (payloadLength < 126) {
  383. header = new Uint8Array(1);
  384. new DataView(header.buffer).setUint8(0, payloadLength);
  385. } else if (payloadLength < 65536) {
  386. header = new Uint8Array(3);
  387. var view = new DataView(header.buffer);
  388. view.setUint8(0, 126);
  389. view.setUint16(1, payloadLength);
  390. } else {
  391. header = new Uint8Array(9);
  392. var _view = new DataView(header.buffer);
  393. _view.setUint8(0, 127);
  394. _view.setBigUint64(1, BigInt(payloadLength));
  395. }
  396. // first bit indicates whether the payload is plain text (0) or binary (1)
  397. if (packet.data && typeof packet.data !== "string") {
  398. header[0] |= 0x80;
  399. }
  400. controller.enqueue(header);
  401. controller.enqueue(encodedPacket);
  402. });
  403. }
  404. });
  405. }
  406. var TEXT_DECODER;
  407. function totalLength(chunks) {
  408. return chunks.reduce(function (acc, chunk) {
  409. return acc + chunk.length;
  410. }, 0);
  411. }
  412. function concatChunks(chunks, size) {
  413. if (chunks[0].length === size) {
  414. return chunks.shift();
  415. }
  416. var buffer = new Uint8Array(size);
  417. var j = 0;
  418. for (var i = 0; i < size; i++) {
  419. buffer[i] = chunks[0][j++];
  420. if (j === chunks[0].length) {
  421. chunks.shift();
  422. j = 0;
  423. }
  424. }
  425. if (chunks.length && j < chunks[0].length) {
  426. chunks[0] = chunks[0].slice(j);
  427. }
  428. return buffer;
  429. }
  430. function createPacketDecoderStream(maxPayload, binaryType) {
  431. if (!TEXT_DECODER) {
  432. TEXT_DECODER = new TextDecoder();
  433. }
  434. var chunks = [];
  435. var state = 0 /* State.READ_HEADER */;
  436. var expectedLength = -1;
  437. var isBinary = false;
  438. return new TransformStream({
  439. transform: function transform(chunk, controller) {
  440. chunks.push(chunk);
  441. while (true) {
  442. if (state === 0 /* State.READ_HEADER */) {
  443. if (totalLength(chunks) < 1) {
  444. break;
  445. }
  446. var header = concatChunks(chunks, 1);
  447. isBinary = (header[0] & 0x80) === 0x80;
  448. expectedLength = header[0] & 0x7f;
  449. if (expectedLength < 126) {
  450. state = 3 /* State.READ_PAYLOAD */;
  451. } else if (expectedLength === 126) {
  452. state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
  453. } else {
  454. state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
  455. }
  456. } else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
  457. if (totalLength(chunks) < 2) {
  458. break;
  459. }
  460. var headerArray = concatChunks(chunks, 2);
  461. expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
  462. state = 3 /* State.READ_PAYLOAD */;
  463. } else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
  464. if (totalLength(chunks) < 8) {
  465. break;
  466. }
  467. var _headerArray = concatChunks(chunks, 8);
  468. var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length);
  469. var n = view.getUint32(0);
  470. if (n > Math.pow(2, 53 - 32) - 1) {
  471. // the maximum safe integer in JavaScript is 2^53 - 1
  472. controller.enqueue(ERROR_PACKET);
  473. break;
  474. }
  475. expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
  476. state = 3 /* State.READ_PAYLOAD */;
  477. } else {
  478. if (totalLength(chunks) < expectedLength) {
  479. break;
  480. }
  481. var data = concatChunks(chunks, expectedLength);
  482. controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
  483. state = 0 /* State.READ_HEADER */;
  484. }
  485. if (expectedLength === 0 || expectedLength > maxPayload) {
  486. controller.enqueue(ERROR_PACKET);
  487. break;
  488. }
  489. }
  490. }
  491. });
  492. }
  493. var protocol$1 = 4;
  494. /**
  495. * Initialize a new `Emitter`.
  496. *
  497. * @api public
  498. */
  499. function Emitter(obj) {
  500. if (obj) return mixin(obj);
  501. }
  502. /**
  503. * Mixin the emitter properties.
  504. *
  505. * @param {Object} obj
  506. * @return {Object}
  507. * @api private
  508. */
  509. function mixin(obj) {
  510. for (var key in Emitter.prototype) {
  511. obj[key] = Emitter.prototype[key];
  512. }
  513. return obj;
  514. }
  515. /**
  516. * Listen on the given `event` with `fn`.
  517. *
  518. * @param {String} event
  519. * @param {Function} fn
  520. * @return {Emitter}
  521. * @api public
  522. */
  523. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  524. this._callbacks = this._callbacks || {};
  525. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  526. return this;
  527. };
  528. /**
  529. * Adds an `event` listener that will be invoked a single
  530. * time then automatically removed.
  531. *
  532. * @param {String} event
  533. * @param {Function} fn
  534. * @return {Emitter}
  535. * @api public
  536. */
  537. Emitter.prototype.once = function (event, fn) {
  538. function on() {
  539. this.off(event, on);
  540. fn.apply(this, arguments);
  541. }
  542. on.fn = fn;
  543. this.on(event, on);
  544. return this;
  545. };
  546. /**
  547. * Remove the given callback for `event` or all
  548. * registered callbacks.
  549. *
  550. * @param {String} event
  551. * @param {Function} fn
  552. * @return {Emitter}
  553. * @api public
  554. */
  555. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  556. this._callbacks = this._callbacks || {};
  557. // all
  558. if (0 == arguments.length) {
  559. this._callbacks = {};
  560. return this;
  561. }
  562. // specific event
  563. var callbacks = this._callbacks['$' + event];
  564. if (!callbacks) return this;
  565. // remove all handlers
  566. if (1 == arguments.length) {
  567. delete this._callbacks['$' + event];
  568. return this;
  569. }
  570. // remove specific handler
  571. var cb;
  572. for (var i = 0; i < callbacks.length; i++) {
  573. cb = callbacks[i];
  574. if (cb === fn || cb.fn === fn) {
  575. callbacks.splice(i, 1);
  576. break;
  577. }
  578. }
  579. // Remove event specific arrays for event types that no
  580. // one is subscribed for to avoid memory leak.
  581. if (callbacks.length === 0) {
  582. delete this._callbacks['$' + event];
  583. }
  584. return this;
  585. };
  586. /**
  587. * Emit `event` with the given args.
  588. *
  589. * @param {String} event
  590. * @param {Mixed} ...
  591. * @return {Emitter}
  592. */
  593. Emitter.prototype.emit = function (event) {
  594. this._callbacks = this._callbacks || {};
  595. var args = new Array(arguments.length - 1),
  596. callbacks = this._callbacks['$' + event];
  597. for (var i = 1; i < arguments.length; i++) {
  598. args[i - 1] = arguments[i];
  599. }
  600. if (callbacks) {
  601. callbacks = callbacks.slice(0);
  602. for (var i = 0, len = callbacks.length; i < len; ++i) {
  603. callbacks[i].apply(this, args);
  604. }
  605. }
  606. return this;
  607. };
  608. // alias used for reserved events (protected method)
  609. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  610. /**
  611. * Return array of callbacks for `event`.
  612. *
  613. * @param {String} event
  614. * @return {Array}
  615. * @api public
  616. */
  617. Emitter.prototype.listeners = function (event) {
  618. this._callbacks = this._callbacks || {};
  619. return this._callbacks['$' + event] || [];
  620. };
  621. /**
  622. * Check if this emitter has `event` handlers.
  623. *
  624. * @param {String} event
  625. * @return {Boolean}
  626. * @api public
  627. */
  628. Emitter.prototype.hasListeners = function (event) {
  629. return !!this.listeners(event).length;
  630. };
  631. var nextTick = function () {
  632. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  633. if (isPromiseAvailable) {
  634. return function (cb) {
  635. return Promise.resolve().then(cb);
  636. };
  637. } else {
  638. return function (cb, setTimeoutFn) {
  639. return setTimeoutFn(cb, 0);
  640. };
  641. }
  642. }();
  643. var globalThisShim = function () {
  644. if (typeof self !== "undefined") {
  645. return self;
  646. } else if (typeof window !== "undefined") {
  647. return window;
  648. } else {
  649. return Function("return this")();
  650. }
  651. }();
  652. var defaultBinaryType = "arraybuffer";
  653. function createCookieJar() {}
  654. function pick(obj) {
  655. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  656. attr[_key - 1] = arguments[_key];
  657. }
  658. return attr.reduce(function (acc, k) {
  659. if (obj.hasOwnProperty(k)) {
  660. acc[k] = obj[k];
  661. }
  662. return acc;
  663. }, {});
  664. }
  665. // Keep a reference to the real timeout functions so they can be used when overridden
  666. var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
  667. var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
  668. function installTimerFunctions(obj, opts) {
  669. if (opts.useNativeTimers) {
  670. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
  671. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
  672. } else {
  673. obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
  674. obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
  675. }
  676. }
  677. // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  678. var BASE64_OVERHEAD = 1.33;
  679. // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  680. function byteLength(obj) {
  681. if (typeof obj === "string") {
  682. return utf8Length(obj);
  683. }
  684. // arraybuffer or blob
  685. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  686. }
  687. function utf8Length(str) {
  688. var c = 0,
  689. length = 0;
  690. for (var i = 0, l = str.length; i < l; i++) {
  691. c = str.charCodeAt(i);
  692. if (c < 0x80) {
  693. length += 1;
  694. } else if (c < 0x800) {
  695. length += 2;
  696. } else if (c < 0xd800 || c >= 0xe000) {
  697. length += 3;
  698. } else {
  699. i++;
  700. length += 4;
  701. }
  702. }
  703. return length;
  704. }
  705. /**
  706. * Generates a random 8-characters string.
  707. */
  708. function randomString() {
  709. return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
  710. }
  711. // imported from https://github.com/galkn/querystring
  712. /**
  713. * Compiles a querystring
  714. * Returns string representation of the object
  715. *
  716. * @param {Object}
  717. * @api private
  718. */
  719. function encode(obj) {
  720. var str = '';
  721. for (var i in obj) {
  722. if (obj.hasOwnProperty(i)) {
  723. if (str.length) str += '&';
  724. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  725. }
  726. }
  727. return str;
  728. }
  729. /**
  730. * Parses a simple querystring into an object
  731. *
  732. * @param {String} qs
  733. * @api private
  734. */
  735. function decode(qs) {
  736. var qry = {};
  737. var pairs = qs.split('&');
  738. for (var i = 0, l = pairs.length; i < l; i++) {
  739. var pair = pairs[i].split('=');
  740. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  741. }
  742. return qry;
  743. }
  744. var TransportError = /*#__PURE__*/function (_Error) {
  745. function TransportError(reason, description, context) {
  746. var _this;
  747. _this = _Error.call(this, reason) || this;
  748. _this.description = description;
  749. _this.context = context;
  750. _this.type = "TransportError";
  751. return _this;
  752. }
  753. _inheritsLoose(TransportError, _Error);
  754. return TransportError;
  755. }( /*#__PURE__*/_wrapNativeSuper(Error));
  756. var Transport = /*#__PURE__*/function (_Emitter) {
  757. /**
  758. * Transport abstract constructor.
  759. *
  760. * @param {Object} opts - options
  761. * @protected
  762. */
  763. function Transport(opts) {
  764. var _this2;
  765. _this2 = _Emitter.call(this) || this;
  766. _this2.writable = false;
  767. installTimerFunctions(_this2, opts);
  768. _this2.opts = opts;
  769. _this2.query = opts.query;
  770. _this2.socket = opts.socket;
  771. _this2.supportsBinary = !opts.forceBase64;
  772. return _this2;
  773. }
  774. /**
  775. * Emits an error.
  776. *
  777. * @param {String} reason
  778. * @param description
  779. * @param context - the error context
  780. * @return {Transport} for chaining
  781. * @protected
  782. */
  783. _inheritsLoose(Transport, _Emitter);
  784. var _proto = Transport.prototype;
  785. _proto.onError = function onError(reason, description, context) {
  786. _Emitter.prototype.emitReserved.call(this, "error", new TransportError(reason, description, context));
  787. return this;
  788. }
  789. /**
  790. * Opens the transport.
  791. */;
  792. _proto.open = function open() {
  793. this.readyState = "opening";
  794. this.doOpen();
  795. return this;
  796. }
  797. /**
  798. * Closes the transport.
  799. */;
  800. _proto.close = function close() {
  801. if (this.readyState === "opening" || this.readyState === "open") {
  802. this.doClose();
  803. this.onClose();
  804. }
  805. return this;
  806. }
  807. /**
  808. * Sends multiple packets.
  809. *
  810. * @param {Array} packets
  811. */;
  812. _proto.send = function send(packets) {
  813. if (this.readyState === "open") {
  814. this.write(packets);
  815. }
  816. }
  817. /**
  818. * Called upon open
  819. *
  820. * @protected
  821. */;
  822. _proto.onOpen = function onOpen() {
  823. this.readyState = "open";
  824. this.writable = true;
  825. _Emitter.prototype.emitReserved.call(this, "open");
  826. }
  827. /**
  828. * Called with data.
  829. *
  830. * @param {String} data
  831. * @protected
  832. */;
  833. _proto.onData = function onData(data) {
  834. var packet = decodePacket(data, this.socket.binaryType);
  835. this.onPacket(packet);
  836. }
  837. /**
  838. * Called with a decoded packet.
  839. *
  840. * @protected
  841. */;
  842. _proto.onPacket = function onPacket(packet) {
  843. _Emitter.prototype.emitReserved.call(this, "packet", packet);
  844. }
  845. /**
  846. * Called upon close.
  847. *
  848. * @protected
  849. */;
  850. _proto.onClose = function onClose(details) {
  851. this.readyState = "closed";
  852. _Emitter.prototype.emitReserved.call(this, "close", details);
  853. }
  854. /**
  855. * Pauses the transport, in order not to lose packets during an upgrade.
  856. *
  857. * @param onPause
  858. */;
  859. _proto.pause = function pause(onPause) {};
  860. _proto.createUri = function createUri(schema) {
  861. var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  862. return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
  863. };
  864. _proto._hostname = function _hostname() {
  865. var hostname = this.opts.hostname;
  866. return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
  867. };
  868. _proto._port = function _port() {
  869. if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
  870. return ":" + this.opts.port;
  871. } else {
  872. return "";
  873. }
  874. };
  875. _proto._query = function _query(query) {
  876. var encodedQuery = encode(query);
  877. return encodedQuery.length ? "?" + encodedQuery : "";
  878. };
  879. return Transport;
  880. }(Emitter);
  881. var Polling = /*#__PURE__*/function (_Transport) {
  882. function Polling() {
  883. var _this;
  884. _this = _Transport.apply(this, arguments) || this;
  885. _this._polling = false;
  886. return _this;
  887. }
  888. _inheritsLoose(Polling, _Transport);
  889. var _proto = Polling.prototype;
  890. /**
  891. * Opens the socket (triggers polling). We write a PING message to determine
  892. * when the transport is open.
  893. *
  894. * @protected
  895. */
  896. _proto.doOpen = function doOpen() {
  897. this._poll();
  898. }
  899. /**
  900. * Pauses polling.
  901. *
  902. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  903. * @package
  904. */;
  905. _proto.pause = function pause(onPause) {
  906. var _this2 = this;
  907. this.readyState = "pausing";
  908. var pause = function pause() {
  909. _this2.readyState = "paused";
  910. onPause();
  911. };
  912. if (this._polling || !this.writable) {
  913. var total = 0;
  914. if (this._polling) {
  915. total++;
  916. this.once("pollComplete", function () {
  917. --total || pause();
  918. });
  919. }
  920. if (!this.writable) {
  921. total++;
  922. this.once("drain", function () {
  923. --total || pause();
  924. });
  925. }
  926. } else {
  927. pause();
  928. }
  929. }
  930. /**
  931. * Starts polling cycle.
  932. *
  933. * @private
  934. */;
  935. _proto._poll = function _poll() {
  936. this._polling = true;
  937. this.doPoll();
  938. this.emitReserved("poll");
  939. }
  940. /**
  941. * Overloads onData to detect payloads.
  942. *
  943. * @protected
  944. */;
  945. _proto.onData = function onData(data) {
  946. var _this3 = this;
  947. var callback = function callback(packet) {
  948. // if its the first message we consider the transport open
  949. if ("opening" === _this3.readyState && packet.type === "open") {
  950. _this3.onOpen();
  951. }
  952. // if its a close packet, we close the ongoing requests
  953. if ("close" === packet.type) {
  954. _this3.onClose({
  955. description: "transport closed by the server"
  956. });
  957. return false;
  958. }
  959. // otherwise bypass onData and handle the message
  960. _this3.onPacket(packet);
  961. };
  962. // decode payload
  963. decodePayload(data, this.socket.binaryType).forEach(callback);
  964. // if an event did not trigger closing
  965. if ("closed" !== this.readyState) {
  966. // if we got data we're not polling
  967. this._polling = false;
  968. this.emitReserved("pollComplete");
  969. if ("open" === this.readyState) {
  970. this._poll();
  971. }
  972. }
  973. }
  974. /**
  975. * For polling, send a close packet.
  976. *
  977. * @protected
  978. */;
  979. _proto.doClose = function doClose() {
  980. var _this4 = this;
  981. var close = function close() {
  982. _this4.write([{
  983. type: "close"
  984. }]);
  985. };
  986. if ("open" === this.readyState) {
  987. close();
  988. } else {
  989. // in case we're trying to close while
  990. // handshaking is in progress (GH-164)
  991. this.once("open", close);
  992. }
  993. }
  994. /**
  995. * Writes a packets payload.
  996. *
  997. * @param {Array} packets - data packets
  998. * @protected
  999. */;
  1000. _proto.write = function write(packets) {
  1001. var _this5 = this;
  1002. this.writable = false;
  1003. encodePayload(packets, function (data) {
  1004. _this5.doWrite(data, function () {
  1005. _this5.writable = true;
  1006. _this5.emitReserved("drain");
  1007. });
  1008. });
  1009. }
  1010. /**
  1011. * Generates uri for connection.
  1012. *
  1013. * @private
  1014. */;
  1015. _proto.uri = function uri() {
  1016. var schema = this.opts.secure ? "https" : "http";
  1017. var query = this.query || {};
  1018. // cache busting is forced
  1019. if (false !== this.opts.timestampRequests) {
  1020. query[this.opts.timestampParam] = randomString();
  1021. }
  1022. if (!this.supportsBinary && !query.sid) {
  1023. query.b64 = 1;
  1024. }
  1025. return this.createUri(schema, query);
  1026. };
  1027. return _createClass(Polling, [{
  1028. key: "name",
  1029. get: function get() {
  1030. return "polling";
  1031. }
  1032. }]);
  1033. }(Transport);
  1034. // imported from https://github.com/component/has-cors
  1035. var value = false;
  1036. try {
  1037. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  1038. } catch (err) {
  1039. // if XMLHttp support is disabled in IE then it will throw
  1040. // when trying to create
  1041. }
  1042. var hasCORS = value;
  1043. function empty() {}
  1044. var BaseXHR = /*#__PURE__*/function (_Polling) {
  1045. /**
  1046. * XHR Polling constructor.
  1047. *
  1048. * @param {Object} opts
  1049. * @package
  1050. */
  1051. function BaseXHR(opts) {
  1052. var _this;
  1053. _this = _Polling.call(this, opts) || this;
  1054. if (typeof location !== "undefined") {
  1055. var isSSL = "https:" === location.protocol;
  1056. var port = location.port;
  1057. // some user agents have empty `location.port`
  1058. if (!port) {
  1059. port = isSSL ? "443" : "80";
  1060. }
  1061. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  1062. }
  1063. return _this;
  1064. }
  1065. /**
  1066. * Sends data.
  1067. *
  1068. * @param {String} data to send.
  1069. * @param {Function} called upon flush.
  1070. * @private
  1071. */
  1072. _inheritsLoose(BaseXHR, _Polling);
  1073. var _proto = BaseXHR.prototype;
  1074. _proto.doWrite = function doWrite(data, fn) {
  1075. var _this2 = this;
  1076. var req = this.request({
  1077. method: "POST",
  1078. data: data
  1079. });
  1080. req.on("success", fn);
  1081. req.on("error", function (xhrStatus, context) {
  1082. _this2.onError("xhr post error", xhrStatus, context);
  1083. });
  1084. }
  1085. /**
  1086. * Starts a poll cycle.
  1087. *
  1088. * @private
  1089. */;
  1090. _proto.doPoll = function doPoll() {
  1091. var _this3 = this;
  1092. var req = this.request();
  1093. req.on("data", this.onData.bind(this));
  1094. req.on("error", function (xhrStatus, context) {
  1095. _this3.onError("xhr poll error", xhrStatus, context);
  1096. });
  1097. this.pollXhr = req;
  1098. };
  1099. return BaseXHR;
  1100. }(Polling);
  1101. var Request = /*#__PURE__*/function (_Emitter) {
  1102. /**
  1103. * Request constructor
  1104. *
  1105. * @param {Object} options
  1106. * @package
  1107. */
  1108. function Request(createRequest, uri, opts) {
  1109. var _this4;
  1110. _this4 = _Emitter.call(this) || this;
  1111. _this4.createRequest = createRequest;
  1112. installTimerFunctions(_this4, opts);
  1113. _this4._opts = opts;
  1114. _this4._method = opts.method || "GET";
  1115. _this4._uri = uri;
  1116. _this4._data = undefined !== opts.data ? opts.data : null;
  1117. _this4._create();
  1118. return _this4;
  1119. }
  1120. /**
  1121. * Creates the XHR object and sends the request.
  1122. *
  1123. * @private
  1124. */
  1125. _inheritsLoose(Request, _Emitter);
  1126. var _proto2 = Request.prototype;
  1127. _proto2._create = function _create() {
  1128. var _this5 = this;
  1129. var _a;
  1130. var opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1131. opts.xdomain = !!this._opts.xd;
  1132. var xhr = this._xhr = this.createRequest(opts);
  1133. try {
  1134. xhr.open(this._method, this._uri, true);
  1135. try {
  1136. if (this._opts.extraHeaders) {
  1137. // @ts-ignore
  1138. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1139. for (var i in this._opts.extraHeaders) {
  1140. if (this._opts.extraHeaders.hasOwnProperty(i)) {
  1141. xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
  1142. }
  1143. }
  1144. }
  1145. } catch (e) {}
  1146. if ("POST" === this._method) {
  1147. try {
  1148. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1149. } catch (e) {}
  1150. }
  1151. try {
  1152. xhr.setRequestHeader("Accept", "*/*");
  1153. } catch (e) {}
  1154. (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  1155. // ie6 check
  1156. if ("withCredentials" in xhr) {
  1157. xhr.withCredentials = this._opts.withCredentials;
  1158. }
  1159. if (this._opts.requestTimeout) {
  1160. xhr.timeout = this._opts.requestTimeout;
  1161. }
  1162. xhr.onreadystatechange = function () {
  1163. var _a;
  1164. if (xhr.readyState === 3) {
  1165. (_a = _this5._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
  1166. // @ts-ignore
  1167. xhr.getResponseHeader("set-cookie"));
  1168. }
  1169. if (4 !== xhr.readyState) return;
  1170. if (200 === xhr.status || 1223 === xhr.status) {
  1171. _this5._onLoad();
  1172. } else {
  1173. // make sure the `error` event handler that's user-set
  1174. // does not throw in the same tick and gets caught here
  1175. _this5.setTimeoutFn(function () {
  1176. _this5._onError(typeof xhr.status === "number" ? xhr.status : 0);
  1177. }, 0);
  1178. }
  1179. };
  1180. xhr.send(this._data);
  1181. } catch (e) {
  1182. // Need to defer since .create() is called directly from the constructor
  1183. // and thus the 'error' event can only be only bound *after* this exception
  1184. // occurs. Therefore, also, we cannot throw here at all.
  1185. this.setTimeoutFn(function () {
  1186. _this5._onError(e);
  1187. }, 0);
  1188. return;
  1189. }
  1190. if (typeof document !== "undefined") {
  1191. this._index = Request.requestsCount++;
  1192. Request.requests[this._index] = this;
  1193. }
  1194. }
  1195. /**
  1196. * Called upon error.
  1197. *
  1198. * @private
  1199. */;
  1200. _proto2._onError = function _onError(err) {
  1201. this.emitReserved("error", err, this._xhr);
  1202. this._cleanup(true);
  1203. }
  1204. /**
  1205. * Cleans up house.
  1206. *
  1207. * @private
  1208. */;
  1209. _proto2._cleanup = function _cleanup(fromError) {
  1210. if ("undefined" === typeof this._xhr || null === this._xhr) {
  1211. return;
  1212. }
  1213. this._xhr.onreadystatechange = empty;
  1214. if (fromError) {
  1215. try {
  1216. this._xhr.abort();
  1217. } catch (e) {}
  1218. }
  1219. if (typeof document !== "undefined") {
  1220. delete Request.requests[this._index];
  1221. }
  1222. this._xhr = null;
  1223. }
  1224. /**
  1225. * Called upon load.
  1226. *
  1227. * @private
  1228. */;
  1229. _proto2._onLoad = function _onLoad() {
  1230. var data = this._xhr.responseText;
  1231. if (data !== null) {
  1232. this.emitReserved("data", data);
  1233. this.emitReserved("success");
  1234. this._cleanup();
  1235. }
  1236. }
  1237. /**
  1238. * Aborts the request.
  1239. *
  1240. * @package
  1241. */;
  1242. _proto2.abort = function abort() {
  1243. this._cleanup();
  1244. };
  1245. return Request;
  1246. }(Emitter);
  1247. Request.requestsCount = 0;
  1248. Request.requests = {};
  1249. /**
  1250. * Aborts pending requests when unloading the window. This is needed to prevent
  1251. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1252. * emitted.
  1253. */
  1254. if (typeof document !== "undefined") {
  1255. // @ts-ignore
  1256. if (typeof attachEvent === "function") {
  1257. // @ts-ignore
  1258. attachEvent("onunload", unloadHandler);
  1259. } else if (typeof addEventListener === "function") {
  1260. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1261. addEventListener(terminationEvent, unloadHandler, false);
  1262. }
  1263. }
  1264. function unloadHandler() {
  1265. for (var i in Request.requests) {
  1266. if (Request.requests.hasOwnProperty(i)) {
  1267. Request.requests[i].abort();
  1268. }
  1269. }
  1270. }
  1271. var hasXHR2 = function () {
  1272. var xhr = newRequest({
  1273. xdomain: false
  1274. });
  1275. return xhr && xhr.responseType !== null;
  1276. }();
  1277. /**
  1278. * HTTP long-polling based on the built-in `XMLHttpRequest` object.
  1279. *
  1280. * Usage: browser
  1281. *
  1282. * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  1283. */
  1284. var XHR = /*#__PURE__*/function (_BaseXHR) {
  1285. function XHR(opts) {
  1286. var _this6;
  1287. _this6 = _BaseXHR.call(this, opts) || this;
  1288. var forceBase64 = opts && opts.forceBase64;
  1289. _this6.supportsBinary = hasXHR2 && !forceBase64;
  1290. return _this6;
  1291. }
  1292. _inheritsLoose(XHR, _BaseXHR);
  1293. var _proto3 = XHR.prototype;
  1294. _proto3.request = function request() {
  1295. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1296. _extends(opts, {
  1297. xd: this.xd
  1298. }, this.opts);
  1299. return new Request(newRequest, this.uri(), opts);
  1300. };
  1301. return XHR;
  1302. }(BaseXHR);
  1303. function newRequest(opts) {
  1304. var xdomain = opts.xdomain;
  1305. // XMLHttpRequest can be disabled on IE
  1306. try {
  1307. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  1308. return new XMLHttpRequest();
  1309. }
  1310. } catch (e) {}
  1311. if (!xdomain) {
  1312. try {
  1313. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  1314. } catch (e) {}
  1315. }
  1316. }
  1317. // detect ReactNative environment
  1318. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1319. var BaseWS = /*#__PURE__*/function (_Transport) {
  1320. function BaseWS() {
  1321. return _Transport.apply(this, arguments) || this;
  1322. }
  1323. _inheritsLoose(BaseWS, _Transport);
  1324. var _proto = BaseWS.prototype;
  1325. _proto.doOpen = function doOpen() {
  1326. var uri = this.uri();
  1327. var protocols = this.opts.protocols;
  1328. // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1329. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1330. if (this.opts.extraHeaders) {
  1331. opts.headers = this.opts.extraHeaders;
  1332. }
  1333. try {
  1334. this.ws = this.createSocket(uri, protocols, opts);
  1335. } catch (err) {
  1336. return this.emitReserved("error", err);
  1337. }
  1338. this.ws.binaryType = this.socket.binaryType;
  1339. this.addEventListeners();
  1340. }
  1341. /**
  1342. * Adds event listeners to the socket
  1343. *
  1344. * @private
  1345. */;
  1346. _proto.addEventListeners = function addEventListeners() {
  1347. var _this = this;
  1348. this.ws.onopen = function () {
  1349. if (_this.opts.autoUnref) {
  1350. _this.ws._socket.unref();
  1351. }
  1352. _this.onOpen();
  1353. };
  1354. this.ws.onclose = function (closeEvent) {
  1355. return _this.onClose({
  1356. description: "websocket connection closed",
  1357. context: closeEvent
  1358. });
  1359. };
  1360. this.ws.onmessage = function (ev) {
  1361. return _this.onData(ev.data);
  1362. };
  1363. this.ws.onerror = function (e) {
  1364. return _this.onError("websocket error", e);
  1365. };
  1366. };
  1367. _proto.write = function write(packets) {
  1368. var _this2 = this;
  1369. this.writable = false;
  1370. // encodePacket efficient as it uses WS framing
  1371. // no need for encodePayload
  1372. var _loop = function _loop() {
  1373. var packet = packets[i];
  1374. var lastPacket = i === packets.length - 1;
  1375. encodePacket(packet, _this2.supportsBinary, function (data) {
  1376. // Sometimes the websocket has already been closed but the browser didn't
  1377. // have a chance of informing us about it yet, in that case send will
  1378. // throw an error
  1379. try {
  1380. _this2.doWrite(packet, data);
  1381. } catch (e) {}
  1382. if (lastPacket) {
  1383. // fake drain
  1384. // defer to next tick to allow Socket to clear writeBuffer
  1385. nextTick(function () {
  1386. _this2.writable = true;
  1387. _this2.emitReserved("drain");
  1388. }, _this2.setTimeoutFn);
  1389. }
  1390. });
  1391. };
  1392. for (var i = 0; i < packets.length; i++) {
  1393. _loop();
  1394. }
  1395. };
  1396. _proto.doClose = function doClose() {
  1397. if (typeof this.ws !== "undefined") {
  1398. this.ws.onerror = function () {};
  1399. this.ws.close();
  1400. this.ws = null;
  1401. }
  1402. }
  1403. /**
  1404. * Generates uri for connection.
  1405. *
  1406. * @private
  1407. */;
  1408. _proto.uri = function uri() {
  1409. var schema = this.opts.secure ? "wss" : "ws";
  1410. var query = this.query || {};
  1411. // append timestamp to URI
  1412. if (this.opts.timestampRequests) {
  1413. query[this.opts.timestampParam] = randomString();
  1414. }
  1415. // communicate binary support capabilities
  1416. if (!this.supportsBinary) {
  1417. query.b64 = 1;
  1418. }
  1419. return this.createUri(schema, query);
  1420. };
  1421. return _createClass(BaseWS, [{
  1422. key: "name",
  1423. get: function get() {
  1424. return "websocket";
  1425. }
  1426. }]);
  1427. }(Transport);
  1428. var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  1429. /**
  1430. * WebSocket transport based on the built-in `WebSocket` object.
  1431. *
  1432. * Usage: browser, Node.js (since v21), Deno, Bun
  1433. *
  1434. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
  1435. * @see https://caniuse.com/mdn-api_websocket
  1436. * @see https://nodejs.org/api/globals.html#websocket
  1437. */
  1438. var WS = /*#__PURE__*/function (_BaseWS) {
  1439. function WS() {
  1440. return _BaseWS.apply(this, arguments) || this;
  1441. }
  1442. _inheritsLoose(WS, _BaseWS);
  1443. var _proto2 = WS.prototype;
  1444. _proto2.createSocket = function createSocket(uri, protocols, opts) {
  1445. return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
  1446. };
  1447. _proto2.doWrite = function doWrite(_packet, data) {
  1448. this.ws.send(data);
  1449. };
  1450. return WS;
  1451. }(BaseWS);
  1452. /**
  1453. * WebTransport transport based on the built-in `WebTransport` object.
  1454. *
  1455. * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
  1456. *
  1457. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
  1458. * @see https://caniuse.com/webtransport
  1459. */
  1460. var WT = /*#__PURE__*/function (_Transport) {
  1461. function WT() {
  1462. return _Transport.apply(this, arguments) || this;
  1463. }
  1464. _inheritsLoose(WT, _Transport);
  1465. var _proto = WT.prototype;
  1466. _proto.doOpen = function doOpen() {
  1467. var _this = this;
  1468. try {
  1469. // @ts-ignore
  1470. this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  1471. } catch (err) {
  1472. return this.emitReserved("error", err);
  1473. }
  1474. this._transport.closed.then(function () {
  1475. _this.onClose();
  1476. })["catch"](function (err) {
  1477. _this.onError("webtransport error", err);
  1478. });
  1479. // note: we could have used async/await, but that would require some additional polyfills
  1480. this._transport.ready.then(function () {
  1481. _this._transport.createBidirectionalStream().then(function (stream) {
  1482. var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType);
  1483. var reader = stream.readable.pipeThrough(decoderStream).getReader();
  1484. var encoderStream = createPacketEncoderStream();
  1485. encoderStream.readable.pipeTo(stream.writable);
  1486. _this._writer = encoderStream.writable.getWriter();
  1487. var read = function read() {
  1488. reader.read().then(function (_ref) {
  1489. var done = _ref.done,
  1490. value = _ref.value;
  1491. if (done) {
  1492. return;
  1493. }
  1494. _this.onPacket(value);
  1495. read();
  1496. })["catch"](function (err) {});
  1497. };
  1498. read();
  1499. var packet = {
  1500. type: "open"
  1501. };
  1502. if (_this.query.sid) {
  1503. packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}");
  1504. }
  1505. _this._writer.write(packet).then(function () {
  1506. return _this.onOpen();
  1507. });
  1508. });
  1509. });
  1510. };
  1511. _proto.write = function write(packets) {
  1512. var _this2 = this;
  1513. this.writable = false;
  1514. var _loop = function _loop() {
  1515. var packet = packets[i];
  1516. var lastPacket = i === packets.length - 1;
  1517. _this2._writer.write(packet).then(function () {
  1518. if (lastPacket) {
  1519. nextTick(function () {
  1520. _this2.writable = true;
  1521. _this2.emitReserved("drain");
  1522. }, _this2.setTimeoutFn);
  1523. }
  1524. });
  1525. };
  1526. for (var i = 0; i < packets.length; i++) {
  1527. _loop();
  1528. }
  1529. };
  1530. _proto.doClose = function doClose() {
  1531. var _a;
  1532. (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
  1533. };
  1534. return _createClass(WT, [{
  1535. key: "name",
  1536. get: function get() {
  1537. return "webtransport";
  1538. }
  1539. }]);
  1540. }(Transport);
  1541. var transports = {
  1542. websocket: WS,
  1543. webtransport: WT,
  1544. polling: XHR
  1545. };
  1546. // imported from https://github.com/galkn/parseuri
  1547. /**
  1548. * Parses a URI
  1549. *
  1550. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  1551. *
  1552. * See:
  1553. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  1554. * - https://caniuse.com/url
  1555. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  1556. *
  1557. * History of the parse() method:
  1558. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  1559. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  1560. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  1561. *
  1562. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  1563. * @api private
  1564. */
  1565. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  1566. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  1567. function parse(str) {
  1568. if (str.length > 8000) {
  1569. throw "URI too long";
  1570. }
  1571. var src = str,
  1572. b = str.indexOf('['),
  1573. e = str.indexOf(']');
  1574. if (b != -1 && e != -1) {
  1575. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  1576. }
  1577. var m = re.exec(str || ''),
  1578. uri = {},
  1579. i = 14;
  1580. while (i--) {
  1581. uri[parts[i]] = m[i] || '';
  1582. }
  1583. if (b != -1 && e != -1) {
  1584. uri.source = src;
  1585. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  1586. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  1587. uri.ipv6uri = true;
  1588. }
  1589. uri.pathNames = pathNames(uri, uri['path']);
  1590. uri.queryKey = queryKey(uri, uri['query']);
  1591. return uri;
  1592. }
  1593. function pathNames(obj, path) {
  1594. var regx = /\/{2,9}/g,
  1595. names = path.replace(regx, "/").split("/");
  1596. if (path.slice(0, 1) == '/' || path.length === 0) {
  1597. names.splice(0, 1);
  1598. }
  1599. if (path.slice(-1) == '/') {
  1600. names.splice(names.length - 1, 1);
  1601. }
  1602. return names;
  1603. }
  1604. function queryKey(uri, query) {
  1605. var data = {};
  1606. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  1607. if ($1) {
  1608. data[$1] = $2;
  1609. }
  1610. });
  1611. return data;
  1612. }
  1613. var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
  1614. var OFFLINE_EVENT_LISTENERS = [];
  1615. if (withEventListeners) {
  1616. // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
  1617. // script, so we create one single event listener here which will forward the event to the socket instances
  1618. addEventListener("offline", function () {
  1619. OFFLINE_EVENT_LISTENERS.forEach(function (listener) {
  1620. return listener();
  1621. });
  1622. }, false);
  1623. }
  1624. /**
  1625. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  1626. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  1627. *
  1628. * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
  1629. * successfully establishes the connection.
  1630. *
  1631. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  1632. *
  1633. * @example
  1634. * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
  1635. *
  1636. * const socket = new SocketWithoutUpgrade({
  1637. * transports: [WebSocket]
  1638. * });
  1639. *
  1640. * socket.on("open", () => {
  1641. * socket.send("hello");
  1642. * });
  1643. *
  1644. * @see SocketWithUpgrade
  1645. * @see Socket
  1646. */
  1647. var SocketWithoutUpgrade = /*#__PURE__*/function (_Emitter) {
  1648. /**
  1649. * Socket constructor.
  1650. *
  1651. * @param {String|Object} uri - uri or options
  1652. * @param {Object} opts - options
  1653. */
  1654. function SocketWithoutUpgrade(uri, opts) {
  1655. var _this;
  1656. _this = _Emitter.call(this) || this;
  1657. _this.binaryType = defaultBinaryType;
  1658. _this.writeBuffer = [];
  1659. _this._prevBufferLen = 0;
  1660. _this._pingInterval = -1;
  1661. _this._pingTimeout = -1;
  1662. _this._maxPayload = -1;
  1663. /**
  1664. * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
  1665. * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
  1666. */
  1667. _this._pingTimeoutTime = Infinity;
  1668. if (uri && "object" === _typeof(uri)) {
  1669. opts = uri;
  1670. uri = null;
  1671. }
  1672. if (uri) {
  1673. var parsedUri = parse(uri);
  1674. opts.hostname = parsedUri.host;
  1675. opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
  1676. opts.port = parsedUri.port;
  1677. if (parsedUri.query) opts.query = parsedUri.query;
  1678. } else if (opts.host) {
  1679. opts.hostname = parse(opts.host).host;
  1680. }
  1681. installTimerFunctions(_this, opts);
  1682. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  1683. if (opts.hostname && !opts.port) {
  1684. // if no port is specified manually, use the protocol default
  1685. opts.port = _this.secure ? "443" : "80";
  1686. }
  1687. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  1688. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  1689. _this.transports = [];
  1690. _this._transportsByName = {};
  1691. opts.transports.forEach(function (t) {
  1692. var transportName = t.prototype.name;
  1693. _this.transports.push(transportName);
  1694. _this._transportsByName[transportName] = t;
  1695. });
  1696. _this.opts = _extends({
  1697. path: "/engine.io",
  1698. agent: false,
  1699. withCredentials: false,
  1700. upgrade: true,
  1701. timestampParam: "t",
  1702. rememberUpgrade: false,
  1703. addTrailingSlash: true,
  1704. rejectUnauthorized: true,
  1705. perMessageDeflate: {
  1706. threshold: 1024
  1707. },
  1708. transportOptions: {},
  1709. closeOnBeforeunload: false
  1710. }, opts);
  1711. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  1712. if (typeof _this.opts.query === "string") {
  1713. _this.opts.query = decode(_this.opts.query);
  1714. }
  1715. if (withEventListeners) {
  1716. if (_this.opts.closeOnBeforeunload) {
  1717. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  1718. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  1719. // closed/reloaded)
  1720. _this._beforeunloadEventListener = function () {
  1721. if (_this.transport) {
  1722. // silently close the transport
  1723. _this.transport.removeAllListeners();
  1724. _this.transport.close();
  1725. }
  1726. };
  1727. addEventListener("beforeunload", _this._beforeunloadEventListener, false);
  1728. }
  1729. if (_this.hostname !== "localhost") {
  1730. _this._offlineEventListener = function () {
  1731. _this._onClose("transport close", {
  1732. description: "network connection lost"
  1733. });
  1734. };
  1735. OFFLINE_EVENT_LISTENERS.push(_this._offlineEventListener);
  1736. }
  1737. }
  1738. if (_this.opts.withCredentials) {
  1739. _this._cookieJar = createCookieJar();
  1740. }
  1741. _this._open();
  1742. return _this;
  1743. }
  1744. /**
  1745. * Creates transport of the given type.
  1746. *
  1747. * @param {String} name - transport name
  1748. * @return {Transport}
  1749. * @private
  1750. */
  1751. _inheritsLoose(SocketWithoutUpgrade, _Emitter);
  1752. var _proto = SocketWithoutUpgrade.prototype;
  1753. _proto.createTransport = function createTransport(name) {
  1754. var query = _extends({}, this.opts.query);
  1755. // append engine.io protocol identifier
  1756. query.EIO = protocol$1;
  1757. // transport name
  1758. query.transport = name;
  1759. // session id if we already have one
  1760. if (this.id) query.sid = this.id;
  1761. var opts = _extends({}, this.opts, {
  1762. query: query,
  1763. socket: this,
  1764. hostname: this.hostname,
  1765. secure: this.secure,
  1766. port: this.port
  1767. }, this.opts.transportOptions[name]);
  1768. return new this._transportsByName[name](opts);
  1769. }
  1770. /**
  1771. * Initializes transport to use and starts probe.
  1772. *
  1773. * @private
  1774. */;
  1775. _proto._open = function _open() {
  1776. var _this2 = this;
  1777. if (this.transports.length === 0) {
  1778. // Emit error on next tick so it can be listened to
  1779. this.setTimeoutFn(function () {
  1780. _this2.emitReserved("error", "No transports available");
  1781. }, 0);
  1782. return;
  1783. }
  1784. var transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
  1785. this.readyState = "opening";
  1786. var transport = this.createTransport(transportName);
  1787. transport.open();
  1788. this.setTransport(transport);
  1789. }
  1790. /**
  1791. * Sets the current transport. Disables the existing one (if any).
  1792. *
  1793. * @private
  1794. */;
  1795. _proto.setTransport = function setTransport(transport) {
  1796. var _this3 = this;
  1797. if (this.transport) {
  1798. this.transport.removeAllListeners();
  1799. }
  1800. // set up transport
  1801. this.transport = transport;
  1802. // set up transport listeners
  1803. transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", function (reason) {
  1804. return _this3._onClose("transport close", reason);
  1805. });
  1806. }
  1807. /**
  1808. * Called when connection is deemed open.
  1809. *
  1810. * @private
  1811. */;
  1812. _proto.onOpen = function onOpen() {
  1813. this.readyState = "open";
  1814. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
  1815. this.emitReserved("open");
  1816. this.flush();
  1817. }
  1818. /**
  1819. * Handles a packet.
  1820. *
  1821. * @private
  1822. */;
  1823. _proto._onPacket = function _onPacket(packet) {
  1824. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1825. this.emitReserved("packet", packet);
  1826. // Socket is live - any packet counts
  1827. this.emitReserved("heartbeat");
  1828. switch (packet.type) {
  1829. case "open":
  1830. this.onHandshake(JSON.parse(packet.data));
  1831. break;
  1832. case "ping":
  1833. this._sendPacket("pong");
  1834. this.emitReserved("ping");
  1835. this.emitReserved("pong");
  1836. this._resetPingTimeout();
  1837. break;
  1838. case "error":
  1839. var err = new Error("server error");
  1840. // @ts-ignore
  1841. err.code = packet.data;
  1842. this._onError(err);
  1843. break;
  1844. case "message":
  1845. this.emitReserved("data", packet.data);
  1846. this.emitReserved("message", packet.data);
  1847. break;
  1848. }
  1849. }
  1850. }
  1851. /**
  1852. * Called upon handshake completion.
  1853. *
  1854. * @param {Object} data - handshake obj
  1855. * @private
  1856. */;
  1857. _proto.onHandshake = function onHandshake(data) {
  1858. this.emitReserved("handshake", data);
  1859. this.id = data.sid;
  1860. this.transport.query.sid = data.sid;
  1861. this._pingInterval = data.pingInterval;
  1862. this._pingTimeout = data.pingTimeout;
  1863. this._maxPayload = data.maxPayload;
  1864. this.onOpen();
  1865. // In case open handler closes socket
  1866. if ("closed" === this.readyState) return;
  1867. this._resetPingTimeout();
  1868. }
  1869. /**
  1870. * Sets and resets ping timeout timer based on server pings.
  1871. *
  1872. * @private
  1873. */;
  1874. _proto._resetPingTimeout = function _resetPingTimeout() {
  1875. var _this4 = this;
  1876. this.clearTimeoutFn(this._pingTimeoutTimer);
  1877. var delay = this._pingInterval + this._pingTimeout;
  1878. this._pingTimeoutTime = Date.now() + delay;
  1879. this._pingTimeoutTimer = this.setTimeoutFn(function () {
  1880. _this4._onClose("ping timeout");
  1881. }, delay);
  1882. if (this.opts.autoUnref) {
  1883. this._pingTimeoutTimer.unref();
  1884. }
  1885. }
  1886. /**
  1887. * Called on `drain` event
  1888. *
  1889. * @private
  1890. */;
  1891. _proto._onDrain = function _onDrain() {
  1892. this.writeBuffer.splice(0, this._prevBufferLen);
  1893. // setting prevBufferLen = 0 is very important
  1894. // for example, when upgrading, upgrade packet is sent over,
  1895. // and a nonzero prevBufferLen could cause problems on `drain`
  1896. this._prevBufferLen = 0;
  1897. if (0 === this.writeBuffer.length) {
  1898. this.emitReserved("drain");
  1899. } else {
  1900. this.flush();
  1901. }
  1902. }
  1903. /**
  1904. * Flush write buffers.
  1905. *
  1906. * @private
  1907. */;
  1908. _proto.flush = function flush() {
  1909. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  1910. var packets = this._getWritablePackets();
  1911. this.transport.send(packets);
  1912. // keep track of current length of writeBuffer
  1913. // splice writeBuffer and callbackBuffer on `drain`
  1914. this._prevBufferLen = packets.length;
  1915. this.emitReserved("flush");
  1916. }
  1917. }
  1918. /**
  1919. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  1920. * long-polling)
  1921. *
  1922. * @private
  1923. */;
  1924. _proto._getWritablePackets = function _getWritablePackets() {
  1925. var shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  1926. if (!shouldCheckPayloadSize) {
  1927. return this.writeBuffer;
  1928. }
  1929. var payloadSize = 1; // first packet type
  1930. for (var i = 0; i < this.writeBuffer.length; i++) {
  1931. var data = this.writeBuffer[i].data;
  1932. if (data) {
  1933. payloadSize += byteLength(data);
  1934. }
  1935. if (i > 0 && payloadSize > this._maxPayload) {
  1936. return this.writeBuffer.slice(0, i);
  1937. }
  1938. payloadSize += 2; // separator + packet type
  1939. }
  1940. return this.writeBuffer;
  1941. }
  1942. /**
  1943. * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
  1944. *
  1945. * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
  1946. * `write()` method then the message would not be buffered by the Socket.IO client.
  1947. *
  1948. * @return {boolean}
  1949. * @private
  1950. */
  1951. /* private */;
  1952. _proto._hasPingExpired = function _hasPingExpired() {
  1953. var _this5 = this;
  1954. if (!this._pingTimeoutTime) return true;
  1955. var hasExpired = Date.now() > this._pingTimeoutTime;
  1956. if (hasExpired) {
  1957. this._pingTimeoutTime = 0;
  1958. nextTick(function () {
  1959. _this5._onClose("ping timeout");
  1960. }, this.setTimeoutFn);
  1961. }
  1962. return hasExpired;
  1963. }
  1964. /**
  1965. * Sends a message.
  1966. *
  1967. * @param {String} msg - message.
  1968. * @param {Object} options.
  1969. * @param {Function} fn - callback function.
  1970. * @return {Socket} for chaining.
  1971. */;
  1972. _proto.write = function write(msg, options, fn) {
  1973. this._sendPacket("message", msg, options, fn);
  1974. return this;
  1975. }
  1976. /**
  1977. * Sends a message. Alias of {@link Socket#write}.
  1978. *
  1979. * @param {String} msg - message.
  1980. * @param {Object} options.
  1981. * @param {Function} fn - callback function.
  1982. * @return {Socket} for chaining.
  1983. */;
  1984. _proto.send = function send(msg, options, fn) {
  1985. this._sendPacket("message", msg, options, fn);
  1986. return this;
  1987. }
  1988. /**
  1989. * Sends a packet.
  1990. *
  1991. * @param {String} type: packet type.
  1992. * @param {String} data.
  1993. * @param {Object} options.
  1994. * @param {Function} fn - callback function.
  1995. * @private
  1996. */;
  1997. _proto._sendPacket = function _sendPacket(type, data, options, fn) {
  1998. if ("function" === typeof data) {
  1999. fn = data;
  2000. data = undefined;
  2001. }
  2002. if ("function" === typeof options) {
  2003. fn = options;
  2004. options = null;
  2005. }
  2006. if ("closing" === this.readyState || "closed" === this.readyState) {
  2007. return;
  2008. }
  2009. options = options || {};
  2010. options.compress = false !== options.compress;
  2011. var packet = {
  2012. type: type,
  2013. data: data,
  2014. options: options
  2015. };
  2016. this.emitReserved("packetCreate", packet);
  2017. this.writeBuffer.push(packet);
  2018. if (fn) this.once("flush", fn);
  2019. this.flush();
  2020. }
  2021. /**
  2022. * Closes the connection.
  2023. */;
  2024. _proto.close = function close() {
  2025. var _this6 = this;
  2026. var close = function close() {
  2027. _this6._onClose("forced close");
  2028. _this6.transport.close();
  2029. };
  2030. var cleanupAndClose = function cleanupAndClose() {
  2031. _this6.off("upgrade", cleanupAndClose);
  2032. _this6.off("upgradeError", cleanupAndClose);
  2033. close();
  2034. };
  2035. var waitForUpgrade = function waitForUpgrade() {
  2036. // wait for upgrade to finish since we can't send packets while pausing a transport
  2037. _this6.once("upgrade", cleanupAndClose);
  2038. _this6.once("upgradeError", cleanupAndClose);
  2039. };
  2040. if ("opening" === this.readyState || "open" === this.readyState) {
  2041. this.readyState = "closing";
  2042. if (this.writeBuffer.length) {
  2043. this.once("drain", function () {
  2044. if (_this6.upgrading) {
  2045. waitForUpgrade();
  2046. } else {
  2047. close();
  2048. }
  2049. });
  2050. } else if (this.upgrading) {
  2051. waitForUpgrade();
  2052. } else {
  2053. close();
  2054. }
  2055. }
  2056. return this;
  2057. }
  2058. /**
  2059. * Called upon transport error
  2060. *
  2061. * @private
  2062. */;
  2063. _proto._onError = function _onError(err) {
  2064. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2065. if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
  2066. this.transports.shift();
  2067. return this._open();
  2068. }
  2069. this.emitReserved("error", err);
  2070. this._onClose("transport error", err);
  2071. }
  2072. /**
  2073. * Called upon transport close.
  2074. *
  2075. * @private
  2076. */;
  2077. _proto._onClose = function _onClose(reason, description) {
  2078. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2079. // clear timers
  2080. this.clearTimeoutFn(this._pingTimeoutTimer);
  2081. // stop event from firing again for transport
  2082. this.transport.removeAllListeners("close");
  2083. // ensure transport won't stay open
  2084. this.transport.close();
  2085. // ignore further transport communication
  2086. this.transport.removeAllListeners();
  2087. if (withEventListeners) {
  2088. if (this._beforeunloadEventListener) {
  2089. removeEventListener("beforeunload", this._beforeunloadEventListener, false);
  2090. }
  2091. if (this._offlineEventListener) {
  2092. var i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
  2093. if (i !== -1) {
  2094. OFFLINE_EVENT_LISTENERS.splice(i, 1);
  2095. }
  2096. }
  2097. }
  2098. // set ready state
  2099. this.readyState = "closed";
  2100. // clear session id
  2101. this.id = null;
  2102. // emit close event
  2103. this.emitReserved("close", reason, description);
  2104. // clean buffers after, so users can still
  2105. // grab the buffers on `close` event
  2106. this.writeBuffer = [];
  2107. this._prevBufferLen = 0;
  2108. }
  2109. };
  2110. return SocketWithoutUpgrade;
  2111. }(Emitter);
  2112. SocketWithoutUpgrade.protocol = protocol$1;
  2113. /**
  2114. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2115. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2116. *
  2117. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2118. * low-level transport, it will try to upgrade to a better transport.
  2119. *
  2120. * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
  2121. *
  2122. * @example
  2123. * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
  2124. *
  2125. * const socket = new SocketWithUpgrade({
  2126. * transports: [WebSocket]
  2127. * });
  2128. *
  2129. * socket.on("open", () => {
  2130. * socket.send("hello");
  2131. * });
  2132. *
  2133. * @see SocketWithoutUpgrade
  2134. * @see Socket
  2135. */
  2136. var SocketWithUpgrade = /*#__PURE__*/function (_SocketWithoutUpgrade) {
  2137. function SocketWithUpgrade() {
  2138. var _this7;
  2139. _this7 = _SocketWithoutUpgrade.apply(this, arguments) || this;
  2140. _this7._upgrades = [];
  2141. return _this7;
  2142. }
  2143. _inheritsLoose(SocketWithUpgrade, _SocketWithoutUpgrade);
  2144. var _proto2 = SocketWithUpgrade.prototype;
  2145. _proto2.onOpen = function onOpen() {
  2146. _SocketWithoutUpgrade.prototype.onOpen.call(this);
  2147. if ("open" === this.readyState && this.opts.upgrade) {
  2148. for (var i = 0; i < this._upgrades.length; i++) {
  2149. this._probe(this._upgrades[i]);
  2150. }
  2151. }
  2152. }
  2153. /**
  2154. * Probes a transport.
  2155. *
  2156. * @param {String} name - transport name
  2157. * @private
  2158. */;
  2159. _proto2._probe = function _probe(name) {
  2160. var _this8 = this;
  2161. var transport = this.createTransport(name);
  2162. var failed = false;
  2163. SocketWithoutUpgrade.priorWebsocketSuccess = false;
  2164. var onTransportOpen = function onTransportOpen() {
  2165. if (failed) return;
  2166. transport.send([{
  2167. type: "ping",
  2168. data: "probe"
  2169. }]);
  2170. transport.once("packet", function (msg) {
  2171. if (failed) return;
  2172. if ("pong" === msg.type && "probe" === msg.data) {
  2173. _this8.upgrading = true;
  2174. _this8.emitReserved("upgrading", transport);
  2175. if (!transport) return;
  2176. SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
  2177. _this8.transport.pause(function () {
  2178. if (failed) return;
  2179. if ("closed" === _this8.readyState) return;
  2180. cleanup();
  2181. _this8.setTransport(transport);
  2182. transport.send([{
  2183. type: "upgrade"
  2184. }]);
  2185. _this8.emitReserved("upgrade", transport);
  2186. transport = null;
  2187. _this8.upgrading = false;
  2188. _this8.flush();
  2189. });
  2190. } else {
  2191. var err = new Error("probe error");
  2192. // @ts-ignore
  2193. err.transport = transport.name;
  2194. _this8.emitReserved("upgradeError", err);
  2195. }
  2196. });
  2197. };
  2198. function freezeTransport() {
  2199. if (failed) return;
  2200. // Any callback called by transport should be ignored since now
  2201. failed = true;
  2202. cleanup();
  2203. transport.close();
  2204. transport = null;
  2205. }
  2206. // Handle any error that happens while probing
  2207. var onerror = function onerror(err) {
  2208. var error = new Error("probe error: " + err);
  2209. // @ts-ignore
  2210. error.transport = transport.name;
  2211. freezeTransport();
  2212. _this8.emitReserved("upgradeError", error);
  2213. };
  2214. function onTransportClose() {
  2215. onerror("transport closed");
  2216. }
  2217. // When the socket is closed while we're probing
  2218. function onclose() {
  2219. onerror("socket closed");
  2220. }
  2221. // When the socket is upgraded while we're probing
  2222. function onupgrade(to) {
  2223. if (transport && to.name !== transport.name) {
  2224. freezeTransport();
  2225. }
  2226. }
  2227. // Remove all listeners on the transport and on self
  2228. var cleanup = function cleanup() {
  2229. transport.removeListener("open", onTransportOpen);
  2230. transport.removeListener("error", onerror);
  2231. transport.removeListener("close", onTransportClose);
  2232. _this8.off("close", onclose);
  2233. _this8.off("upgrading", onupgrade);
  2234. };
  2235. transport.once("open", onTransportOpen);
  2236. transport.once("error", onerror);
  2237. transport.once("close", onTransportClose);
  2238. this.once("close", onclose);
  2239. this.once("upgrading", onupgrade);
  2240. if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
  2241. // favor WebTransport
  2242. this.setTimeoutFn(function () {
  2243. if (!failed) {
  2244. transport.open();
  2245. }
  2246. }, 200);
  2247. } else {
  2248. transport.open();
  2249. }
  2250. };
  2251. _proto2.onHandshake = function onHandshake(data) {
  2252. this._upgrades = this._filterUpgrades(data.upgrades);
  2253. _SocketWithoutUpgrade.prototype.onHandshake.call(this, data);
  2254. }
  2255. /**
  2256. * Filters upgrades, returning only those matching client transports.
  2257. *
  2258. * @param {Array} upgrades - server upgrades
  2259. * @private
  2260. */;
  2261. _proto2._filterUpgrades = function _filterUpgrades(upgrades) {
  2262. var filteredUpgrades = [];
  2263. for (var i = 0; i < upgrades.length; i++) {
  2264. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2265. }
  2266. return filteredUpgrades;
  2267. };
  2268. return SocketWithUpgrade;
  2269. }(SocketWithoutUpgrade);
  2270. /**
  2271. * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
  2272. * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
  2273. *
  2274. * This class comes with an upgrade mechanism, which means that once the connection is established with the first
  2275. * low-level transport, it will try to upgrade to a better transport.
  2276. *
  2277. * @example
  2278. * import { Socket } from "engine.io-client";
  2279. *
  2280. * const socket = new Socket();
  2281. *
  2282. * socket.on("open", () => {
  2283. * socket.send("hello");
  2284. * });
  2285. *
  2286. * @see SocketWithoutUpgrade
  2287. * @see SocketWithUpgrade
  2288. */
  2289. var Socket$1 = /*#__PURE__*/function (_SocketWithUpgrade) {
  2290. function Socket(uri) {
  2291. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2292. var o = _typeof(uri) === "object" ? uri : opts;
  2293. if (!o.transports || o.transports && typeof o.transports[0] === "string") {
  2294. o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map(function (transportName) {
  2295. return transports[transportName];
  2296. }).filter(function (t) {
  2297. return !!t;
  2298. });
  2299. }
  2300. return _SocketWithUpgrade.call(this, uri, o) || this;
  2301. }
  2302. _inheritsLoose(Socket, _SocketWithUpgrade);
  2303. return Socket;
  2304. }(SocketWithUpgrade);
  2305. Socket$1.protocol;
  2306. function getDefaultExportFromCjs (x) {
  2307. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2308. }
  2309. var browser = {exports: {}};
  2310. var ms;
  2311. var hasRequiredMs;
  2312. function requireMs() {
  2313. if (hasRequiredMs) return ms;
  2314. hasRequiredMs = 1;
  2315. var s = 1000;
  2316. var m = s * 60;
  2317. var h = m * 60;
  2318. var d = h * 24;
  2319. var w = d * 7;
  2320. var y = d * 365.25;
  2321. /**
  2322. * Parse or format the given `val`.
  2323. *
  2324. * Options:
  2325. *
  2326. * - `long` verbose formatting [false]
  2327. *
  2328. * @param {String|Number} val
  2329. * @param {Object} [options]
  2330. * @throws {Error} throw an error if val is not a non-empty string or a number
  2331. * @return {String|Number}
  2332. * @api public
  2333. */
  2334. ms = function ms(val, options) {
  2335. options = options || {};
  2336. var type = _typeof(val);
  2337. if (type === 'string' && val.length > 0) {
  2338. return parse(val);
  2339. } else if (type === 'number' && isFinite(val)) {
  2340. return options["long"] ? fmtLong(val) : fmtShort(val);
  2341. }
  2342. throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
  2343. };
  2344. /**
  2345. * Parse the given `str` and return milliseconds.
  2346. *
  2347. * @param {String} str
  2348. * @return {Number}
  2349. * @api private
  2350. */
  2351. function parse(str) {
  2352. str = String(str);
  2353. if (str.length > 100) {
  2354. return;
  2355. }
  2356. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
  2357. if (!match) {
  2358. return;
  2359. }
  2360. var n = parseFloat(match[1]);
  2361. var type = (match[2] || 'ms').toLowerCase();
  2362. switch (type) {
  2363. case 'years':
  2364. case 'year':
  2365. case 'yrs':
  2366. case 'yr':
  2367. case 'y':
  2368. return n * y;
  2369. case 'weeks':
  2370. case 'week':
  2371. case 'w':
  2372. return n * w;
  2373. case 'days':
  2374. case 'day':
  2375. case 'd':
  2376. return n * d;
  2377. case 'hours':
  2378. case 'hour':
  2379. case 'hrs':
  2380. case 'hr':
  2381. case 'h':
  2382. return n * h;
  2383. case 'minutes':
  2384. case 'minute':
  2385. case 'mins':
  2386. case 'min':
  2387. case 'm':
  2388. return n * m;
  2389. case 'seconds':
  2390. case 'second':
  2391. case 'secs':
  2392. case 'sec':
  2393. case 's':
  2394. return n * s;
  2395. case 'milliseconds':
  2396. case 'millisecond':
  2397. case 'msecs':
  2398. case 'msec':
  2399. case 'ms':
  2400. return n;
  2401. default:
  2402. return undefined;
  2403. }
  2404. }
  2405. /**
  2406. * Short format for `ms`.
  2407. *
  2408. * @param {Number} ms
  2409. * @return {String}
  2410. * @api private
  2411. */
  2412. function fmtShort(ms) {
  2413. var msAbs = Math.abs(ms);
  2414. if (msAbs >= d) {
  2415. return Math.round(ms / d) + 'd';
  2416. }
  2417. if (msAbs >= h) {
  2418. return Math.round(ms / h) + 'h';
  2419. }
  2420. if (msAbs >= m) {
  2421. return Math.round(ms / m) + 'm';
  2422. }
  2423. if (msAbs >= s) {
  2424. return Math.round(ms / s) + 's';
  2425. }
  2426. return ms + 'ms';
  2427. }
  2428. /**
  2429. * Long format for `ms`.
  2430. *
  2431. * @param {Number} ms
  2432. * @return {String}
  2433. * @api private
  2434. */
  2435. function fmtLong(ms) {
  2436. var msAbs = Math.abs(ms);
  2437. if (msAbs >= d) {
  2438. return plural(ms, msAbs, d, 'day');
  2439. }
  2440. if (msAbs >= h) {
  2441. return plural(ms, msAbs, h, 'hour');
  2442. }
  2443. if (msAbs >= m) {
  2444. return plural(ms, msAbs, m, 'minute');
  2445. }
  2446. if (msAbs >= s) {
  2447. return plural(ms, msAbs, s, 'second');
  2448. }
  2449. return ms + ' ms';
  2450. }
  2451. /**
  2452. * Pluralization helper.
  2453. */
  2454. function plural(ms, msAbs, n, name) {
  2455. var isPlural = msAbs >= n * 1.5;
  2456. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  2457. }
  2458. return ms;
  2459. }
  2460. /**
  2461. * This is the common logic for both the Node.js and web browser
  2462. * implementations of `debug()`.
  2463. */
  2464. function setup(env) {
  2465. createDebug.debug = createDebug;
  2466. createDebug["default"] = createDebug;
  2467. createDebug.coerce = coerce;
  2468. createDebug.disable = disable;
  2469. createDebug.enable = enable;
  2470. createDebug.enabled = enabled;
  2471. createDebug.humanize = requireMs();
  2472. createDebug.destroy = destroy;
  2473. Object.keys(env).forEach(function (key) {
  2474. createDebug[key] = env[key];
  2475. });
  2476. /**
  2477. * The currently active debug mode names, and names to skip.
  2478. */
  2479. createDebug.names = [];
  2480. createDebug.skips = [];
  2481. /**
  2482. * Map of special "%n" handling functions, for the debug "format" argument.
  2483. *
  2484. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  2485. */
  2486. createDebug.formatters = {};
  2487. /**
  2488. * Selects a color for a debug namespace
  2489. * @param {String} namespace The namespace string for the debug instance to be colored
  2490. * @return {Number|String} An ANSI color code for the given namespace
  2491. * @api private
  2492. */
  2493. function selectColor(namespace) {
  2494. var hash = 0;
  2495. for (var i = 0; i < namespace.length; i++) {
  2496. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  2497. hash |= 0; // Convert to 32bit integer
  2498. }
  2499. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  2500. }
  2501. createDebug.selectColor = selectColor;
  2502. /**
  2503. * Create a debugger with the given `namespace`.
  2504. *
  2505. * @param {String} namespace
  2506. * @return {Function}
  2507. * @api public
  2508. */
  2509. function createDebug(namespace) {
  2510. var prevTime;
  2511. var enableOverride = null;
  2512. var namespacesCache;
  2513. var enabledCache;
  2514. function debug() {
  2515. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2516. args[_key] = arguments[_key];
  2517. }
  2518. // Disabled?
  2519. if (!debug.enabled) {
  2520. return;
  2521. }
  2522. var self = debug;
  2523. // Set `diff` timestamp
  2524. var curr = Number(new Date());
  2525. var ms = curr - (prevTime || curr);
  2526. self.diff = ms;
  2527. self.prev = prevTime;
  2528. self.curr = curr;
  2529. prevTime = curr;
  2530. args[0] = createDebug.coerce(args[0]);
  2531. if (typeof args[0] !== 'string') {
  2532. // Anything else let's inspect with %O
  2533. args.unshift('%O');
  2534. }
  2535. // Apply any `formatters` transformations
  2536. var index = 0;
  2537. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  2538. // If we encounter an escaped % then don't increase the array index
  2539. if (match === '%%') {
  2540. return '%';
  2541. }
  2542. index++;
  2543. var formatter = createDebug.formatters[format];
  2544. if (typeof formatter === 'function') {
  2545. var val = args[index];
  2546. match = formatter.call(self, val);
  2547. // Now we need to remove `args[index]` since it's inlined in the `format`
  2548. args.splice(index, 1);
  2549. index--;
  2550. }
  2551. return match;
  2552. });
  2553. // Apply env-specific formatting (colors, etc.)
  2554. createDebug.formatArgs.call(self, args);
  2555. var logFn = self.log || createDebug.log;
  2556. logFn.apply(self, args);
  2557. }
  2558. debug.namespace = namespace;
  2559. debug.useColors = createDebug.useColors();
  2560. debug.color = createDebug.selectColor(namespace);
  2561. debug.extend = extend;
  2562. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  2563. Object.defineProperty(debug, 'enabled', {
  2564. enumerable: true,
  2565. configurable: false,
  2566. get: function get() {
  2567. if (enableOverride !== null) {
  2568. return enableOverride;
  2569. }
  2570. if (namespacesCache !== createDebug.namespaces) {
  2571. namespacesCache = createDebug.namespaces;
  2572. enabledCache = createDebug.enabled(namespace);
  2573. }
  2574. return enabledCache;
  2575. },
  2576. set: function set(v) {
  2577. enableOverride = v;
  2578. }
  2579. });
  2580. // Env-specific initialization logic for debug instances
  2581. if (typeof createDebug.init === 'function') {
  2582. createDebug.init(debug);
  2583. }
  2584. return debug;
  2585. }
  2586. function extend(namespace, delimiter) {
  2587. var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  2588. newDebug.log = this.log;
  2589. return newDebug;
  2590. }
  2591. /**
  2592. * Enables a debug mode by namespaces. This can include modes
  2593. * separated by a colon and wildcards.
  2594. *
  2595. * @param {String} namespaces
  2596. * @api public
  2597. */
  2598. function enable(namespaces) {
  2599. createDebug.save(namespaces);
  2600. createDebug.namespaces = namespaces;
  2601. createDebug.names = [];
  2602. createDebug.skips = [];
  2603. var split = (typeof namespaces === 'string' ? namespaces : '').trim().replace(/\s+/g, ',').split(',').filter(Boolean);
  2604. var _iterator = _createForOfIteratorHelper(split),
  2605. _step;
  2606. try {
  2607. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  2608. var ns = _step.value;
  2609. if (ns[0] === '-') {
  2610. createDebug.skips.push(ns.slice(1));
  2611. } else {
  2612. createDebug.names.push(ns);
  2613. }
  2614. }
  2615. } catch (err) {
  2616. _iterator.e(err);
  2617. } finally {
  2618. _iterator.f();
  2619. }
  2620. }
  2621. /**
  2622. * Checks if the given string matches a namespace template, honoring
  2623. * asterisks as wildcards.
  2624. *
  2625. * @param {String} search
  2626. * @param {String} template
  2627. * @return {Boolean}
  2628. */
  2629. function matchesTemplate(search, template) {
  2630. var searchIndex = 0;
  2631. var templateIndex = 0;
  2632. var starIndex = -1;
  2633. var matchIndex = 0;
  2634. while (searchIndex < search.length) {
  2635. if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
  2636. // Match character or proceed with wildcard
  2637. if (template[templateIndex] === '*') {
  2638. starIndex = templateIndex;
  2639. matchIndex = searchIndex;
  2640. templateIndex++; // Skip the '*'
  2641. } else {
  2642. searchIndex++;
  2643. templateIndex++;
  2644. }
  2645. } else if (starIndex !== -1) {
  2646. // eslint-disable-line no-negated-condition
  2647. // Backtrack to the last '*' and try to match more characters
  2648. templateIndex = starIndex + 1;
  2649. matchIndex++;
  2650. searchIndex = matchIndex;
  2651. } else {
  2652. return false; // No match
  2653. }
  2654. }
  2655. // Handle trailing '*' in template
  2656. while (templateIndex < template.length && template[templateIndex] === '*') {
  2657. templateIndex++;
  2658. }
  2659. return templateIndex === template.length;
  2660. }
  2661. /**
  2662. * Disable debug output.
  2663. *
  2664. * @return {String} namespaces
  2665. * @api public
  2666. */
  2667. function disable() {
  2668. var namespaces = [].concat(_toConsumableArray(createDebug.names), _toConsumableArray(createDebug.skips.map(function (namespace) {
  2669. return '-' + namespace;
  2670. }))).join(',');
  2671. createDebug.enable('');
  2672. return namespaces;
  2673. }
  2674. /**
  2675. * Returns true if the given mode name is enabled, false otherwise.
  2676. *
  2677. * @param {String} name
  2678. * @return {Boolean}
  2679. * @api public
  2680. */
  2681. function enabled(name) {
  2682. var _iterator2 = _createForOfIteratorHelper(createDebug.skips),
  2683. _step2;
  2684. try {
  2685. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  2686. var skip = _step2.value;
  2687. if (matchesTemplate(name, skip)) {
  2688. return false;
  2689. }
  2690. }
  2691. } catch (err) {
  2692. _iterator2.e(err);
  2693. } finally {
  2694. _iterator2.f();
  2695. }
  2696. var _iterator3 = _createForOfIteratorHelper(createDebug.names),
  2697. _step3;
  2698. try {
  2699. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  2700. var ns = _step3.value;
  2701. if (matchesTemplate(name, ns)) {
  2702. return true;
  2703. }
  2704. }
  2705. } catch (err) {
  2706. _iterator3.e(err);
  2707. } finally {
  2708. _iterator3.f();
  2709. }
  2710. return false;
  2711. }
  2712. /**
  2713. * Coerce `val`.
  2714. *
  2715. * @param {Mixed} val
  2716. * @return {Mixed}
  2717. * @api private
  2718. */
  2719. function coerce(val) {
  2720. if (val instanceof Error) {
  2721. return val.stack || val.message;
  2722. }
  2723. return val;
  2724. }
  2725. /**
  2726. * XXX DO NOT USE. This is a temporary stub function.
  2727. * XXX It WILL be removed in the next major release.
  2728. */
  2729. function destroy() {
  2730. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2731. }
  2732. createDebug.enable(createDebug.load());
  2733. return createDebug;
  2734. }
  2735. var common = setup;
  2736. /* eslint-env browser */
  2737. browser.exports;
  2738. (function (module, exports) {
  2739. /**
  2740. * This is the web browser implementation of `debug()`.
  2741. */
  2742. exports.formatArgs = formatArgs;
  2743. exports.save = save;
  2744. exports.load = load;
  2745. exports.useColors = useColors;
  2746. exports.storage = localstorage();
  2747. exports.destroy = function () {
  2748. var warned = false;
  2749. return function () {
  2750. if (!warned) {
  2751. warned = true;
  2752. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2753. }
  2754. };
  2755. }();
  2756. /**
  2757. * Colors.
  2758. */
  2759. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  2760. /**
  2761. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2762. * and the Firebug extension (any Firefox version) are known
  2763. * to support "%c" CSS customizations.
  2764. *
  2765. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2766. */
  2767. // eslint-disable-next-line complexity
  2768. function useColors() {
  2769. // NB: In an Electron preload script, document will be defined but not fully
  2770. // initialized. Since we know we're in Chrome, we'll just detect this case
  2771. // explicitly
  2772. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  2773. return true;
  2774. }
  2775. // Internet Explorer and Edge do not support colors.
  2776. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  2777. return false;
  2778. }
  2779. var m;
  2780. // Is webkit? http://stackoverflow.com/a/16459606/376773
  2781. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  2782. // eslint-disable-next-line no-return-assign
  2783. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
  2784. // Is firebug? http://stackoverflow.com/a/398120/376773
  2785. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
  2786. // Is firefox >= v31?
  2787. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2788. typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 ||
  2789. // Double check webkit in userAgent just in case we are in a worker
  2790. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  2791. }
  2792. /**
  2793. * Colorize log arguments if enabled.
  2794. *
  2795. * @api public
  2796. */
  2797. function formatArgs(args) {
  2798. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  2799. if (!this.useColors) {
  2800. return;
  2801. }
  2802. var c = 'color: ' + this.color;
  2803. args.splice(1, 0, c, 'color: inherit');
  2804. // The final "%c" is somewhat tricky, because there could be other
  2805. // arguments passed either before or after the %c, so we need to
  2806. // figure out the correct index to insert the CSS into
  2807. var index = 0;
  2808. var lastC = 0;
  2809. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  2810. if (match === '%%') {
  2811. return;
  2812. }
  2813. index++;
  2814. if (match === '%c') {
  2815. // We only are interested in the *last* %c
  2816. // (the user may have provided their own)
  2817. lastC = index;
  2818. }
  2819. });
  2820. args.splice(lastC, 0, c);
  2821. }
  2822. /**
  2823. * Invokes `console.debug()` when available.
  2824. * No-op when `console.debug` is not a "function".
  2825. * If `console.debug` is not available, falls back
  2826. * to `console.log`.
  2827. *
  2828. * @api public
  2829. */
  2830. exports.log = console.debug || console.log || function () {};
  2831. /**
  2832. * Save `namespaces`.
  2833. *
  2834. * @param {String} namespaces
  2835. * @api private
  2836. */
  2837. function save(namespaces) {
  2838. try {
  2839. if (namespaces) {
  2840. exports.storage.setItem('debug', namespaces);
  2841. } else {
  2842. exports.storage.removeItem('debug');
  2843. }
  2844. } catch (error) {
  2845. // Swallow
  2846. // XXX (@Qix-) should we be logging these?
  2847. }
  2848. }
  2849. /**
  2850. * Load `namespaces`.
  2851. *
  2852. * @return {String} returns the previously persisted debug modes
  2853. * @api private
  2854. */
  2855. function load() {
  2856. var r;
  2857. try {
  2858. r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG');
  2859. } catch (error) {
  2860. // Swallow
  2861. // XXX (@Qix-) should we be logging these?
  2862. }
  2863. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  2864. if (!r && typeof process !== 'undefined' && 'env' in process) {
  2865. r = process.env.DEBUG;
  2866. }
  2867. return r;
  2868. }
  2869. /**
  2870. * Localstorage attempts to return the localstorage.
  2871. *
  2872. * This is necessary because safari throws
  2873. * when a user disables cookies/localstorage
  2874. * and you attempt to access it.
  2875. *
  2876. * @return {LocalStorage}
  2877. * @api private
  2878. */
  2879. function localstorage() {
  2880. try {
  2881. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  2882. // The Browser also has localStorage in the global context.
  2883. return localStorage;
  2884. } catch (error) {
  2885. // Swallow
  2886. // XXX (@Qix-) should we be logging these?
  2887. }
  2888. }
  2889. module.exports = common(exports);
  2890. var formatters = module.exports.formatters;
  2891. /**
  2892. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2893. */
  2894. formatters.j = function (v) {
  2895. try {
  2896. return JSON.stringify(v);
  2897. } catch (error) {
  2898. return '[UnexpectedJSONParseError]: ' + error.message;
  2899. }
  2900. };
  2901. })(browser, browser.exports);
  2902. var browserExports = browser.exports;
  2903. var debugModule = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
  2904. var debug$3 = debugModule("socket.io-client:url"); // debug()
  2905. /**
  2906. * URL parser.
  2907. *
  2908. * @param uri - url
  2909. * @param path - the request path of the connection
  2910. * @param loc - An object meant to mimic window.location.
  2911. * Defaults to window.location.
  2912. * @public
  2913. */
  2914. function url(uri) {
  2915. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2916. var loc = arguments.length > 2 ? arguments[2] : undefined;
  2917. var obj = uri;
  2918. // default to window.location
  2919. loc = loc || typeof location !== "undefined" && location;
  2920. if (null == uri) uri = loc.protocol + "//" + loc.host;
  2921. // relative path support
  2922. if (typeof uri === "string") {
  2923. if ("/" === uri.charAt(0)) {
  2924. if ("/" === uri.charAt(1)) {
  2925. uri = loc.protocol + uri;
  2926. } else {
  2927. uri = loc.host + uri;
  2928. }
  2929. }
  2930. if (!/^(https?|wss?):\/\//.test(uri)) {
  2931. debug$3("protocol-less url %s", uri);
  2932. if ("undefined" !== typeof loc) {
  2933. uri = loc.protocol + "//" + uri;
  2934. } else {
  2935. uri = "https://" + uri;
  2936. }
  2937. }
  2938. // parse
  2939. debug$3("parse %s", uri);
  2940. obj = parse(uri);
  2941. }
  2942. // make sure we treat `localhost:80` and `localhost` equally
  2943. if (!obj.port) {
  2944. if (/^(http|ws)$/.test(obj.protocol)) {
  2945. obj.port = "80";
  2946. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  2947. obj.port = "443";
  2948. }
  2949. }
  2950. obj.path = obj.path || "/";
  2951. var ipv6 = obj.host.indexOf(":") !== -1;
  2952. var host = ipv6 ? "[" + obj.host + "]" : obj.host;
  2953. // define unique id
  2954. obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
  2955. // define href
  2956. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  2957. return obj;
  2958. }
  2959. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2960. var isView = function isView(obj) {
  2961. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2962. };
  2963. var toString = Object.prototype.toString;
  2964. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2965. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2966. /**
  2967. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2968. *
  2969. * @private
  2970. */
  2971. function isBinary(obj) {
  2972. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2973. }
  2974. function hasBinary(obj, toJSON) {
  2975. if (!obj || _typeof(obj) !== "object") {
  2976. return false;
  2977. }
  2978. if (Array.isArray(obj)) {
  2979. for (var i = 0, l = obj.length; i < l; i++) {
  2980. if (hasBinary(obj[i])) {
  2981. return true;
  2982. }
  2983. }
  2984. return false;
  2985. }
  2986. if (isBinary(obj)) {
  2987. return true;
  2988. }
  2989. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2990. return hasBinary(obj.toJSON(), true);
  2991. }
  2992. for (var key in obj) {
  2993. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2994. return true;
  2995. }
  2996. }
  2997. return false;
  2998. }
  2999. /**
  3000. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  3001. *
  3002. * @param {Object} packet - socket.io event packet
  3003. * @return {Object} with deconstructed packet and list of buffers
  3004. * @public
  3005. */
  3006. function deconstructPacket(packet) {
  3007. var buffers = [];
  3008. var packetData = packet.data;
  3009. var pack = packet;
  3010. pack.data = _deconstructPacket(packetData, buffers);
  3011. pack.attachments = buffers.length; // number of binary 'attachments'
  3012. return {
  3013. packet: pack,
  3014. buffers: buffers
  3015. };
  3016. }
  3017. function _deconstructPacket(data, buffers) {
  3018. if (!data) return data;
  3019. if (isBinary(data)) {
  3020. var placeholder = {
  3021. _placeholder: true,
  3022. num: buffers.length
  3023. };
  3024. buffers.push(data);
  3025. return placeholder;
  3026. } else if (Array.isArray(data)) {
  3027. var newData = new Array(data.length);
  3028. for (var i = 0; i < data.length; i++) {
  3029. newData[i] = _deconstructPacket(data[i], buffers);
  3030. }
  3031. return newData;
  3032. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  3033. var _newData = {};
  3034. for (var key in data) {
  3035. if (Object.prototype.hasOwnProperty.call(data, key)) {
  3036. _newData[key] = _deconstructPacket(data[key], buffers);
  3037. }
  3038. }
  3039. return _newData;
  3040. }
  3041. return data;
  3042. }
  3043. /**
  3044. * Reconstructs a binary packet from its placeholder packet and buffers
  3045. *
  3046. * @param {Object} packet - event packet with placeholders
  3047. * @param {Array} buffers - binary buffers to put in placeholder positions
  3048. * @return {Object} reconstructed packet
  3049. * @public
  3050. */
  3051. function reconstructPacket(packet, buffers) {
  3052. packet.data = _reconstructPacket(packet.data, buffers);
  3053. delete packet.attachments; // no longer useful
  3054. return packet;
  3055. }
  3056. function _reconstructPacket(data, buffers) {
  3057. if (!data) return data;
  3058. if (data && data._placeholder === true) {
  3059. var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
  3060. if (isIndexValid) {
  3061. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  3062. } else {
  3063. throw new Error("illegal attachments");
  3064. }
  3065. } else if (Array.isArray(data)) {
  3066. for (var i = 0; i < data.length; i++) {
  3067. data[i] = _reconstructPacket(data[i], buffers);
  3068. }
  3069. } else if (_typeof(data) === "object") {
  3070. for (var key in data) {
  3071. if (Object.prototype.hasOwnProperty.call(data, key)) {
  3072. data[key] = _reconstructPacket(data[key], buffers);
  3073. }
  3074. }
  3075. }
  3076. return data;
  3077. }
  3078. /**
  3079. * These strings must not be used as event names, as they have a special meaning.
  3080. */
  3081. var RESERVED_EVENTS$1 = ["connect",
  3082. // used on the client side
  3083. "connect_error",
  3084. // used on the client side
  3085. "disconnect",
  3086. // used on both sides
  3087. "disconnecting",
  3088. // used on the server side
  3089. "newListener",
  3090. // used by the Node.js EventEmitter
  3091. "removeListener" // used by the Node.js EventEmitter
  3092. ];
  3093. /**
  3094. * Protocol version.
  3095. *
  3096. * @public
  3097. */
  3098. var protocol = 5;
  3099. var PacketType;
  3100. (function (PacketType) {
  3101. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  3102. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  3103. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  3104. PacketType[PacketType["ACK"] = 3] = "ACK";
  3105. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  3106. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  3107. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  3108. })(PacketType || (PacketType = {}));
  3109. /**
  3110. * A socket.io Encoder instance
  3111. */
  3112. var Encoder = /*#__PURE__*/function () {
  3113. /**
  3114. * Encoder constructor
  3115. *
  3116. * @param {function} replacer - custom replacer to pass down to JSON.parse
  3117. */
  3118. function Encoder(replacer) {
  3119. this.replacer = replacer;
  3120. }
  3121. /**
  3122. * Encode a packet as a single string if non-binary, or as a
  3123. * buffer sequence, depending on packet type.
  3124. *
  3125. * @param {Object} obj - packet object
  3126. */
  3127. var _proto = Encoder.prototype;
  3128. _proto.encode = function encode(obj) {
  3129. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  3130. if (hasBinary(obj)) {
  3131. return this.encodeAsBinary({
  3132. type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
  3133. nsp: obj.nsp,
  3134. data: obj.data,
  3135. id: obj.id
  3136. });
  3137. }
  3138. }
  3139. return [this.encodeAsString(obj)];
  3140. }
  3141. /**
  3142. * Encode packet as string.
  3143. */;
  3144. _proto.encodeAsString = function encodeAsString(obj) {
  3145. // first is type
  3146. var str = "" + obj.type;
  3147. // attachments if we have them
  3148. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  3149. str += obj.attachments + "-";
  3150. }
  3151. // if we have a namespace other than `/`
  3152. // we append it followed by a comma `,`
  3153. if (obj.nsp && "/" !== obj.nsp) {
  3154. str += obj.nsp + ",";
  3155. }
  3156. // immediately followed by the id
  3157. if (null != obj.id) {
  3158. str += obj.id;
  3159. }
  3160. // json data
  3161. if (null != obj.data) {
  3162. str += JSON.stringify(obj.data, this.replacer);
  3163. }
  3164. return str;
  3165. }
  3166. /**
  3167. * Encode packet as 'buffer sequence' by removing blobs, and
  3168. * deconstructing packet into object with placeholders and
  3169. * a list of buffers.
  3170. */;
  3171. _proto.encodeAsBinary = function encodeAsBinary(obj) {
  3172. var deconstruction = deconstructPacket(obj);
  3173. var pack = this.encodeAsString(deconstruction.packet);
  3174. var buffers = deconstruction.buffers;
  3175. buffers.unshift(pack); // add packet info to beginning of data list
  3176. return buffers; // write all the buffers
  3177. };
  3178. return Encoder;
  3179. }();
  3180. /**
  3181. * A socket.io Decoder instance
  3182. *
  3183. * @return {Object} decoder
  3184. */
  3185. var Decoder = /*#__PURE__*/function (_Emitter) {
  3186. /**
  3187. * Decoder constructor
  3188. *
  3189. * @param {function} reviver - custom reviver to pass down to JSON.stringify
  3190. */
  3191. function Decoder(reviver) {
  3192. var _this;
  3193. _this = _Emitter.call(this) || this;
  3194. _this.reviver = reviver;
  3195. return _this;
  3196. }
  3197. /**
  3198. * Decodes an encoded packet string into packet JSON.
  3199. *
  3200. * @param {String} obj - encoded packet
  3201. */
  3202. _inheritsLoose(Decoder, _Emitter);
  3203. var _proto2 = Decoder.prototype;
  3204. _proto2.add = function add(obj) {
  3205. var packet;
  3206. if (typeof obj === "string") {
  3207. if (this.reconstructor) {
  3208. throw new Error("got plaintext data when reconstructing a packet");
  3209. }
  3210. packet = this.decodeString(obj);
  3211. var isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
  3212. if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
  3213. packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
  3214. // binary packet's json
  3215. this.reconstructor = new BinaryReconstructor(packet);
  3216. // no attachments, labeled binary but no binary data to follow
  3217. if (packet.attachments === 0) {
  3218. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3219. }
  3220. } else {
  3221. // non-binary full packet
  3222. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3223. }
  3224. } else if (isBinary(obj) || obj.base64) {
  3225. // raw binary data
  3226. if (!this.reconstructor) {
  3227. throw new Error("got binary data when not reconstructing a packet");
  3228. } else {
  3229. packet = this.reconstructor.takeBinaryData(obj);
  3230. if (packet) {
  3231. // received final buffer
  3232. this.reconstructor = null;
  3233. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3234. }
  3235. }
  3236. } else {
  3237. throw new Error("Unknown type: " + obj);
  3238. }
  3239. }
  3240. /**
  3241. * Decode a packet String (JSON data)
  3242. *
  3243. * @param {String} str
  3244. * @return {Object} packet
  3245. */;
  3246. _proto2.decodeString = function decodeString(str) {
  3247. var i = 0;
  3248. // look up type
  3249. var p = {
  3250. type: Number(str.charAt(0))
  3251. };
  3252. if (PacketType[p.type] === undefined) {
  3253. throw new Error("unknown packet type " + p.type);
  3254. }
  3255. // look up attachments if type binary
  3256. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  3257. var start = i + 1;
  3258. while (str.charAt(++i) !== "-" && i != str.length) {}
  3259. var buf = str.substring(start, i);
  3260. if (buf != Number(buf) || str.charAt(i) !== "-") {
  3261. throw new Error("Illegal attachments");
  3262. }
  3263. p.attachments = Number(buf);
  3264. }
  3265. // look up namespace (if any)
  3266. if ("/" === str.charAt(i + 1)) {
  3267. var _start = i + 1;
  3268. while (++i) {
  3269. var c = str.charAt(i);
  3270. if ("," === c) break;
  3271. if (i === str.length) break;
  3272. }
  3273. p.nsp = str.substring(_start, i);
  3274. } else {
  3275. p.nsp = "/";
  3276. }
  3277. // look up id
  3278. var next = str.charAt(i + 1);
  3279. if ("" !== next && Number(next) == next) {
  3280. var _start2 = i + 1;
  3281. while (++i) {
  3282. var _c = str.charAt(i);
  3283. if (null == _c || Number(_c) != _c) {
  3284. --i;
  3285. break;
  3286. }
  3287. if (i === str.length) break;
  3288. }
  3289. p.id = Number(str.substring(_start2, i + 1));
  3290. }
  3291. // look up json data
  3292. if (str.charAt(++i)) {
  3293. var payload = this.tryParse(str.substr(i));
  3294. if (Decoder.isPayloadValid(p.type, payload)) {
  3295. p.data = payload;
  3296. } else {
  3297. throw new Error("invalid payload");
  3298. }
  3299. }
  3300. return p;
  3301. };
  3302. _proto2.tryParse = function tryParse(str) {
  3303. try {
  3304. return JSON.parse(str, this.reviver);
  3305. } catch (e) {
  3306. return false;
  3307. }
  3308. };
  3309. Decoder.isPayloadValid = function isPayloadValid(type, payload) {
  3310. switch (type) {
  3311. case PacketType.CONNECT:
  3312. return isObject(payload);
  3313. case PacketType.DISCONNECT:
  3314. return payload === undefined;
  3315. case PacketType.CONNECT_ERROR:
  3316. return typeof payload === "string" || isObject(payload);
  3317. case PacketType.EVENT:
  3318. case PacketType.BINARY_EVENT:
  3319. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3320. case PacketType.ACK:
  3321. case PacketType.BINARY_ACK:
  3322. return Array.isArray(payload);
  3323. }
  3324. }
  3325. /**
  3326. * Deallocates a parser's resources
  3327. */;
  3328. _proto2.destroy = function destroy() {
  3329. if (this.reconstructor) {
  3330. this.reconstructor.finishedReconstruction();
  3331. this.reconstructor = null;
  3332. }
  3333. };
  3334. return Decoder;
  3335. }(Emitter);
  3336. /**
  3337. * A manager of a binary event's 'buffer sequence'. Should
  3338. * be constructed whenever a packet of type BINARY_EVENT is
  3339. * decoded.
  3340. *
  3341. * @param {Object} packet
  3342. * @return {BinaryReconstructor} initialized reconstructor
  3343. */
  3344. var BinaryReconstructor = /*#__PURE__*/function () {
  3345. function BinaryReconstructor(packet) {
  3346. this.packet = packet;
  3347. this.buffers = [];
  3348. this.reconPack = packet;
  3349. }
  3350. /**
  3351. * Method to be called when binary data received from connection
  3352. * after a BINARY_EVENT packet.
  3353. *
  3354. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  3355. * @return {null | Object} returns null if more binary data is expected or
  3356. * a reconstructed packet object if all buffers have been received.
  3357. */
  3358. var _proto3 = BinaryReconstructor.prototype;
  3359. _proto3.takeBinaryData = function takeBinaryData(binData) {
  3360. this.buffers.push(binData);
  3361. if (this.buffers.length === this.reconPack.attachments) {
  3362. // done with buffer list
  3363. var packet = reconstructPacket(this.reconPack, this.buffers);
  3364. this.finishedReconstruction();
  3365. return packet;
  3366. }
  3367. return null;
  3368. }
  3369. /**
  3370. * Cleans up binary packet reconstruction variables.
  3371. */;
  3372. _proto3.finishedReconstruction = function finishedReconstruction() {
  3373. this.reconPack = null;
  3374. this.buffers = [];
  3375. };
  3376. return BinaryReconstructor;
  3377. }();
  3378. function isNamespaceValid(nsp) {
  3379. return typeof nsp === "string";
  3380. }
  3381. // see https://caniuse.com/mdn-javascript_builtins_number_isinteger
  3382. var isInteger = Number.isInteger || function (value) {
  3383. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  3384. };
  3385. function isAckIdValid(id) {
  3386. return id === undefined || isInteger(id);
  3387. }
  3388. // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
  3389. function isObject(value) {
  3390. return Object.prototype.toString.call(value) === "[object Object]";
  3391. }
  3392. function isDataValid(type, payload) {
  3393. switch (type) {
  3394. case PacketType.CONNECT:
  3395. return payload === undefined || isObject(payload);
  3396. case PacketType.DISCONNECT:
  3397. return payload === undefined;
  3398. case PacketType.EVENT:
  3399. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3400. case PacketType.ACK:
  3401. return Array.isArray(payload);
  3402. case PacketType.CONNECT_ERROR:
  3403. return typeof payload === "string" || isObject(payload);
  3404. default:
  3405. return false;
  3406. }
  3407. }
  3408. function isPacketValid(packet) {
  3409. return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
  3410. }
  3411. var parser = /*#__PURE__*/Object.freeze({
  3412. __proto__: null,
  3413. protocol: protocol,
  3414. get PacketType () { return PacketType; },
  3415. Encoder: Encoder,
  3416. Decoder: Decoder,
  3417. isPacketValid: isPacketValid
  3418. });
  3419. function on(obj, ev, fn) {
  3420. obj.on(ev, fn);
  3421. return function subDestroy() {
  3422. obj.off(ev, fn);
  3423. };
  3424. }
  3425. var debug$2 = debugModule("socket.io-client:socket"); // debug()
  3426. /**
  3427. * Internal events.
  3428. * These events can't be emitted by the user.
  3429. */
  3430. var RESERVED_EVENTS = Object.freeze({
  3431. connect: 1,
  3432. connect_error: 1,
  3433. disconnect: 1,
  3434. disconnecting: 1,
  3435. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  3436. newListener: 1,
  3437. removeListener: 1
  3438. });
  3439. /**
  3440. * A Socket is the fundamental class for interacting with the server.
  3441. *
  3442. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  3443. *
  3444. * @example
  3445. * const socket = io();
  3446. *
  3447. * socket.on("connect", () => {
  3448. * console.log("connected");
  3449. * });
  3450. *
  3451. * // send an event to the server
  3452. * socket.emit("foo", "bar");
  3453. *
  3454. * socket.on("foobar", () => {
  3455. * // an event was received from the server
  3456. * });
  3457. *
  3458. * // upon disconnection
  3459. * socket.on("disconnect", (reason) => {
  3460. * console.log(`disconnected due to ${reason}`);
  3461. * });
  3462. */
  3463. var Socket = /*#__PURE__*/function (_Emitter) {
  3464. /**
  3465. * `Socket` constructor.
  3466. */
  3467. function Socket(io, nsp, opts) {
  3468. var _this;
  3469. _this = _Emitter.call(this) || this;
  3470. /**
  3471. * Whether the socket is currently connected to the server.
  3472. *
  3473. * @example
  3474. * const socket = io();
  3475. *
  3476. * socket.on("connect", () => {
  3477. * console.log(socket.connected); // true
  3478. * });
  3479. *
  3480. * socket.on("disconnect", () => {
  3481. * console.log(socket.connected); // false
  3482. * });
  3483. */
  3484. _this.connected = false;
  3485. /**
  3486. * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
  3487. * be transmitted by the server.
  3488. */
  3489. _this.recovered = false;
  3490. /**
  3491. * Buffer for packets received before the CONNECT packet
  3492. */
  3493. _this.receiveBuffer = [];
  3494. /**
  3495. * Buffer for packets that will be sent once the socket is connected
  3496. */
  3497. _this.sendBuffer = [];
  3498. /**
  3499. * The queue of packets to be sent with retry in case of failure.
  3500. *
  3501. * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
  3502. * @private
  3503. */
  3504. _this._queue = [];
  3505. /**
  3506. * A sequence to generate the ID of the {@link QueuedPacket}.
  3507. * @private
  3508. */
  3509. _this._queueSeq = 0;
  3510. _this.ids = 0;
  3511. /**
  3512. * A map containing acknowledgement handlers.
  3513. *
  3514. * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
  3515. *
  3516. * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
  3517. * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
  3518. * - `const value = await socket.emitWithAck("test")`
  3519. *
  3520. * From those that don't:
  3521. *
  3522. * - `socket.emit("test", (value) => { ... });`
  3523. *
  3524. * In the first case, the handlers will be called with an error when:
  3525. *
  3526. * - the timeout is reached
  3527. * - the socket gets disconnected
  3528. *
  3529. * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
  3530. * an acknowledgement from the server.
  3531. *
  3532. * @private
  3533. */
  3534. _this.acks = {};
  3535. _this.flags = {};
  3536. _this.io = io;
  3537. _this.nsp = nsp;
  3538. if (opts && opts.auth) {
  3539. _this.auth = opts.auth;
  3540. }
  3541. _this._opts = _extends({}, opts);
  3542. if (_this.io._autoConnect) _this.open();
  3543. return _this;
  3544. }
  3545. /**
  3546. * Whether the socket is currently disconnected
  3547. *
  3548. * @example
  3549. * const socket = io();
  3550. *
  3551. * socket.on("connect", () => {
  3552. * console.log(socket.disconnected); // false
  3553. * });
  3554. *
  3555. * socket.on("disconnect", () => {
  3556. * console.log(socket.disconnected); // true
  3557. * });
  3558. */
  3559. _inheritsLoose(Socket, _Emitter);
  3560. var _proto = Socket.prototype;
  3561. /**
  3562. * Subscribe to open, close and packet events
  3563. *
  3564. * @private
  3565. */
  3566. _proto.subEvents = function subEvents() {
  3567. if (this.subs) return;
  3568. var io = this.io;
  3569. 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))];
  3570. }
  3571. /**
  3572. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  3573. *
  3574. * @example
  3575. * const socket = io();
  3576. *
  3577. * console.log(socket.active); // true
  3578. *
  3579. * socket.on("disconnect", (reason) => {
  3580. * if (reason === "io server disconnect") {
  3581. * // the disconnection was initiated by the server, you need to manually reconnect
  3582. * console.log(socket.active); // false
  3583. * }
  3584. * // else the socket will automatically try to reconnect
  3585. * console.log(socket.active); // true
  3586. * });
  3587. */;
  3588. /**
  3589. * "Opens" the socket.
  3590. *
  3591. * @example
  3592. * const socket = io({
  3593. * autoConnect: false
  3594. * });
  3595. *
  3596. * socket.connect();
  3597. */
  3598. _proto.connect = function connect() {
  3599. if (this.connected) return this;
  3600. this.subEvents();
  3601. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  3602. if ("open" === this.io._readyState) this.onopen();
  3603. return this;
  3604. }
  3605. /**
  3606. * Alias for {@link connect()}.
  3607. */;
  3608. _proto.open = function open() {
  3609. return this.connect();
  3610. }
  3611. /**
  3612. * Sends a `message` event.
  3613. *
  3614. * This method mimics the WebSocket.send() method.
  3615. *
  3616. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  3617. *
  3618. * @example
  3619. * socket.send("hello");
  3620. *
  3621. * // this is equivalent to
  3622. * socket.emit("message", "hello");
  3623. *
  3624. * @return self
  3625. */;
  3626. _proto.send = function send() {
  3627. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3628. args[_key] = arguments[_key];
  3629. }
  3630. args.unshift("message");
  3631. this.emit.apply(this, args);
  3632. return this;
  3633. }
  3634. /**
  3635. * Override `emit`.
  3636. * If the event is in `events`, it's emitted normally.
  3637. *
  3638. * @example
  3639. * socket.emit("hello", "world");
  3640. *
  3641. * // all serializable datastructures are supported (no need to call JSON.stringify)
  3642. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  3643. *
  3644. * // with an acknowledgement from the server
  3645. * socket.emit("hello", "world", (val) => {
  3646. * // ...
  3647. * });
  3648. *
  3649. * @return self
  3650. */;
  3651. _proto.emit = function emit(ev) {
  3652. var _a, _b, _c;
  3653. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  3654. throw new Error('"' + ev.toString() + '" is a reserved event name');
  3655. }
  3656. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3657. args[_key2 - 1] = arguments[_key2];
  3658. }
  3659. args.unshift(ev);
  3660. if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
  3661. this._addToQueue(args);
  3662. return this;
  3663. }
  3664. var packet = {
  3665. type: PacketType.EVENT,
  3666. data: args
  3667. };
  3668. packet.options = {};
  3669. packet.options.compress = this.flags.compress !== false;
  3670. // event ack callback
  3671. if ("function" === typeof args[args.length - 1]) {
  3672. var id = this.ids++;
  3673. debug$2("emitting packet with ack id %d", id);
  3674. var ack = args.pop();
  3675. this._registerAckCallback(id, ack);
  3676. packet.id = id;
  3677. }
  3678. var isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
  3679. var isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
  3680. var discardPacket = this.flags["volatile"] && !isTransportWritable;
  3681. if (discardPacket) {
  3682. debug$2("discard packet as the transport is not currently writable");
  3683. } else if (isConnected) {
  3684. this.notifyOutgoingListeners(packet);
  3685. this.packet(packet);
  3686. } else {
  3687. this.sendBuffer.push(packet);
  3688. }
  3689. this.flags = {};
  3690. return this;
  3691. }
  3692. /**
  3693. * @private
  3694. */;
  3695. _proto._registerAckCallback = function _registerAckCallback(id, ack) {
  3696. var _this2 = this;
  3697. var _a;
  3698. var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  3699. if (timeout === undefined) {
  3700. this.acks[id] = ack;
  3701. return;
  3702. }
  3703. // @ts-ignore
  3704. var timer = this.io.setTimeoutFn(function () {
  3705. delete _this2.acks[id];
  3706. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  3707. if (_this2.sendBuffer[i].id === id) {
  3708. debug$2("removing packet with ack id %d from the buffer", id);
  3709. _this2.sendBuffer.splice(i, 1);
  3710. }
  3711. }
  3712. debug$2("event with ack id %d has timed out after %d ms", id, timeout);
  3713. ack.call(_this2, new Error("operation has timed out"));
  3714. }, timeout);
  3715. var fn = function fn() {
  3716. // @ts-ignore
  3717. _this2.io.clearTimeoutFn(timer);
  3718. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  3719. args[_key3] = arguments[_key3];
  3720. }
  3721. ack.apply(_this2, args);
  3722. };
  3723. fn.withError = true;
  3724. this.acks[id] = fn;
  3725. }
  3726. /**
  3727. * Emits an event and waits for an acknowledgement
  3728. *
  3729. * @example
  3730. * // without timeout
  3731. * const response = await socket.emitWithAck("hello", "world");
  3732. *
  3733. * // with a specific timeout
  3734. * try {
  3735. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  3736. * } catch (err) {
  3737. * // the server did not acknowledge the event in the given delay
  3738. * }
  3739. *
  3740. * @return a Promise that will be fulfilled when the server acknowledges the event
  3741. */;
  3742. _proto.emitWithAck = function emitWithAck(ev) {
  3743. var _this3 = this;
  3744. for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  3745. args[_key4 - 1] = arguments[_key4];
  3746. }
  3747. return new Promise(function (resolve, reject) {
  3748. var fn = function fn(arg1, arg2) {
  3749. return arg1 ? reject(arg1) : resolve(arg2);
  3750. };
  3751. fn.withError = true;
  3752. args.push(fn);
  3753. _this3.emit.apply(_this3, [ev].concat(args));
  3754. });
  3755. }
  3756. /**
  3757. * Add the packet to the queue.
  3758. * @param args
  3759. * @private
  3760. */;
  3761. _proto._addToQueue = function _addToQueue(args) {
  3762. var _this4 = this;
  3763. var ack;
  3764. if (typeof args[args.length - 1] === "function") {
  3765. ack = args.pop();
  3766. }
  3767. var packet = {
  3768. id: this._queueSeq++,
  3769. tryCount: 0,
  3770. pending: false,
  3771. args: args,
  3772. flags: _extends({
  3773. fromQueue: true
  3774. }, this.flags)
  3775. };
  3776. args.push(function (err) {
  3777. if (packet !== _this4._queue[0]) {
  3778. return debug$2("packet [%d] already acknowledged", packet.id);
  3779. }
  3780. var hasError = err !== null;
  3781. if (hasError) {
  3782. if (packet.tryCount > _this4._opts.retries) {
  3783. debug$2("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
  3784. _this4._queue.shift();
  3785. if (ack) {
  3786. ack(err);
  3787. }
  3788. }
  3789. } else {
  3790. debug$2("packet [%d] was successfully sent", packet.id);
  3791. _this4._queue.shift();
  3792. if (ack) {
  3793. for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  3794. responseArgs[_key5 - 1] = arguments[_key5];
  3795. }
  3796. ack.apply(void 0, [null].concat(responseArgs));
  3797. }
  3798. }
  3799. packet.pending = false;
  3800. return _this4._drainQueue();
  3801. });
  3802. this._queue.push(packet);
  3803. this._drainQueue();
  3804. }
  3805. /**
  3806. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  3807. * @param force - whether to resend a packet that has not been acknowledged yet
  3808. *
  3809. * @private
  3810. */;
  3811. _proto._drainQueue = function _drainQueue() {
  3812. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  3813. debug$2("draining queue");
  3814. if (!this.connected || this._queue.length === 0) {
  3815. return;
  3816. }
  3817. var packet = this._queue[0];
  3818. if (packet.pending && !force) {
  3819. debug$2("packet [%d] has already been sent and is waiting for an ack", packet.id);
  3820. return;
  3821. }
  3822. packet.pending = true;
  3823. packet.tryCount++;
  3824. debug$2("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
  3825. this.flags = packet.flags;
  3826. this.emit.apply(this, packet.args);
  3827. }
  3828. /**
  3829. * Sends a packet.
  3830. *
  3831. * @param packet
  3832. * @private
  3833. */;
  3834. _proto.packet = function packet(_packet) {
  3835. _packet.nsp = this.nsp;
  3836. this.io._packet(_packet);
  3837. }
  3838. /**
  3839. * Called upon engine `open`.
  3840. *
  3841. * @private
  3842. */;
  3843. _proto.onopen = function onopen() {
  3844. var _this5 = this;
  3845. debug$2("transport is open - connecting");
  3846. if (typeof this.auth == "function") {
  3847. this.auth(function (data) {
  3848. _this5._sendConnectPacket(data);
  3849. });
  3850. } else {
  3851. this._sendConnectPacket(this.auth);
  3852. }
  3853. }
  3854. /**
  3855. * Sends a CONNECT packet to initiate the Socket.IO session.
  3856. *
  3857. * @param data
  3858. * @private
  3859. */;
  3860. _proto._sendConnectPacket = function _sendConnectPacket(data) {
  3861. this.packet({
  3862. type: PacketType.CONNECT,
  3863. data: this._pid ? _extends({
  3864. pid: this._pid,
  3865. offset: this._lastOffset
  3866. }, data) : data
  3867. });
  3868. }
  3869. /**
  3870. * Called upon engine or manager `error`.
  3871. *
  3872. * @param err
  3873. * @private
  3874. */;
  3875. _proto.onerror = function onerror(err) {
  3876. if (!this.connected) {
  3877. this.emitReserved("connect_error", err);
  3878. }
  3879. }
  3880. /**
  3881. * Called upon engine `close`.
  3882. *
  3883. * @param reason
  3884. * @param description
  3885. * @private
  3886. */;
  3887. _proto.onclose = function onclose(reason, description) {
  3888. debug$2("close (%s)", reason);
  3889. this.connected = false;
  3890. delete this.id;
  3891. this.emitReserved("disconnect", reason, description);
  3892. this._clearAcks();
  3893. }
  3894. /**
  3895. * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
  3896. * the server.
  3897. *
  3898. * @private
  3899. */;
  3900. _proto._clearAcks = function _clearAcks() {
  3901. var _this6 = this;
  3902. Object.keys(this.acks).forEach(function (id) {
  3903. var isBuffered = _this6.sendBuffer.some(function (packet) {
  3904. return String(packet.id) === id;
  3905. });
  3906. if (!isBuffered) {
  3907. // note: handlers that do not accept an error as first argument are ignored here
  3908. var ack = _this6.acks[id];
  3909. delete _this6.acks[id];
  3910. if (ack.withError) {
  3911. ack.call(_this6, new Error("socket has been disconnected"));
  3912. }
  3913. }
  3914. });
  3915. }
  3916. /**
  3917. * Called with socket packet.
  3918. *
  3919. * @param packet
  3920. * @private
  3921. */;
  3922. _proto.onpacket = function onpacket(packet) {
  3923. var sameNamespace = packet.nsp === this.nsp;
  3924. if (!sameNamespace) return;
  3925. switch (packet.type) {
  3926. case PacketType.CONNECT:
  3927. if (packet.data && packet.data.sid) {
  3928. this.onconnect(packet.data.sid, packet.data.pid);
  3929. } else {
  3930. 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/)"));
  3931. }
  3932. break;
  3933. case PacketType.EVENT:
  3934. case PacketType.BINARY_EVENT:
  3935. this.onevent(packet);
  3936. break;
  3937. case PacketType.ACK:
  3938. case PacketType.BINARY_ACK:
  3939. this.onack(packet);
  3940. break;
  3941. case PacketType.DISCONNECT:
  3942. this.ondisconnect();
  3943. break;
  3944. case PacketType.CONNECT_ERROR:
  3945. this.destroy();
  3946. var err = new Error(packet.data.message);
  3947. // @ts-ignore
  3948. err.data = packet.data.data;
  3949. this.emitReserved("connect_error", err);
  3950. break;
  3951. }
  3952. }
  3953. /**
  3954. * Called upon a server event.
  3955. *
  3956. * @param packet
  3957. * @private
  3958. */;
  3959. _proto.onevent = function onevent(packet) {
  3960. var args = packet.data || [];
  3961. debug$2("emitting event %j", args);
  3962. if (null != packet.id) {
  3963. debug$2("attaching ack callback to event");
  3964. args.push(this.ack(packet.id));
  3965. }
  3966. if (this.connected) {
  3967. this.emitEvent(args);
  3968. } else {
  3969. this.receiveBuffer.push(Object.freeze(args));
  3970. }
  3971. };
  3972. _proto.emitEvent = function emitEvent(args) {
  3973. if (this._anyListeners && this._anyListeners.length) {
  3974. var listeners = this._anyListeners.slice();
  3975. var _iterator = _createForOfIteratorHelper(listeners),
  3976. _step;
  3977. try {
  3978. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3979. var listener = _step.value;
  3980. listener.apply(this, args);
  3981. }
  3982. } catch (err) {
  3983. _iterator.e(err);
  3984. } finally {
  3985. _iterator.f();
  3986. }
  3987. }
  3988. _Emitter.prototype.emit.apply(this, args);
  3989. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  3990. this._lastOffset = args[args.length - 1];
  3991. }
  3992. }
  3993. /**
  3994. * Produces an ack callback to emit with an event.
  3995. *
  3996. * @private
  3997. */;
  3998. _proto.ack = function ack(id) {
  3999. var self = this;
  4000. var sent = false;
  4001. return function () {
  4002. // prevent double callbacks
  4003. if (sent) return;
  4004. sent = true;
  4005. for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  4006. args[_key6] = arguments[_key6];
  4007. }
  4008. debug$2("sending ack %j", args);
  4009. self.packet({
  4010. type: PacketType.ACK,
  4011. id: id,
  4012. data: args
  4013. });
  4014. };
  4015. }
  4016. /**
  4017. * Called upon a server acknowledgement.
  4018. *
  4019. * @param packet
  4020. * @private
  4021. */;
  4022. _proto.onack = function onack(packet) {
  4023. var ack = this.acks[packet.id];
  4024. if (typeof ack !== "function") {
  4025. debug$2("bad ack %s", packet.id);
  4026. return;
  4027. }
  4028. delete this.acks[packet.id];
  4029. debug$2("calling ack %s with %j", packet.id, packet.data);
  4030. // @ts-ignore FIXME ack is incorrectly inferred as 'never'
  4031. if (ack.withError) {
  4032. packet.data.unshift(null);
  4033. }
  4034. // @ts-ignore
  4035. ack.apply(this, packet.data);
  4036. }
  4037. /**
  4038. * Called upon server connect.
  4039. *
  4040. * @private
  4041. */;
  4042. _proto.onconnect = function onconnect(id, pid) {
  4043. debug$2("socket connected with id %s", id);
  4044. this.id = id;
  4045. this.recovered = pid && this._pid === pid;
  4046. this._pid = pid; // defined only if connection state recovery is enabled
  4047. this.connected = true;
  4048. this.emitBuffered();
  4049. this._drainQueue(true);
  4050. this.emitReserved("connect");
  4051. }
  4052. /**
  4053. * Emit buffered events (received and emitted).
  4054. *
  4055. * @private
  4056. */;
  4057. _proto.emitBuffered = function emitBuffered() {
  4058. var _this7 = this;
  4059. this.receiveBuffer.forEach(function (args) {
  4060. return _this7.emitEvent(args);
  4061. });
  4062. this.receiveBuffer = [];
  4063. this.sendBuffer.forEach(function (packet) {
  4064. _this7.notifyOutgoingListeners(packet);
  4065. _this7.packet(packet);
  4066. });
  4067. this.sendBuffer = [];
  4068. }
  4069. /**
  4070. * Called upon server disconnect.
  4071. *
  4072. * @private
  4073. */;
  4074. _proto.ondisconnect = function ondisconnect() {
  4075. debug$2("server disconnect (%s)", this.nsp);
  4076. this.destroy();
  4077. this.onclose("io server disconnect");
  4078. }
  4079. /**
  4080. * Called upon forced client/server side disconnections,
  4081. * this method ensures the manager stops tracking us and
  4082. * that reconnections don't get triggered for this.
  4083. *
  4084. * @private
  4085. */;
  4086. _proto.destroy = function destroy() {
  4087. if (this.subs) {
  4088. // clean subscriptions to avoid reconnections
  4089. this.subs.forEach(function (subDestroy) {
  4090. return subDestroy();
  4091. });
  4092. this.subs = undefined;
  4093. }
  4094. this.io["_destroy"](this);
  4095. }
  4096. /**
  4097. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  4098. *
  4099. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  4100. *
  4101. * @example
  4102. * const socket = io();
  4103. *
  4104. * socket.on("disconnect", (reason) => {
  4105. * // console.log(reason); prints "io client disconnect"
  4106. * });
  4107. *
  4108. * socket.disconnect();
  4109. *
  4110. * @return self
  4111. */;
  4112. _proto.disconnect = function disconnect() {
  4113. if (this.connected) {
  4114. debug$2("performing disconnect (%s)", this.nsp);
  4115. this.packet({
  4116. type: PacketType.DISCONNECT
  4117. });
  4118. }
  4119. // remove socket from pool
  4120. this.destroy();
  4121. if (this.connected) {
  4122. // fire events
  4123. this.onclose("io client disconnect");
  4124. }
  4125. return this;
  4126. }
  4127. /**
  4128. * Alias for {@link disconnect()}.
  4129. *
  4130. * @return self
  4131. */;
  4132. _proto.close = function close() {
  4133. return this.disconnect();
  4134. }
  4135. /**
  4136. * Sets the compress flag.
  4137. *
  4138. * @example
  4139. * socket.compress(false).emit("hello");
  4140. *
  4141. * @param compress - if `true`, compresses the sending data
  4142. * @return self
  4143. */;
  4144. _proto.compress = function compress(_compress) {
  4145. this.flags.compress = _compress;
  4146. return this;
  4147. }
  4148. /**
  4149. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  4150. * ready to send messages.
  4151. *
  4152. * @example
  4153. * socket.volatile.emit("hello"); // the server may or may not receive it
  4154. *
  4155. * @returns self
  4156. */;
  4157. /**
  4158. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  4159. * given number of milliseconds have elapsed without an acknowledgement from the server:
  4160. *
  4161. * @example
  4162. * socket.timeout(5000).emit("my-event", (err) => {
  4163. * if (err) {
  4164. * // the server did not acknowledge the event in the given delay
  4165. * }
  4166. * });
  4167. *
  4168. * @returns self
  4169. */
  4170. _proto.timeout = function timeout(_timeout) {
  4171. this.flags.timeout = _timeout;
  4172. return this;
  4173. }
  4174. /**
  4175. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4176. * callback.
  4177. *
  4178. * @example
  4179. * socket.onAny((event, ...args) => {
  4180. * console.log(`got ${event}`);
  4181. * });
  4182. *
  4183. * @param listener
  4184. */;
  4185. _proto.onAny = function onAny(listener) {
  4186. this._anyListeners = this._anyListeners || [];
  4187. this._anyListeners.push(listener);
  4188. return this;
  4189. }
  4190. /**
  4191. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4192. * callback. The listener is added to the beginning of the listeners array.
  4193. *
  4194. * @example
  4195. * socket.prependAny((event, ...args) => {
  4196. * console.log(`got event ${event}`);
  4197. * });
  4198. *
  4199. * @param listener
  4200. */;
  4201. _proto.prependAny = function prependAny(listener) {
  4202. this._anyListeners = this._anyListeners || [];
  4203. this._anyListeners.unshift(listener);
  4204. return this;
  4205. }
  4206. /**
  4207. * Removes the listener that will be fired when any event is emitted.
  4208. *
  4209. * @example
  4210. * const catchAllListener = (event, ...args) => {
  4211. * console.log(`got event ${event}`);
  4212. * }
  4213. *
  4214. * socket.onAny(catchAllListener);
  4215. *
  4216. * // remove a specific listener
  4217. * socket.offAny(catchAllListener);
  4218. *
  4219. * // or remove all listeners
  4220. * socket.offAny();
  4221. *
  4222. * @param listener
  4223. */;
  4224. _proto.offAny = function offAny(listener) {
  4225. if (!this._anyListeners) {
  4226. return this;
  4227. }
  4228. if (listener) {
  4229. var listeners = this._anyListeners;
  4230. for (var i = 0; i < listeners.length; i++) {
  4231. if (listener === listeners[i]) {
  4232. listeners.splice(i, 1);
  4233. return this;
  4234. }
  4235. }
  4236. } else {
  4237. this._anyListeners = [];
  4238. }
  4239. return this;
  4240. }
  4241. /**
  4242. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4243. * e.g. to remove listeners.
  4244. */;
  4245. _proto.listenersAny = function listenersAny() {
  4246. return this._anyListeners || [];
  4247. }
  4248. /**
  4249. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4250. * callback.
  4251. *
  4252. * Note: acknowledgements sent to the server are not included.
  4253. *
  4254. * @example
  4255. * socket.onAnyOutgoing((event, ...args) => {
  4256. * console.log(`sent event ${event}`);
  4257. * });
  4258. *
  4259. * @param listener
  4260. */;
  4261. _proto.onAnyOutgoing = function onAnyOutgoing(listener) {
  4262. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4263. this._anyOutgoingListeners.push(listener);
  4264. return this;
  4265. }
  4266. /**
  4267. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4268. * callback. The listener is added to the beginning of the listeners array.
  4269. *
  4270. * Note: acknowledgements sent to the server are not included.
  4271. *
  4272. * @example
  4273. * socket.prependAnyOutgoing((event, ...args) => {
  4274. * console.log(`sent event ${event}`);
  4275. * });
  4276. *
  4277. * @param listener
  4278. */;
  4279. _proto.prependAnyOutgoing = function prependAnyOutgoing(listener) {
  4280. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4281. this._anyOutgoingListeners.unshift(listener);
  4282. return this;
  4283. }
  4284. /**
  4285. * Removes the listener that will be fired when any event is emitted.
  4286. *
  4287. * @example
  4288. * const catchAllListener = (event, ...args) => {
  4289. * console.log(`sent event ${event}`);
  4290. * }
  4291. *
  4292. * socket.onAnyOutgoing(catchAllListener);
  4293. *
  4294. * // remove a specific listener
  4295. * socket.offAnyOutgoing(catchAllListener);
  4296. *
  4297. * // or remove all listeners
  4298. * socket.offAnyOutgoing();
  4299. *
  4300. * @param [listener] - the catch-all listener (optional)
  4301. */;
  4302. _proto.offAnyOutgoing = function offAnyOutgoing(listener) {
  4303. if (!this._anyOutgoingListeners) {
  4304. return this;
  4305. }
  4306. if (listener) {
  4307. var listeners = this._anyOutgoingListeners;
  4308. for (var i = 0; i < listeners.length; i++) {
  4309. if (listener === listeners[i]) {
  4310. listeners.splice(i, 1);
  4311. return this;
  4312. }
  4313. }
  4314. } else {
  4315. this._anyOutgoingListeners = [];
  4316. }
  4317. return this;
  4318. }
  4319. /**
  4320. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4321. * e.g. to remove listeners.
  4322. */;
  4323. _proto.listenersAnyOutgoing = function listenersAnyOutgoing() {
  4324. return this._anyOutgoingListeners || [];
  4325. }
  4326. /**
  4327. * Notify the listeners for each packet sent
  4328. *
  4329. * @param packet
  4330. *
  4331. * @private
  4332. */;
  4333. _proto.notifyOutgoingListeners = function notifyOutgoingListeners(packet) {
  4334. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  4335. var listeners = this._anyOutgoingListeners.slice();
  4336. var _iterator2 = _createForOfIteratorHelper(listeners),
  4337. _step2;
  4338. try {
  4339. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4340. var listener = _step2.value;
  4341. listener.apply(this, packet.data);
  4342. }
  4343. } catch (err) {
  4344. _iterator2.e(err);
  4345. } finally {
  4346. _iterator2.f();
  4347. }
  4348. }
  4349. };
  4350. return _createClass(Socket, [{
  4351. key: "disconnected",
  4352. get: function get() {
  4353. return !this.connected;
  4354. }
  4355. }, {
  4356. key: "active",
  4357. get: function get() {
  4358. return !!this.subs;
  4359. }
  4360. }, {
  4361. key: "volatile",
  4362. get: function get() {
  4363. this.flags["volatile"] = true;
  4364. return this;
  4365. }
  4366. }]);
  4367. }(Emitter);
  4368. /**
  4369. * Initialize backoff timer with `opts`.
  4370. *
  4371. * - `min` initial timeout in milliseconds [100]
  4372. * - `max` max timeout [10000]
  4373. * - `jitter` [0]
  4374. * - `factor` [2]
  4375. *
  4376. * @param {Object} opts
  4377. * @api public
  4378. */
  4379. function Backoff(opts) {
  4380. opts = opts || {};
  4381. this.ms = opts.min || 100;
  4382. this.max = opts.max || 10000;
  4383. this.factor = opts.factor || 2;
  4384. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  4385. this.attempts = 0;
  4386. }
  4387. /**
  4388. * Return the backoff duration.
  4389. *
  4390. * @return {Number}
  4391. * @api public
  4392. */
  4393. Backoff.prototype.duration = function () {
  4394. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  4395. if (this.jitter) {
  4396. var rand = Math.random();
  4397. var deviation = Math.floor(rand * this.jitter * ms);
  4398. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  4399. }
  4400. return Math.min(ms, this.max) | 0;
  4401. };
  4402. /**
  4403. * Reset the number of attempts.
  4404. *
  4405. * @api public
  4406. */
  4407. Backoff.prototype.reset = function () {
  4408. this.attempts = 0;
  4409. };
  4410. /**
  4411. * Set the minimum duration
  4412. *
  4413. * @api public
  4414. */
  4415. Backoff.prototype.setMin = function (min) {
  4416. this.ms = min;
  4417. };
  4418. /**
  4419. * Set the maximum duration
  4420. *
  4421. * @api public
  4422. */
  4423. Backoff.prototype.setMax = function (max) {
  4424. this.max = max;
  4425. };
  4426. /**
  4427. * Set the jitter
  4428. *
  4429. * @api public
  4430. */
  4431. Backoff.prototype.setJitter = function (jitter) {
  4432. this.jitter = jitter;
  4433. };
  4434. var debug$1 = debugModule("socket.io-client:manager"); // debug()
  4435. var Manager = /*#__PURE__*/function (_Emitter) {
  4436. function Manager(uri, opts) {
  4437. var _this;
  4438. var _a;
  4439. _this = _Emitter.call(this) || this;
  4440. _this.nsps = {};
  4441. _this.subs = [];
  4442. if (uri && "object" === _typeof(uri)) {
  4443. opts = uri;
  4444. uri = undefined;
  4445. }
  4446. opts = opts || {};
  4447. opts.path = opts.path || "/socket.io";
  4448. _this.opts = opts;
  4449. installTimerFunctions(_this, opts);
  4450. _this.reconnection(opts.reconnection !== false);
  4451. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  4452. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  4453. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  4454. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  4455. _this.backoff = new Backoff({
  4456. min: _this.reconnectionDelay(),
  4457. max: _this.reconnectionDelayMax(),
  4458. jitter: _this.randomizationFactor()
  4459. });
  4460. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  4461. _this._readyState = "closed";
  4462. _this.uri = uri;
  4463. var _parser = opts.parser || parser;
  4464. _this.encoder = new _parser.Encoder();
  4465. _this.decoder = new _parser.Decoder();
  4466. _this._autoConnect = opts.autoConnect !== false;
  4467. if (_this._autoConnect) _this.open();
  4468. return _this;
  4469. }
  4470. _inheritsLoose(Manager, _Emitter);
  4471. var _proto = Manager.prototype;
  4472. _proto.reconnection = function reconnection(v) {
  4473. if (!arguments.length) return this._reconnection;
  4474. this._reconnection = !!v;
  4475. if (!v) {
  4476. this.skipReconnect = true;
  4477. }
  4478. return this;
  4479. };
  4480. _proto.reconnectionAttempts = function reconnectionAttempts(v) {
  4481. if (v === undefined) return this._reconnectionAttempts;
  4482. this._reconnectionAttempts = v;
  4483. return this;
  4484. };
  4485. _proto.reconnectionDelay = function reconnectionDelay(v) {
  4486. var _a;
  4487. if (v === undefined) return this._reconnectionDelay;
  4488. this._reconnectionDelay = v;
  4489. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  4490. return this;
  4491. };
  4492. _proto.randomizationFactor = function randomizationFactor(v) {
  4493. var _a;
  4494. if (v === undefined) return this._randomizationFactor;
  4495. this._randomizationFactor = v;
  4496. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  4497. return this;
  4498. };
  4499. _proto.reconnectionDelayMax = function reconnectionDelayMax(v) {
  4500. var _a;
  4501. if (v === undefined) return this._reconnectionDelayMax;
  4502. this._reconnectionDelayMax = v;
  4503. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  4504. return this;
  4505. };
  4506. _proto.timeout = function timeout(v) {
  4507. if (!arguments.length) return this._timeout;
  4508. this._timeout = v;
  4509. return this;
  4510. }
  4511. /**
  4512. * Starts trying to reconnect if reconnection is enabled and we have not
  4513. * started reconnecting yet
  4514. *
  4515. * @private
  4516. */;
  4517. _proto.maybeReconnectOnOpen = function maybeReconnectOnOpen() {
  4518. // Only try to reconnect if it's the first time we're connecting
  4519. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  4520. // keeps reconnection from firing twice for the same reconnection loop
  4521. this.reconnect();
  4522. }
  4523. }
  4524. /**
  4525. * Sets the current transport `socket`.
  4526. *
  4527. * @param {Function} fn - optional, callback
  4528. * @return self
  4529. * @public
  4530. */;
  4531. _proto.open = function open(fn) {
  4532. var _this2 = this;
  4533. debug$1("readyState %s", this._readyState);
  4534. if (~this._readyState.indexOf("open")) return this;
  4535. debug$1("opening %s", this.uri);
  4536. this.engine = new Socket$1(this.uri, this.opts);
  4537. var socket = this.engine;
  4538. var self = this;
  4539. this._readyState = "opening";
  4540. this.skipReconnect = false;
  4541. // emit `open`
  4542. var openSubDestroy = on(socket, "open", function () {
  4543. self.onopen();
  4544. fn && fn();
  4545. });
  4546. var onError = function onError(err) {
  4547. debug$1("error");
  4548. _this2.cleanup();
  4549. _this2._readyState = "closed";
  4550. _this2.emitReserved("error", err);
  4551. if (fn) {
  4552. fn(err);
  4553. } else {
  4554. // Only do this if there is no fn to handle the error
  4555. _this2.maybeReconnectOnOpen();
  4556. }
  4557. };
  4558. // emit `error`
  4559. var errorSub = on(socket, "error", onError);
  4560. if (false !== this._timeout) {
  4561. var timeout = this._timeout;
  4562. debug$1("connect attempt will timeout after %d", timeout);
  4563. // set timer
  4564. var timer = this.setTimeoutFn(function () {
  4565. debug$1("connect attempt timed out after %d", timeout);
  4566. openSubDestroy();
  4567. onError(new Error("timeout"));
  4568. socket.close();
  4569. }, timeout);
  4570. if (this.opts.autoUnref) {
  4571. timer.unref();
  4572. }
  4573. this.subs.push(function () {
  4574. _this2.clearTimeoutFn(timer);
  4575. });
  4576. }
  4577. this.subs.push(openSubDestroy);
  4578. this.subs.push(errorSub);
  4579. return this;
  4580. }
  4581. /**
  4582. * Alias for open()
  4583. *
  4584. * @return self
  4585. * @public
  4586. */;
  4587. _proto.connect = function connect(fn) {
  4588. return this.open(fn);
  4589. }
  4590. /**
  4591. * Called upon transport open.
  4592. *
  4593. * @private
  4594. */;
  4595. _proto.onopen = function onopen() {
  4596. debug$1("open");
  4597. // clear old subs
  4598. this.cleanup();
  4599. // mark as open
  4600. this._readyState = "open";
  4601. this.emitReserved("open");
  4602. // add new subs
  4603. var socket = this.engine;
  4604. 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)),
  4605. // @ts-ignore
  4606. on(this.decoder, "decoded", this.ondecoded.bind(this)));
  4607. }
  4608. /**
  4609. * Called upon a ping.
  4610. *
  4611. * @private
  4612. */;
  4613. _proto.onping = function onping() {
  4614. this.emitReserved("ping");
  4615. }
  4616. /**
  4617. * Called with data.
  4618. *
  4619. * @private
  4620. */;
  4621. _proto.ondata = function ondata(data) {
  4622. try {
  4623. this.decoder.add(data);
  4624. } catch (e) {
  4625. this.onclose("parse error", e);
  4626. }
  4627. }
  4628. /**
  4629. * Called when parser fully decodes a packet.
  4630. *
  4631. * @private
  4632. */;
  4633. _proto.ondecoded = function ondecoded(packet) {
  4634. var _this3 = this;
  4635. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  4636. nextTick(function () {
  4637. _this3.emitReserved("packet", packet);
  4638. }, this.setTimeoutFn);
  4639. }
  4640. /**
  4641. * Called upon socket error.
  4642. *
  4643. * @private
  4644. */;
  4645. _proto.onerror = function onerror(err) {
  4646. debug$1("error", err);
  4647. this.emitReserved("error", err);
  4648. }
  4649. /**
  4650. * Creates a new socket for the given `nsp`.
  4651. *
  4652. * @return {Socket}
  4653. * @public
  4654. */;
  4655. _proto.socket = function socket(nsp, opts) {
  4656. var socket = this.nsps[nsp];
  4657. if (!socket) {
  4658. socket = new Socket(this, nsp, opts);
  4659. this.nsps[nsp] = socket;
  4660. } else if (this._autoConnect && !socket.active) {
  4661. socket.connect();
  4662. }
  4663. return socket;
  4664. }
  4665. /**
  4666. * Called upon a socket close.
  4667. *
  4668. * @param socket
  4669. * @private
  4670. */;
  4671. _proto._destroy = function _destroy(socket) {
  4672. var nsps = Object.keys(this.nsps);
  4673. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  4674. var nsp = _nsps[_i];
  4675. var _socket = this.nsps[nsp];
  4676. if (_socket.active) {
  4677. debug$1("socket %s is still active, skipping close", nsp);
  4678. return;
  4679. }
  4680. }
  4681. this._close();
  4682. }
  4683. /**
  4684. * Writes a packet.
  4685. *
  4686. * @param packet
  4687. * @private
  4688. */;
  4689. _proto._packet = function _packet(packet) {
  4690. debug$1("writing packet %j", packet);
  4691. var encodedPackets = this.encoder.encode(packet);
  4692. for (var i = 0; i < encodedPackets.length; i++) {
  4693. this.engine.write(encodedPackets[i], packet.options);
  4694. }
  4695. }
  4696. /**
  4697. * Clean up transport subscriptions and packet buffer.
  4698. *
  4699. * @private
  4700. */;
  4701. _proto.cleanup = function cleanup() {
  4702. debug$1("cleanup");
  4703. this.subs.forEach(function (subDestroy) {
  4704. return subDestroy();
  4705. });
  4706. this.subs.length = 0;
  4707. this.decoder.destroy();
  4708. }
  4709. /**
  4710. * Close the current socket.
  4711. *
  4712. * @private
  4713. */;
  4714. _proto._close = function _close() {
  4715. debug$1("disconnect");
  4716. this.skipReconnect = true;
  4717. this._reconnecting = false;
  4718. this.onclose("forced close");
  4719. }
  4720. /**
  4721. * Alias for close()
  4722. *
  4723. * @private
  4724. */;
  4725. _proto.disconnect = function disconnect() {
  4726. return this._close();
  4727. }
  4728. /**
  4729. * Called when:
  4730. *
  4731. * - the low-level engine is closed
  4732. * - the parser encountered a badly formatted packet
  4733. * - all sockets are disconnected
  4734. *
  4735. * @private
  4736. */;
  4737. _proto.onclose = function onclose(reason, description) {
  4738. var _a;
  4739. debug$1("closed due to %s", reason);
  4740. this.cleanup();
  4741. (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
  4742. this.backoff.reset();
  4743. this._readyState = "closed";
  4744. this.emitReserved("close", reason, description);
  4745. if (this._reconnection && !this.skipReconnect) {
  4746. this.reconnect();
  4747. }
  4748. }
  4749. /**
  4750. * Attempt a reconnection.
  4751. *
  4752. * @private
  4753. */;
  4754. _proto.reconnect = function reconnect() {
  4755. var _this4 = this;
  4756. if (this._reconnecting || this.skipReconnect) return this;
  4757. var self = this;
  4758. if (this.backoff.attempts >= this._reconnectionAttempts) {
  4759. debug$1("reconnect failed");
  4760. this.backoff.reset();
  4761. this.emitReserved("reconnect_failed");
  4762. this._reconnecting = false;
  4763. } else {
  4764. var delay = this.backoff.duration();
  4765. debug$1("will wait %dms before reconnect attempt", delay);
  4766. this._reconnecting = true;
  4767. var timer = this.setTimeoutFn(function () {
  4768. if (self.skipReconnect) return;
  4769. debug$1("attempting reconnect");
  4770. _this4.emitReserved("reconnect_attempt", self.backoff.attempts);
  4771. // check again for the case socket closed in above events
  4772. if (self.skipReconnect) return;
  4773. self.open(function (err) {
  4774. if (err) {
  4775. debug$1("reconnect attempt error");
  4776. self._reconnecting = false;
  4777. self.reconnect();
  4778. _this4.emitReserved("reconnect_error", err);
  4779. } else {
  4780. debug$1("reconnect success");
  4781. self.onreconnect();
  4782. }
  4783. });
  4784. }, delay);
  4785. if (this.opts.autoUnref) {
  4786. timer.unref();
  4787. }
  4788. this.subs.push(function () {
  4789. _this4.clearTimeoutFn(timer);
  4790. });
  4791. }
  4792. }
  4793. /**
  4794. * Called upon successful reconnect.
  4795. *
  4796. * @private
  4797. */;
  4798. _proto.onreconnect = function onreconnect() {
  4799. var attempt = this.backoff.attempts;
  4800. this._reconnecting = false;
  4801. this.backoff.reset();
  4802. this.emitReserved("reconnect", attempt);
  4803. };
  4804. return Manager;
  4805. }(Emitter);
  4806. var debug = debugModule("socket.io-client"); // debug()
  4807. /**
  4808. * Managers cache.
  4809. */
  4810. var cache = {};
  4811. function lookup(uri, opts) {
  4812. if (_typeof(uri) === "object") {
  4813. opts = uri;
  4814. uri = undefined;
  4815. }
  4816. opts = opts || {};
  4817. var parsed = url(uri, opts.path || "/socket.io");
  4818. var source = parsed.source;
  4819. var id = parsed.id;
  4820. var path = parsed.path;
  4821. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  4822. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  4823. var io;
  4824. if (newConnection) {
  4825. debug("ignoring socket cache for %s", source);
  4826. io = new Manager(source, opts);
  4827. } else {
  4828. if (!cache[id]) {
  4829. debug("new io instance for %s", source);
  4830. cache[id] = new Manager(source, opts);
  4831. }
  4832. io = cache[id];
  4833. }
  4834. if (parsed.query && !opts.query) {
  4835. opts.query = parsed.queryKey;
  4836. }
  4837. return io.socket(parsed.path, opts);
  4838. }
  4839. // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  4840. // namespace (e.g. `io.connect(...)`), for backward compatibility
  4841. _extends(lookup, {
  4842. Manager: Manager,
  4843. Socket: Socket,
  4844. io: lookup,
  4845. connect: lookup
  4846. });
  4847. return lookup;
  4848. }));
  4849. //# sourceMappingURL=socket.io.js.map