socket.io.js 112 KB

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