socket.io.js 180 KB

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