socket.io.js 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908
  1. /*!
  2. * Socket.IO v4.8.1
  3. * (c) 2014-2024 Guillermo Rauch
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.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 i;
  2604. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  2605. var len = split.length;
  2606. for (i = 0; i < len; i++) {
  2607. if (!split[i]) {
  2608. // ignore empty strings
  2609. continue;
  2610. }
  2611. namespaces = split[i].replace(/\*/g, '.*?');
  2612. if (namespaces[0] === '-') {
  2613. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  2614. } else {
  2615. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  2616. }
  2617. }
  2618. }
  2619. /**
  2620. * Disable debug output.
  2621. *
  2622. * @return {String} namespaces
  2623. * @api public
  2624. */
  2625. function disable() {
  2626. var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
  2627. return '-' + namespace;
  2628. }))).join(',');
  2629. createDebug.enable('');
  2630. return namespaces;
  2631. }
  2632. /**
  2633. * Returns true if the given mode name is enabled, false otherwise.
  2634. *
  2635. * @param {String} name
  2636. * @return {Boolean}
  2637. * @api public
  2638. */
  2639. function enabled(name) {
  2640. if (name[name.length - 1] === '*') {
  2641. return true;
  2642. }
  2643. var i;
  2644. var len;
  2645. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  2646. if (createDebug.skips[i].test(name)) {
  2647. return false;
  2648. }
  2649. }
  2650. for (i = 0, len = createDebug.names.length; i < len; i++) {
  2651. if (createDebug.names[i].test(name)) {
  2652. return true;
  2653. }
  2654. }
  2655. return false;
  2656. }
  2657. /**
  2658. * Convert regexp to namespace
  2659. *
  2660. * @param {RegExp} regxep
  2661. * @return {String} namespace
  2662. * @api private
  2663. */
  2664. function toNamespace(regexp) {
  2665. return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
  2666. }
  2667. /**
  2668. * Coerce `val`.
  2669. *
  2670. * @param {Mixed} val
  2671. * @return {Mixed}
  2672. * @api private
  2673. */
  2674. function coerce(val) {
  2675. if (val instanceof Error) {
  2676. return val.stack || val.message;
  2677. }
  2678. return val;
  2679. }
  2680. /**
  2681. * XXX DO NOT USE. This is a temporary stub function.
  2682. * XXX It WILL be removed in the next major release.
  2683. */
  2684. function destroy() {
  2685. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2686. }
  2687. createDebug.enable(createDebug.load());
  2688. return createDebug;
  2689. }
  2690. var common = setup;
  2691. /* eslint-env browser */
  2692. browser.exports;
  2693. (function (module, exports) {
  2694. /**
  2695. * This is the web browser implementation of `debug()`.
  2696. */
  2697. exports.formatArgs = formatArgs;
  2698. exports.save = save;
  2699. exports.load = load;
  2700. exports.useColors = useColors;
  2701. exports.storage = localstorage();
  2702. exports.destroy = function () {
  2703. var warned = false;
  2704. return function () {
  2705. if (!warned) {
  2706. warned = true;
  2707. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2708. }
  2709. };
  2710. }();
  2711. /**
  2712. * Colors.
  2713. */
  2714. 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'];
  2715. /**
  2716. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2717. * and the Firebug extension (any Firefox version) are known
  2718. * to support "%c" CSS customizations.
  2719. *
  2720. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2721. */
  2722. // eslint-disable-next-line complexity
  2723. function useColors() {
  2724. // NB: In an Electron preload script, document will be defined but not fully
  2725. // initialized. Since we know we're in Chrome, we'll just detect this case
  2726. // explicitly
  2727. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  2728. return true;
  2729. }
  2730. // Internet Explorer and Edge do not support colors.
  2731. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  2732. return false;
  2733. }
  2734. // Is webkit? http://stackoverflow.com/a/16459606/376773
  2735. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  2736. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
  2737. // Is firebug? http://stackoverflow.com/a/398120/376773
  2738. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
  2739. // Is firefox >= v31?
  2740. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2741. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
  2742. // Double check webkit in userAgent just in case we are in a worker
  2743. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  2744. }
  2745. /**
  2746. * Colorize log arguments if enabled.
  2747. *
  2748. * @api public
  2749. */
  2750. function formatArgs(args) {
  2751. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  2752. if (!this.useColors) {
  2753. return;
  2754. }
  2755. var c = 'color: ' + this.color;
  2756. args.splice(1, 0, c, 'color: inherit');
  2757. // The final "%c" is somewhat tricky, because there could be other
  2758. // arguments passed either before or after the %c, so we need to
  2759. // figure out the correct index to insert the CSS into
  2760. var index = 0;
  2761. var lastC = 0;
  2762. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  2763. if (match === '%%') {
  2764. return;
  2765. }
  2766. index++;
  2767. if (match === '%c') {
  2768. // We only are interested in the *last* %c
  2769. // (the user may have provided their own)
  2770. lastC = index;
  2771. }
  2772. });
  2773. args.splice(lastC, 0, c);
  2774. }
  2775. /**
  2776. * Invokes `console.debug()` when available.
  2777. * No-op when `console.debug` is not a "function".
  2778. * If `console.debug` is not available, falls back
  2779. * to `console.log`.
  2780. *
  2781. * @api public
  2782. */
  2783. exports.log = console.debug || console.log || function () {};
  2784. /**
  2785. * Save `namespaces`.
  2786. *
  2787. * @param {String} namespaces
  2788. * @api private
  2789. */
  2790. function save(namespaces) {
  2791. try {
  2792. if (namespaces) {
  2793. exports.storage.setItem('debug', namespaces);
  2794. } else {
  2795. exports.storage.removeItem('debug');
  2796. }
  2797. } catch (error) {
  2798. // Swallow
  2799. // XXX (@Qix-) should we be logging these?
  2800. }
  2801. }
  2802. /**
  2803. * Load `namespaces`.
  2804. *
  2805. * @return {String} returns the previously persisted debug modes
  2806. * @api private
  2807. */
  2808. function load() {
  2809. var r;
  2810. try {
  2811. r = exports.storage.getItem('debug');
  2812. } catch (error) {
  2813. // Swallow
  2814. // XXX (@Qix-) should we be logging these?
  2815. }
  2816. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  2817. if (!r && typeof process !== 'undefined' && 'env' in process) {
  2818. r = process.env.DEBUG;
  2819. }
  2820. return r;
  2821. }
  2822. /**
  2823. * Localstorage attempts to return the localstorage.
  2824. *
  2825. * This is necessary because safari throws
  2826. * when a user disables cookies/localstorage
  2827. * and you attempt to access it.
  2828. *
  2829. * @return {LocalStorage}
  2830. * @api private
  2831. */
  2832. function localstorage() {
  2833. try {
  2834. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  2835. // The Browser also has localStorage in the global context.
  2836. return localStorage;
  2837. } catch (error) {
  2838. // Swallow
  2839. // XXX (@Qix-) should we be logging these?
  2840. }
  2841. }
  2842. module.exports = common(exports);
  2843. var formatters = module.exports.formatters;
  2844. /**
  2845. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2846. */
  2847. formatters.j = function (v) {
  2848. try {
  2849. return JSON.stringify(v);
  2850. } catch (error) {
  2851. return '[UnexpectedJSONParseError]: ' + error.message;
  2852. }
  2853. };
  2854. })(browser, browser.exports);
  2855. var browserExports = browser.exports;
  2856. var debugModule = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
  2857. var debug$3 = debugModule("socket.io-client:url"); // debug()
  2858. /**
  2859. * URL parser.
  2860. *
  2861. * @param uri - url
  2862. * @param path - the request path of the connection
  2863. * @param loc - An object meant to mimic window.location.
  2864. * Defaults to window.location.
  2865. * @public
  2866. */
  2867. function url(uri) {
  2868. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2869. var loc = arguments.length > 2 ? arguments[2] : undefined;
  2870. var obj = uri;
  2871. // default to window.location
  2872. loc = loc || typeof location !== "undefined" && location;
  2873. if (null == uri) uri = loc.protocol + "//" + loc.host;
  2874. // relative path support
  2875. if (typeof uri === "string") {
  2876. if ("/" === uri.charAt(0)) {
  2877. if ("/" === uri.charAt(1)) {
  2878. uri = loc.protocol + uri;
  2879. } else {
  2880. uri = loc.host + uri;
  2881. }
  2882. }
  2883. if (!/^(https?|wss?):\/\//.test(uri)) {
  2884. debug$3("protocol-less url %s", uri);
  2885. if ("undefined" !== typeof loc) {
  2886. uri = loc.protocol + "//" + uri;
  2887. } else {
  2888. uri = "https://" + uri;
  2889. }
  2890. }
  2891. // parse
  2892. debug$3("parse %s", uri);
  2893. obj = parse(uri);
  2894. }
  2895. // make sure we treat `localhost:80` and `localhost` equally
  2896. if (!obj.port) {
  2897. if (/^(http|ws)$/.test(obj.protocol)) {
  2898. obj.port = "80";
  2899. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  2900. obj.port = "443";
  2901. }
  2902. }
  2903. obj.path = obj.path || "/";
  2904. var ipv6 = obj.host.indexOf(":") !== -1;
  2905. var host = ipv6 ? "[" + obj.host + "]" : obj.host;
  2906. // define unique id
  2907. obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
  2908. // define href
  2909. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  2910. return obj;
  2911. }
  2912. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2913. var isView = function isView(obj) {
  2914. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2915. };
  2916. var toString = Object.prototype.toString;
  2917. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2918. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2919. /**
  2920. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2921. *
  2922. * @private
  2923. */
  2924. function isBinary(obj) {
  2925. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2926. }
  2927. function hasBinary(obj, toJSON) {
  2928. if (!obj || _typeof(obj) !== "object") {
  2929. return false;
  2930. }
  2931. if (Array.isArray(obj)) {
  2932. for (var i = 0, l = obj.length; i < l; i++) {
  2933. if (hasBinary(obj[i])) {
  2934. return true;
  2935. }
  2936. }
  2937. return false;
  2938. }
  2939. if (isBinary(obj)) {
  2940. return true;
  2941. }
  2942. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2943. return hasBinary(obj.toJSON(), true);
  2944. }
  2945. for (var key in obj) {
  2946. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2947. return true;
  2948. }
  2949. }
  2950. return false;
  2951. }
  2952. /**
  2953. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  2954. *
  2955. * @param {Object} packet - socket.io event packet
  2956. * @return {Object} with deconstructed packet and list of buffers
  2957. * @public
  2958. */
  2959. function deconstructPacket(packet) {
  2960. var buffers = [];
  2961. var packetData = packet.data;
  2962. var pack = packet;
  2963. pack.data = _deconstructPacket(packetData, buffers);
  2964. pack.attachments = buffers.length; // number of binary 'attachments'
  2965. return {
  2966. packet: pack,
  2967. buffers: buffers
  2968. };
  2969. }
  2970. function _deconstructPacket(data, buffers) {
  2971. if (!data) return data;
  2972. if (isBinary(data)) {
  2973. var placeholder = {
  2974. _placeholder: true,
  2975. num: buffers.length
  2976. };
  2977. buffers.push(data);
  2978. return placeholder;
  2979. } else if (Array.isArray(data)) {
  2980. var newData = new Array(data.length);
  2981. for (var i = 0; i < data.length; i++) {
  2982. newData[i] = _deconstructPacket(data[i], buffers);
  2983. }
  2984. return newData;
  2985. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  2986. var _newData = {};
  2987. for (var key in data) {
  2988. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2989. _newData[key] = _deconstructPacket(data[key], buffers);
  2990. }
  2991. }
  2992. return _newData;
  2993. }
  2994. return data;
  2995. }
  2996. /**
  2997. * Reconstructs a binary packet from its placeholder packet and buffers
  2998. *
  2999. * @param {Object} packet - event packet with placeholders
  3000. * @param {Array} buffers - binary buffers to put in placeholder positions
  3001. * @return {Object} reconstructed packet
  3002. * @public
  3003. */
  3004. function reconstructPacket(packet, buffers) {
  3005. packet.data = _reconstructPacket(packet.data, buffers);
  3006. delete packet.attachments; // no longer useful
  3007. return packet;
  3008. }
  3009. function _reconstructPacket(data, buffers) {
  3010. if (!data) return data;
  3011. if (data && data._placeholder === true) {
  3012. var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
  3013. if (isIndexValid) {
  3014. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  3015. } else {
  3016. throw new Error("illegal attachments");
  3017. }
  3018. } else if (Array.isArray(data)) {
  3019. for (var i = 0; i < data.length; i++) {
  3020. data[i] = _reconstructPacket(data[i], buffers);
  3021. }
  3022. } else if (_typeof(data) === "object") {
  3023. for (var key in data) {
  3024. if (Object.prototype.hasOwnProperty.call(data, key)) {
  3025. data[key] = _reconstructPacket(data[key], buffers);
  3026. }
  3027. }
  3028. }
  3029. return data;
  3030. }
  3031. /**
  3032. * These strings must not be used as event names, as they have a special meaning.
  3033. */
  3034. var RESERVED_EVENTS$1 = ["connect",
  3035. // used on the client side
  3036. "connect_error",
  3037. // used on the client side
  3038. "disconnect",
  3039. // used on both sides
  3040. "disconnecting",
  3041. // used on the server side
  3042. "newListener",
  3043. // used by the Node.js EventEmitter
  3044. "removeListener" // used by the Node.js EventEmitter
  3045. ];
  3046. /**
  3047. * Protocol version.
  3048. *
  3049. * @public
  3050. */
  3051. var protocol = 5;
  3052. var PacketType;
  3053. (function (PacketType) {
  3054. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  3055. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  3056. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  3057. PacketType[PacketType["ACK"] = 3] = "ACK";
  3058. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  3059. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  3060. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  3061. })(PacketType || (PacketType = {}));
  3062. /**
  3063. * A socket.io Encoder instance
  3064. */
  3065. var Encoder = /*#__PURE__*/function () {
  3066. /**
  3067. * Encoder constructor
  3068. *
  3069. * @param {function} replacer - custom replacer to pass down to JSON.parse
  3070. */
  3071. function Encoder(replacer) {
  3072. this.replacer = replacer;
  3073. }
  3074. /**
  3075. * Encode a packet as a single string if non-binary, or as a
  3076. * buffer sequence, depending on packet type.
  3077. *
  3078. * @param {Object} obj - packet object
  3079. */
  3080. var _proto = Encoder.prototype;
  3081. _proto.encode = function encode(obj) {
  3082. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  3083. if (hasBinary(obj)) {
  3084. return this.encodeAsBinary({
  3085. type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
  3086. nsp: obj.nsp,
  3087. data: obj.data,
  3088. id: obj.id
  3089. });
  3090. }
  3091. }
  3092. return [this.encodeAsString(obj)];
  3093. }
  3094. /**
  3095. * Encode packet as string.
  3096. */;
  3097. _proto.encodeAsString = function encodeAsString(obj) {
  3098. // first is type
  3099. var str = "" + obj.type;
  3100. // attachments if we have them
  3101. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  3102. str += obj.attachments + "-";
  3103. }
  3104. // if we have a namespace other than `/`
  3105. // we append it followed by a comma `,`
  3106. if (obj.nsp && "/" !== obj.nsp) {
  3107. str += obj.nsp + ",";
  3108. }
  3109. // immediately followed by the id
  3110. if (null != obj.id) {
  3111. str += obj.id;
  3112. }
  3113. // json data
  3114. if (null != obj.data) {
  3115. str += JSON.stringify(obj.data, this.replacer);
  3116. }
  3117. return str;
  3118. }
  3119. /**
  3120. * Encode packet as 'buffer sequence' by removing blobs, and
  3121. * deconstructing packet into object with placeholders and
  3122. * a list of buffers.
  3123. */;
  3124. _proto.encodeAsBinary = function encodeAsBinary(obj) {
  3125. var deconstruction = deconstructPacket(obj);
  3126. var pack = this.encodeAsString(deconstruction.packet);
  3127. var buffers = deconstruction.buffers;
  3128. buffers.unshift(pack); // add packet info to beginning of data list
  3129. return buffers; // write all the buffers
  3130. };
  3131. return Encoder;
  3132. }();
  3133. /**
  3134. * A socket.io Decoder instance
  3135. *
  3136. * @return {Object} decoder
  3137. */
  3138. var Decoder = /*#__PURE__*/function (_Emitter) {
  3139. /**
  3140. * Decoder constructor
  3141. *
  3142. * @param {function} reviver - custom reviver to pass down to JSON.stringify
  3143. */
  3144. function Decoder(reviver) {
  3145. var _this;
  3146. _this = _Emitter.call(this) || this;
  3147. _this.reviver = reviver;
  3148. return _this;
  3149. }
  3150. /**
  3151. * Decodes an encoded packet string into packet JSON.
  3152. *
  3153. * @param {String} obj - encoded packet
  3154. */
  3155. _inheritsLoose(Decoder, _Emitter);
  3156. var _proto2 = Decoder.prototype;
  3157. _proto2.add = function add(obj) {
  3158. var packet;
  3159. if (typeof obj === "string") {
  3160. if (this.reconstructor) {
  3161. throw new Error("got plaintext data when reconstructing a packet");
  3162. }
  3163. packet = this.decodeString(obj);
  3164. var isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
  3165. if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
  3166. packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
  3167. // binary packet's json
  3168. this.reconstructor = new BinaryReconstructor(packet);
  3169. // no attachments, labeled binary but no binary data to follow
  3170. if (packet.attachments === 0) {
  3171. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3172. }
  3173. } else {
  3174. // non-binary full packet
  3175. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3176. }
  3177. } else if (isBinary(obj) || obj.base64) {
  3178. // raw binary data
  3179. if (!this.reconstructor) {
  3180. throw new Error("got binary data when not reconstructing a packet");
  3181. } else {
  3182. packet = this.reconstructor.takeBinaryData(obj);
  3183. if (packet) {
  3184. // received final buffer
  3185. this.reconstructor = null;
  3186. _Emitter.prototype.emitReserved.call(this, "decoded", packet);
  3187. }
  3188. }
  3189. } else {
  3190. throw new Error("Unknown type: " + obj);
  3191. }
  3192. }
  3193. /**
  3194. * Decode a packet String (JSON data)
  3195. *
  3196. * @param {String} str
  3197. * @return {Object} packet
  3198. */;
  3199. _proto2.decodeString = function decodeString(str) {
  3200. var i = 0;
  3201. // look up type
  3202. var p = {
  3203. type: Number(str.charAt(0))
  3204. };
  3205. if (PacketType[p.type] === undefined) {
  3206. throw new Error("unknown packet type " + p.type);
  3207. }
  3208. // look up attachments if type binary
  3209. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  3210. var start = i + 1;
  3211. while (str.charAt(++i) !== "-" && i != str.length) {}
  3212. var buf = str.substring(start, i);
  3213. if (buf != Number(buf) || str.charAt(i) !== "-") {
  3214. throw new Error("Illegal attachments");
  3215. }
  3216. p.attachments = Number(buf);
  3217. }
  3218. // look up namespace (if any)
  3219. if ("/" === str.charAt(i + 1)) {
  3220. var _start = i + 1;
  3221. while (++i) {
  3222. var c = str.charAt(i);
  3223. if ("," === c) break;
  3224. if (i === str.length) break;
  3225. }
  3226. p.nsp = str.substring(_start, i);
  3227. } else {
  3228. p.nsp = "/";
  3229. }
  3230. // look up id
  3231. var next = str.charAt(i + 1);
  3232. if ("" !== next && Number(next) == next) {
  3233. var _start2 = i + 1;
  3234. while (++i) {
  3235. var _c = str.charAt(i);
  3236. if (null == _c || Number(_c) != _c) {
  3237. --i;
  3238. break;
  3239. }
  3240. if (i === str.length) break;
  3241. }
  3242. p.id = Number(str.substring(_start2, i + 1));
  3243. }
  3244. // look up json data
  3245. if (str.charAt(++i)) {
  3246. var payload = this.tryParse(str.substr(i));
  3247. if (Decoder.isPayloadValid(p.type, payload)) {
  3248. p.data = payload;
  3249. } else {
  3250. throw new Error("invalid payload");
  3251. }
  3252. }
  3253. return p;
  3254. };
  3255. _proto2.tryParse = function tryParse(str) {
  3256. try {
  3257. return JSON.parse(str, this.reviver);
  3258. } catch (e) {
  3259. return false;
  3260. }
  3261. };
  3262. Decoder.isPayloadValid = function isPayloadValid(type, payload) {
  3263. switch (type) {
  3264. case PacketType.CONNECT:
  3265. return isObject(payload);
  3266. case PacketType.DISCONNECT:
  3267. return payload === undefined;
  3268. case PacketType.CONNECT_ERROR:
  3269. return typeof payload === "string" || isObject(payload);
  3270. case PacketType.EVENT:
  3271. case PacketType.BINARY_EVENT:
  3272. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3273. case PacketType.ACK:
  3274. case PacketType.BINARY_ACK:
  3275. return Array.isArray(payload);
  3276. }
  3277. }
  3278. /**
  3279. * Deallocates a parser's resources
  3280. */;
  3281. _proto2.destroy = function destroy() {
  3282. if (this.reconstructor) {
  3283. this.reconstructor.finishedReconstruction();
  3284. this.reconstructor = null;
  3285. }
  3286. };
  3287. return Decoder;
  3288. }(Emitter);
  3289. /**
  3290. * A manager of a binary event's 'buffer sequence'. Should
  3291. * be constructed whenever a packet of type BINARY_EVENT is
  3292. * decoded.
  3293. *
  3294. * @param {Object} packet
  3295. * @return {BinaryReconstructor} initialized reconstructor
  3296. */
  3297. var BinaryReconstructor = /*#__PURE__*/function () {
  3298. function BinaryReconstructor(packet) {
  3299. this.packet = packet;
  3300. this.buffers = [];
  3301. this.reconPack = packet;
  3302. }
  3303. /**
  3304. * Method to be called when binary data received from connection
  3305. * after a BINARY_EVENT packet.
  3306. *
  3307. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  3308. * @return {null | Object} returns null if more binary data is expected or
  3309. * a reconstructed packet object if all buffers have been received.
  3310. */
  3311. var _proto3 = BinaryReconstructor.prototype;
  3312. _proto3.takeBinaryData = function takeBinaryData(binData) {
  3313. this.buffers.push(binData);
  3314. if (this.buffers.length === this.reconPack.attachments) {
  3315. // done with buffer list
  3316. var packet = reconstructPacket(this.reconPack, this.buffers);
  3317. this.finishedReconstruction();
  3318. return packet;
  3319. }
  3320. return null;
  3321. }
  3322. /**
  3323. * Cleans up binary packet reconstruction variables.
  3324. */;
  3325. _proto3.finishedReconstruction = function finishedReconstruction() {
  3326. this.reconPack = null;
  3327. this.buffers = [];
  3328. };
  3329. return BinaryReconstructor;
  3330. }();
  3331. function isNamespaceValid(nsp) {
  3332. return typeof nsp === "string";
  3333. }
  3334. // see https://caniuse.com/mdn-javascript_builtins_number_isinteger
  3335. var isInteger = Number.isInteger || function (value) {
  3336. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  3337. };
  3338. function isAckIdValid(id) {
  3339. return id === undefined || isInteger(id);
  3340. }
  3341. // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
  3342. function isObject(value) {
  3343. return Object.prototype.toString.call(value) === "[object Object]";
  3344. }
  3345. function isDataValid(type, payload) {
  3346. switch (type) {
  3347. case PacketType.CONNECT:
  3348. return payload === undefined || isObject(payload);
  3349. case PacketType.DISCONNECT:
  3350. return payload === undefined;
  3351. case PacketType.EVENT:
  3352. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  3353. case PacketType.ACK:
  3354. return Array.isArray(payload);
  3355. case PacketType.CONNECT_ERROR:
  3356. return typeof payload === "string" || isObject(payload);
  3357. default:
  3358. return false;
  3359. }
  3360. }
  3361. function isPacketValid(packet) {
  3362. return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
  3363. }
  3364. var parser = /*#__PURE__*/Object.freeze({
  3365. __proto__: null,
  3366. protocol: protocol,
  3367. get PacketType () { return PacketType; },
  3368. Encoder: Encoder,
  3369. Decoder: Decoder,
  3370. isPacketValid: isPacketValid
  3371. });
  3372. function on(obj, ev, fn) {
  3373. obj.on(ev, fn);
  3374. return function subDestroy() {
  3375. obj.off(ev, fn);
  3376. };
  3377. }
  3378. var debug$2 = debugModule("socket.io-client:socket"); // debug()
  3379. /**
  3380. * Internal events.
  3381. * These events can't be emitted by the user.
  3382. */
  3383. var RESERVED_EVENTS = Object.freeze({
  3384. connect: 1,
  3385. connect_error: 1,
  3386. disconnect: 1,
  3387. disconnecting: 1,
  3388. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  3389. newListener: 1,
  3390. removeListener: 1
  3391. });
  3392. /**
  3393. * A Socket is the fundamental class for interacting with the server.
  3394. *
  3395. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  3396. *
  3397. * @example
  3398. * const socket = io();
  3399. *
  3400. * socket.on("connect", () => {
  3401. * console.log("connected");
  3402. * });
  3403. *
  3404. * // send an event to the server
  3405. * socket.emit("foo", "bar");
  3406. *
  3407. * socket.on("foobar", () => {
  3408. * // an event was received from the server
  3409. * });
  3410. *
  3411. * // upon disconnection
  3412. * socket.on("disconnect", (reason) => {
  3413. * console.log(`disconnected due to ${reason}`);
  3414. * });
  3415. */
  3416. var Socket = /*#__PURE__*/function (_Emitter) {
  3417. /**
  3418. * `Socket` constructor.
  3419. */
  3420. function Socket(io, nsp, opts) {
  3421. var _this;
  3422. _this = _Emitter.call(this) || this;
  3423. /**
  3424. * Whether the socket is currently connected to the server.
  3425. *
  3426. * @example
  3427. * const socket = io();
  3428. *
  3429. * socket.on("connect", () => {
  3430. * console.log(socket.connected); // true
  3431. * });
  3432. *
  3433. * socket.on("disconnect", () => {
  3434. * console.log(socket.connected); // false
  3435. * });
  3436. */
  3437. _this.connected = false;
  3438. /**
  3439. * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
  3440. * be transmitted by the server.
  3441. */
  3442. _this.recovered = false;
  3443. /**
  3444. * Buffer for packets received before the CONNECT packet
  3445. */
  3446. _this.receiveBuffer = [];
  3447. /**
  3448. * Buffer for packets that will be sent once the socket is connected
  3449. */
  3450. _this.sendBuffer = [];
  3451. /**
  3452. * The queue of packets to be sent with retry in case of failure.
  3453. *
  3454. * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
  3455. * @private
  3456. */
  3457. _this._queue = [];
  3458. /**
  3459. * A sequence to generate the ID of the {@link QueuedPacket}.
  3460. * @private
  3461. */
  3462. _this._queueSeq = 0;
  3463. _this.ids = 0;
  3464. /**
  3465. * A map containing acknowledgement handlers.
  3466. *
  3467. * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
  3468. *
  3469. * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
  3470. * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
  3471. * - `const value = await socket.emitWithAck("test")`
  3472. *
  3473. * From those that don't:
  3474. *
  3475. * - `socket.emit("test", (value) => { ... });`
  3476. *
  3477. * In the first case, the handlers will be called with an error when:
  3478. *
  3479. * - the timeout is reached
  3480. * - the socket gets disconnected
  3481. *
  3482. * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
  3483. * an acknowledgement from the server.
  3484. *
  3485. * @private
  3486. */
  3487. _this.acks = {};
  3488. _this.flags = {};
  3489. _this.io = io;
  3490. _this.nsp = nsp;
  3491. if (opts && opts.auth) {
  3492. _this.auth = opts.auth;
  3493. }
  3494. _this._opts = _extends({}, opts);
  3495. if (_this.io._autoConnect) _this.open();
  3496. return _this;
  3497. }
  3498. /**
  3499. * Whether the socket is currently disconnected
  3500. *
  3501. * @example
  3502. * const socket = io();
  3503. *
  3504. * socket.on("connect", () => {
  3505. * console.log(socket.disconnected); // false
  3506. * });
  3507. *
  3508. * socket.on("disconnect", () => {
  3509. * console.log(socket.disconnected); // true
  3510. * });
  3511. */
  3512. _inheritsLoose(Socket, _Emitter);
  3513. var _proto = Socket.prototype;
  3514. /**
  3515. * Subscribe to open, close and packet events
  3516. *
  3517. * @private
  3518. */
  3519. _proto.subEvents = function subEvents() {
  3520. if (this.subs) return;
  3521. var io = this.io;
  3522. 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))];
  3523. }
  3524. /**
  3525. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  3526. *
  3527. * @example
  3528. * const socket = io();
  3529. *
  3530. * console.log(socket.active); // true
  3531. *
  3532. * socket.on("disconnect", (reason) => {
  3533. * if (reason === "io server disconnect") {
  3534. * // the disconnection was initiated by the server, you need to manually reconnect
  3535. * console.log(socket.active); // false
  3536. * }
  3537. * // else the socket will automatically try to reconnect
  3538. * console.log(socket.active); // true
  3539. * });
  3540. */;
  3541. /**
  3542. * "Opens" the socket.
  3543. *
  3544. * @example
  3545. * const socket = io({
  3546. * autoConnect: false
  3547. * });
  3548. *
  3549. * socket.connect();
  3550. */
  3551. _proto.connect = function connect() {
  3552. if (this.connected) return this;
  3553. this.subEvents();
  3554. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  3555. if ("open" === this.io._readyState) this.onopen();
  3556. return this;
  3557. }
  3558. /**
  3559. * Alias for {@link connect()}.
  3560. */;
  3561. _proto.open = function open() {
  3562. return this.connect();
  3563. }
  3564. /**
  3565. * Sends a `message` event.
  3566. *
  3567. * This method mimics the WebSocket.send() method.
  3568. *
  3569. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  3570. *
  3571. * @example
  3572. * socket.send("hello");
  3573. *
  3574. * // this is equivalent to
  3575. * socket.emit("message", "hello");
  3576. *
  3577. * @return self
  3578. */;
  3579. _proto.send = function send() {
  3580. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3581. args[_key] = arguments[_key];
  3582. }
  3583. args.unshift("message");
  3584. this.emit.apply(this, args);
  3585. return this;
  3586. }
  3587. /**
  3588. * Override `emit`.
  3589. * If the event is in `events`, it's emitted normally.
  3590. *
  3591. * @example
  3592. * socket.emit("hello", "world");
  3593. *
  3594. * // all serializable datastructures are supported (no need to call JSON.stringify)
  3595. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  3596. *
  3597. * // with an acknowledgement from the server
  3598. * socket.emit("hello", "world", (val) => {
  3599. * // ...
  3600. * });
  3601. *
  3602. * @return self
  3603. */;
  3604. _proto.emit = function emit(ev) {
  3605. var _a, _b, _c;
  3606. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  3607. throw new Error('"' + ev.toString() + '" is a reserved event name');
  3608. }
  3609. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3610. args[_key2 - 1] = arguments[_key2];
  3611. }
  3612. args.unshift(ev);
  3613. if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
  3614. this._addToQueue(args);
  3615. return this;
  3616. }
  3617. var packet = {
  3618. type: PacketType.EVENT,
  3619. data: args
  3620. };
  3621. packet.options = {};
  3622. packet.options.compress = this.flags.compress !== false;
  3623. // event ack callback
  3624. if ("function" === typeof args[args.length - 1]) {
  3625. var id = this.ids++;
  3626. debug$2("emitting packet with ack id %d", id);
  3627. var ack = args.pop();
  3628. this._registerAckCallback(id, ack);
  3629. packet.id = id;
  3630. }
  3631. var isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
  3632. var isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
  3633. var discardPacket = this.flags["volatile"] && !isTransportWritable;
  3634. if (discardPacket) {
  3635. debug$2("discard packet as the transport is not currently writable");
  3636. } else if (isConnected) {
  3637. this.notifyOutgoingListeners(packet);
  3638. this.packet(packet);
  3639. } else {
  3640. this.sendBuffer.push(packet);
  3641. }
  3642. this.flags = {};
  3643. return this;
  3644. }
  3645. /**
  3646. * @private
  3647. */;
  3648. _proto._registerAckCallback = function _registerAckCallback(id, ack) {
  3649. var _this2 = this;
  3650. var _a;
  3651. var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  3652. if (timeout === undefined) {
  3653. this.acks[id] = ack;
  3654. return;
  3655. }
  3656. // @ts-ignore
  3657. var timer = this.io.setTimeoutFn(function () {
  3658. delete _this2.acks[id];
  3659. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  3660. if (_this2.sendBuffer[i].id === id) {
  3661. debug$2("removing packet with ack id %d from the buffer", id);
  3662. _this2.sendBuffer.splice(i, 1);
  3663. }
  3664. }
  3665. debug$2("event with ack id %d has timed out after %d ms", id, timeout);
  3666. ack.call(_this2, new Error("operation has timed out"));
  3667. }, timeout);
  3668. var fn = function fn() {
  3669. // @ts-ignore
  3670. _this2.io.clearTimeoutFn(timer);
  3671. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  3672. args[_key3] = arguments[_key3];
  3673. }
  3674. ack.apply(_this2, args);
  3675. };
  3676. fn.withError = true;
  3677. this.acks[id] = fn;
  3678. }
  3679. /**
  3680. * Emits an event and waits for an acknowledgement
  3681. *
  3682. * @example
  3683. * // without timeout
  3684. * const response = await socket.emitWithAck("hello", "world");
  3685. *
  3686. * // with a specific timeout
  3687. * try {
  3688. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  3689. * } catch (err) {
  3690. * // the server did not acknowledge the event in the given delay
  3691. * }
  3692. *
  3693. * @return a Promise that will be fulfilled when the server acknowledges the event
  3694. */;
  3695. _proto.emitWithAck = function emitWithAck(ev) {
  3696. var _this3 = this;
  3697. for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  3698. args[_key4 - 1] = arguments[_key4];
  3699. }
  3700. return new Promise(function (resolve, reject) {
  3701. var fn = function fn(arg1, arg2) {
  3702. return arg1 ? reject(arg1) : resolve(arg2);
  3703. };
  3704. fn.withError = true;
  3705. args.push(fn);
  3706. _this3.emit.apply(_this3, [ev].concat(args));
  3707. });
  3708. }
  3709. /**
  3710. * Add the packet to the queue.
  3711. * @param args
  3712. * @private
  3713. */;
  3714. _proto._addToQueue = function _addToQueue(args) {
  3715. var _this4 = this;
  3716. var ack;
  3717. if (typeof args[args.length - 1] === "function") {
  3718. ack = args.pop();
  3719. }
  3720. var packet = {
  3721. id: this._queueSeq++,
  3722. tryCount: 0,
  3723. pending: false,
  3724. args: args,
  3725. flags: _extends({
  3726. fromQueue: true
  3727. }, this.flags)
  3728. };
  3729. args.push(function (err) {
  3730. if (packet !== _this4._queue[0]) {
  3731. // the packet has already been acknowledged
  3732. return;
  3733. }
  3734. var hasError = err !== null;
  3735. if (hasError) {
  3736. if (packet.tryCount > _this4._opts.retries) {
  3737. debug$2("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
  3738. _this4._queue.shift();
  3739. if (ack) {
  3740. ack(err);
  3741. }
  3742. }
  3743. } else {
  3744. debug$2("packet [%d] was successfully sent", packet.id);
  3745. _this4._queue.shift();
  3746. if (ack) {
  3747. for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  3748. responseArgs[_key5 - 1] = arguments[_key5];
  3749. }
  3750. ack.apply(void 0, [null].concat(responseArgs));
  3751. }
  3752. }
  3753. packet.pending = false;
  3754. return _this4._drainQueue();
  3755. });
  3756. this._queue.push(packet);
  3757. this._drainQueue();
  3758. }
  3759. /**
  3760. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  3761. * @param force - whether to resend a packet that has not been acknowledged yet
  3762. *
  3763. * @private
  3764. */;
  3765. _proto._drainQueue = function _drainQueue() {
  3766. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  3767. debug$2("draining queue");
  3768. if (!this.connected || this._queue.length === 0) {
  3769. return;
  3770. }
  3771. var packet = this._queue[0];
  3772. if (packet.pending && !force) {
  3773. debug$2("packet [%d] has already been sent and is waiting for an ack", packet.id);
  3774. return;
  3775. }
  3776. packet.pending = true;
  3777. packet.tryCount++;
  3778. debug$2("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
  3779. this.flags = packet.flags;
  3780. this.emit.apply(this, packet.args);
  3781. }
  3782. /**
  3783. * Sends a packet.
  3784. *
  3785. * @param packet
  3786. * @private
  3787. */;
  3788. _proto.packet = function packet(_packet) {
  3789. _packet.nsp = this.nsp;
  3790. this.io._packet(_packet);
  3791. }
  3792. /**
  3793. * Called upon engine `open`.
  3794. *
  3795. * @private
  3796. */;
  3797. _proto.onopen = function onopen() {
  3798. var _this5 = this;
  3799. debug$2("transport is open - connecting");
  3800. if (typeof this.auth == "function") {
  3801. this.auth(function (data) {
  3802. _this5._sendConnectPacket(data);
  3803. });
  3804. } else {
  3805. this._sendConnectPacket(this.auth);
  3806. }
  3807. }
  3808. /**
  3809. * Sends a CONNECT packet to initiate the Socket.IO session.
  3810. *
  3811. * @param data
  3812. * @private
  3813. */;
  3814. _proto._sendConnectPacket = function _sendConnectPacket(data) {
  3815. this.packet({
  3816. type: PacketType.CONNECT,
  3817. data: this._pid ? _extends({
  3818. pid: this._pid,
  3819. offset: this._lastOffset
  3820. }, data) : data
  3821. });
  3822. }
  3823. /**
  3824. * Called upon engine or manager `error`.
  3825. *
  3826. * @param err
  3827. * @private
  3828. */;
  3829. _proto.onerror = function onerror(err) {
  3830. if (!this.connected) {
  3831. this.emitReserved("connect_error", err);
  3832. }
  3833. }
  3834. /**
  3835. * Called upon engine `close`.
  3836. *
  3837. * @param reason
  3838. * @param description
  3839. * @private
  3840. */;
  3841. _proto.onclose = function onclose(reason, description) {
  3842. debug$2("close (%s)", reason);
  3843. this.connected = false;
  3844. delete this.id;
  3845. this.emitReserved("disconnect", reason, description);
  3846. this._clearAcks();
  3847. }
  3848. /**
  3849. * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
  3850. * the server.
  3851. *
  3852. * @private
  3853. */;
  3854. _proto._clearAcks = function _clearAcks() {
  3855. var _this6 = this;
  3856. Object.keys(this.acks).forEach(function (id) {
  3857. var isBuffered = _this6.sendBuffer.some(function (packet) {
  3858. return String(packet.id) === id;
  3859. });
  3860. if (!isBuffered) {
  3861. // note: handlers that do not accept an error as first argument are ignored here
  3862. var ack = _this6.acks[id];
  3863. delete _this6.acks[id];
  3864. if (ack.withError) {
  3865. ack.call(_this6, new Error("socket has been disconnected"));
  3866. }
  3867. }
  3868. });
  3869. }
  3870. /**
  3871. * Called with socket packet.
  3872. *
  3873. * @param packet
  3874. * @private
  3875. */;
  3876. _proto.onpacket = function onpacket(packet) {
  3877. var sameNamespace = packet.nsp === this.nsp;
  3878. if (!sameNamespace) return;
  3879. switch (packet.type) {
  3880. case PacketType.CONNECT:
  3881. if (packet.data && packet.data.sid) {
  3882. this.onconnect(packet.data.sid, packet.data.pid);
  3883. } else {
  3884. 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/)"));
  3885. }
  3886. break;
  3887. case PacketType.EVENT:
  3888. case PacketType.BINARY_EVENT:
  3889. this.onevent(packet);
  3890. break;
  3891. case PacketType.ACK:
  3892. case PacketType.BINARY_ACK:
  3893. this.onack(packet);
  3894. break;
  3895. case PacketType.DISCONNECT:
  3896. this.ondisconnect();
  3897. break;
  3898. case PacketType.CONNECT_ERROR:
  3899. this.destroy();
  3900. var err = new Error(packet.data.message);
  3901. // @ts-ignore
  3902. err.data = packet.data.data;
  3903. this.emitReserved("connect_error", err);
  3904. break;
  3905. }
  3906. }
  3907. /**
  3908. * Called upon a server event.
  3909. *
  3910. * @param packet
  3911. * @private
  3912. */;
  3913. _proto.onevent = function onevent(packet) {
  3914. var args = packet.data || [];
  3915. debug$2("emitting event %j", args);
  3916. if (null != packet.id) {
  3917. debug$2("attaching ack callback to event");
  3918. args.push(this.ack(packet.id));
  3919. }
  3920. if (this.connected) {
  3921. this.emitEvent(args);
  3922. } else {
  3923. this.receiveBuffer.push(Object.freeze(args));
  3924. }
  3925. };
  3926. _proto.emitEvent = function emitEvent(args) {
  3927. if (this._anyListeners && this._anyListeners.length) {
  3928. var listeners = this._anyListeners.slice();
  3929. var _iterator = _createForOfIteratorHelper(listeners),
  3930. _step;
  3931. try {
  3932. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3933. var listener = _step.value;
  3934. listener.apply(this, args);
  3935. }
  3936. } catch (err) {
  3937. _iterator.e(err);
  3938. } finally {
  3939. _iterator.f();
  3940. }
  3941. }
  3942. _Emitter.prototype.emit.apply(this, args);
  3943. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  3944. this._lastOffset = args[args.length - 1];
  3945. }
  3946. }
  3947. /**
  3948. * Produces an ack callback to emit with an event.
  3949. *
  3950. * @private
  3951. */;
  3952. _proto.ack = function ack(id) {
  3953. var self = this;
  3954. var sent = false;
  3955. return function () {
  3956. // prevent double callbacks
  3957. if (sent) return;
  3958. sent = true;
  3959. for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  3960. args[_key6] = arguments[_key6];
  3961. }
  3962. debug$2("sending ack %j", args);
  3963. self.packet({
  3964. type: PacketType.ACK,
  3965. id: id,
  3966. data: args
  3967. });
  3968. };
  3969. }
  3970. /**
  3971. * Called upon a server acknowledgement.
  3972. *
  3973. * @param packet
  3974. * @private
  3975. */;
  3976. _proto.onack = function onack(packet) {
  3977. var ack = this.acks[packet.id];
  3978. if (typeof ack !== "function") {
  3979. debug$2("bad ack %s", packet.id);
  3980. return;
  3981. }
  3982. delete this.acks[packet.id];
  3983. debug$2("calling ack %s with %j", packet.id, packet.data);
  3984. // @ts-ignore FIXME ack is incorrectly inferred as 'never'
  3985. if (ack.withError) {
  3986. packet.data.unshift(null);
  3987. }
  3988. // @ts-ignore
  3989. ack.apply(this, packet.data);
  3990. }
  3991. /**
  3992. * Called upon server connect.
  3993. *
  3994. * @private
  3995. */;
  3996. _proto.onconnect = function onconnect(id, pid) {
  3997. debug$2("socket connected with id %s", id);
  3998. this.id = id;
  3999. this.recovered = pid && this._pid === pid;
  4000. this._pid = pid; // defined only if connection state recovery is enabled
  4001. this.connected = true;
  4002. this.emitBuffered();
  4003. this.emitReserved("connect");
  4004. this._drainQueue(true);
  4005. }
  4006. /**
  4007. * Emit buffered events (received and emitted).
  4008. *
  4009. * @private
  4010. */;
  4011. _proto.emitBuffered = function emitBuffered() {
  4012. var _this7 = this;
  4013. this.receiveBuffer.forEach(function (args) {
  4014. return _this7.emitEvent(args);
  4015. });
  4016. this.receiveBuffer = [];
  4017. this.sendBuffer.forEach(function (packet) {
  4018. _this7.notifyOutgoingListeners(packet);
  4019. _this7.packet(packet);
  4020. });
  4021. this.sendBuffer = [];
  4022. }
  4023. /**
  4024. * Called upon server disconnect.
  4025. *
  4026. * @private
  4027. */;
  4028. _proto.ondisconnect = function ondisconnect() {
  4029. debug$2("server disconnect (%s)", this.nsp);
  4030. this.destroy();
  4031. this.onclose("io server disconnect");
  4032. }
  4033. /**
  4034. * Called upon forced client/server side disconnections,
  4035. * this method ensures the manager stops tracking us and
  4036. * that reconnections don't get triggered for this.
  4037. *
  4038. * @private
  4039. */;
  4040. _proto.destroy = function destroy() {
  4041. if (this.subs) {
  4042. // clean subscriptions to avoid reconnections
  4043. this.subs.forEach(function (subDestroy) {
  4044. return subDestroy();
  4045. });
  4046. this.subs = undefined;
  4047. }
  4048. this.io["_destroy"](this);
  4049. }
  4050. /**
  4051. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  4052. *
  4053. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  4054. *
  4055. * @example
  4056. * const socket = io();
  4057. *
  4058. * socket.on("disconnect", (reason) => {
  4059. * // console.log(reason); prints "io client disconnect"
  4060. * });
  4061. *
  4062. * socket.disconnect();
  4063. *
  4064. * @return self
  4065. */;
  4066. _proto.disconnect = function disconnect() {
  4067. if (this.connected) {
  4068. debug$2("performing disconnect (%s)", this.nsp);
  4069. this.packet({
  4070. type: PacketType.DISCONNECT
  4071. });
  4072. }
  4073. // remove socket from pool
  4074. this.destroy();
  4075. if (this.connected) {
  4076. // fire events
  4077. this.onclose("io client disconnect");
  4078. }
  4079. return this;
  4080. }
  4081. /**
  4082. * Alias for {@link disconnect()}.
  4083. *
  4084. * @return self
  4085. */;
  4086. _proto.close = function close() {
  4087. return this.disconnect();
  4088. }
  4089. /**
  4090. * Sets the compress flag.
  4091. *
  4092. * @example
  4093. * socket.compress(false).emit("hello");
  4094. *
  4095. * @param compress - if `true`, compresses the sending data
  4096. * @return self
  4097. */;
  4098. _proto.compress = function compress(_compress) {
  4099. this.flags.compress = _compress;
  4100. return this;
  4101. }
  4102. /**
  4103. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  4104. * ready to send messages.
  4105. *
  4106. * @example
  4107. * socket.volatile.emit("hello"); // the server may or may not receive it
  4108. *
  4109. * @returns self
  4110. */;
  4111. /**
  4112. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  4113. * given number of milliseconds have elapsed without an acknowledgement from the server:
  4114. *
  4115. * @example
  4116. * socket.timeout(5000).emit("my-event", (err) => {
  4117. * if (err) {
  4118. * // the server did not acknowledge the event in the given delay
  4119. * }
  4120. * });
  4121. *
  4122. * @returns self
  4123. */
  4124. _proto.timeout = function timeout(_timeout) {
  4125. this.flags.timeout = _timeout;
  4126. return this;
  4127. }
  4128. /**
  4129. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4130. * callback.
  4131. *
  4132. * @example
  4133. * socket.onAny((event, ...args) => {
  4134. * console.log(`got ${event}`);
  4135. * });
  4136. *
  4137. * @param listener
  4138. */;
  4139. _proto.onAny = function onAny(listener) {
  4140. this._anyListeners = this._anyListeners || [];
  4141. this._anyListeners.push(listener);
  4142. return this;
  4143. }
  4144. /**
  4145. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4146. * callback. The listener is added to the beginning of the listeners array.
  4147. *
  4148. * @example
  4149. * socket.prependAny((event, ...args) => {
  4150. * console.log(`got event ${event}`);
  4151. * });
  4152. *
  4153. * @param listener
  4154. */;
  4155. _proto.prependAny = function prependAny(listener) {
  4156. this._anyListeners = this._anyListeners || [];
  4157. this._anyListeners.unshift(listener);
  4158. return this;
  4159. }
  4160. /**
  4161. * Removes the listener that will be fired when any event is emitted.
  4162. *
  4163. * @example
  4164. * const catchAllListener = (event, ...args) => {
  4165. * console.log(`got event ${event}`);
  4166. * }
  4167. *
  4168. * socket.onAny(catchAllListener);
  4169. *
  4170. * // remove a specific listener
  4171. * socket.offAny(catchAllListener);
  4172. *
  4173. * // or remove all listeners
  4174. * socket.offAny();
  4175. *
  4176. * @param listener
  4177. */;
  4178. _proto.offAny = function offAny(listener) {
  4179. if (!this._anyListeners) {
  4180. return this;
  4181. }
  4182. if (listener) {
  4183. var listeners = this._anyListeners;
  4184. for (var i = 0; i < listeners.length; i++) {
  4185. if (listener === listeners[i]) {
  4186. listeners.splice(i, 1);
  4187. return this;
  4188. }
  4189. }
  4190. } else {
  4191. this._anyListeners = [];
  4192. }
  4193. return this;
  4194. }
  4195. /**
  4196. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4197. * e.g. to remove listeners.
  4198. */;
  4199. _proto.listenersAny = function listenersAny() {
  4200. return this._anyListeners || [];
  4201. }
  4202. /**
  4203. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4204. * callback.
  4205. *
  4206. * Note: acknowledgements sent to the server are not included.
  4207. *
  4208. * @example
  4209. * socket.onAnyOutgoing((event, ...args) => {
  4210. * console.log(`sent event ${event}`);
  4211. * });
  4212. *
  4213. * @param listener
  4214. */;
  4215. _proto.onAnyOutgoing = function onAnyOutgoing(listener) {
  4216. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4217. this._anyOutgoingListeners.push(listener);
  4218. return this;
  4219. }
  4220. /**
  4221. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  4222. * callback. The listener is added to the beginning of the listeners array.
  4223. *
  4224. * Note: acknowledgements sent to the server are not included.
  4225. *
  4226. * @example
  4227. * socket.prependAnyOutgoing((event, ...args) => {
  4228. * console.log(`sent event ${event}`);
  4229. * });
  4230. *
  4231. * @param listener
  4232. */;
  4233. _proto.prependAnyOutgoing = function prependAnyOutgoing(listener) {
  4234. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  4235. this._anyOutgoingListeners.unshift(listener);
  4236. return this;
  4237. }
  4238. /**
  4239. * Removes the listener that will be fired when any event is emitted.
  4240. *
  4241. * @example
  4242. * const catchAllListener = (event, ...args) => {
  4243. * console.log(`sent event ${event}`);
  4244. * }
  4245. *
  4246. * socket.onAnyOutgoing(catchAllListener);
  4247. *
  4248. * // remove a specific listener
  4249. * socket.offAnyOutgoing(catchAllListener);
  4250. *
  4251. * // or remove all listeners
  4252. * socket.offAnyOutgoing();
  4253. *
  4254. * @param [listener] - the catch-all listener (optional)
  4255. */;
  4256. _proto.offAnyOutgoing = function offAnyOutgoing(listener) {
  4257. if (!this._anyOutgoingListeners) {
  4258. return this;
  4259. }
  4260. if (listener) {
  4261. var listeners = this._anyOutgoingListeners;
  4262. for (var i = 0; i < listeners.length; i++) {
  4263. if (listener === listeners[i]) {
  4264. listeners.splice(i, 1);
  4265. return this;
  4266. }
  4267. }
  4268. } else {
  4269. this._anyOutgoingListeners = [];
  4270. }
  4271. return this;
  4272. }
  4273. /**
  4274. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  4275. * e.g. to remove listeners.
  4276. */;
  4277. _proto.listenersAnyOutgoing = function listenersAnyOutgoing() {
  4278. return this._anyOutgoingListeners || [];
  4279. }
  4280. /**
  4281. * Notify the listeners for each packet sent
  4282. *
  4283. * @param packet
  4284. *
  4285. * @private
  4286. */;
  4287. _proto.notifyOutgoingListeners = function notifyOutgoingListeners(packet) {
  4288. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  4289. var listeners = this._anyOutgoingListeners.slice();
  4290. var _iterator2 = _createForOfIteratorHelper(listeners),
  4291. _step2;
  4292. try {
  4293. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4294. var listener = _step2.value;
  4295. listener.apply(this, packet.data);
  4296. }
  4297. } catch (err) {
  4298. _iterator2.e(err);
  4299. } finally {
  4300. _iterator2.f();
  4301. }
  4302. }
  4303. };
  4304. return _createClass(Socket, [{
  4305. key: "disconnected",
  4306. get: function get() {
  4307. return !this.connected;
  4308. }
  4309. }, {
  4310. key: "active",
  4311. get: function get() {
  4312. return !!this.subs;
  4313. }
  4314. }, {
  4315. key: "volatile",
  4316. get: function get() {
  4317. this.flags["volatile"] = true;
  4318. return this;
  4319. }
  4320. }]);
  4321. }(Emitter);
  4322. /**
  4323. * Initialize backoff timer with `opts`.
  4324. *
  4325. * - `min` initial timeout in milliseconds [100]
  4326. * - `max` max timeout [10000]
  4327. * - `jitter` [0]
  4328. * - `factor` [2]
  4329. *
  4330. * @param {Object} opts
  4331. * @api public
  4332. */
  4333. function Backoff(opts) {
  4334. opts = opts || {};
  4335. this.ms = opts.min || 100;
  4336. this.max = opts.max || 10000;
  4337. this.factor = opts.factor || 2;
  4338. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  4339. this.attempts = 0;
  4340. }
  4341. /**
  4342. * Return the backoff duration.
  4343. *
  4344. * @return {Number}
  4345. * @api public
  4346. */
  4347. Backoff.prototype.duration = function () {
  4348. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  4349. if (this.jitter) {
  4350. var rand = Math.random();
  4351. var deviation = Math.floor(rand * this.jitter * ms);
  4352. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  4353. }
  4354. return Math.min(ms, this.max) | 0;
  4355. };
  4356. /**
  4357. * Reset the number of attempts.
  4358. *
  4359. * @api public
  4360. */
  4361. Backoff.prototype.reset = function () {
  4362. this.attempts = 0;
  4363. };
  4364. /**
  4365. * Set the minimum duration
  4366. *
  4367. * @api public
  4368. */
  4369. Backoff.prototype.setMin = function (min) {
  4370. this.ms = min;
  4371. };
  4372. /**
  4373. * Set the maximum duration
  4374. *
  4375. * @api public
  4376. */
  4377. Backoff.prototype.setMax = function (max) {
  4378. this.max = max;
  4379. };
  4380. /**
  4381. * Set the jitter
  4382. *
  4383. * @api public
  4384. */
  4385. Backoff.prototype.setJitter = function (jitter) {
  4386. this.jitter = jitter;
  4387. };
  4388. var debug$1 = debugModule("socket.io-client:manager"); // debug()
  4389. var Manager = /*#__PURE__*/function (_Emitter) {
  4390. function Manager(uri, opts) {
  4391. var _this;
  4392. var _a;
  4393. _this = _Emitter.call(this) || this;
  4394. _this.nsps = {};
  4395. _this.subs = [];
  4396. if (uri && "object" === _typeof(uri)) {
  4397. opts = uri;
  4398. uri = undefined;
  4399. }
  4400. opts = opts || {};
  4401. opts.path = opts.path || "/socket.io";
  4402. _this.opts = opts;
  4403. installTimerFunctions(_this, opts);
  4404. _this.reconnection(opts.reconnection !== false);
  4405. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  4406. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  4407. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  4408. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  4409. _this.backoff = new Backoff({
  4410. min: _this.reconnectionDelay(),
  4411. max: _this.reconnectionDelayMax(),
  4412. jitter: _this.randomizationFactor()
  4413. });
  4414. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  4415. _this._readyState = "closed";
  4416. _this.uri = uri;
  4417. var _parser = opts.parser || parser;
  4418. _this.encoder = new _parser.Encoder();
  4419. _this.decoder = new _parser.Decoder();
  4420. _this._autoConnect = opts.autoConnect !== false;
  4421. if (_this._autoConnect) _this.open();
  4422. return _this;
  4423. }
  4424. _inheritsLoose(Manager, _Emitter);
  4425. var _proto = Manager.prototype;
  4426. _proto.reconnection = function reconnection(v) {
  4427. if (!arguments.length) return this._reconnection;
  4428. this._reconnection = !!v;
  4429. if (!v) {
  4430. this.skipReconnect = true;
  4431. }
  4432. return this;
  4433. };
  4434. _proto.reconnectionAttempts = function reconnectionAttempts(v) {
  4435. if (v === undefined) return this._reconnectionAttempts;
  4436. this._reconnectionAttempts = v;
  4437. return this;
  4438. };
  4439. _proto.reconnectionDelay = function reconnectionDelay(v) {
  4440. var _a;
  4441. if (v === undefined) return this._reconnectionDelay;
  4442. this._reconnectionDelay = v;
  4443. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  4444. return this;
  4445. };
  4446. _proto.randomizationFactor = function randomizationFactor(v) {
  4447. var _a;
  4448. if (v === undefined) return this._randomizationFactor;
  4449. this._randomizationFactor = v;
  4450. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  4451. return this;
  4452. };
  4453. _proto.reconnectionDelayMax = function reconnectionDelayMax(v) {
  4454. var _a;
  4455. if (v === undefined) return this._reconnectionDelayMax;
  4456. this._reconnectionDelayMax = v;
  4457. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  4458. return this;
  4459. };
  4460. _proto.timeout = function timeout(v) {
  4461. if (!arguments.length) return this._timeout;
  4462. this._timeout = v;
  4463. return this;
  4464. }
  4465. /**
  4466. * Starts trying to reconnect if reconnection is enabled and we have not
  4467. * started reconnecting yet
  4468. *
  4469. * @private
  4470. */;
  4471. _proto.maybeReconnectOnOpen = function maybeReconnectOnOpen() {
  4472. // Only try to reconnect if it's the first time we're connecting
  4473. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  4474. // keeps reconnection from firing twice for the same reconnection loop
  4475. this.reconnect();
  4476. }
  4477. }
  4478. /**
  4479. * Sets the current transport `socket`.
  4480. *
  4481. * @param {Function} fn - optional, callback
  4482. * @return self
  4483. * @public
  4484. */;
  4485. _proto.open = function open(fn) {
  4486. var _this2 = this;
  4487. debug$1("readyState %s", this._readyState);
  4488. if (~this._readyState.indexOf("open")) return this;
  4489. debug$1("opening %s", this.uri);
  4490. this.engine = new Socket$1(this.uri, this.opts);
  4491. var socket = this.engine;
  4492. var self = this;
  4493. this._readyState = "opening";
  4494. this.skipReconnect = false;
  4495. // emit `open`
  4496. var openSubDestroy = on(socket, "open", function () {
  4497. self.onopen();
  4498. fn && fn();
  4499. });
  4500. var onError = function onError(err) {
  4501. debug$1("error");
  4502. _this2.cleanup();
  4503. _this2._readyState = "closed";
  4504. _this2.emitReserved("error", err);
  4505. if (fn) {
  4506. fn(err);
  4507. } else {
  4508. // Only do this if there is no fn to handle the error
  4509. _this2.maybeReconnectOnOpen();
  4510. }
  4511. };
  4512. // emit `error`
  4513. var errorSub = on(socket, "error", onError);
  4514. if (false !== this._timeout) {
  4515. var timeout = this._timeout;
  4516. debug$1("connect attempt will timeout after %d", timeout);
  4517. // set timer
  4518. var timer = this.setTimeoutFn(function () {
  4519. debug$1("connect attempt timed out after %d", timeout);
  4520. openSubDestroy();
  4521. onError(new Error("timeout"));
  4522. socket.close();
  4523. }, timeout);
  4524. if (this.opts.autoUnref) {
  4525. timer.unref();
  4526. }
  4527. this.subs.push(function () {
  4528. _this2.clearTimeoutFn(timer);
  4529. });
  4530. }
  4531. this.subs.push(openSubDestroy);
  4532. this.subs.push(errorSub);
  4533. return this;
  4534. }
  4535. /**
  4536. * Alias for open()
  4537. *
  4538. * @return self
  4539. * @public
  4540. */;
  4541. _proto.connect = function connect(fn) {
  4542. return this.open(fn);
  4543. }
  4544. /**
  4545. * Called upon transport open.
  4546. *
  4547. * @private
  4548. */;
  4549. _proto.onopen = function onopen() {
  4550. debug$1("open");
  4551. // clear old subs
  4552. this.cleanup();
  4553. // mark as open
  4554. this._readyState = "open";
  4555. this.emitReserved("open");
  4556. // add new subs
  4557. var socket = this.engine;
  4558. 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)),
  4559. // @ts-ignore
  4560. on(this.decoder, "decoded", this.ondecoded.bind(this)));
  4561. }
  4562. /**
  4563. * Called upon a ping.
  4564. *
  4565. * @private
  4566. */;
  4567. _proto.onping = function onping() {
  4568. this.emitReserved("ping");
  4569. }
  4570. /**
  4571. * Called with data.
  4572. *
  4573. * @private
  4574. */;
  4575. _proto.ondata = function ondata(data) {
  4576. try {
  4577. this.decoder.add(data);
  4578. } catch (e) {
  4579. this.onclose("parse error", e);
  4580. }
  4581. }
  4582. /**
  4583. * Called when parser fully decodes a packet.
  4584. *
  4585. * @private
  4586. */;
  4587. _proto.ondecoded = function ondecoded(packet) {
  4588. var _this3 = this;
  4589. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  4590. nextTick(function () {
  4591. _this3.emitReserved("packet", packet);
  4592. }, this.setTimeoutFn);
  4593. }
  4594. /**
  4595. * Called upon socket error.
  4596. *
  4597. * @private
  4598. */;
  4599. _proto.onerror = function onerror(err) {
  4600. debug$1("error", err);
  4601. this.emitReserved("error", err);
  4602. }
  4603. /**
  4604. * Creates a new socket for the given `nsp`.
  4605. *
  4606. * @return {Socket}
  4607. * @public
  4608. */;
  4609. _proto.socket = function socket(nsp, opts) {
  4610. var socket = this.nsps[nsp];
  4611. if (!socket) {
  4612. socket = new Socket(this, nsp, opts);
  4613. this.nsps[nsp] = socket;
  4614. } else if (this._autoConnect && !socket.active) {
  4615. socket.connect();
  4616. }
  4617. return socket;
  4618. }
  4619. /**
  4620. * Called upon a socket close.
  4621. *
  4622. * @param socket
  4623. * @private
  4624. */;
  4625. _proto._destroy = function _destroy(socket) {
  4626. var nsps = Object.keys(this.nsps);
  4627. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  4628. var nsp = _nsps[_i];
  4629. var _socket = this.nsps[nsp];
  4630. if (_socket.active) {
  4631. debug$1("socket %s is still active, skipping close", nsp);
  4632. return;
  4633. }
  4634. }
  4635. this._close();
  4636. }
  4637. /**
  4638. * Writes a packet.
  4639. *
  4640. * @param packet
  4641. * @private
  4642. */;
  4643. _proto._packet = function _packet(packet) {
  4644. debug$1("writing packet %j", packet);
  4645. var encodedPackets = this.encoder.encode(packet);
  4646. for (var i = 0; i < encodedPackets.length; i++) {
  4647. this.engine.write(encodedPackets[i], packet.options);
  4648. }
  4649. }
  4650. /**
  4651. * Clean up transport subscriptions and packet buffer.
  4652. *
  4653. * @private
  4654. */;
  4655. _proto.cleanup = function cleanup() {
  4656. debug$1("cleanup");
  4657. this.subs.forEach(function (subDestroy) {
  4658. return subDestroy();
  4659. });
  4660. this.subs.length = 0;
  4661. this.decoder.destroy();
  4662. }
  4663. /**
  4664. * Close the current socket.
  4665. *
  4666. * @private
  4667. */;
  4668. _proto._close = function _close() {
  4669. debug$1("disconnect");
  4670. this.skipReconnect = true;
  4671. this._reconnecting = false;
  4672. this.onclose("forced close");
  4673. }
  4674. /**
  4675. * Alias for close()
  4676. *
  4677. * @private
  4678. */;
  4679. _proto.disconnect = function disconnect() {
  4680. return this._close();
  4681. }
  4682. /**
  4683. * Called when:
  4684. *
  4685. * - the low-level engine is closed
  4686. * - the parser encountered a badly formatted packet
  4687. * - all sockets are disconnected
  4688. *
  4689. * @private
  4690. */;
  4691. _proto.onclose = function onclose(reason, description) {
  4692. var _a;
  4693. debug$1("closed due to %s", reason);
  4694. this.cleanup();
  4695. (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
  4696. this.backoff.reset();
  4697. this._readyState = "closed";
  4698. this.emitReserved("close", reason, description);
  4699. if (this._reconnection && !this.skipReconnect) {
  4700. this.reconnect();
  4701. }
  4702. }
  4703. /**
  4704. * Attempt a reconnection.
  4705. *
  4706. * @private
  4707. */;
  4708. _proto.reconnect = function reconnect() {
  4709. var _this4 = this;
  4710. if (this._reconnecting || this.skipReconnect) return this;
  4711. var self = this;
  4712. if (this.backoff.attempts >= this._reconnectionAttempts) {
  4713. debug$1("reconnect failed");
  4714. this.backoff.reset();
  4715. this.emitReserved("reconnect_failed");
  4716. this._reconnecting = false;
  4717. } else {
  4718. var delay = this.backoff.duration();
  4719. debug$1("will wait %dms before reconnect attempt", delay);
  4720. this._reconnecting = true;
  4721. var timer = this.setTimeoutFn(function () {
  4722. if (self.skipReconnect) return;
  4723. debug$1("attempting reconnect");
  4724. _this4.emitReserved("reconnect_attempt", self.backoff.attempts);
  4725. // check again for the case socket closed in above events
  4726. if (self.skipReconnect) return;
  4727. self.open(function (err) {
  4728. if (err) {
  4729. debug$1("reconnect attempt error");
  4730. self._reconnecting = false;
  4731. self.reconnect();
  4732. _this4.emitReserved("reconnect_error", err);
  4733. } else {
  4734. debug$1("reconnect success");
  4735. self.onreconnect();
  4736. }
  4737. });
  4738. }, delay);
  4739. if (this.opts.autoUnref) {
  4740. timer.unref();
  4741. }
  4742. this.subs.push(function () {
  4743. _this4.clearTimeoutFn(timer);
  4744. });
  4745. }
  4746. }
  4747. /**
  4748. * Called upon successful reconnect.
  4749. *
  4750. * @private
  4751. */;
  4752. _proto.onreconnect = function onreconnect() {
  4753. var attempt = this.backoff.attempts;
  4754. this._reconnecting = false;
  4755. this.backoff.reset();
  4756. this.emitReserved("reconnect", attempt);
  4757. };
  4758. return Manager;
  4759. }(Emitter);
  4760. var debug = debugModule("socket.io-client"); // debug()
  4761. /**
  4762. * Managers cache.
  4763. */
  4764. var cache = {};
  4765. function lookup(uri, opts) {
  4766. if (_typeof(uri) === "object") {
  4767. opts = uri;
  4768. uri = undefined;
  4769. }
  4770. opts = opts || {};
  4771. var parsed = url(uri, opts.path || "/socket.io");
  4772. var source = parsed.source;
  4773. var id = parsed.id;
  4774. var path = parsed.path;
  4775. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  4776. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  4777. var io;
  4778. if (newConnection) {
  4779. debug("ignoring socket cache for %s", source);
  4780. io = new Manager(source, opts);
  4781. } else {
  4782. if (!cache[id]) {
  4783. debug("new io instance for %s", source);
  4784. cache[id] = new Manager(source, opts);
  4785. }
  4786. io = cache[id];
  4787. }
  4788. if (parsed.query && !opts.query) {
  4789. opts.query = parsed.queryKey;
  4790. }
  4791. return io.socket(parsed.path, opts);
  4792. }
  4793. // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  4794. // namespace (e.g. `io.connect(...)`), for backward compatibility
  4795. _extends(lookup, {
  4796. Manager: Manager,
  4797. Socket: Socket,
  4798. io: lookup,
  4799. connect: lookup
  4800. });
  4801. return lookup;
  4802. }));
  4803. //# sourceMappingURL=socket.io.js.map