socket.io.dev.js 151 KB

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