socket.io.slim.dev.js 130 KB

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