Socket.io.js 210 KB

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