socket.io.js 181 KB

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