socket.io.js 225 KB

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