12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory());
- })(this, (function () { 'use strict';
- function _typeof(obj) {
- "@babel/helpers - typeof";
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
- return typeof obj;
- } : function (obj) {
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- }, _typeof(obj);
- }
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
- }
- function _extends() {
- _extends = Object.assign ? Object.assign.bind() : function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- Object.defineProperty(subClass, "prototype", {
- writable: false
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct()) {
- _construct = Reflect.construct.bind();
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
- }
- function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- } else if (call !== void 0) {
- throw new TypeError("Derived constructors may only return object or undefined");
- }
- return _assertThisInitialized(self);
- }
- function _createSuper(Derived) {
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
- return function _createSuperInternal() {
- var Super = _getPrototypeOf(Derived),
- result;
- if (hasNativeReflectConstruct) {
- var NewTarget = _getPrototypeOf(this).constructor;
- result = Reflect.construct(Super, arguments, NewTarget);
- } else {
- result = Super.apply(this, arguments);
- }
- return _possibleConstructorReturn(this, result);
- };
- }
- function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
- }
- return object;
- }
- function _get() {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- _get = Reflect.get.bind();
- } else {
- _get = function _get(target, property, receiver) {
- var base = _superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
- if (desc.get) {
- return desc.get.call(arguments.length < 3 ? target : receiver);
- }
- return desc.value;
- };
- }
- return _get.apply(this, arguments);
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
- return arr2;
- }
- function _createForOfIteratorHelper(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (!it) {
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- var F = function () {};
- return {
- s: F,
- n: function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- },
- e: function (e) {
- throw e;
- },
- f: F
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function () {
- it = it.call(o);
- },
- n: function () {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function (e) {
- didErr = true;
- err = e;
- },
- f: function () {
- try {
- if (!normalCompletion && it.return != null) it.return();
- } finally {
- if (didErr) throw err;
- }
- }
- };
- }
- function _toPrimitive(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
- }
- function _toPropertyKey(arg) {
- var key = _toPrimitive(arg, "string");
- return typeof key === "symbol" ? key : String(key);
- }
- var PACKET_TYPES = Object.create(null);
- PACKET_TYPES["open"] = "0";
- PACKET_TYPES["close"] = "1";
- PACKET_TYPES["ping"] = "2";
- PACKET_TYPES["pong"] = "3";
- PACKET_TYPES["message"] = "4";
- PACKET_TYPES["upgrade"] = "5";
- PACKET_TYPES["noop"] = "6";
- var PACKET_TYPES_REVERSE = Object.create(null);
- Object.keys(PACKET_TYPES).forEach(function (key) {
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
- });
- var ERROR_PACKET = {
- type: "error",
- data: "parser error"
- };
- var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
- var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
-
- var isView$1 = function isView(obj) {
- return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
- };
- var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
- var type = _ref.type,
- data = _ref.data;
- if (withNativeBlob$1 && data instanceof Blob) {
- if (supportsBinary) {
- return callback(data);
- } else {
- return encodeBlobAsBase64(data, callback);
- }
- } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
- if (supportsBinary) {
- return callback(data);
- } else {
- return encodeBlobAsBase64(new Blob([data]), callback);
- }
- }
-
- return callback(PACKET_TYPES[type] + (data || ""));
- };
- var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
- var fileReader = new FileReader();
- fileReader.onload = function () {
- var content = fileReader.result.split(",")[1];
- callback("b" + (content || ""));
- };
- return fileReader.readAsDataURL(data);
- };
- function toArray(data) {
- if (data instanceof Uint8Array) {
- return data;
- } else if (data instanceof ArrayBuffer) {
- return new Uint8Array(data);
- } else {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
- }
- }
- var TEXT_ENCODER;
- function encodePacketToBinary(packet, callback) {
- if (withNativeBlob$1 && packet.data instanceof Blob) {
- return packet.data.arrayBuffer().then(toArray).then(callback);
- } else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
- return callback(toArray(packet.data));
- }
- encodePacket(packet, false, function (encoded) {
- if (!TEXT_ENCODER) {
- TEXT_ENCODER = new TextEncoder();
- }
- callback(TEXT_ENCODER.encode(encoded));
- });
- }
-
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
-
- var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$1 = 0; i$1 < chars.length; i$1++) {
- lookup$1[chars.charCodeAt(i$1)] = i$1;
- }
- var decode$1 = function decode(base64) {
- var bufferLength = base64.length * 0.75,
- len = base64.length,
- i,
- p = 0,
- encoded1,
- encoded2,
- encoded3,
- encoded4;
- if (base64[base64.length - 1] === '=') {
- bufferLength--;
- if (base64[base64.length - 2] === '=') {
- bufferLength--;
- }
- }
- var arraybuffer = new ArrayBuffer(bufferLength),
- bytes = new Uint8Array(arraybuffer);
- for (i = 0; i < len; i += 4) {
- encoded1 = lookup$1[base64.charCodeAt(i)];
- encoded2 = lookup$1[base64.charCodeAt(i + 1)];
- encoded3 = lookup$1[base64.charCodeAt(i + 2)];
- encoded4 = lookup$1[base64.charCodeAt(i + 3)];
- bytes[p++] = encoded1 << 2 | encoded2 >> 4;
- bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
- bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
- }
- return arraybuffer;
- };
- var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
- var decodePacket = function decodePacket(encodedPacket, binaryType) {
- if (typeof encodedPacket !== "string") {
- return {
- type: "message",
- data: mapBinary(encodedPacket, binaryType)
- };
- }
- var type = encodedPacket.charAt(0);
- if (type === "b") {
- return {
- type: "message",
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
- };
- }
- var packetType = PACKET_TYPES_REVERSE[type];
- if (!packetType) {
- return ERROR_PACKET;
- }
- return encodedPacket.length > 1 ? {
- type: PACKET_TYPES_REVERSE[type],
- data: encodedPacket.substring(1)
- } : {
- type: PACKET_TYPES_REVERSE[type]
- };
- };
- var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
- if (withNativeArrayBuffer$1) {
- var decoded = decode$1(data);
- return mapBinary(decoded, binaryType);
- } else {
- return {
- base64: true,
- data: data
- };
- }
- };
- var mapBinary = function mapBinary(data, binaryType) {
- switch (binaryType) {
- case "blob":
- if (data instanceof Blob) {
-
- return data;
- } else {
-
- return new Blob([data]);
- }
- case "arraybuffer":
- default:
- if (data instanceof ArrayBuffer) {
-
- return data;
- } else {
-
- return data.buffer;
- }
- }
- };
- var SEPARATOR = String.fromCharCode(30);
- var encodePayload = function encodePayload(packets, callback) {
-
- var length = packets.length;
- var encodedPackets = new Array(length);
- var count = 0;
- packets.forEach(function (packet, i) {
-
- encodePacket(packet, false, function (encodedPacket) {
- encodedPackets[i] = encodedPacket;
- if (++count === length) {
- callback(encodedPackets.join(SEPARATOR));
- }
- });
- });
- };
- var decodePayload = function decodePayload(encodedPayload, binaryType) {
- var encodedPackets = encodedPayload.split(SEPARATOR);
- var packets = [];
- for (var i = 0; i < encodedPackets.length; i++) {
- var decodedPacket = decodePacket(encodedPackets[i], binaryType);
- packets.push(decodedPacket);
- if (decodedPacket.type === "error") {
- break;
- }
- }
- return packets;
- };
- function createPacketEncoderStream() {
- return new TransformStream({
- transform: function transform(packet, controller) {
- encodePacketToBinary(packet, function (encodedPacket) {
- var payloadLength = encodedPacket.length;
- var header;
-
- if (payloadLength < 126) {
- header = new Uint8Array(1);
- new DataView(header.buffer).setUint8(0, payloadLength);
- } else if (payloadLength < 65536) {
- header = new Uint8Array(3);
- var view = new DataView(header.buffer);
- view.setUint8(0, 126);
- view.setUint16(1, payloadLength);
- } else {
- header = new Uint8Array(9);
- var _view = new DataView(header.buffer);
- _view.setUint8(0, 127);
- _view.setBigUint64(1, BigInt(payloadLength));
- }
-
- if (packet.data && typeof packet.data !== "string") {
- header[0] |= 0x80;
- }
- controller.enqueue(header);
- controller.enqueue(encodedPacket);
- });
- }
- });
- }
- var TEXT_DECODER;
- function totalLength(chunks) {
- return chunks.reduce(function (acc, chunk) {
- return acc + chunk.length;
- }, 0);
- }
- function concatChunks(chunks, size) {
- if (chunks[0].length === size) {
- return chunks.shift();
- }
- var buffer = new Uint8Array(size);
- var j = 0;
- for (var i = 0; i < size; i++) {
- buffer[i] = chunks[0][j++];
- if (j === chunks[0].length) {
- chunks.shift();
- j = 0;
- }
- }
- if (chunks.length && j < chunks[0].length) {
- chunks[0] = chunks[0].slice(j);
- }
- return buffer;
- }
- function createPacketDecoderStream(maxPayload, binaryType) {
- if (!TEXT_DECODER) {
- TEXT_DECODER = new TextDecoder();
- }
- var chunks = [];
- var state = 0 ;
- var expectedLength = -1;
- var isBinary = false;
- return new TransformStream({
- transform: function transform(chunk, controller) {
- chunks.push(chunk);
- while (true) {
- if (state === 0 ) {
- if (totalLength(chunks) < 1) {
- break;
- }
- var header = concatChunks(chunks, 1);
- isBinary = (header[0] & 0x80) === 0x80;
- expectedLength = header[0] & 0x7f;
- if (expectedLength < 126) {
- state = 3 ;
- } else if (expectedLength === 126) {
- state = 1 ;
- } else {
- state = 2 ;
- }
- } else if (state === 1 ) {
- if (totalLength(chunks) < 2) {
- break;
- }
- var headerArray = concatChunks(chunks, 2);
- expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
- state = 3 ;
- } else if (state === 2 ) {
- if (totalLength(chunks) < 8) {
- break;
- }
- var _headerArray = concatChunks(chunks, 8);
- var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length);
- var n = view.getUint32(0);
- if (n > Math.pow(2, 53 - 32) - 1) {
-
- controller.enqueue(ERROR_PACKET);
- break;
- }
- expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
- state = 3 ;
- } else {
- if (totalLength(chunks) < expectedLength) {
- break;
- }
- var data = concatChunks(chunks, expectedLength);
- controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
- state = 0 ;
- }
- if (expectedLength === 0 || expectedLength > maxPayload) {
- controller.enqueue(ERROR_PACKET);
- break;
- }
- }
- }
- });
- }
- var protocol$1 = 4;
-
- function Emitter(obj) {
- if (obj) return mixin(obj);
- }
-
- function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
- }
- return obj;
- }
-
- Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
- this._callbacks = this._callbacks || {};
- (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
- return this;
- };
-
- Emitter.prototype.once = function (event, fn) {
- function on() {
- this.off(event, on);
- fn.apply(this, arguments);
- }
- on.fn = fn;
- this.on(event, on);
- return this;
- };
-
- Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
- this._callbacks = this._callbacks || {};
-
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- }
-
- var callbacks = this._callbacks['$' + event];
- if (!callbacks) return this;
-
- if (1 == arguments.length) {
- delete this._callbacks['$' + event];
- return this;
- }
-
- var cb;
- for (var i = 0; i < callbacks.length; i++) {
- cb = callbacks[i];
- if (cb === fn || cb.fn === fn) {
- callbacks.splice(i, 1);
- break;
- }
- }
-
-
- if (callbacks.length === 0) {
- delete this._callbacks['$' + event];
- }
- return this;
- };
-
- Emitter.prototype.emit = function (event) {
- this._callbacks = this._callbacks || {};
- var args = new Array(arguments.length - 1),
- callbacks = this._callbacks['$' + event];
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- return this;
- };
-
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
-
- Emitter.prototype.listeners = function (event) {
- this._callbacks = this._callbacks || {};
- return this._callbacks['$' + event] || [];
- };
-
- Emitter.prototype.hasListeners = function (event) {
- return !!this.listeners(event).length;
- };
- var globalThisShim = function () {
- if (typeof self !== "undefined") {
- return self;
- } else if (typeof window !== "undefined") {
- return window;
- } else {
- return Function("return this")();
- }
- }();
- function pick(obj) {
- for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- attr[_key - 1] = arguments[_key];
- }
- return attr.reduce(function (acc, k) {
- if (obj.hasOwnProperty(k)) {
- acc[k] = obj[k];
- }
- return acc;
- }, {});
- }
-
- var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
- var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
- function installTimerFunctions(obj, opts) {
- if (opts.useNativeTimers) {
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
- } else {
- obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
- obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
- }
- }
-
- var BASE64_OVERHEAD = 1.33;
-
- function byteLength(obj) {
- if (typeof obj === "string") {
- return utf8Length(obj);
- }
-
- return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
- }
- function utf8Length(str) {
- var c = 0,
- length = 0;
- for (var i = 0, l = str.length; i < l; i++) {
- c = str.charCodeAt(i);
- if (c < 0x80) {
- length += 1;
- } else if (c < 0x800) {
- length += 2;
- } else if (c < 0xd800 || c >= 0xe000) {
- length += 3;
- } else {
- i++;
- length += 4;
- }
- }
- return length;
- }
-
-
- function encode$1(obj) {
- var str = '';
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (str.length) str += '&';
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
- }
- }
- return str;
- }
-
- function decode(qs) {
- var qry = {};
- var pairs = qs.split('&');
- for (var i = 0, l = pairs.length; i < l; i++) {
- var pair = pairs[i].split('=');
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
- }
- return qry;
- }
- var TransportError = function (_Error) {
- _inherits(TransportError, _Error);
- var _super = _createSuper(TransportError);
- function TransportError(reason, description, context) {
- var _this;
- _classCallCheck(this, TransportError);
- _this = _super.call(this, reason);
- _this.description = description;
- _this.context = context;
- _this.type = "TransportError";
- return _this;
- }
- return _createClass(TransportError);
- }( _wrapNativeSuper(Error));
- var Transport = function (_Emitter) {
- _inherits(Transport, _Emitter);
- var _super2 = _createSuper(Transport);
-
- function Transport(opts) {
- var _this2;
- _classCallCheck(this, Transport);
- _this2 = _super2.call(this);
- _this2.writable = false;
- installTimerFunctions(_assertThisInitialized(_this2), opts);
- _this2.opts = opts;
- _this2.query = opts.query;
- _this2.socket = opts.socket;
- return _this2;
- }
-
- _createClass(Transport, [{
- key: "onError",
- value: function onError(reason, description, context) {
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
- return this;
- }
-
- }, {
- key: "open",
- value: function open() {
- this.readyState = "opening";
- this.doOpen();
- return this;
- }
-
- }, {
- key: "close",
- value: function close() {
- if (this.readyState === "opening" || this.readyState === "open") {
- this.doClose();
- this.onClose();
- }
- return this;
- }
-
- }, {
- key: "send",
- value: function send(packets) {
- if (this.readyState === "open") {
- this.write(packets);
- }
- }
-
- }, {
- key: "onOpen",
- value: function onOpen() {
- this.readyState = "open";
- this.writable = true;
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
- }
-
- }, {
- key: "onData",
- value: function onData(data) {
- var packet = decodePacket(data, this.socket.binaryType);
- this.onPacket(packet);
- }
-
- }, {
- key: "onPacket",
- value: function onPacket(packet) {
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
- }
-
- }, {
- key: "onClose",
- value: function onClose(details) {
- this.readyState = "closed";
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
- }
-
- }, {
- key: "pause",
- value: function pause(onPause) {}
- }, {
- key: "createUri",
- value: function createUri(schema) {
- var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
- }
- }, {
- key: "_hostname",
- value: function _hostname() {
- var hostname = this.opts.hostname;
- return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
- }
- }, {
- key: "_port",
- value: function _port() {
- if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
- return ":" + this.opts.port;
- } else {
- return "";
- }
- }
- }, {
- key: "_query",
- value: function _query(query) {
- var encodedQuery = encode$1(query);
- return encodedQuery.length ? "?" + encodedQuery : "";
- }
- }]);
- return Transport;
- }(Emitter);
-
- var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
- length = 64,
- map = {};
- var seed = 0,
- i = 0,
- prev;
-
- function encode(num) {
- var encoded = '';
- do {
- encoded = alphabet[num % length] + encoded;
- num = Math.floor(num / length);
- } while (num > 0);
- return encoded;
- }
-
- function yeast() {
- var now = encode(+new Date());
- if (now !== prev) return seed = 0, prev = now;
- return now + '.' + encode(seed++);
- }
-
-
-
- for (; i < length; i++) map[alphabet[i]] = i;
-
- var value = false;
- try {
- value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
- } catch (err) {
-
-
- }
- var hasCORS = value;
-
- function XHR(opts) {
- var xdomain = opts.xdomain;
-
- try {
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
- return new XMLHttpRequest();
- }
- } catch (e) {}
- if (!xdomain) {
- try {
- return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
- } catch (e) {}
- }
- }
- function createCookieJar() {}
- function empty() {}
- var hasXHR2 = function () {
- var xhr = new XHR({
- xdomain: false
- });
- return null != xhr.responseType;
- }();
- var Polling = function (_Transport) {
- _inherits(Polling, _Transport);
- var _super = _createSuper(Polling);
-
- function Polling(opts) {
- var _this;
- _classCallCheck(this, Polling);
- _this = _super.call(this, opts);
- _this.polling = false;
- if (typeof location !== "undefined") {
- var isSSL = "https:" === location.protocol;
- var port = location.port;
-
- if (!port) {
- port = isSSL ? "443" : "80";
- }
- _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
- }
-
- var forceBase64 = opts && opts.forceBase64;
- _this.supportsBinary = hasXHR2 && !forceBase64;
- if (_this.opts.withCredentials) {
- _this.cookieJar = createCookieJar();
- }
- return _this;
- }
- _createClass(Polling, [{
- key: "name",
- get: function get() {
- return "polling";
- }
-
- }, {
- key: "doOpen",
- value: function doOpen() {
- this.poll();
- }
-
- }, {
- key: "pause",
- value: function pause(onPause) {
- var _this2 = this;
- this.readyState = "pausing";
- var pause = function pause() {
- _this2.readyState = "paused";
- onPause();
- };
- if (this.polling || !this.writable) {
- var total = 0;
- if (this.polling) {
- total++;
- this.once("pollComplete", function () {
- --total || pause();
- });
- }
- if (!this.writable) {
- total++;
- this.once("drain", function () {
- --total || pause();
- });
- }
- } else {
- pause();
- }
- }
-
- }, {
- key: "poll",
- value: function poll() {
- this.polling = true;
- this.doPoll();
- this.emitReserved("poll");
- }
-
- }, {
- key: "onData",
- value: function onData(data) {
- var _this3 = this;
- var callback = function callback(packet) {
-
- if ("opening" === _this3.readyState && packet.type === "open") {
- _this3.onOpen();
- }
-
- if ("close" === packet.type) {
- _this3.onClose({
- description: "transport closed by the server"
- });
- return false;
- }
-
- _this3.onPacket(packet);
- };
-
- decodePayload(data, this.socket.binaryType).forEach(callback);
-
- if ("closed" !== this.readyState) {
-
- this.polling = false;
- this.emitReserved("pollComplete");
- if ("open" === this.readyState) {
- this.poll();
- }
- }
- }
-
- }, {
- key: "doClose",
- value: function doClose() {
- var _this4 = this;
- var close = function close() {
- _this4.write([{
- type: "close"
- }]);
- };
- if ("open" === this.readyState) {
- close();
- } else {
-
-
- this.once("open", close);
- }
- }
-
- }, {
- key: "write",
- value: function write(packets) {
- var _this5 = this;
- this.writable = false;
- encodePayload(packets, function (data) {
- _this5.doWrite(data, function () {
- _this5.writable = true;
- _this5.emitReserved("drain");
- });
- });
- }
-
- }, {
- key: "uri",
- value: function uri() {
- var schema = this.opts.secure ? "https" : "http";
- var query = this.query || {};
-
- if (false !== this.opts.timestampRequests) {
- query[this.opts.timestampParam] = yeast();
- }
- if (!this.supportsBinary && !query.sid) {
- query.b64 = 1;
- }
- return this.createUri(schema, query);
- }
-
- }, {
- key: "request",
- value: function request() {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- _extends(opts, {
- xd: this.xd,
- cookieJar: this.cookieJar
- }, this.opts);
- return new Request(this.uri(), opts);
- }
-
- }, {
- key: "doWrite",
- value: function doWrite(data, fn) {
- var _this6 = this;
- var req = this.request({
- method: "POST",
- data: data
- });
- req.on("success", fn);
- req.on("error", function (xhrStatus, context) {
- _this6.onError("xhr post error", xhrStatus, context);
- });
- }
-
- }, {
- key: "doPoll",
- value: function doPoll() {
- var _this7 = this;
- var req = this.request();
- req.on("data", this.onData.bind(this));
- req.on("error", function (xhrStatus, context) {
- _this7.onError("xhr poll error", xhrStatus, context);
- });
- this.pollXhr = req;
- }
- }]);
- return Polling;
- }(Transport);
- var Request = function (_Emitter) {
- _inherits(Request, _Emitter);
- var _super2 = _createSuper(Request);
-
- function Request(uri, opts) {
- var _this8;
- _classCallCheck(this, Request);
- _this8 = _super2.call(this);
- installTimerFunctions(_assertThisInitialized(_this8), opts);
- _this8.opts = opts;
- _this8.method = opts.method || "GET";
- _this8.uri = uri;
- _this8.data = undefined !== opts.data ? opts.data : null;
- _this8.create();
- return _this8;
- }
-
- _createClass(Request, [{
- key: "create",
- value: function create() {
- var _this9 = this;
- var _a;
- var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
- opts.xdomain = !!this.opts.xd;
- var xhr = this.xhr = new XHR(opts);
- try {
- xhr.open(this.method, this.uri, true);
- try {
- if (this.opts.extraHeaders) {
- xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
- for (var i in this.opts.extraHeaders) {
- if (this.opts.extraHeaders.hasOwnProperty(i)) {
- xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
- }
- }
- }
- } catch (e) {}
- if ("POST" === this.method) {
- try {
- xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
- } catch (e) {}
- }
- try {
- xhr.setRequestHeader("Accept", "*/*");
- } catch (e) {}
- (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
-
- if ("withCredentials" in xhr) {
- xhr.withCredentials = this.opts.withCredentials;
- }
- if (this.opts.requestTimeout) {
- xhr.timeout = this.opts.requestTimeout;
- }
- xhr.onreadystatechange = function () {
- var _a;
- if (xhr.readyState === 3) {
- (_a = _this9.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr);
- }
- if (4 !== xhr.readyState) return;
- if (200 === xhr.status || 1223 === xhr.status) {
- _this9.onLoad();
- } else {
-
-
- _this9.setTimeoutFn(function () {
- _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
- }, 0);
- }
- };
- xhr.send(this.data);
- } catch (e) {
-
-
-
- this.setTimeoutFn(function () {
- _this9.onError(e);
- }, 0);
- return;
- }
- if (typeof document !== "undefined") {
- this.index = Request.requestsCount++;
- Request.requests[this.index] = this;
- }
- }
-
- }, {
- key: "onError",
- value: function onError(err) {
- this.emitReserved("error", err, this.xhr);
- this.cleanup(true);
- }
-
- }, {
- key: "cleanup",
- value: function cleanup(fromError) {
- if ("undefined" === typeof this.xhr || null === this.xhr) {
- return;
- }
- this.xhr.onreadystatechange = empty;
- if (fromError) {
- try {
- this.xhr.abort();
- } catch (e) {}
- }
- if (typeof document !== "undefined") {
- delete Request.requests[this.index];
- }
- this.xhr = null;
- }
-
- }, {
- key: "onLoad",
- value: function onLoad() {
- var data = this.xhr.responseText;
- if (data !== null) {
- this.emitReserved("data", data);
- this.emitReserved("success");
- this.cleanup();
- }
- }
-
- }, {
- key: "abort",
- value: function abort() {
- this.cleanup();
- }
- }]);
- return Request;
- }(Emitter);
- Request.requestsCount = 0;
- Request.requests = {};
-
- if (typeof document !== "undefined") {
-
- if (typeof attachEvent === "function") {
-
- attachEvent("onunload", unloadHandler);
- } else if (typeof addEventListener === "function") {
- var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
- addEventListener(terminationEvent, unloadHandler, false);
- }
- }
- function unloadHandler() {
- for (var i in Request.requests) {
- if (Request.requests.hasOwnProperty(i)) {
- Request.requests[i].abort();
- }
- }
- }
- var nextTick = function () {
- var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
- if (isPromiseAvailable) {
- return function (cb) {
- return Promise.resolve().then(cb);
- };
- } else {
- return function (cb, setTimeoutFn) {
- return setTimeoutFn(cb, 0);
- };
- }
- }();
- var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
- var usingBrowserWebSocket = true;
- var defaultBinaryType = "arraybuffer";
-
- var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
- var WS = function (_Transport) {
- _inherits(WS, _Transport);
- var _super = _createSuper(WS);
-
- function WS(opts) {
- var _this;
- _classCallCheck(this, WS);
- _this = _super.call(this, opts);
- _this.supportsBinary = !opts.forceBase64;
- return _this;
- }
- _createClass(WS, [{
- key: "name",
- get: function get() {
- return "websocket";
- }
- }, {
- key: "doOpen",
- value: function doOpen() {
- if (!this.check()) {
-
- return;
- }
- var uri = this.uri();
- var protocols = this.opts.protocols;
-
- var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
- if (this.opts.extraHeaders) {
- opts.headers = this.opts.extraHeaders;
- }
- try {
- this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
- } catch (err) {
- return this.emitReserved("error", err);
- }
- this.ws.binaryType = this.socket.binaryType;
- this.addEventListeners();
- }
-
- }, {
- key: "addEventListeners",
- value: function addEventListeners() {
- var _this2 = this;
- this.ws.onopen = function () {
- if (_this2.opts.autoUnref) {
- _this2.ws._socket.unref();
- }
- _this2.onOpen();
- };
- this.ws.onclose = function (closeEvent) {
- return _this2.onClose({
- description: "websocket connection closed",
- context: closeEvent
- });
- };
- this.ws.onmessage = function (ev) {
- return _this2.onData(ev.data);
- };
- this.ws.onerror = function (e) {
- return _this2.onError("websocket error", e);
- };
- }
- }, {
- key: "write",
- value: function write(packets) {
- var _this3 = this;
- this.writable = false;
-
-
- var _loop = function _loop() {
- var packet = packets[i];
- var lastPacket = i === packets.length - 1;
- encodePacket(packet, _this3.supportsBinary, function (data) {
-
- var opts = {};
-
-
-
- try {
- if (usingBrowserWebSocket) {
-
- _this3.ws.send(data);
- }
- } catch (e) {}
- if (lastPacket) {
-
-
- nextTick(function () {
- _this3.writable = true;
- _this3.emitReserved("drain");
- }, _this3.setTimeoutFn);
- }
- });
- };
- for (var i = 0; i < packets.length; i++) {
- _loop();
- }
- }
- }, {
- key: "doClose",
- value: function doClose() {
- if (typeof this.ws !== "undefined") {
- this.ws.close();
- this.ws = null;
- }
- }
-
- }, {
- key: "uri",
- value: function uri() {
- var schema = this.opts.secure ? "wss" : "ws";
- var query = this.query || {};
-
- if (this.opts.timestampRequests) {
- query[this.opts.timestampParam] = yeast();
- }
-
- if (!this.supportsBinary) {
- query.b64 = 1;
- }
- return this.createUri(schema, query);
- }
-
- }, {
- key: "check",
- value: function check() {
- return !!WebSocket;
- }
- }]);
- return WS;
- }(Transport);
- var WT = function (_Transport) {
- _inherits(WT, _Transport);
- var _super = _createSuper(WT);
- function WT() {
- _classCallCheck(this, WT);
- return _super.apply(this, arguments);
- }
- _createClass(WT, [{
- key: "name",
- get: function get() {
- return "webtransport";
- }
- }, {
- key: "doOpen",
- value: function doOpen() {
- var _this = this;
-
- if (typeof WebTransport !== "function") {
- return;
- }
-
- this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
- this.transport.closed.then(function () {
- _this.onClose();
- })["catch"](function (err) {
- _this.onError("webtransport error", err);
- });
-
- this.transport.ready.then(function () {
- _this.transport.createBidirectionalStream().then(function (stream) {
- var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType);
- var reader = stream.readable.pipeThrough(decoderStream).getReader();
- var encoderStream = createPacketEncoderStream();
- encoderStream.readable.pipeTo(stream.writable);
- _this.writer = encoderStream.writable.getWriter();
- var read = function read() {
- reader.read().then(function (_ref) {
- var done = _ref.done,
- value = _ref.value;
- if (done) {
- return;
- }
- _this.onPacket(value);
- read();
- })["catch"](function (err) {});
- };
- read();
- var packet = {
- type: "open"
- };
- if (_this.query.sid) {
- packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}");
- }
- _this.writer.write(packet).then(function () {
- return _this.onOpen();
- });
- });
- });
- }
- }, {
- key: "write",
- value: function write(packets) {
- var _this2 = this;
- this.writable = false;
- var _loop = function _loop() {
- var packet = packets[i];
- var lastPacket = i === packets.length - 1;
- _this2.writer.write(packet).then(function () {
- if (lastPacket) {
- nextTick(function () {
- _this2.writable = true;
- _this2.emitReserved("drain");
- }, _this2.setTimeoutFn);
- }
- });
- };
- for (var i = 0; i < packets.length; i++) {
- _loop();
- }
- }
- }, {
- key: "doClose",
- value: function doClose() {
- var _a;
- (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close();
- }
- }]);
- return WT;
- }(Transport);
- var transports = {
- websocket: WS,
- webtransport: WT,
- polling: Polling
- };
-
-
- var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
- var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
- function parse(str) {
- var src = str,
- b = str.indexOf('['),
- e = str.indexOf(']');
- if (b != -1 && e != -1) {
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
- }
- var m = re.exec(str || ''),
- uri = {},
- i = 14;
- while (i--) {
- uri[parts[i]] = m[i] || '';
- }
- if (b != -1 && e != -1) {
- uri.source = src;
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
- uri.ipv6uri = true;
- }
- uri.pathNames = pathNames(uri, uri['path']);
- uri.queryKey = queryKey(uri, uri['query']);
- return uri;
- }
- function pathNames(obj, path) {
- var regx = /\/{2,9}/g,
- names = path.replace(regx, "/").split("/");
- if (path.slice(0, 1) == '/' || path.length === 0) {
- names.splice(0, 1);
- }
- if (path.slice(-1) == '/') {
- names.splice(names.length - 1, 1);
- }
- return names;
- }
- function queryKey(uri, query) {
- var data = {};
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
- if ($1) {
- data[$1] = $2;
- }
- });
- return data;
- }
- var Socket$1 = function (_Emitter) {
- _inherits(Socket, _Emitter);
- var _super = _createSuper(Socket);
-
- function Socket(uri) {
- var _this;
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- _classCallCheck(this, Socket);
- _this = _super.call(this);
- _this.binaryType = defaultBinaryType;
- _this.writeBuffer = [];
- if (uri && "object" === _typeof(uri)) {
- opts = uri;
- uri = null;
- }
- if (uri) {
- uri = parse(uri);
- opts.hostname = uri.host;
- opts.secure = uri.protocol === "https" || uri.protocol === "wss";
- opts.port = uri.port;
- if (uri.query) opts.query = uri.query;
- } else if (opts.host) {
- opts.hostname = parse(opts.host).host;
- }
- installTimerFunctions(_assertThisInitialized(_this), opts);
- _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
- if (opts.hostname && !opts.port) {
-
- opts.port = _this.secure ? "443" : "80";
- }
- _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
- _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
- _this.transports = opts.transports || ["polling", "websocket", "webtransport"];
- _this.writeBuffer = [];
- _this.prevBufferLen = 0;
- _this.opts = _extends({
- path: "/engine.io",
- agent: false,
- withCredentials: false,
- upgrade: true,
- timestampParam: "t",
- rememberUpgrade: false,
- addTrailingSlash: true,
- rejectUnauthorized: true,
- perMessageDeflate: {
- threshold: 1024
- },
- transportOptions: {},
- closeOnBeforeunload: false
- }, opts);
- _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
- if (typeof _this.opts.query === "string") {
- _this.opts.query = decode(_this.opts.query);
- }
-
- _this.id = null;
- _this.upgrades = null;
- _this.pingInterval = null;
- _this.pingTimeout = null;
-
- _this.pingTimeoutTimer = null;
- if (typeof addEventListener === "function") {
- if (_this.opts.closeOnBeforeunload) {
-
-
-
- _this.beforeunloadEventListener = function () {
- if (_this.transport) {
-
- _this.transport.removeAllListeners();
- _this.transport.close();
- }
- };
- addEventListener("beforeunload", _this.beforeunloadEventListener, false);
- }
- if (_this.hostname !== "localhost") {
- _this.offlineEventListener = function () {
- _this.onClose("transport close", {
- description: "network connection lost"
- });
- };
- addEventListener("offline", _this.offlineEventListener, false);
- }
- }
- _this.open();
- return _this;
- }
-
- _createClass(Socket, [{
- key: "createTransport",
- value: function createTransport(name) {
- var query = _extends({}, this.opts.query);
-
- query.EIO = protocol$1;
-
- query.transport = name;
-
- if (this.id) query.sid = this.id;
- var opts = _extends({}, this.opts, {
- query: query,
- socket: this,
- hostname: this.hostname,
- secure: this.secure,
- port: this.port
- }, this.opts.transportOptions[name]);
- return new transports[name](opts);
- }
-
- }, {
- key: "open",
- value: function open() {
- var _this2 = this;
- var transport;
- if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
- transport = "websocket";
- } else if (0 === this.transports.length) {
-
- this.setTimeoutFn(function () {
- _this2.emitReserved("error", "No transports available");
- }, 0);
- return;
- } else {
- transport = this.transports[0];
- }
- this.readyState = "opening";
-
- try {
- transport = this.createTransport(transport);
- } catch (e) {
- this.transports.shift();
- this.open();
- return;
- }
- transport.open();
- this.setTransport(transport);
- }
-
- }, {
- key: "setTransport",
- value: function setTransport(transport) {
- var _this3 = this;
- if (this.transport) {
- this.transport.removeAllListeners();
- }
-
- this.transport = transport;
-
- transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
- return _this3.onClose("transport close", reason);
- });
- }
-
- }, {
- key: "probe",
- value: function probe(name) {
- var _this4 = this;
- var transport = this.createTransport(name);
- var failed = false;
- Socket.priorWebsocketSuccess = false;
- var onTransportOpen = function onTransportOpen() {
- if (failed) return;
- transport.send([{
- type: "ping",
- data: "probe"
- }]);
- transport.once("packet", function (msg) {
- if (failed) return;
- if ("pong" === msg.type && "probe" === msg.data) {
- _this4.upgrading = true;
- _this4.emitReserved("upgrading", transport);
- if (!transport) return;
- Socket.priorWebsocketSuccess = "websocket" === transport.name;
- _this4.transport.pause(function () {
- if (failed) return;
- if ("closed" === _this4.readyState) return;
- cleanup();
- _this4.setTransport(transport);
- transport.send([{
- type: "upgrade"
- }]);
- _this4.emitReserved("upgrade", transport);
- transport = null;
- _this4.upgrading = false;
- _this4.flush();
- });
- } else {
- var err = new Error("probe error");
-
- err.transport = transport.name;
- _this4.emitReserved("upgradeError", err);
- }
- });
- };
- function freezeTransport() {
- if (failed) return;
-
- failed = true;
- cleanup();
- transport.close();
- transport = null;
- }
-
- var onerror = function onerror(err) {
- var error = new Error("probe error: " + err);
-
- error.transport = transport.name;
- freezeTransport();
- _this4.emitReserved("upgradeError", error);
- };
- function onTransportClose() {
- onerror("transport closed");
- }
-
- function onclose() {
- onerror("socket closed");
- }
-
- function onupgrade(to) {
- if (transport && to.name !== transport.name) {
- freezeTransport();
- }
- }
-
- var cleanup = function cleanup() {
- transport.removeListener("open", onTransportOpen);
- transport.removeListener("error", onerror);
- transport.removeListener("close", onTransportClose);
- _this4.off("close", onclose);
- _this4.off("upgrading", onupgrade);
- };
- transport.once("open", onTransportOpen);
- transport.once("error", onerror);
- transport.once("close", onTransportClose);
- this.once("close", onclose);
- this.once("upgrading", onupgrade);
- if (this.upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
-
- this.setTimeoutFn(function () {
- if (!failed) {
- transport.open();
- }
- }, 200);
- } else {
- transport.open();
- }
- }
-
- }, {
- key: "onOpen",
- value: function onOpen() {
- this.readyState = "open";
- Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
- this.emitReserved("open");
- this.flush();
-
-
- if ("open" === this.readyState && this.opts.upgrade) {
- var i = 0;
- var l = this.upgrades.length;
- for (; i < l; i++) {
- this.probe(this.upgrades[i]);
- }
- }
- }
-
- }, {
- key: "onPacket",
- value: function onPacket(packet) {
- if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
- this.emitReserved("packet", packet);
-
- this.emitReserved("heartbeat");
- this.resetPingTimeout();
- switch (packet.type) {
- case "open":
- this.onHandshake(JSON.parse(packet.data));
- break;
- case "ping":
- this.sendPacket("pong");
- this.emitReserved("ping");
- this.emitReserved("pong");
- break;
- case "error":
- var err = new Error("server error");
-
- err.code = packet.data;
- this.onError(err);
- break;
- case "message":
- this.emitReserved("data", packet.data);
- this.emitReserved("message", packet.data);
- break;
- }
- }
- }
-
- }, {
- key: "onHandshake",
- value: function onHandshake(data) {
- this.emitReserved("handshake", data);
- this.id = data.sid;
- this.transport.query.sid = data.sid;
- this.upgrades = this.filterUpgrades(data.upgrades);
- this.pingInterval = data.pingInterval;
- this.pingTimeout = data.pingTimeout;
- this.maxPayload = data.maxPayload;
- this.onOpen();
-
- if ("closed" === this.readyState) return;
- this.resetPingTimeout();
- }
-
- }, {
- key: "resetPingTimeout",
- value: function resetPingTimeout() {
- var _this5 = this;
- this.clearTimeoutFn(this.pingTimeoutTimer);
- this.pingTimeoutTimer = this.setTimeoutFn(function () {
- _this5.onClose("ping timeout");
- }, this.pingInterval + this.pingTimeout);
- if (this.opts.autoUnref) {
- this.pingTimeoutTimer.unref();
- }
- }
-
- }, {
- key: "onDrain",
- value: function onDrain() {
- this.writeBuffer.splice(0, this.prevBufferLen);
-
-
-
- this.prevBufferLen = 0;
- if (0 === this.writeBuffer.length) {
- this.emitReserved("drain");
- } else {
- this.flush();
- }
- }
-
- }, {
- key: "flush",
- value: function flush() {
- if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
- var packets = this.getWritablePackets();
- this.transport.send(packets);
-
-
- this.prevBufferLen = packets.length;
- this.emitReserved("flush");
- }
- }
-
- }, {
- key: "getWritablePackets",
- value: function getWritablePackets() {
- var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
- if (!shouldCheckPayloadSize) {
- return this.writeBuffer;
- }
- var payloadSize = 1;
- for (var i = 0; i < this.writeBuffer.length; i++) {
- var data = this.writeBuffer[i].data;
- if (data) {
- payloadSize += byteLength(data);
- }
- if (i > 0 && payloadSize > this.maxPayload) {
- return this.writeBuffer.slice(0, i);
- }
- payloadSize += 2;
- }
- return this.writeBuffer;
- }
-
- }, {
- key: "write",
- value: function write(msg, options, fn) {
- this.sendPacket("message", msg, options, fn);
- return this;
- }
- }, {
- key: "send",
- value: function send(msg, options, fn) {
- this.sendPacket("message", msg, options, fn);
- return this;
- }
-
- }, {
- key: "sendPacket",
- value: function sendPacket(type, data, options, fn) {
- if ("function" === typeof data) {
- fn = data;
- data = undefined;
- }
- if ("function" === typeof options) {
- fn = options;
- options = null;
- }
- if ("closing" === this.readyState || "closed" === this.readyState) {
- return;
- }
- options = options || {};
- options.compress = false !== options.compress;
- var packet = {
- type: type,
- data: data,
- options: options
- };
- this.emitReserved("packetCreate", packet);
- this.writeBuffer.push(packet);
- if (fn) this.once("flush", fn);
- this.flush();
- }
-
- }, {
- key: "close",
- value: function close() {
- var _this6 = this;
- var close = function close() {
- _this6.onClose("forced close");
- _this6.transport.close();
- };
- var cleanupAndClose = function cleanupAndClose() {
- _this6.off("upgrade", cleanupAndClose);
- _this6.off("upgradeError", cleanupAndClose);
- close();
- };
- var waitForUpgrade = function waitForUpgrade() {
-
- _this6.once("upgrade", cleanupAndClose);
- _this6.once("upgradeError", cleanupAndClose);
- };
- if ("opening" === this.readyState || "open" === this.readyState) {
- this.readyState = "closing";
- if (this.writeBuffer.length) {
- this.once("drain", function () {
- if (_this6.upgrading) {
- waitForUpgrade();
- } else {
- close();
- }
- });
- } else if (this.upgrading) {
- waitForUpgrade();
- } else {
- close();
- }
- }
- return this;
- }
-
- }, {
- key: "onError",
- value: function onError(err) {
- Socket.priorWebsocketSuccess = false;
- this.emitReserved("error", err);
- this.onClose("transport error", err);
- }
-
- }, {
- key: "onClose",
- value: function onClose(reason, description) {
- if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
-
- this.clearTimeoutFn(this.pingTimeoutTimer);
-
- this.transport.removeAllListeners("close");
-
- this.transport.close();
-
- this.transport.removeAllListeners();
- if (typeof removeEventListener === "function") {
- removeEventListener("beforeunload", this.beforeunloadEventListener, false);
- removeEventListener("offline", this.offlineEventListener, false);
- }
-
- this.readyState = "closed";
-
- this.id = null;
-
- this.emitReserved("close", reason, description);
-
-
- this.writeBuffer = [];
- this.prevBufferLen = 0;
- }
- }
-
- }, {
- key: "filterUpgrades",
- value: function filterUpgrades(upgrades) {
- var filteredUpgrades = [];
- var i = 0;
- var j = upgrades.length;
- for (; i < j; i++) {
- if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
- }
- return filteredUpgrades;
- }
- }]);
- return Socket;
- }(Emitter);
- Socket$1.protocol = protocol$1;
- Socket$1.protocol;
-
- function url(uri) {
- var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
- var loc = arguments.length > 2 ? arguments[2] : undefined;
- var obj = uri;
-
- loc = loc || typeof location !== "undefined" && location;
- if (null == uri) uri = loc.protocol + "//" + loc.host;
-
- if (typeof uri === "string") {
- if ("/" === uri.charAt(0)) {
- if ("/" === uri.charAt(1)) {
- uri = loc.protocol + uri;
- } else {
- uri = loc.host + uri;
- }
- }
- if (!/^(https?|wss?):\/\//.test(uri)) {
- if ("undefined" !== typeof loc) {
- uri = loc.protocol + "//" + uri;
- } else {
- uri = "https://" + uri;
- }
- }
-
- obj = parse(uri);
- }
-
- if (!obj.port) {
- if (/^(http|ws)$/.test(obj.protocol)) {
- obj.port = "80";
- } else if (/^(http|ws)s$/.test(obj.protocol)) {
- obj.port = "443";
- }
- }
- obj.path = obj.path || "/";
- var ipv6 = obj.host.indexOf(":") !== -1;
- var host = ipv6 ? "[" + obj.host + "]" : obj.host;
-
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
-
- obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
- return obj;
- }
- var withNativeArrayBuffer = typeof ArrayBuffer === "function";
- var isView = function isView(obj) {
- return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
- };
- var toString = Object.prototype.toString;
- var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
- var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
-
- function isBinary(obj) {
- return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
- }
- function hasBinary(obj, toJSON) {
- if (!obj || _typeof(obj) !== "object") {
- return false;
- }
- if (Array.isArray(obj)) {
- for (var i = 0, l = obj.length; i < l; i++) {
- if (hasBinary(obj[i])) {
- return true;
- }
- }
- return false;
- }
- if (isBinary(obj)) {
- return true;
- }
- if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
- return hasBinary(obj.toJSON(), true);
- }
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
- return true;
- }
- }
- return false;
- }
-
- function deconstructPacket(packet) {
- var buffers = [];
- var packetData = packet.data;
- var pack = packet;
- pack.data = _deconstructPacket(packetData, buffers);
- pack.attachments = buffers.length;
- return {
- packet: pack,
- buffers: buffers
- };
- }
- function _deconstructPacket(data, buffers) {
- if (!data) return data;
- if (isBinary(data)) {
- var placeholder = {
- _placeholder: true,
- num: buffers.length
- };
- buffers.push(data);
- return placeholder;
- } else if (Array.isArray(data)) {
- var newData = new Array(data.length);
- for (var i = 0; i < data.length; i++) {
- newData[i] = _deconstructPacket(data[i], buffers);
- }
- return newData;
- } else if (_typeof(data) === "object" && !(data instanceof Date)) {
- var _newData = {};
- for (var key in data) {
- if (Object.prototype.hasOwnProperty.call(data, key)) {
- _newData[key] = _deconstructPacket(data[key], buffers);
- }
- }
- return _newData;
- }
- return data;
- }
-
- function reconstructPacket(packet, buffers) {
- packet.data = _reconstructPacket(packet.data, buffers);
- delete packet.attachments;
- return packet;
- }
- function _reconstructPacket(data, buffers) {
- if (!data) return data;
- if (data && data._placeholder === true) {
- var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
- if (isIndexValid) {
- return buffers[data.num];
- } else {
- throw new Error("illegal attachments");
- }
- } else if (Array.isArray(data)) {
- for (var i = 0; i < data.length; i++) {
- data[i] = _reconstructPacket(data[i], buffers);
- }
- } else if (_typeof(data) === "object") {
- for (var key in data) {
- if (Object.prototype.hasOwnProperty.call(data, key)) {
- data[key] = _reconstructPacket(data[key], buffers);
- }
- }
- }
- return data;
- }
-
- var RESERVED_EVENTS$1 = ["connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener"
- ];
-
- var protocol = 5;
- var PacketType;
- (function (PacketType) {
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
- PacketType[PacketType["ACK"] = 3] = "ACK";
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
- })(PacketType || (PacketType = {}));
-
- var Encoder = function () {
-
- function Encoder(replacer) {
- _classCallCheck(this, Encoder);
- this.replacer = replacer;
- }
-
- _createClass(Encoder, [{
- key: "encode",
- value: function encode(obj) {
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
- if (hasBinary(obj)) {
- return this.encodeAsBinary({
- type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
- nsp: obj.nsp,
- data: obj.data,
- id: obj.id
- });
- }
- }
- return [this.encodeAsString(obj)];
- }
-
- }, {
- key: "encodeAsString",
- value: function encodeAsString(obj) {
-
- var str = "" + obj.type;
-
- if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
- str += obj.attachments + "-";
- }
-
-
- if (obj.nsp && "/" !== obj.nsp) {
- str += obj.nsp + ",";
- }
-
- if (null != obj.id) {
- str += obj.id;
- }
-
- if (null != obj.data) {
- str += JSON.stringify(obj.data, this.replacer);
- }
- return str;
- }
-
- }, {
- key: "encodeAsBinary",
- value: function encodeAsBinary(obj) {
- var deconstruction = deconstructPacket(obj);
- var pack = this.encodeAsString(deconstruction.packet);
- var buffers = deconstruction.buffers;
- buffers.unshift(pack);
- return buffers;
- }
- }]);
- return Encoder;
- }();
-
- function isObject(value) {
- return Object.prototype.toString.call(value) === "[object Object]";
- }
-
- var Decoder = function (_Emitter) {
- _inherits(Decoder, _Emitter);
- var _super = _createSuper(Decoder);
-
- function Decoder(reviver) {
- var _this;
- _classCallCheck(this, Decoder);
- _this = _super.call(this);
- _this.reviver = reviver;
- return _this;
- }
-
- _createClass(Decoder, [{
- key: "add",
- value: function add(obj) {
- var packet;
- if (typeof obj === "string") {
- if (this.reconstructor) {
- throw new Error("got plaintext data when reconstructing a packet");
- }
- packet = this.decodeString(obj);
- var isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
-
- this.reconstructor = new BinaryReconstructor(packet);
-
- if (packet.attachments === 0) {
- _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
- }
- } else {
-
- _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
- }
- } else if (isBinary(obj) || obj.base64) {
-
- if (!this.reconstructor) {
- throw new Error("got binary data when not reconstructing a packet");
- } else {
- packet = this.reconstructor.takeBinaryData(obj);
- if (packet) {
-
- this.reconstructor = null;
- _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
- }
- }
- } else {
- throw new Error("Unknown type: " + obj);
- }
- }
-
- }, {
- key: "decodeString",
- value: function decodeString(str) {
- var i = 0;
-
- var p = {
- type: Number(str.charAt(0))
- };
- if (PacketType[p.type] === undefined) {
- throw new Error("unknown packet type " + p.type);
- }
-
- if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
- var start = i + 1;
- while (str.charAt(++i) !== "-" && i != str.length) {}
- var buf = str.substring(start, i);
- if (buf != Number(buf) || str.charAt(i) !== "-") {
- throw new Error("Illegal attachments");
- }
- p.attachments = Number(buf);
- }
-
- if ("/" === str.charAt(i + 1)) {
- var _start = i + 1;
- while (++i) {
- var c = str.charAt(i);
- if ("," === c) break;
- if (i === str.length) break;
- }
- p.nsp = str.substring(_start, i);
- } else {
- p.nsp = "/";
- }
-
- var next = str.charAt(i + 1);
- if ("" !== next && Number(next) == next) {
- var _start2 = i + 1;
- while (++i) {
- var _c = str.charAt(i);
- if (null == _c || Number(_c) != _c) {
- --i;
- break;
- }
- if (i === str.length) break;
- }
- p.id = Number(str.substring(_start2, i + 1));
- }
-
- if (str.charAt(++i)) {
- var payload = this.tryParse(str.substr(i));
- if (Decoder.isPayloadValid(p.type, payload)) {
- p.data = payload;
- } else {
- throw new Error("invalid payload");
- }
- }
- return p;
- }
- }, {
- key: "tryParse",
- value: function tryParse(str) {
- try {
- return JSON.parse(str, this.reviver);
- } catch (e) {
- return false;
- }
- }
- }, {
- key: "destroy",
- value:
-
- function destroy() {
- if (this.reconstructor) {
- this.reconstructor.finishedReconstruction();
- this.reconstructor = null;
- }
- }
- }], [{
- key: "isPayloadValid",
- value: function isPayloadValid(type, payload) {
- switch (type) {
- case PacketType.CONNECT:
- return isObject(payload);
- case PacketType.DISCONNECT:
- return payload === undefined;
- case PacketType.CONNECT_ERROR:
- return typeof payload === "string" || isObject(payload);
- case PacketType.EVENT:
- case PacketType.BINARY_EVENT:
- return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
- case PacketType.ACK:
- case PacketType.BINARY_ACK:
- return Array.isArray(payload);
- }
- }
- }]);
- return Decoder;
- }(Emitter);
-
- var BinaryReconstructor = function () {
- function BinaryReconstructor(packet) {
- _classCallCheck(this, BinaryReconstructor);
- this.packet = packet;
- this.buffers = [];
- this.reconPack = packet;
- }
-
- _createClass(BinaryReconstructor, [{
- key: "takeBinaryData",
- value: function takeBinaryData(binData) {
- this.buffers.push(binData);
- if (this.buffers.length === this.reconPack.attachments) {
-
- var packet = reconstructPacket(this.reconPack, this.buffers);
- this.finishedReconstruction();
- return packet;
- }
- return null;
- }
-
- }, {
- key: "finishedReconstruction",
- value: function finishedReconstruction() {
- this.reconPack = null;
- this.buffers = [];
- }
- }]);
- return BinaryReconstructor;
- }();
- var parser = Object.freeze({
- __proto__: null,
- protocol: protocol,
- get PacketType () { return PacketType; },
- Encoder: Encoder,
- Decoder: Decoder
- });
- function on(obj, ev, fn) {
- obj.on(ev, fn);
- return function subDestroy() {
- obj.off(ev, fn);
- };
- }
-
- var RESERVED_EVENTS = Object.freeze({
- connect: 1,
- connect_error: 1,
- disconnect: 1,
- disconnecting: 1,
-
- newListener: 1,
- removeListener: 1
- });
-
- var Socket = function (_Emitter) {
- _inherits(Socket, _Emitter);
- var _super = _createSuper(Socket);
-
- function Socket(io, nsp, opts) {
- var _this;
- _classCallCheck(this, Socket);
- _this = _super.call(this);
-
- _this.connected = false;
-
- _this.recovered = false;
-
- _this.receiveBuffer = [];
-
- _this.sendBuffer = [];
-
- _this._queue = [];
-
- _this._queueSeq = 0;
- _this.ids = 0;
- _this.acks = {};
- _this.flags = {};
- _this.io = io;
- _this.nsp = nsp;
- if (opts && opts.auth) {
- _this.auth = opts.auth;
- }
- _this._opts = _extends({}, opts);
- if (_this.io._autoConnect) _this.open();
- return _this;
- }
-
- _createClass(Socket, [{
- key: "disconnected",
- get: function get() {
- return !this.connected;
- }
-
- }, {
- key: "subEvents",
- value: function subEvents() {
- if (this.subs) return;
- var io = this.io;
- 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))];
- }
-
- }, {
- key: "active",
- get: function get() {
- return !!this.subs;
- }
-
- }, {
- key: "connect",
- value: function connect() {
- if (this.connected) return this;
- this.subEvents();
- if (!this.io["_reconnecting"]) this.io.open();
- if ("open" === this.io._readyState) this.onopen();
- return this;
- }
-
- }, {
- key: "open",
- value: function open() {
- return this.connect();
- }
-
- }, {
- key: "send",
- value: function send() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- args.unshift("message");
- this.emit.apply(this, args);
- return this;
- }
-
- }, {
- key: "emit",
- value: function emit(ev) {
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
- throw new Error('"' + ev.toString() + '" is a reserved event name');
- }
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- args[_key2 - 1] = arguments[_key2];
- }
- args.unshift(ev);
- if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
- this._addToQueue(args);
- return this;
- }
- var packet = {
- type: PacketType.EVENT,
- data: args
- };
- packet.options = {};
- packet.options.compress = this.flags.compress !== false;
-
- if ("function" === typeof args[args.length - 1]) {
- var id = this.ids++;
- var ack = args.pop();
- this._registerAckCallback(id, ack);
- packet.id = id;
- }
- var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable;
- var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected);
- if (discardPacket) ; else if (this.connected) {
- this.notifyOutgoingListeners(packet);
- this.packet(packet);
- } else {
- this.sendBuffer.push(packet);
- }
- this.flags = {};
- return this;
- }
-
- }, {
- key: "_registerAckCallback",
- value: function _registerAckCallback(id, ack) {
- var _this2 = this;
- var _a;
- var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
- if (timeout === undefined) {
- this.acks[id] = ack;
- return;
- }
-
- var timer = this.io.setTimeoutFn(function () {
- delete _this2.acks[id];
- for (var i = 0; i < _this2.sendBuffer.length; i++) {
- if (_this2.sendBuffer[i].id === id) {
- _this2.sendBuffer.splice(i, 1);
- }
- }
- ack.call(_this2, new Error("operation has timed out"));
- }, timeout);
- this.acks[id] = function () {
-
- _this2.io.clearTimeoutFn(timer);
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- args[_key3] = arguments[_key3];
- }
- ack.apply(_this2, [null].concat(args));
- };
- }
-
- }, {
- key: "emitWithAck",
- value: function emitWithAck(ev) {
- var _this3 = this;
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
- args[_key4 - 1] = arguments[_key4];
- }
-
- var withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined;
- return new Promise(function (resolve, reject) {
- args.push(function (arg1, arg2) {
- if (withErr) {
- return arg1 ? reject(arg1) : resolve(arg2);
- } else {
- return resolve(arg1);
- }
- });
- _this3.emit.apply(_this3, [ev].concat(args));
- });
- }
-
- }, {
- key: "_addToQueue",
- value: function _addToQueue(args) {
- var _this4 = this;
- var ack;
- if (typeof args[args.length - 1] === "function") {
- ack = args.pop();
- }
- var packet = {
- id: this._queueSeq++,
- tryCount: 0,
- pending: false,
- args: args,
- flags: _extends({
- fromQueue: true
- }, this.flags)
- };
- args.push(function (err) {
- if (packet !== _this4._queue[0]) {
-
- return;
- }
- var hasError = err !== null;
- if (hasError) {
- if (packet.tryCount > _this4._opts.retries) {
- _this4._queue.shift();
- if (ack) {
- ack(err);
- }
- }
- } else {
- _this4._queue.shift();
- if (ack) {
- for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
- responseArgs[_key5 - 1] = arguments[_key5];
- }
- ack.apply(void 0, [null].concat(responseArgs));
- }
- }
- packet.pending = false;
- return _this4._drainQueue();
- });
- this._queue.push(packet);
- this._drainQueue();
- }
-
- }, {
- key: "_drainQueue",
- value: function _drainQueue() {
- var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
- if (!this.connected || this._queue.length === 0) {
- return;
- }
- var packet = this._queue[0];
- if (packet.pending && !force) {
- return;
- }
- packet.pending = true;
- packet.tryCount++;
- this.flags = packet.flags;
- this.emit.apply(this, packet.args);
- }
-
- }, {
- key: "packet",
- value: function packet(_packet) {
- _packet.nsp = this.nsp;
- this.io._packet(_packet);
- }
-
- }, {
- key: "onopen",
- value: function onopen() {
- var _this5 = this;
- if (typeof this.auth == "function") {
- this.auth(function (data) {
- _this5._sendConnectPacket(data);
- });
- } else {
- this._sendConnectPacket(this.auth);
- }
- }
-
- }, {
- key: "_sendConnectPacket",
- value: function _sendConnectPacket(data) {
- this.packet({
- type: PacketType.CONNECT,
- data: this._pid ? _extends({
- pid: this._pid,
- offset: this._lastOffset
- }, data) : data
- });
- }
-
- }, {
- key: "onerror",
- value: function onerror(err) {
- if (!this.connected) {
- this.emitReserved("connect_error", err);
- }
- }
-
- }, {
- key: "onclose",
- value: function onclose(reason, description) {
- this.connected = false;
- delete this.id;
- this.emitReserved("disconnect", reason, description);
- }
-
- }, {
- key: "onpacket",
- value: function onpacket(packet) {
- var sameNamespace = packet.nsp === this.nsp;
- if (!sameNamespace) return;
- switch (packet.type) {
- case PacketType.CONNECT:
- if (packet.data && packet.data.sid) {
- this.onconnect(packet.data.sid, packet.data.pid);
- } else {
- 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/)"));
- }
- break;
- case PacketType.EVENT:
- case PacketType.BINARY_EVENT:
- this.onevent(packet);
- break;
- case PacketType.ACK:
- case PacketType.BINARY_ACK:
- this.onack(packet);
- break;
- case PacketType.DISCONNECT:
- this.ondisconnect();
- break;
- case PacketType.CONNECT_ERROR:
- this.destroy();
- var err = new Error(packet.data.message);
-
- err.data = packet.data.data;
- this.emitReserved("connect_error", err);
- break;
- }
- }
-
- }, {
- key: "onevent",
- value: function onevent(packet) {
- var args = packet.data || [];
- if (null != packet.id) {
- args.push(this.ack(packet.id));
- }
- if (this.connected) {
- this.emitEvent(args);
- } else {
- this.receiveBuffer.push(Object.freeze(args));
- }
- }
- }, {
- key: "emitEvent",
- value: function emitEvent(args) {
- if (this._anyListeners && this._anyListeners.length) {
- var listeners = this._anyListeners.slice();
- var _iterator = _createForOfIteratorHelper(listeners),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var listener = _step.value;
- listener.apply(this, args);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- }
- _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args);
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
- this._lastOffset = args[args.length - 1];
- }
- }
-
- }, {
- key: "ack",
- value: function ack(id) {
- var self = this;
- var sent = false;
- return function () {
-
- if (sent) return;
- sent = true;
- for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
- args[_key6] = arguments[_key6];
- }
- self.packet({
- type: PacketType.ACK,
- id: id,
- data: args
- });
- };
- }
-
- }, {
- key: "onack",
- value: function onack(packet) {
- var ack = this.acks[packet.id];
- if ("function" === typeof ack) {
- ack.apply(this, packet.data);
- delete this.acks[packet.id];
- }
- }
-
- }, {
- key: "onconnect",
- value: function onconnect(id, pid) {
- this.id = id;
- this.recovered = pid && this._pid === pid;
- this._pid = pid;
- this.connected = true;
- this.emitBuffered();
- this.emitReserved("connect");
- this._drainQueue(true);
- }
-
- }, {
- key: "emitBuffered",
- value: function emitBuffered() {
- var _this6 = this;
- this.receiveBuffer.forEach(function (args) {
- return _this6.emitEvent(args);
- });
- this.receiveBuffer = [];
- this.sendBuffer.forEach(function (packet) {
- _this6.notifyOutgoingListeners(packet);
- _this6.packet(packet);
- });
- this.sendBuffer = [];
- }
-
- }, {
- key: "ondisconnect",
- value: function ondisconnect() {
- this.destroy();
- this.onclose("io server disconnect");
- }
-
- }, {
- key: "destroy",
- value: function destroy() {
- if (this.subs) {
-
- this.subs.forEach(function (subDestroy) {
- return subDestroy();
- });
- this.subs = undefined;
- }
- this.io["_destroy"](this);
- }
-
- }, {
- key: "disconnect",
- value: function disconnect() {
- if (this.connected) {
- this.packet({
- type: PacketType.DISCONNECT
- });
- }
-
- this.destroy();
- if (this.connected) {
-
- this.onclose("io client disconnect");
- }
- return this;
- }
-
- }, {
- key: "close",
- value: function close() {
- return this.disconnect();
- }
-
- }, {
- key: "compress",
- value: function compress(_compress) {
- this.flags.compress = _compress;
- return this;
- }
-
- }, {
- key: "volatile",
- get: function get() {
- this.flags["volatile"] = true;
- return this;
- }
-
- }, {
- key: "timeout",
- value: function timeout(_timeout) {
- this.flags.timeout = _timeout;
- return this;
- }
-
- }, {
- key: "onAny",
- value: function onAny(listener) {
- this._anyListeners = this._anyListeners || [];
- this._anyListeners.push(listener);
- return this;
- }
-
- }, {
- key: "prependAny",
- value: function prependAny(listener) {
- this._anyListeners = this._anyListeners || [];
- this._anyListeners.unshift(listener);
- return this;
- }
-
- }, {
- key: "offAny",
- value: function offAny(listener) {
- if (!this._anyListeners) {
- return this;
- }
- if (listener) {
- var listeners = this._anyListeners;
- for (var i = 0; i < listeners.length; i++) {
- if (listener === listeners[i]) {
- listeners.splice(i, 1);
- return this;
- }
- }
- } else {
- this._anyListeners = [];
- }
- return this;
- }
-
- }, {
- key: "listenersAny",
- value: function listenersAny() {
- return this._anyListeners || [];
- }
-
- }, {
- key: "onAnyOutgoing",
- value: function onAnyOutgoing(listener) {
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
- this._anyOutgoingListeners.push(listener);
- return this;
- }
-
- }, {
- key: "prependAnyOutgoing",
- value: function prependAnyOutgoing(listener) {
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
- this._anyOutgoingListeners.unshift(listener);
- return this;
- }
-
- }, {
- key: "offAnyOutgoing",
- value: function offAnyOutgoing(listener) {
- if (!this._anyOutgoingListeners) {
- return this;
- }
- if (listener) {
- var listeners = this._anyOutgoingListeners;
- for (var i = 0; i < listeners.length; i++) {
- if (listener === listeners[i]) {
- listeners.splice(i, 1);
- return this;
- }
- }
- } else {
- this._anyOutgoingListeners = [];
- }
- return this;
- }
-
- }, {
- key: "listenersAnyOutgoing",
- value: function listenersAnyOutgoing() {
- return this._anyOutgoingListeners || [];
- }
-
- }, {
- key: "notifyOutgoingListeners",
- value: function notifyOutgoingListeners(packet) {
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
- var listeners = this._anyOutgoingListeners.slice();
- var _iterator2 = _createForOfIteratorHelper(listeners),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var listener = _step2.value;
- listener.apply(this, packet.data);
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- }
- }
- }]);
- return Socket;
- }(Emitter);
-
- function Backoff(opts) {
- opts = opts || {};
- this.ms = opts.min || 100;
- this.max = opts.max || 10000;
- this.factor = opts.factor || 2;
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
- this.attempts = 0;
- }
-
- Backoff.prototype.duration = function () {
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
- if (this.jitter) {
- var rand = Math.random();
- var deviation = Math.floor(rand * this.jitter * ms);
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
- }
- return Math.min(ms, this.max) | 0;
- };
-
- Backoff.prototype.reset = function () {
- this.attempts = 0;
- };
-
- Backoff.prototype.setMin = function (min) {
- this.ms = min;
- };
-
- Backoff.prototype.setMax = function (max) {
- this.max = max;
- };
-
- Backoff.prototype.setJitter = function (jitter) {
- this.jitter = jitter;
- };
- var Manager = function (_Emitter) {
- _inherits(Manager, _Emitter);
- var _super = _createSuper(Manager);
- function Manager(uri, opts) {
- var _this;
- _classCallCheck(this, Manager);
- var _a;
- _this = _super.call(this);
- _this.nsps = {};
- _this.subs = [];
- if (uri && "object" === _typeof(uri)) {
- opts = uri;
- uri = undefined;
- }
- opts = opts || {};
- opts.path = opts.path || "/socket.io";
- _this.opts = opts;
- installTimerFunctions(_assertThisInitialized(_this), opts);
- _this.reconnection(opts.reconnection !== false);
- _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
- _this.reconnectionDelay(opts.reconnectionDelay || 1000);
- _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
- _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
- _this.backoff = new Backoff({
- min: _this.reconnectionDelay(),
- max: _this.reconnectionDelayMax(),
- jitter: _this.randomizationFactor()
- });
- _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
- _this._readyState = "closed";
- _this.uri = uri;
- var _parser = opts.parser || parser;
- _this.encoder = new _parser.Encoder();
- _this.decoder = new _parser.Decoder();
- _this._autoConnect = opts.autoConnect !== false;
- if (_this._autoConnect) _this.open();
- return _this;
- }
- _createClass(Manager, [{
- key: "reconnection",
- value: function reconnection(v) {
- if (!arguments.length) return this._reconnection;
- this._reconnection = !!v;
- return this;
- }
- }, {
- key: "reconnectionAttempts",
- value: function reconnectionAttempts(v) {
- if (v === undefined) return this._reconnectionAttempts;
- this._reconnectionAttempts = v;
- return this;
- }
- }, {
- key: "reconnectionDelay",
- value: function reconnectionDelay(v) {
- var _a;
- if (v === undefined) return this._reconnectionDelay;
- this._reconnectionDelay = v;
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
- return this;
- }
- }, {
- key: "randomizationFactor",
- value: function randomizationFactor(v) {
- var _a;
- if (v === undefined) return this._randomizationFactor;
- this._randomizationFactor = v;
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
- return this;
- }
- }, {
- key: "reconnectionDelayMax",
- value: function reconnectionDelayMax(v) {
- var _a;
- if (v === undefined) return this._reconnectionDelayMax;
- this._reconnectionDelayMax = v;
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
- return this;
- }
- }, {
- key: "timeout",
- value: function timeout(v) {
- if (!arguments.length) return this._timeout;
- this._timeout = v;
- return this;
- }
-
- }, {
- key: "maybeReconnectOnOpen",
- value: function maybeReconnectOnOpen() {
-
- if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
-
- this.reconnect();
- }
- }
-
- }, {
- key: "open",
- value: function open(fn) {
- var _this2 = this;
- if (~this._readyState.indexOf("open")) return this;
- this.engine = new Socket$1(this.uri, this.opts);
- var socket = this.engine;
- var self = this;
- this._readyState = "opening";
- this.skipReconnect = false;
-
- var openSubDestroy = on(socket, "open", function () {
- self.onopen();
- fn && fn();
- });
- var onError = function onError(err) {
- _this2.cleanup();
- _this2._readyState = "closed";
- _this2.emitReserved("error", err);
- if (fn) {
- fn(err);
- } else {
-
- _this2.maybeReconnectOnOpen();
- }
- };
-
- var errorSub = on(socket, "error", onError);
- if (false !== this._timeout) {
- var timeout = this._timeout;
-
- var timer = this.setTimeoutFn(function () {
- openSubDestroy();
- onError(new Error("timeout"));
- socket.close();
- }, timeout);
- if (this.opts.autoUnref) {
- timer.unref();
- }
- this.subs.push(function () {
- _this2.clearTimeoutFn(timer);
- });
- }
- this.subs.push(openSubDestroy);
- this.subs.push(errorSub);
- return this;
- }
-
- }, {
- key: "connect",
- value: function connect(fn) {
- return this.open(fn);
- }
-
- }, {
- key: "onopen",
- value: function onopen() {
-
- this.cleanup();
-
- this._readyState = "open";
- this.emitReserved("open");
-
- var socket = this.engine;
- 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)));
- }
-
- }, {
- key: "onping",
- value: function onping() {
- this.emitReserved("ping");
- }
-
- }, {
- key: "ondata",
- value: function ondata(data) {
- try {
- this.decoder.add(data);
- } catch (e) {
- this.onclose("parse error", e);
- }
- }
-
- }, {
- key: "ondecoded",
- value: function ondecoded(packet) {
- var _this3 = this;
-
- nextTick(function () {
- _this3.emitReserved("packet", packet);
- }, this.setTimeoutFn);
- }
-
- }, {
- key: "onerror",
- value: function onerror(err) {
- this.emitReserved("error", err);
- }
-
- }, {
- key: "socket",
- value: function socket(nsp, opts) {
- var socket = this.nsps[nsp];
- if (!socket) {
- socket = new Socket(this, nsp, opts);
- this.nsps[nsp] = socket;
- } else if (this._autoConnect && !socket.active) {
- socket.connect();
- }
- return socket;
- }
-
- }, {
- key: "_destroy",
- value: function _destroy(socket) {
- var nsps = Object.keys(this.nsps);
- for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
- var nsp = _nsps[_i];
- var _socket = this.nsps[nsp];
- if (_socket.active) {
- return;
- }
- }
- this._close();
- }
-
- }, {
- key: "_packet",
- value: function _packet(packet) {
- var encodedPackets = this.encoder.encode(packet);
- for (var i = 0; i < encodedPackets.length; i++) {
- this.engine.write(encodedPackets[i], packet.options);
- }
- }
-
- }, {
- key: "cleanup",
- value: function cleanup() {
- this.subs.forEach(function (subDestroy) {
- return subDestroy();
- });
- this.subs.length = 0;
- this.decoder.destroy();
- }
-
- }, {
- key: "_close",
- value: function _close() {
- this.skipReconnect = true;
- this._reconnecting = false;
- this.onclose("forced close");
- if (this.engine) this.engine.close();
- }
-
- }, {
- key: "disconnect",
- value: function disconnect() {
- return this._close();
- }
-
- }, {
- key: "onclose",
- value: function onclose(reason, description) {
- this.cleanup();
- this.backoff.reset();
- this._readyState = "closed";
- this.emitReserved("close", reason, description);
- if (this._reconnection && !this.skipReconnect) {
- this.reconnect();
- }
- }
-
- }, {
- key: "reconnect",
- value: function reconnect() {
- var _this4 = this;
- if (this._reconnecting || this.skipReconnect) return this;
- var self = this;
- if (this.backoff.attempts >= this._reconnectionAttempts) {
- this.backoff.reset();
- this.emitReserved("reconnect_failed");
- this._reconnecting = false;
- } else {
- var delay = this.backoff.duration();
- this._reconnecting = true;
- var timer = this.setTimeoutFn(function () {
- if (self.skipReconnect) return;
- _this4.emitReserved("reconnect_attempt", self.backoff.attempts);
-
- if (self.skipReconnect) return;
- self.open(function (err) {
- if (err) {
- self._reconnecting = false;
- self.reconnect();
- _this4.emitReserved("reconnect_error", err);
- } else {
- self.onreconnect();
- }
- });
- }, delay);
- if (this.opts.autoUnref) {
- timer.unref();
- }
- this.subs.push(function () {
- _this4.clearTimeoutFn(timer);
- });
- }
- }
-
- }, {
- key: "onreconnect",
- value: function onreconnect() {
- var attempt = this.backoff.attempts;
- this._reconnecting = false;
- this.backoff.reset();
- this.emitReserved("reconnect", attempt);
- }
- }]);
- return Manager;
- }(Emitter);
-
- var cache = {};
- function lookup(uri, opts) {
- if (_typeof(uri) === "object") {
- opts = uri;
- uri = undefined;
- }
- opts = opts || {};
- var parsed = url(uri, opts.path || "/socket.io");
- var source = parsed.source;
- var id = parsed.id;
- var path = parsed.path;
- var sameNamespace = cache[id] && path in cache[id]["nsps"];
- var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
- var io;
- if (newConnection) {
- io = new Manager(source, opts);
- } else {
- if (!cache[id]) {
- cache[id] = new Manager(source, opts);
- }
- io = cache[id];
- }
- if (parsed.query && !opts.query) {
- opts.query = parsed.queryKey;
- }
- return io.socket(parsed.path, opts);
- }
-
-
- _extends(lookup, {
- Manager: Manager,
- Socket: Socket,
- io: lookup,
- connect: lookup
- });
- return lookup;
- }));
|