sockjs.js 183 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944
  1. /* sockjs-client v1.5.1 | http://sockjs.org | MIT license */
  2. (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.SockJS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  3. (function (global){
  4. 'use strict';
  5. var transportList = require('./transport-list');
  6. module.exports = require('./main')(transportList);
  7. // TODO can't get rid of this until all servers do
  8. if ('_sockjs_onload' in global) {
  9. setTimeout(global._sockjs_onload, 1);
  10. }
  11. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12. },{"./main":14,"./transport-list":16}],2:[function(require,module,exports){
  13. 'use strict';
  14. var inherits = require('inherits')
  15. , Event = require('./event')
  16. ;
  17. function CloseEvent() {
  18. Event.call(this);
  19. this.initEvent('close', false, false);
  20. this.wasClean = false;
  21. this.code = 0;
  22. this.reason = '';
  23. }
  24. inherits(CloseEvent, Event);
  25. module.exports = CloseEvent;
  26. },{"./event":4,"inherits":57}],3:[function(require,module,exports){
  27. 'use strict';
  28. var inherits = require('inherits')
  29. , EventTarget = require('./eventtarget')
  30. ;
  31. function EventEmitter() {
  32. EventTarget.call(this);
  33. }
  34. inherits(EventEmitter, EventTarget);
  35. EventEmitter.prototype.removeAllListeners = function(type) {
  36. if (type) {
  37. delete this._listeners[type];
  38. } else {
  39. this._listeners = {};
  40. }
  41. };
  42. EventEmitter.prototype.once = function(type, listener) {
  43. var self = this
  44. , fired = false;
  45. function g() {
  46. self.removeListener(type, g);
  47. if (!fired) {
  48. fired = true;
  49. listener.apply(this, arguments);
  50. }
  51. }
  52. this.on(type, g);
  53. };
  54. EventEmitter.prototype.emit = function() {
  55. var type = arguments[0];
  56. var listeners = this._listeners[type];
  57. if (!listeners) {
  58. return;
  59. }
  60. // equivalent of Array.prototype.slice.call(arguments, 1);
  61. var l = arguments.length;
  62. var args = new Array(l - 1);
  63. for (var ai = 1; ai < l; ai++) {
  64. args[ai - 1] = arguments[ai];
  65. }
  66. for (var i = 0; i < listeners.length; i++) {
  67. listeners[i].apply(this, args);
  68. }
  69. };
  70. EventEmitter.prototype.on = EventEmitter.prototype.addListener = EventTarget.prototype.addEventListener;
  71. EventEmitter.prototype.removeListener = EventTarget.prototype.removeEventListener;
  72. module.exports.EventEmitter = EventEmitter;
  73. },{"./eventtarget":5,"inherits":57}],4:[function(require,module,exports){
  74. 'use strict';
  75. function Event(eventType) {
  76. this.type = eventType;
  77. }
  78. Event.prototype.initEvent = function(eventType, canBubble, cancelable) {
  79. this.type = eventType;
  80. this.bubbles = canBubble;
  81. this.cancelable = cancelable;
  82. this.timeStamp = +new Date();
  83. return this;
  84. };
  85. Event.prototype.stopPropagation = function() {};
  86. Event.prototype.preventDefault = function() {};
  87. Event.CAPTURING_PHASE = 1;
  88. Event.AT_TARGET = 2;
  89. Event.BUBBLING_PHASE = 3;
  90. module.exports = Event;
  91. },{}],5:[function(require,module,exports){
  92. 'use strict';
  93. /* Simplified implementation of DOM2 EventTarget.
  94. * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
  95. */
  96. function EventTarget() {
  97. this._listeners = {};
  98. }
  99. EventTarget.prototype.addEventListener = function(eventType, listener) {
  100. if (!(eventType in this._listeners)) {
  101. this._listeners[eventType] = [];
  102. }
  103. var arr = this._listeners[eventType];
  104. // #4
  105. if (arr.indexOf(listener) === -1) {
  106. // Make a copy so as not to interfere with a current dispatchEvent.
  107. arr = arr.concat([listener]);
  108. }
  109. this._listeners[eventType] = arr;
  110. };
  111. EventTarget.prototype.removeEventListener = function(eventType, listener) {
  112. var arr = this._listeners[eventType];
  113. if (!arr) {
  114. return;
  115. }
  116. var idx = arr.indexOf(listener);
  117. if (idx !== -1) {
  118. if (arr.length > 1) {
  119. // Make a copy so as not to interfere with a current dispatchEvent.
  120. this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));
  121. } else {
  122. delete this._listeners[eventType];
  123. }
  124. return;
  125. }
  126. };
  127. EventTarget.prototype.dispatchEvent = function() {
  128. var event = arguments[0];
  129. var t = event.type;
  130. // equivalent of Array.prototype.slice.call(arguments, 0);
  131. var args = arguments.length === 1 ? [event] : Array.apply(null, arguments);
  132. // TODO: This doesn't match the real behavior; per spec, onfoo get
  133. // their place in line from the /first/ time they're set from
  134. // non-null. Although WebKit bumps it to the end every time it's
  135. // set.
  136. if (this['on' + t]) {
  137. this['on' + t].apply(this, args);
  138. }
  139. if (t in this._listeners) {
  140. // Grab a reference to the listeners list. removeEventListener may alter the list.
  141. var listeners = this._listeners[t];
  142. for (var i = 0; i < listeners.length; i++) {
  143. listeners[i].apply(this, args);
  144. }
  145. }
  146. };
  147. module.exports = EventTarget;
  148. },{}],6:[function(require,module,exports){
  149. 'use strict';
  150. var inherits = require('inherits')
  151. , Event = require('./event')
  152. ;
  153. function TransportMessageEvent(data) {
  154. Event.call(this);
  155. this.initEvent('message', false, false);
  156. this.data = data;
  157. }
  158. inherits(TransportMessageEvent, Event);
  159. module.exports = TransportMessageEvent;
  160. },{"./event":4,"inherits":57}],7:[function(require,module,exports){
  161. 'use strict';
  162. var JSON3 = require('json3')
  163. , iframeUtils = require('./utils/iframe')
  164. ;
  165. function FacadeJS(transport) {
  166. this._transport = transport;
  167. transport.on('message', this._transportMessage.bind(this));
  168. transport.on('close', this._transportClose.bind(this));
  169. }
  170. FacadeJS.prototype._transportClose = function(code, reason) {
  171. iframeUtils.postMessage('c', JSON3.stringify([code, reason]));
  172. };
  173. FacadeJS.prototype._transportMessage = function(frame) {
  174. iframeUtils.postMessage('t', frame);
  175. };
  176. FacadeJS.prototype._send = function(data) {
  177. this._transport.send(data);
  178. };
  179. FacadeJS.prototype._close = function() {
  180. this._transport.close();
  181. this._transport.removeAllListeners();
  182. };
  183. module.exports = FacadeJS;
  184. },{"./utils/iframe":47,"json3":58}],8:[function(require,module,exports){
  185. (function (process){
  186. 'use strict';
  187. var urlUtils = require('./utils/url')
  188. , eventUtils = require('./utils/event')
  189. , JSON3 = require('json3')
  190. , FacadeJS = require('./facade')
  191. , InfoIframeReceiver = require('./info-iframe-receiver')
  192. , iframeUtils = require('./utils/iframe')
  193. , loc = require('./location')
  194. ;
  195. var debug = function() {};
  196. if (process.env.NODE_ENV !== 'production') {
  197. debug = require('debug')('sockjs-client:iframe-bootstrap');
  198. }
  199. module.exports = function(SockJS, availableTransports) {
  200. var transportMap = {};
  201. availableTransports.forEach(function(at) {
  202. if (at.facadeTransport) {
  203. transportMap[at.facadeTransport.transportName] = at.facadeTransport;
  204. }
  205. });
  206. // hard-coded for the info iframe
  207. // TODO see if we can make this more dynamic
  208. transportMap[InfoIframeReceiver.transportName] = InfoIframeReceiver;
  209. var parentOrigin;
  210. /* eslint-disable camelcase */
  211. SockJS.bootstrap_iframe = function() {
  212. /* eslint-enable camelcase */
  213. var facade;
  214. iframeUtils.currentWindowId = loc.hash.slice(1);
  215. var onMessage = function(e) {
  216. if (e.source !== parent) {
  217. return;
  218. }
  219. if (typeof parentOrigin === 'undefined') {
  220. parentOrigin = e.origin;
  221. }
  222. if (e.origin !== parentOrigin) {
  223. return;
  224. }
  225. var iframeMessage;
  226. try {
  227. iframeMessage = JSON3.parse(e.data);
  228. } catch (ignored) {
  229. debug('bad json', e.data);
  230. return;
  231. }
  232. if (iframeMessage.windowId !== iframeUtils.currentWindowId) {
  233. return;
  234. }
  235. switch (iframeMessage.type) {
  236. case 's':
  237. var p;
  238. try {
  239. p = JSON3.parse(iframeMessage.data);
  240. } catch (ignored) {
  241. debug('bad json', iframeMessage.data);
  242. break;
  243. }
  244. var version = p[0];
  245. var transport = p[1];
  246. var transUrl = p[2];
  247. var baseUrl = p[3];
  248. debug(version, transport, transUrl, baseUrl);
  249. // change this to semver logic
  250. if (version !== SockJS.version) {
  251. throw new Error('Incompatible SockJS! Main site uses:' +
  252. ' "' + version + '", the iframe:' +
  253. ' "' + SockJS.version + '".');
  254. }
  255. if (!urlUtils.isOriginEqual(transUrl, loc.href) ||
  256. !urlUtils.isOriginEqual(baseUrl, loc.href)) {
  257. throw new Error('Can\'t connect to different domain from within an ' +
  258. 'iframe. (' + loc.href + ', ' + transUrl + ', ' + baseUrl + ')');
  259. }
  260. facade = new FacadeJS(new transportMap[transport](transUrl, baseUrl));
  261. break;
  262. case 'm':
  263. facade._send(iframeMessage.data);
  264. break;
  265. case 'c':
  266. if (facade) {
  267. facade._close();
  268. }
  269. facade = null;
  270. break;
  271. }
  272. };
  273. eventUtils.attachEvent('message', onMessage);
  274. // Start
  275. iframeUtils.postMessage('s');
  276. };
  277. };
  278. }).call(this,{ env: {} })
  279. },{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,"debug":55,"json3":58}],9:[function(require,module,exports){
  280. (function (process){
  281. 'use strict';
  282. var EventEmitter = require('events').EventEmitter
  283. , inherits = require('inherits')
  284. , JSON3 = require('json3')
  285. , objectUtils = require('./utils/object')
  286. ;
  287. var debug = function() {};
  288. if (process.env.NODE_ENV !== 'production') {
  289. debug = require('debug')('sockjs-client:info-ajax');
  290. }
  291. function InfoAjax(url, AjaxObject) {
  292. EventEmitter.call(this);
  293. var self = this;
  294. var t0 = +new Date();
  295. this.xo = new AjaxObject('GET', url);
  296. this.xo.once('finish', function(status, text) {
  297. var info, rtt;
  298. if (status === 200) {
  299. rtt = (+new Date()) - t0;
  300. if (text) {
  301. try {
  302. info = JSON3.parse(text);
  303. } catch (e) {
  304. debug('bad json', text);
  305. }
  306. }
  307. if (!objectUtils.isObject(info)) {
  308. info = {};
  309. }
  310. }
  311. self.emit('finish', info, rtt);
  312. self.removeAllListeners();
  313. });
  314. }
  315. inherits(InfoAjax, EventEmitter);
  316. InfoAjax.prototype.close = function() {
  317. this.removeAllListeners();
  318. this.xo.close();
  319. };
  320. module.exports = InfoAjax;
  321. }).call(this,{ env: {} })
  322. },{"./utils/object":49,"debug":55,"events":3,"inherits":57,"json3":58}],10:[function(require,module,exports){
  323. 'use strict';
  324. var inherits = require('inherits')
  325. , EventEmitter = require('events').EventEmitter
  326. , JSON3 = require('json3')
  327. , XHRLocalObject = require('./transport/sender/xhr-local')
  328. , InfoAjax = require('./info-ajax')
  329. ;
  330. function InfoReceiverIframe(transUrl) {
  331. var self = this;
  332. EventEmitter.call(this);
  333. this.ir = new InfoAjax(transUrl, XHRLocalObject);
  334. this.ir.once('finish', function(info, rtt) {
  335. self.ir = null;
  336. self.emit('message', JSON3.stringify([info, rtt]));
  337. });
  338. }
  339. inherits(InfoReceiverIframe, EventEmitter);
  340. InfoReceiverIframe.transportName = 'iframe-info-receiver';
  341. InfoReceiverIframe.prototype.close = function() {
  342. if (this.ir) {
  343. this.ir.close();
  344. this.ir = null;
  345. }
  346. this.removeAllListeners();
  347. };
  348. module.exports = InfoReceiverIframe;
  349. },{"./info-ajax":9,"./transport/sender/xhr-local":37,"events":3,"inherits":57,"json3":58}],11:[function(require,module,exports){
  350. (function (process,global){
  351. 'use strict';
  352. var EventEmitter = require('events').EventEmitter
  353. , inherits = require('inherits')
  354. , JSON3 = require('json3')
  355. , utils = require('./utils/event')
  356. , IframeTransport = require('./transport/iframe')
  357. , InfoReceiverIframe = require('./info-iframe-receiver')
  358. ;
  359. var debug = function() {};
  360. if (process.env.NODE_ENV !== 'production') {
  361. debug = require('debug')('sockjs-client:info-iframe');
  362. }
  363. function InfoIframe(baseUrl, url) {
  364. var self = this;
  365. EventEmitter.call(this);
  366. var go = function() {
  367. var ifr = self.ifr = new IframeTransport(InfoReceiverIframe.transportName, url, baseUrl);
  368. ifr.once('message', function(msg) {
  369. if (msg) {
  370. var d;
  371. try {
  372. d = JSON3.parse(msg);
  373. } catch (e) {
  374. debug('bad json', msg);
  375. self.emit('finish');
  376. self.close();
  377. return;
  378. }
  379. var info = d[0], rtt = d[1];
  380. self.emit('finish', info, rtt);
  381. }
  382. self.close();
  383. });
  384. ifr.once('close', function() {
  385. self.emit('finish');
  386. self.close();
  387. });
  388. };
  389. // TODO this seems the same as the 'needBody' from transports
  390. if (!global.document.body) {
  391. utils.attachEvent('load', go);
  392. } else {
  393. go();
  394. }
  395. }
  396. inherits(InfoIframe, EventEmitter);
  397. InfoIframe.enabled = function() {
  398. return IframeTransport.enabled();
  399. };
  400. InfoIframe.prototype.close = function() {
  401. if (this.ifr) {
  402. this.ifr.close();
  403. }
  404. this.removeAllListeners();
  405. this.ifr = null;
  406. };
  407. module.exports = InfoIframe;
  408. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  409. },{"./info-iframe-receiver":10,"./transport/iframe":22,"./utils/event":46,"debug":55,"events":3,"inherits":57,"json3":58}],12:[function(require,module,exports){
  410. (function (process){
  411. 'use strict';
  412. var EventEmitter = require('events').EventEmitter
  413. , inherits = require('inherits')
  414. , urlUtils = require('./utils/url')
  415. , XDR = require('./transport/sender/xdr')
  416. , XHRCors = require('./transport/sender/xhr-cors')
  417. , XHRLocal = require('./transport/sender/xhr-local')
  418. , XHRFake = require('./transport/sender/xhr-fake')
  419. , InfoIframe = require('./info-iframe')
  420. , InfoAjax = require('./info-ajax')
  421. ;
  422. var debug = function() {};
  423. if (process.env.NODE_ENV !== 'production') {
  424. debug = require('debug')('sockjs-client:info-receiver');
  425. }
  426. function InfoReceiver(baseUrl, urlInfo) {
  427. debug(baseUrl);
  428. var self = this;
  429. EventEmitter.call(this);
  430. setTimeout(function() {
  431. self.doXhr(baseUrl, urlInfo);
  432. }, 0);
  433. }
  434. inherits(InfoReceiver, EventEmitter);
  435. // TODO this is currently ignoring the list of available transports and the whitelist
  436. InfoReceiver._getReceiver = function(baseUrl, url, urlInfo) {
  437. // determine method of CORS support (if needed)
  438. if (urlInfo.sameOrigin) {
  439. return new InfoAjax(url, XHRLocal);
  440. }
  441. if (XHRCors.enabled) {
  442. return new InfoAjax(url, XHRCors);
  443. }
  444. if (XDR.enabled && urlInfo.sameScheme) {
  445. return new InfoAjax(url, XDR);
  446. }
  447. if (InfoIframe.enabled()) {
  448. return new InfoIframe(baseUrl, url);
  449. }
  450. return new InfoAjax(url, XHRFake);
  451. };
  452. InfoReceiver.prototype.doXhr = function(baseUrl, urlInfo) {
  453. var self = this
  454. , url = urlUtils.addPath(baseUrl, '/info')
  455. ;
  456. debug('doXhr', url);
  457. this.xo = InfoReceiver._getReceiver(baseUrl, url, urlInfo);
  458. this.timeoutRef = setTimeout(function() {
  459. debug('timeout');
  460. self._cleanup(false);
  461. self.emit('finish');
  462. }, InfoReceiver.timeout);
  463. this.xo.once('finish', function(info, rtt) {
  464. debug('finish', info, rtt);
  465. self._cleanup(true);
  466. self.emit('finish', info, rtt);
  467. });
  468. };
  469. InfoReceiver.prototype._cleanup = function(wasClean) {
  470. debug('_cleanup');
  471. clearTimeout(this.timeoutRef);
  472. this.timeoutRef = null;
  473. if (!wasClean && this.xo) {
  474. this.xo.close();
  475. }
  476. this.xo = null;
  477. };
  478. InfoReceiver.prototype.close = function() {
  479. debug('close');
  480. this.removeAllListeners();
  481. this._cleanup(false);
  482. };
  483. InfoReceiver.timeout = 8000;
  484. module.exports = InfoReceiver;
  485. }).call(this,{ env: {} })
  486. },{"./info-ajax":9,"./info-iframe":11,"./transport/sender/xdr":34,"./transport/sender/xhr-cors":35,"./transport/sender/xhr-fake":36,"./transport/sender/xhr-local":37,"./utils/url":52,"debug":55,"events":3,"inherits":57}],13:[function(require,module,exports){
  487. (function (global){
  488. 'use strict';
  489. module.exports = global.location || {
  490. origin: 'http://localhost:80'
  491. , protocol: 'http:'
  492. , host: 'localhost'
  493. , port: 80
  494. , href: 'http://localhost/'
  495. , hash: ''
  496. };
  497. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  498. },{}],14:[function(require,module,exports){
  499. (function (process,global){
  500. 'use strict';
  501. require('./shims');
  502. var URL = require('url-parse')
  503. , inherits = require('inherits')
  504. , JSON3 = require('json3')
  505. , random = require('./utils/random')
  506. , escape = require('./utils/escape')
  507. , urlUtils = require('./utils/url')
  508. , eventUtils = require('./utils/event')
  509. , transport = require('./utils/transport')
  510. , objectUtils = require('./utils/object')
  511. , browser = require('./utils/browser')
  512. , log = require('./utils/log')
  513. , Event = require('./event/event')
  514. , EventTarget = require('./event/eventtarget')
  515. , loc = require('./location')
  516. , CloseEvent = require('./event/close')
  517. , TransportMessageEvent = require('./event/trans-message')
  518. , InfoReceiver = require('./info-receiver')
  519. ;
  520. var debug = function() {};
  521. if (process.env.NODE_ENV !== 'production') {
  522. debug = require('debug')('sockjs-client:main');
  523. }
  524. var transports;
  525. // follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface
  526. function SockJS(url, protocols, options) {
  527. if (!(this instanceof SockJS)) {
  528. return new SockJS(url, protocols, options);
  529. }
  530. if (arguments.length < 1) {
  531. throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  532. }
  533. EventTarget.call(this);
  534. this.readyState = SockJS.CONNECTING;
  535. this.extensions = '';
  536. this.protocol = '';
  537. // non-standard extension
  538. options = options || {};
  539. if (options.protocols_whitelist) {
  540. log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  541. }
  542. this._transportsWhitelist = options.transports;
  543. this._transportOptions = options.transportOptions || {};
  544. this._timeout = options.timeout || 0;
  545. var sessionId = options.sessionId || 8;
  546. if (typeof sessionId === 'function') {
  547. this._generateSessionId = sessionId;
  548. } else if (typeof sessionId === 'number') {
  549. this._generateSessionId = function() {
  550. return random.string(sessionId);
  551. };
  552. } else {
  553. throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  554. }
  555. this._server = options.server || random.numberString(1000);
  556. // Step 1 of WS spec - parse and validate the url. Issue #8
  557. var parsedUrl = new URL(url);
  558. if (!parsedUrl.host || !parsedUrl.protocol) {
  559. throw new SyntaxError("The URL '" + url + "' is invalid");
  560. } else if (parsedUrl.hash) {
  561. throw new SyntaxError('The URL must not contain a fragment');
  562. } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
  563. throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  564. }
  565. var secure = parsedUrl.protocol === 'https:';
  566. // Step 2 - don't allow secure origin with an insecure protocol
  567. if (loc.protocol === 'https:' && !secure) {
  568. // exception is 127.0.0.0/8 and ::1 urls
  569. if (!urlUtils.isLoopbackAddr(parsedUrl.hostname)) {
  570. throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  571. }
  572. }
  573. // Step 3 - check port access - no need here
  574. // Step 4 - parse protocols argument
  575. if (!protocols) {
  576. protocols = [];
  577. } else if (!Array.isArray(protocols)) {
  578. protocols = [protocols];
  579. }
  580. // Step 5 - check protocols argument
  581. var sortedProtocols = protocols.sort();
  582. sortedProtocols.forEach(function(proto, i) {
  583. if (!proto) {
  584. throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
  585. }
  586. if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
  587. throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
  588. }
  589. });
  590. // Step 6 - convert origin
  591. var o = urlUtils.getOrigin(loc.href);
  592. this._origin = o ? o.toLowerCase() : null;
  593. // remove the trailing slash
  594. parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));
  595. // store the sanitized url
  596. this.url = parsedUrl.href;
  597. debug('using url', this.url);
  598. // Step 7 - start connection in background
  599. // obtain server info
  600. // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  601. this._urlInfo = {
  602. nullOrigin: !browser.hasDomain()
  603. , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  604. , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  605. };
  606. this._ir = new InfoReceiver(this.url, this._urlInfo);
  607. this._ir.once('finish', this._receiveInfo.bind(this));
  608. }
  609. inherits(SockJS, EventTarget);
  610. function userSetCode(code) {
  611. return code === 1000 || (code >= 3000 && code <= 4999);
  612. }
  613. SockJS.prototype.close = function(code, reason) {
  614. // Step 1
  615. if (code && !userSetCode(code)) {
  616. throw new Error('InvalidAccessError: Invalid code');
  617. }
  618. // Step 2.4 states the max is 123 bytes, but we are just checking length
  619. if (reason && reason.length > 123) {
  620. throw new SyntaxError('reason argument has an invalid length');
  621. }
  622. // Step 3.1
  623. if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {
  624. return;
  625. }
  626. // TODO look at docs to determine how to set this
  627. var wasClean = true;
  628. this._close(code || 1000, reason || 'Normal closure', wasClean);
  629. };
  630. SockJS.prototype.send = function(data) {
  631. // #13 - convert anything non-string to string
  632. // TODO this currently turns objects into [object Object]
  633. if (typeof data !== 'string') {
  634. data = '' + data;
  635. }
  636. if (this.readyState === SockJS.CONNECTING) {
  637. throw new Error('InvalidStateError: The connection has not been established yet');
  638. }
  639. if (this.readyState !== SockJS.OPEN) {
  640. return;
  641. }
  642. this._transport.send(escape.quote(data));
  643. };
  644. SockJS.version = require('./version');
  645. SockJS.CONNECTING = 0;
  646. SockJS.OPEN = 1;
  647. SockJS.CLOSING = 2;
  648. SockJS.CLOSED = 3;
  649. SockJS.prototype._receiveInfo = function(info, rtt) {
  650. debug('_receiveInfo', rtt);
  651. this._ir = null;
  652. if (!info) {
  653. this._close(1002, 'Cannot connect to server');
  654. return;
  655. }
  656. // establish a round-trip timeout (RTO) based on the
  657. // round-trip time (RTT)
  658. this._rto = this.countRTO(rtt);
  659. // allow server to override url used for the actual transport
  660. this._transUrl = info.base_url ? info.base_url : this.url;
  661. info = objectUtils.extend(info, this._urlInfo);
  662. debug('info', info);
  663. // determine list of desired and supported transports
  664. var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);
  665. this._transports = enabledTransports.main;
  666. debug(this._transports.length + ' enabled transports');
  667. this._connect();
  668. };
  669. SockJS.prototype._connect = function() {
  670. for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {
  671. debug('attempt', Transport.transportName);
  672. if (Transport.needBody) {
  673. if (!global.document.body ||
  674. (typeof global.document.readyState !== 'undefined' &&
  675. global.document.readyState !== 'complete' &&
  676. global.document.readyState !== 'interactive')) {
  677. debug('waiting for body');
  678. this._transports.unshift(Transport);
  679. eventUtils.attachEvent('load', this._connect.bind(this));
  680. return;
  681. }
  682. }
  683. // calculate timeout based on RTO and round trips. Default to 5s
  684. var timeoutMs = Math.max(this._timeout, (this._rto * Transport.roundTrips) || 5000);
  685. this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
  686. debug('using timeout', timeoutMs);
  687. var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());
  688. var options = this._transportOptions[Transport.transportName];
  689. debug('transport url', transportUrl);
  690. var transportObj = new Transport(transportUrl, this._transUrl, options);
  691. transportObj.on('message', this._transportMessage.bind(this));
  692. transportObj.once('close', this._transportClose.bind(this));
  693. transportObj.transportName = Transport.transportName;
  694. this._transport = transportObj;
  695. return;
  696. }
  697. this._close(2000, 'All transports failed', false);
  698. };
  699. SockJS.prototype._transportTimeout = function() {
  700. debug('_transportTimeout');
  701. if (this.readyState === SockJS.CONNECTING) {
  702. if (this._transport) {
  703. this._transport.close();
  704. }
  705. this._transportClose(2007, 'Transport timed out');
  706. }
  707. };
  708. SockJS.prototype._transportMessage = function(msg) {
  709. debug('_transportMessage', msg);
  710. var self = this
  711. , type = msg.slice(0, 1)
  712. , content = msg.slice(1)
  713. , payload
  714. ;
  715. // first check for messages that don't need a payload
  716. switch (type) {
  717. case 'o':
  718. this._open();
  719. return;
  720. case 'h':
  721. this.dispatchEvent(new Event('heartbeat'));
  722. debug('heartbeat', this.transport);
  723. return;
  724. }
  725. if (content) {
  726. try {
  727. payload = JSON3.parse(content);
  728. } catch (e) {
  729. debug('bad json', content);
  730. }
  731. }
  732. if (typeof payload === 'undefined') {
  733. debug('empty payload', content);
  734. return;
  735. }
  736. switch (type) {
  737. case 'a':
  738. if (Array.isArray(payload)) {
  739. payload.forEach(function(p) {
  740. debug('message', self.transport, p);
  741. self.dispatchEvent(new TransportMessageEvent(p));
  742. });
  743. }
  744. break;
  745. case 'm':
  746. debug('message', this.transport, payload);
  747. this.dispatchEvent(new TransportMessageEvent(payload));
  748. break;
  749. case 'c':
  750. if (Array.isArray(payload) && payload.length === 2) {
  751. this._close(payload[0], payload[1], true);
  752. }
  753. break;
  754. }
  755. };
  756. SockJS.prototype._transportClose = function(code, reason) {
  757. debug('_transportClose', this.transport, code, reason);
  758. if (this._transport) {
  759. this._transport.removeAllListeners();
  760. this._transport = null;
  761. this.transport = null;
  762. }
  763. if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {
  764. this._connect();
  765. return;
  766. }
  767. this._close(code, reason);
  768. };
  769. SockJS.prototype._open = function() {
  770. debug('_open', this._transport && this._transport.transportName, this.readyState);
  771. if (this.readyState === SockJS.CONNECTING) {
  772. if (this._transportTimeoutId) {
  773. clearTimeout(this._transportTimeoutId);
  774. this._transportTimeoutId = null;
  775. }
  776. this.readyState = SockJS.OPEN;
  777. this.transport = this._transport.transportName;
  778. this.dispatchEvent(new Event('open'));
  779. debug('connected', this.transport);
  780. } else {
  781. // The server might have been restarted, and lost track of our
  782. // connection.
  783. this._close(1006, 'Server lost session');
  784. }
  785. };
  786. SockJS.prototype._close = function(code, reason, wasClean) {
  787. debug('_close', this.transport, code, reason, wasClean, this.readyState);
  788. var forceFail = false;
  789. if (this._ir) {
  790. forceFail = true;
  791. this._ir.close();
  792. this._ir = null;
  793. }
  794. if (this._transport) {
  795. this._transport.close();
  796. this._transport = null;
  797. this.transport = null;
  798. }
  799. if (this.readyState === SockJS.CLOSED) {
  800. throw new Error('InvalidStateError: SockJS has already been closed');
  801. }
  802. this.readyState = SockJS.CLOSING;
  803. setTimeout(function() {
  804. this.readyState = SockJS.CLOSED;
  805. if (forceFail) {
  806. this.dispatchEvent(new Event('error'));
  807. }
  808. var e = new CloseEvent('close');
  809. e.wasClean = wasClean || false;
  810. e.code = code || 1000;
  811. e.reason = reason;
  812. this.dispatchEvent(e);
  813. this.onmessage = this.onclose = this.onerror = null;
  814. debug('disconnected');
  815. }.bind(this), 0);
  816. };
  817. // See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
  818. // and RFC 2988.
  819. SockJS.prototype.countRTO = function(rtt) {
  820. // In a local environment, when using IE8/9 and the `jsonp-polling`
  821. // transport the time needed to establish a connection (the time that pass
  822. // from the opening of the transport to the call of `_dispatchOpen`) is
  823. // around 200msec (the lower bound used in the article above) and this
  824. // causes spurious timeouts. For this reason we calculate a value slightly
  825. // larger than that used in the article.
  826. if (rtt > 100) {
  827. return 4 * rtt; // rto > 400msec
  828. }
  829. return 300 + rtt; // 300msec < rto <= 400msec
  830. };
  831. module.exports = function(availableTransports) {
  832. transports = transport(availableTransports);
  833. require('./iframe-bootstrap')(SockJS, availableTransports);
  834. return SockJS;
  835. };
  836. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  837. },{"./event/close":2,"./event/event":4,"./event/eventtarget":5,"./event/trans-message":6,"./iframe-bootstrap":8,"./info-receiver":12,"./location":13,"./shims":15,"./utils/browser":44,"./utils/escape":45,"./utils/event":46,"./utils/log":48,"./utils/object":49,"./utils/random":50,"./utils/transport":51,"./utils/url":52,"./version":53,"debug":55,"inherits":57,"json3":58,"url-parse":61}],15:[function(require,module,exports){
  838. /* eslint-disable */
  839. /* jscs: disable */
  840. 'use strict';
  841. // pulled specific shims from https://github.com/es-shims/es5-shim
  842. var ArrayPrototype = Array.prototype;
  843. var ObjectPrototype = Object.prototype;
  844. var FunctionPrototype = Function.prototype;
  845. var StringPrototype = String.prototype;
  846. var array_slice = ArrayPrototype.slice;
  847. var _toString = ObjectPrototype.toString;
  848. var isFunction = function (val) {
  849. return ObjectPrototype.toString.call(val) === '[object Function]';
  850. };
  851. var isArray = function isArray(obj) {
  852. return _toString.call(obj) === '[object Array]';
  853. };
  854. var isString = function isString(obj) {
  855. return _toString.call(obj) === '[object String]';
  856. };
  857. var supportsDescriptors = Object.defineProperty && (function () {
  858. try {
  859. Object.defineProperty({}, 'x', {});
  860. return true;
  861. } catch (e) { /* this is ES3 */
  862. return false;
  863. }
  864. }());
  865. // Define configurable, writable and non-enumerable props
  866. // if they don't exist.
  867. var defineProperty;
  868. if (supportsDescriptors) {
  869. defineProperty = function (object, name, method, forceAssign) {
  870. if (!forceAssign && (name in object)) { return; }
  871. Object.defineProperty(object, name, {
  872. configurable: true,
  873. enumerable: false,
  874. writable: true,
  875. value: method
  876. });
  877. };
  878. } else {
  879. defineProperty = function (object, name, method, forceAssign) {
  880. if (!forceAssign && (name in object)) { return; }
  881. object[name] = method;
  882. };
  883. }
  884. var defineProperties = function (object, map, forceAssign) {
  885. for (var name in map) {
  886. if (ObjectPrototype.hasOwnProperty.call(map, name)) {
  887. defineProperty(object, name, map[name], forceAssign);
  888. }
  889. }
  890. };
  891. var toObject = function (o) {
  892. if (o == null) { // this matches both null and undefined
  893. throw new TypeError("can't convert " + o + ' to object');
  894. }
  895. return Object(o);
  896. };
  897. //
  898. // Util
  899. // ======
  900. //
  901. // ES5 9.4
  902. // http://es5.github.com/#x9.4
  903. // http://jsperf.com/to-integer
  904. function toInteger(num) {
  905. var n = +num;
  906. if (n !== n) { // isNaN
  907. n = 0;
  908. } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  909. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  910. }
  911. return n;
  912. }
  913. function ToUint32(x) {
  914. return x >>> 0;
  915. }
  916. //
  917. // Function
  918. // ========
  919. //
  920. // ES-5 15.3.4.5
  921. // http://es5.github.com/#x15.3.4.5
  922. function Empty() {}
  923. defineProperties(FunctionPrototype, {
  924. bind: function bind(that) { // .length is 1
  925. // 1. Let Target be the this value.
  926. var target = this;
  927. // 2. If IsCallable(Target) is false, throw a TypeError exception.
  928. if (!isFunction(target)) {
  929. throw new TypeError('Function.prototype.bind called on incompatible ' + target);
  930. }
  931. // 3. Let A be a new (possibly empty) internal list of all of the
  932. // argument values provided after thisArg (arg1, arg2 etc), in order.
  933. // XXX slicedArgs will stand in for "A" if used
  934. var args = array_slice.call(arguments, 1); // for normal call
  935. // 4. Let F be a new native ECMAScript object.
  936. // 11. Set the [[Prototype]] internal property of F to the standard
  937. // built-in Function prototype object as specified in 15.3.3.1.
  938. // 12. Set the [[Call]] internal property of F as described in
  939. // 15.3.4.5.1.
  940. // 13. Set the [[Construct]] internal property of F as described in
  941. // 15.3.4.5.2.
  942. // 14. Set the [[HasInstance]] internal property of F as described in
  943. // 15.3.4.5.3.
  944. var binder = function () {
  945. if (this instanceof bound) {
  946. // 15.3.4.5.2 [[Construct]]
  947. // When the [[Construct]] internal method of a function object,
  948. // F that was created using the bind function is called with a
  949. // list of arguments ExtraArgs, the following steps are taken:
  950. // 1. Let target be the value of F's [[TargetFunction]]
  951. // internal property.
  952. // 2. If target has no [[Construct]] internal method, a
  953. // TypeError exception is thrown.
  954. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal
  955. // property.
  956. // 4. Let args be a new list containing the same values as the
  957. // list boundArgs in the same order followed by the same
  958. // values as the list ExtraArgs in the same order.
  959. // 5. Return the result of calling the [[Construct]] internal
  960. // method of target providing args as the arguments.
  961. var result = target.apply(
  962. this,
  963. args.concat(array_slice.call(arguments))
  964. );
  965. if (Object(result) === result) {
  966. return result;
  967. }
  968. return this;
  969. } else {
  970. // 15.3.4.5.1 [[Call]]
  971. // When the [[Call]] internal method of a function object, F,
  972. // which was created using the bind function is called with a
  973. // this value and a list of arguments ExtraArgs, the following
  974. // steps are taken:
  975. // 1. Let boundArgs be the value of F's [[BoundArgs]] internal
  976. // property.
  977. // 2. Let boundThis be the value of F's [[BoundThis]] internal
  978. // property.
  979. // 3. Let target be the value of F's [[TargetFunction]] internal
  980. // property.
  981. // 4. Let args be a new list containing the same values as the
  982. // list boundArgs in the same order followed by the same
  983. // values as the list ExtraArgs in the same order.
  984. // 5. Return the result of calling the [[Call]] internal method
  985. // of target providing boundThis as the this value and
  986. // providing args as the arguments.
  987. // equiv: target.call(this, ...boundArgs, ...args)
  988. return target.apply(
  989. that,
  990. args.concat(array_slice.call(arguments))
  991. );
  992. }
  993. };
  994. // 15. If the [[Class]] internal property of Target is "Function", then
  995. // a. Let L be the length property of Target minus the length of A.
  996. // b. Set the length own property of F to either 0 or L, whichever is
  997. // larger.
  998. // 16. Else set the length own property of F to 0.
  999. var boundLength = Math.max(0, target.length - args.length);
  1000. // 17. Set the attributes of the length own property of F to the values
  1001. // specified in 15.3.5.1.
  1002. var boundArgs = [];
  1003. for (var i = 0; i < boundLength; i++) {
  1004. boundArgs.push('$' + i);
  1005. }
  1006. // XXX Build a dynamic function with desired amount of arguments is the only
  1007. // way to set the length property of a function.
  1008. // In environments where Content Security Policies enabled (Chrome extensions,
  1009. // for ex.) all use of eval or Function costructor throws an exception.
  1010. // However in all of these environments Function.prototype.bind exists
  1011. // and so this code will never be executed.
  1012. var bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
  1013. if (target.prototype) {
  1014. Empty.prototype = target.prototype;
  1015. bound.prototype = new Empty();
  1016. // Clean up dangling references.
  1017. Empty.prototype = null;
  1018. }
  1019. // TODO
  1020. // 18. Set the [[Extensible]] internal property of F to true.
  1021. // TODO
  1022. // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
  1023. // 20. Call the [[DefineOwnProperty]] internal method of F with
  1024. // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
  1025. // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
  1026. // false.
  1027. // 21. Call the [[DefineOwnProperty]] internal method of F with
  1028. // arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
  1029. // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
  1030. // and false.
  1031. // TODO
  1032. // NOTE Function objects created using Function.prototype.bind do not
  1033. // have a prototype property or the [[Code]], [[FormalParameters]], and
  1034. // [[Scope]] internal properties.
  1035. // XXX can't delete prototype in pure-js.
  1036. // 22. Return F.
  1037. return bound;
  1038. }
  1039. });
  1040. //
  1041. // Array
  1042. // =====
  1043. //
  1044. // ES5 15.4.3.2
  1045. // http://es5.github.com/#x15.4.3.2
  1046. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
  1047. defineProperties(Array, { isArray: isArray });
  1048. var boxedString = Object('a');
  1049. var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
  1050. var properlyBoxesContext = function properlyBoxed(method) {
  1051. // Check node 0.6.21 bug where third parameter is not boxed
  1052. var properlyBoxesNonStrict = true;
  1053. var properlyBoxesStrict = true;
  1054. if (method) {
  1055. method.call('foo', function (_, __, context) {
  1056. if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
  1057. });
  1058. method.call([1], function () {
  1059. 'use strict';
  1060. properlyBoxesStrict = typeof this === 'string';
  1061. }, 'x');
  1062. }
  1063. return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
  1064. };
  1065. defineProperties(ArrayPrototype, {
  1066. forEach: function forEach(fun /*, thisp*/) {
  1067. var object = toObject(this),
  1068. self = splitString && isString(this) ? this.split('') : object,
  1069. thisp = arguments[1],
  1070. i = -1,
  1071. length = self.length >>> 0;
  1072. // If no callback function or if callback is not a callable function
  1073. if (!isFunction(fun)) {
  1074. throw new TypeError(); // TODO message
  1075. }
  1076. while (++i < length) {
  1077. if (i in self) {
  1078. // Invoke the callback function with call, passing arguments:
  1079. // context, property value, property key, thisArg object
  1080. // context
  1081. fun.call(thisp, self[i], i, object);
  1082. }
  1083. }
  1084. }
  1085. }, !properlyBoxesContext(ArrayPrototype.forEach));
  1086. // ES5 15.4.4.14
  1087. // http://es5.github.com/#x15.4.4.14
  1088. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
  1089. var hasFirefox2IndexOfBug = Array.prototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
  1090. defineProperties(ArrayPrototype, {
  1091. indexOf: function indexOf(sought /*, fromIndex */ ) {
  1092. var self = splitString && isString(this) ? this.split('') : toObject(this),
  1093. length = self.length >>> 0;
  1094. if (!length) {
  1095. return -1;
  1096. }
  1097. var i = 0;
  1098. if (arguments.length > 1) {
  1099. i = toInteger(arguments[1]);
  1100. }
  1101. // handle negative indices
  1102. i = i >= 0 ? i : Math.max(0, length + i);
  1103. for (; i < length; i++) {
  1104. if (i in self && self[i] === sought) {
  1105. return i;
  1106. }
  1107. }
  1108. return -1;
  1109. }
  1110. }, hasFirefox2IndexOfBug);
  1111. //
  1112. // String
  1113. // ======
  1114. //
  1115. // ES5 15.5.4.14
  1116. // http://es5.github.com/#x15.5.4.14
  1117. // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
  1118. // Many browsers do not split properly with regular expressions or they
  1119. // do not perform the split correctly under obscure conditions.
  1120. // See http://blog.stevenlevithan.com/archives/cross-browser-split
  1121. // I've tested in many browsers and this seems to cover the deviant ones:
  1122. // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
  1123. // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
  1124. // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
  1125. // [undefined, "t", undefined, "e", ...]
  1126. // ''.split(/.?/) should be [], not [""]
  1127. // '.'.split(/()()/) should be ["."], not ["", "", "."]
  1128. var string_split = StringPrototype.split;
  1129. if (
  1130. 'ab'.split(/(?:ab)*/).length !== 2 ||
  1131. '.'.split(/(.?)(.?)/).length !== 4 ||
  1132. 'tesst'.split(/(s)*/)[1] === 't' ||
  1133. 'test'.split(/(?:)/, -1).length !== 4 ||
  1134. ''.split(/.?/).length ||
  1135. '.'.split(/()()/).length > 1
  1136. ) {
  1137. (function () {
  1138. var compliantExecNpcg = /()??/.exec('')[1] === void 0; // NPCG: nonparticipating capturing group
  1139. StringPrototype.split = function (separator, limit) {
  1140. var string = this;
  1141. if (separator === void 0 && limit === 0) {
  1142. return [];
  1143. }
  1144. // If `separator` is not a regex, use native split
  1145. if (_toString.call(separator) !== '[object RegExp]') {
  1146. return string_split.call(this, separator, limit);
  1147. }
  1148. var output = [],
  1149. flags = (separator.ignoreCase ? 'i' : '') +
  1150. (separator.multiline ? 'm' : '') +
  1151. (separator.extended ? 'x' : '') + // Proposed for ES6
  1152. (separator.sticky ? 'y' : ''), // Firefox 3+
  1153. lastLastIndex = 0,
  1154. // Make `global` and avoid `lastIndex` issues by working with a copy
  1155. separator2, match, lastIndex, lastLength;
  1156. separator = new RegExp(separator.source, flags + 'g');
  1157. string += ''; // Type-convert
  1158. if (!compliantExecNpcg) {
  1159. // Doesn't need flags gy, but they don't hurt
  1160. separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
  1161. }
  1162. /* Values for `limit`, per the spec:
  1163. * If undefined: 4294967295 // Math.pow(2, 32) - 1
  1164. * If 0, Infinity, or NaN: 0
  1165. * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
  1166. * If negative number: 4294967296 - Math.floor(Math.abs(limit))
  1167. * If other: Type-convert, then use the above rules
  1168. */
  1169. limit = limit === void 0 ?
  1170. -1 >>> 0 : // Math.pow(2, 32) - 1
  1171. ToUint32(limit);
  1172. while (match = separator.exec(string)) {
  1173. // `separator.lastIndex` is not reliable cross-browser
  1174. lastIndex = match.index + match[0].length;
  1175. if (lastIndex > lastLastIndex) {
  1176. output.push(string.slice(lastLastIndex, match.index));
  1177. // Fix browsers whose `exec` methods don't consistently return `undefined` for
  1178. // nonparticipating capturing groups
  1179. if (!compliantExecNpcg && match.length > 1) {
  1180. match[0].replace(separator2, function () {
  1181. for (var i = 1; i < arguments.length - 2; i++) {
  1182. if (arguments[i] === void 0) {
  1183. match[i] = void 0;
  1184. }
  1185. }
  1186. });
  1187. }
  1188. if (match.length > 1 && match.index < string.length) {
  1189. ArrayPrototype.push.apply(output, match.slice(1));
  1190. }
  1191. lastLength = match[0].length;
  1192. lastLastIndex = lastIndex;
  1193. if (output.length >= limit) {
  1194. break;
  1195. }
  1196. }
  1197. if (separator.lastIndex === match.index) {
  1198. separator.lastIndex++; // Avoid an infinite loop
  1199. }
  1200. }
  1201. if (lastLastIndex === string.length) {
  1202. if (lastLength || !separator.test('')) {
  1203. output.push('');
  1204. }
  1205. } else {
  1206. output.push(string.slice(lastLastIndex));
  1207. }
  1208. return output.length > limit ? output.slice(0, limit) : output;
  1209. };
  1210. }());
  1211. // [bugfix, chrome]
  1212. // If separator is undefined, then the result array contains just one String,
  1213. // which is the this value (converted to a String). If limit is not undefined,
  1214. // then the output array is truncated so that it contains no more than limit
  1215. // elements.
  1216. // "0".split(undefined, 0) -> []
  1217. } else if ('0'.split(void 0, 0).length) {
  1218. StringPrototype.split = function split(separator, limit) {
  1219. if (separator === void 0 && limit === 0) { return []; }
  1220. return string_split.call(this, separator, limit);
  1221. };
  1222. }
  1223. // ECMA-262, 3rd B.2.3
  1224. // Not an ECMAScript standard, although ECMAScript 3rd Edition has a
  1225. // non-normative section suggesting uniform semantics and it should be
  1226. // normalized across all browsers
  1227. // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
  1228. var string_substr = StringPrototype.substr;
  1229. var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
  1230. defineProperties(StringPrototype, {
  1231. substr: function substr(start, length) {
  1232. return string_substr.call(
  1233. this,
  1234. start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,
  1235. length
  1236. );
  1237. }
  1238. }, hasNegativeSubstrBug);
  1239. },{}],16:[function(require,module,exports){
  1240. 'use strict';
  1241. module.exports = [
  1242. // streaming transports
  1243. require('./transport/websocket')
  1244. , require('./transport/xhr-streaming')
  1245. , require('./transport/xdr-streaming')
  1246. , require('./transport/eventsource')
  1247. , require('./transport/lib/iframe-wrap')(require('./transport/eventsource'))
  1248. // polling transports
  1249. , require('./transport/htmlfile')
  1250. , require('./transport/lib/iframe-wrap')(require('./transport/htmlfile'))
  1251. , require('./transport/xhr-polling')
  1252. , require('./transport/xdr-polling')
  1253. , require('./transport/lib/iframe-wrap')(require('./transport/xhr-polling'))
  1254. , require('./transport/jsonp-polling')
  1255. ];
  1256. },{"./transport/eventsource":20,"./transport/htmlfile":21,"./transport/jsonp-polling":23,"./transport/lib/iframe-wrap":26,"./transport/websocket":38,"./transport/xdr-polling":39,"./transport/xdr-streaming":40,"./transport/xhr-polling":41,"./transport/xhr-streaming":42}],17:[function(require,module,exports){
  1257. (function (process,global){
  1258. 'use strict';
  1259. var EventEmitter = require('events').EventEmitter
  1260. , inherits = require('inherits')
  1261. , utils = require('../../utils/event')
  1262. , urlUtils = require('../../utils/url')
  1263. , XHR = global.XMLHttpRequest
  1264. ;
  1265. var debug = function() {};
  1266. if (process.env.NODE_ENV !== 'production') {
  1267. debug = require('debug')('sockjs-client:browser:xhr');
  1268. }
  1269. function AbstractXHRObject(method, url, payload, opts) {
  1270. debug(method, url);
  1271. var self = this;
  1272. EventEmitter.call(this);
  1273. setTimeout(function () {
  1274. self._start(method, url, payload, opts);
  1275. }, 0);
  1276. }
  1277. inherits(AbstractXHRObject, EventEmitter);
  1278. AbstractXHRObject.prototype._start = function(method, url, payload, opts) {
  1279. var self = this;
  1280. try {
  1281. this.xhr = new XHR();
  1282. } catch (x) {
  1283. // intentionally empty
  1284. }
  1285. if (!this.xhr) {
  1286. debug('no xhr');
  1287. this.emit('finish', 0, 'no xhr support');
  1288. this._cleanup();
  1289. return;
  1290. }
  1291. // several browsers cache POSTs
  1292. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  1293. // Explorer tends to keep connection open, even after the
  1294. // tab gets closed: http://bugs.jquery.com/ticket/5280
  1295. this.unloadRef = utils.unloadAdd(function() {
  1296. debug('unload cleanup');
  1297. self._cleanup(true);
  1298. });
  1299. try {
  1300. this.xhr.open(method, url, true);
  1301. if (this.timeout && 'timeout' in this.xhr) {
  1302. this.xhr.timeout = this.timeout;
  1303. this.xhr.ontimeout = function() {
  1304. debug('xhr timeout');
  1305. self.emit('finish', 0, '');
  1306. self._cleanup(false);
  1307. };
  1308. }
  1309. } catch (e) {
  1310. debug('exception', e);
  1311. // IE raises an exception on wrong port.
  1312. this.emit('finish', 0, '');
  1313. this._cleanup(false);
  1314. return;
  1315. }
  1316. if ((!opts || !opts.noCredentials) && AbstractXHRObject.supportsCORS) {
  1317. debug('withCredentials');
  1318. // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :
  1319. // "This never affects same-site requests."
  1320. this.xhr.withCredentials = true;
  1321. }
  1322. if (opts && opts.headers) {
  1323. for (var key in opts.headers) {
  1324. this.xhr.setRequestHeader(key, opts.headers[key]);
  1325. }
  1326. }
  1327. this.xhr.onreadystatechange = function() {
  1328. if (self.xhr) {
  1329. var x = self.xhr;
  1330. var text, status;
  1331. debug('readyState', x.readyState);
  1332. switch (x.readyState) {
  1333. case 3:
  1334. // IE doesn't like peeking into responseText or status
  1335. // on Microsoft.XMLHTTP and readystate=3
  1336. try {
  1337. status = x.status;
  1338. text = x.responseText;
  1339. } catch (e) {
  1340. // intentionally empty
  1341. }
  1342. debug('status', status);
  1343. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1344. if (status === 1223) {
  1345. status = 204;
  1346. }
  1347. // IE does return readystate == 3 for 404 answers.
  1348. if (status === 200 && text && text.length > 0) {
  1349. debug('chunk');
  1350. self.emit('chunk', status, text);
  1351. }
  1352. break;
  1353. case 4:
  1354. status = x.status;
  1355. debug('status', status);
  1356. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1357. if (status === 1223) {
  1358. status = 204;
  1359. }
  1360. // IE returns this for a bad port
  1361. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx
  1362. if (status === 12005 || status === 12029) {
  1363. status = 0;
  1364. }
  1365. debug('finish', status, x.responseText);
  1366. self.emit('finish', status, x.responseText);
  1367. self._cleanup(false);
  1368. break;
  1369. }
  1370. }
  1371. };
  1372. try {
  1373. self.xhr.send(payload);
  1374. } catch (e) {
  1375. self.emit('finish', 0, '');
  1376. self._cleanup(false);
  1377. }
  1378. };
  1379. AbstractXHRObject.prototype._cleanup = function(abort) {
  1380. debug('cleanup');
  1381. if (!this.xhr) {
  1382. return;
  1383. }
  1384. this.removeAllListeners();
  1385. utils.unloadDel(this.unloadRef);
  1386. // IE needs this field to be a function
  1387. this.xhr.onreadystatechange = function() {};
  1388. if (this.xhr.ontimeout) {
  1389. this.xhr.ontimeout = null;
  1390. }
  1391. if (abort) {
  1392. try {
  1393. this.xhr.abort();
  1394. } catch (x) {
  1395. // intentionally empty
  1396. }
  1397. }
  1398. this.unloadRef = this.xhr = null;
  1399. };
  1400. AbstractXHRObject.prototype.close = function() {
  1401. debug('close');
  1402. this._cleanup(true);
  1403. };
  1404. AbstractXHRObject.enabled = !!XHR;
  1405. // override XMLHttpRequest for IE6/7
  1406. // obfuscate to avoid firewalls
  1407. var axo = ['Active'].concat('Object').join('X');
  1408. if (!AbstractXHRObject.enabled && (axo in global)) {
  1409. debug('overriding xmlhttprequest');
  1410. XHR = function() {
  1411. try {
  1412. return new global[axo]('Microsoft.XMLHTTP');
  1413. } catch (e) {
  1414. return null;
  1415. }
  1416. };
  1417. AbstractXHRObject.enabled = !!new XHR();
  1418. }
  1419. var cors = false;
  1420. try {
  1421. cors = 'withCredentials' in new XHR();
  1422. } catch (ignored) {
  1423. // intentionally empty
  1424. }
  1425. AbstractXHRObject.supportsCORS = cors;
  1426. module.exports = AbstractXHRObject;
  1427. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1428. },{"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],18:[function(require,module,exports){
  1429. (function (global){
  1430. module.exports = global.EventSource;
  1431. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1432. },{}],19:[function(require,module,exports){
  1433. (function (global){
  1434. 'use strict';
  1435. var Driver = global.WebSocket || global.MozWebSocket;
  1436. if (Driver) {
  1437. module.exports = function WebSocketBrowserDriver(url) {
  1438. return new Driver(url);
  1439. };
  1440. } else {
  1441. module.exports = undefined;
  1442. }
  1443. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1444. },{}],20:[function(require,module,exports){
  1445. 'use strict';
  1446. var inherits = require('inherits')
  1447. , AjaxBasedTransport = require('./lib/ajax-based')
  1448. , EventSourceReceiver = require('./receiver/eventsource')
  1449. , XHRCorsObject = require('./sender/xhr-cors')
  1450. , EventSourceDriver = require('eventsource')
  1451. ;
  1452. function EventSourceTransport(transUrl) {
  1453. if (!EventSourceTransport.enabled()) {
  1454. throw new Error('Transport created when disabled');
  1455. }
  1456. AjaxBasedTransport.call(this, transUrl, '/eventsource', EventSourceReceiver, XHRCorsObject);
  1457. }
  1458. inherits(EventSourceTransport, AjaxBasedTransport);
  1459. EventSourceTransport.enabled = function() {
  1460. return !!EventSourceDriver;
  1461. };
  1462. EventSourceTransport.transportName = 'eventsource';
  1463. EventSourceTransport.roundTrips = 2;
  1464. module.exports = EventSourceTransport;
  1465. },{"./lib/ajax-based":24,"./receiver/eventsource":29,"./sender/xhr-cors":35,"eventsource":18,"inherits":57}],21:[function(require,module,exports){
  1466. 'use strict';
  1467. var inherits = require('inherits')
  1468. , HtmlfileReceiver = require('./receiver/htmlfile')
  1469. , XHRLocalObject = require('./sender/xhr-local')
  1470. , AjaxBasedTransport = require('./lib/ajax-based')
  1471. ;
  1472. function HtmlFileTransport(transUrl) {
  1473. if (!HtmlfileReceiver.enabled) {
  1474. throw new Error('Transport created when disabled');
  1475. }
  1476. AjaxBasedTransport.call(this, transUrl, '/htmlfile', HtmlfileReceiver, XHRLocalObject);
  1477. }
  1478. inherits(HtmlFileTransport, AjaxBasedTransport);
  1479. HtmlFileTransport.enabled = function(info) {
  1480. return HtmlfileReceiver.enabled && info.sameOrigin;
  1481. };
  1482. HtmlFileTransport.transportName = 'htmlfile';
  1483. HtmlFileTransport.roundTrips = 2;
  1484. module.exports = HtmlFileTransport;
  1485. },{"./lib/ajax-based":24,"./receiver/htmlfile":30,"./sender/xhr-local":37,"inherits":57}],22:[function(require,module,exports){
  1486. (function (process){
  1487. 'use strict';
  1488. // Few cool transports do work only for same-origin. In order to make
  1489. // them work cross-domain we shall use iframe, served from the
  1490. // remote domain. New browsers have capabilities to communicate with
  1491. // cross domain iframe using postMessage(). In IE it was implemented
  1492. // from IE 8+, but of course, IE got some details wrong:
  1493. // http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx
  1494. // http://stevesouders.com/misc/test-postmessage.php
  1495. var inherits = require('inherits')
  1496. , JSON3 = require('json3')
  1497. , EventEmitter = require('events').EventEmitter
  1498. , version = require('../version')
  1499. , urlUtils = require('../utils/url')
  1500. , iframeUtils = require('../utils/iframe')
  1501. , eventUtils = require('../utils/event')
  1502. , random = require('../utils/random')
  1503. ;
  1504. var debug = function() {};
  1505. if (process.env.NODE_ENV !== 'production') {
  1506. debug = require('debug')('sockjs-client:transport:iframe');
  1507. }
  1508. function IframeTransport(transport, transUrl, baseUrl) {
  1509. if (!IframeTransport.enabled()) {
  1510. throw new Error('Transport created when disabled');
  1511. }
  1512. EventEmitter.call(this);
  1513. var self = this;
  1514. this.origin = urlUtils.getOrigin(baseUrl);
  1515. this.baseUrl = baseUrl;
  1516. this.transUrl = transUrl;
  1517. this.transport = transport;
  1518. this.windowId = random.string(8);
  1519. var iframeUrl = urlUtils.addPath(baseUrl, '/iframe.html') + '#' + this.windowId;
  1520. debug(transport, transUrl, iframeUrl);
  1521. this.iframeObj = iframeUtils.createIframe(iframeUrl, function(r) {
  1522. debug('err callback');
  1523. self.emit('close', 1006, 'Unable to load an iframe (' + r + ')');
  1524. self.close();
  1525. });
  1526. this.onmessageCallback = this._message.bind(this);
  1527. eventUtils.attachEvent('message', this.onmessageCallback);
  1528. }
  1529. inherits(IframeTransport, EventEmitter);
  1530. IframeTransport.prototype.close = function() {
  1531. debug('close');
  1532. this.removeAllListeners();
  1533. if (this.iframeObj) {
  1534. eventUtils.detachEvent('message', this.onmessageCallback);
  1535. try {
  1536. // When the iframe is not loaded, IE raises an exception
  1537. // on 'contentWindow'.
  1538. this.postMessage('c');
  1539. } catch (x) {
  1540. // intentionally empty
  1541. }
  1542. this.iframeObj.cleanup();
  1543. this.iframeObj = null;
  1544. this.onmessageCallback = this.iframeObj = null;
  1545. }
  1546. };
  1547. IframeTransport.prototype._message = function(e) {
  1548. debug('message', e.data);
  1549. if (!urlUtils.isOriginEqual(e.origin, this.origin)) {
  1550. debug('not same origin', e.origin, this.origin);
  1551. return;
  1552. }
  1553. var iframeMessage;
  1554. try {
  1555. iframeMessage = JSON3.parse(e.data);
  1556. } catch (ignored) {
  1557. debug('bad json', e.data);
  1558. return;
  1559. }
  1560. if (iframeMessage.windowId !== this.windowId) {
  1561. debug('mismatched window id', iframeMessage.windowId, this.windowId);
  1562. return;
  1563. }
  1564. switch (iframeMessage.type) {
  1565. case 's':
  1566. this.iframeObj.loaded();
  1567. // window global dependency
  1568. this.postMessage('s', JSON3.stringify([
  1569. version
  1570. , this.transport
  1571. , this.transUrl
  1572. , this.baseUrl
  1573. ]));
  1574. break;
  1575. case 't':
  1576. this.emit('message', iframeMessage.data);
  1577. break;
  1578. case 'c':
  1579. var cdata;
  1580. try {
  1581. cdata = JSON3.parse(iframeMessage.data);
  1582. } catch (ignored) {
  1583. debug('bad json', iframeMessage.data);
  1584. return;
  1585. }
  1586. this.emit('close', cdata[0], cdata[1]);
  1587. this.close();
  1588. break;
  1589. }
  1590. };
  1591. IframeTransport.prototype.postMessage = function(type, data) {
  1592. debug('postMessage', type, data);
  1593. this.iframeObj.post(JSON3.stringify({
  1594. windowId: this.windowId
  1595. , type: type
  1596. , data: data || ''
  1597. }), this.origin);
  1598. };
  1599. IframeTransport.prototype.send = function(message) {
  1600. debug('send', message);
  1601. this.postMessage('m', message);
  1602. };
  1603. IframeTransport.enabled = function() {
  1604. return iframeUtils.iframeEnabled;
  1605. };
  1606. IframeTransport.transportName = 'iframe';
  1607. IframeTransport.roundTrips = 2;
  1608. module.exports = IframeTransport;
  1609. }).call(this,{ env: {} })
  1610. },{"../utils/event":46,"../utils/iframe":47,"../utils/random":50,"../utils/url":52,"../version":53,"debug":55,"events":3,"inherits":57,"json3":58}],23:[function(require,module,exports){
  1611. (function (global){
  1612. 'use strict';
  1613. // The simplest and most robust transport, using the well-know cross
  1614. // domain hack - JSONP. This transport is quite inefficient - one
  1615. // message could use up to one http request. But at least it works almost
  1616. // everywhere.
  1617. // Known limitations:
  1618. // o you will get a spinning cursor
  1619. // o for Konqueror a dumb timer is needed to detect errors
  1620. var inherits = require('inherits')
  1621. , SenderReceiver = require('./lib/sender-receiver')
  1622. , JsonpReceiver = require('./receiver/jsonp')
  1623. , jsonpSender = require('./sender/jsonp')
  1624. ;
  1625. function JsonPTransport(transUrl) {
  1626. if (!JsonPTransport.enabled()) {
  1627. throw new Error('Transport created when disabled');
  1628. }
  1629. SenderReceiver.call(this, transUrl, '/jsonp', jsonpSender, JsonpReceiver);
  1630. }
  1631. inherits(JsonPTransport, SenderReceiver);
  1632. JsonPTransport.enabled = function() {
  1633. return !!global.document;
  1634. };
  1635. JsonPTransport.transportName = 'jsonp-polling';
  1636. JsonPTransport.roundTrips = 1;
  1637. JsonPTransport.needBody = true;
  1638. module.exports = JsonPTransport;
  1639. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1640. },{"./lib/sender-receiver":28,"./receiver/jsonp":31,"./sender/jsonp":33,"inherits":57}],24:[function(require,module,exports){
  1641. (function (process){
  1642. 'use strict';
  1643. var inherits = require('inherits')
  1644. , urlUtils = require('../../utils/url')
  1645. , SenderReceiver = require('./sender-receiver')
  1646. ;
  1647. var debug = function() {};
  1648. if (process.env.NODE_ENV !== 'production') {
  1649. debug = require('debug')('sockjs-client:ajax-based');
  1650. }
  1651. function createAjaxSender(AjaxObject) {
  1652. return function(url, payload, callback) {
  1653. debug('create ajax sender', url, payload);
  1654. var opt = {};
  1655. if (typeof payload === 'string') {
  1656. opt.headers = {'Content-type': 'text/plain'};
  1657. }
  1658. var ajaxUrl = urlUtils.addPath(url, '/xhr_send');
  1659. var xo = new AjaxObject('POST', ajaxUrl, payload, opt);
  1660. xo.once('finish', function(status) {
  1661. debug('finish', status);
  1662. xo = null;
  1663. if (status !== 200 && status !== 204) {
  1664. return callback(new Error('http status ' + status));
  1665. }
  1666. callback();
  1667. });
  1668. return function() {
  1669. debug('abort');
  1670. xo.close();
  1671. xo = null;
  1672. var err = new Error('Aborted');
  1673. err.code = 1000;
  1674. callback(err);
  1675. };
  1676. };
  1677. }
  1678. function AjaxBasedTransport(transUrl, urlSuffix, Receiver, AjaxObject) {
  1679. SenderReceiver.call(this, transUrl, urlSuffix, createAjaxSender(AjaxObject), Receiver, AjaxObject);
  1680. }
  1681. inherits(AjaxBasedTransport, SenderReceiver);
  1682. module.exports = AjaxBasedTransport;
  1683. }).call(this,{ env: {} })
  1684. },{"../../utils/url":52,"./sender-receiver":28,"debug":55,"inherits":57}],25:[function(require,module,exports){
  1685. (function (process){
  1686. 'use strict';
  1687. var inherits = require('inherits')
  1688. , EventEmitter = require('events').EventEmitter
  1689. ;
  1690. var debug = function() {};
  1691. if (process.env.NODE_ENV !== 'production') {
  1692. debug = require('debug')('sockjs-client:buffered-sender');
  1693. }
  1694. function BufferedSender(url, sender) {
  1695. debug(url);
  1696. EventEmitter.call(this);
  1697. this.sendBuffer = [];
  1698. this.sender = sender;
  1699. this.url = url;
  1700. }
  1701. inherits(BufferedSender, EventEmitter);
  1702. BufferedSender.prototype.send = function(message) {
  1703. debug('send', message);
  1704. this.sendBuffer.push(message);
  1705. if (!this.sendStop) {
  1706. this.sendSchedule();
  1707. }
  1708. };
  1709. // For polling transports in a situation when in the message callback,
  1710. // new message is being send. If the sending connection was started
  1711. // before receiving one, it is possible to saturate the network and
  1712. // timeout due to the lack of receiving socket. To avoid that we delay
  1713. // sending messages by some small time, in order to let receiving
  1714. // connection be started beforehand. This is only a halfmeasure and
  1715. // does not fix the big problem, but it does make the tests go more
  1716. // stable on slow networks.
  1717. BufferedSender.prototype.sendScheduleWait = function() {
  1718. debug('sendScheduleWait');
  1719. var self = this;
  1720. var tref;
  1721. this.sendStop = function() {
  1722. debug('sendStop');
  1723. self.sendStop = null;
  1724. clearTimeout(tref);
  1725. };
  1726. tref = setTimeout(function() {
  1727. debug('timeout');
  1728. self.sendStop = null;
  1729. self.sendSchedule();
  1730. }, 25);
  1731. };
  1732. BufferedSender.prototype.sendSchedule = function() {
  1733. debug('sendSchedule', this.sendBuffer.length);
  1734. var self = this;
  1735. if (this.sendBuffer.length > 0) {
  1736. var payload = '[' + this.sendBuffer.join(',') + ']';
  1737. this.sendStop = this.sender(this.url, payload, function(err) {
  1738. self.sendStop = null;
  1739. if (err) {
  1740. debug('error', err);
  1741. self.emit('close', err.code || 1006, 'Sending error: ' + err);
  1742. self.close();
  1743. } else {
  1744. self.sendScheduleWait();
  1745. }
  1746. });
  1747. this.sendBuffer = [];
  1748. }
  1749. };
  1750. BufferedSender.prototype._cleanup = function() {
  1751. debug('_cleanup');
  1752. this.removeAllListeners();
  1753. };
  1754. BufferedSender.prototype.close = function() {
  1755. debug('close');
  1756. this._cleanup();
  1757. if (this.sendStop) {
  1758. this.sendStop();
  1759. this.sendStop = null;
  1760. }
  1761. };
  1762. module.exports = BufferedSender;
  1763. }).call(this,{ env: {} })
  1764. },{"debug":55,"events":3,"inherits":57}],26:[function(require,module,exports){
  1765. (function (global){
  1766. 'use strict';
  1767. var inherits = require('inherits')
  1768. , IframeTransport = require('../iframe')
  1769. , objectUtils = require('../../utils/object')
  1770. ;
  1771. module.exports = function(transport) {
  1772. function IframeWrapTransport(transUrl, baseUrl) {
  1773. IframeTransport.call(this, transport.transportName, transUrl, baseUrl);
  1774. }
  1775. inherits(IframeWrapTransport, IframeTransport);
  1776. IframeWrapTransport.enabled = function(url, info) {
  1777. if (!global.document) {
  1778. return false;
  1779. }
  1780. var iframeInfo = objectUtils.extend({}, info);
  1781. iframeInfo.sameOrigin = true;
  1782. return transport.enabled(iframeInfo) && IframeTransport.enabled();
  1783. };
  1784. IframeWrapTransport.transportName = 'iframe-' + transport.transportName;
  1785. IframeWrapTransport.needBody = true;
  1786. IframeWrapTransport.roundTrips = IframeTransport.roundTrips + transport.roundTrips - 1; // html, javascript (2) + transport - no CORS (1)
  1787. IframeWrapTransport.facadeTransport = transport;
  1788. return IframeWrapTransport;
  1789. };
  1790. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1791. },{"../../utils/object":49,"../iframe":22,"inherits":57}],27:[function(require,module,exports){
  1792. (function (process){
  1793. 'use strict';
  1794. var inherits = require('inherits')
  1795. , EventEmitter = require('events').EventEmitter
  1796. ;
  1797. var debug = function() {};
  1798. if (process.env.NODE_ENV !== 'production') {
  1799. debug = require('debug')('sockjs-client:polling');
  1800. }
  1801. function Polling(Receiver, receiveUrl, AjaxObject) {
  1802. debug(receiveUrl);
  1803. EventEmitter.call(this);
  1804. this.Receiver = Receiver;
  1805. this.receiveUrl = receiveUrl;
  1806. this.AjaxObject = AjaxObject;
  1807. this._scheduleReceiver();
  1808. }
  1809. inherits(Polling, EventEmitter);
  1810. Polling.prototype._scheduleReceiver = function() {
  1811. debug('_scheduleReceiver');
  1812. var self = this;
  1813. var poll = this.poll = new this.Receiver(this.receiveUrl, this.AjaxObject);
  1814. poll.on('message', function(msg) {
  1815. debug('message', msg);
  1816. self.emit('message', msg);
  1817. });
  1818. poll.once('close', function(code, reason) {
  1819. debug('close', code, reason, self.pollIsClosing);
  1820. self.poll = poll = null;
  1821. if (!self.pollIsClosing) {
  1822. if (reason === 'network') {
  1823. self._scheduleReceiver();
  1824. } else {
  1825. self.emit('close', code || 1006, reason);
  1826. self.removeAllListeners();
  1827. }
  1828. }
  1829. });
  1830. };
  1831. Polling.prototype.abort = function() {
  1832. debug('abort');
  1833. this.removeAllListeners();
  1834. this.pollIsClosing = true;
  1835. if (this.poll) {
  1836. this.poll.abort();
  1837. }
  1838. };
  1839. module.exports = Polling;
  1840. }).call(this,{ env: {} })
  1841. },{"debug":55,"events":3,"inherits":57}],28:[function(require,module,exports){
  1842. (function (process){
  1843. 'use strict';
  1844. var inherits = require('inherits')
  1845. , urlUtils = require('../../utils/url')
  1846. , BufferedSender = require('./buffered-sender')
  1847. , Polling = require('./polling')
  1848. ;
  1849. var debug = function() {};
  1850. if (process.env.NODE_ENV !== 'production') {
  1851. debug = require('debug')('sockjs-client:sender-receiver');
  1852. }
  1853. function SenderReceiver(transUrl, urlSuffix, senderFunc, Receiver, AjaxObject) {
  1854. var pollUrl = urlUtils.addPath(transUrl, urlSuffix);
  1855. debug(pollUrl);
  1856. var self = this;
  1857. BufferedSender.call(this, transUrl, senderFunc);
  1858. this.poll = new Polling(Receiver, pollUrl, AjaxObject);
  1859. this.poll.on('message', function(msg) {
  1860. debug('poll message', msg);
  1861. self.emit('message', msg);
  1862. });
  1863. this.poll.once('close', function(code, reason) {
  1864. debug('poll close', code, reason);
  1865. self.poll = null;
  1866. self.emit('close', code, reason);
  1867. self.close();
  1868. });
  1869. }
  1870. inherits(SenderReceiver, BufferedSender);
  1871. SenderReceiver.prototype.close = function() {
  1872. BufferedSender.prototype.close.call(this);
  1873. debug('close');
  1874. this.removeAllListeners();
  1875. if (this.poll) {
  1876. this.poll.abort();
  1877. this.poll = null;
  1878. }
  1879. };
  1880. module.exports = SenderReceiver;
  1881. }).call(this,{ env: {} })
  1882. },{"../../utils/url":52,"./buffered-sender":25,"./polling":27,"debug":55,"inherits":57}],29:[function(require,module,exports){
  1883. (function (process){
  1884. 'use strict';
  1885. var inherits = require('inherits')
  1886. , EventEmitter = require('events').EventEmitter
  1887. , EventSourceDriver = require('eventsource')
  1888. ;
  1889. var debug = function() {};
  1890. if (process.env.NODE_ENV !== 'production') {
  1891. debug = require('debug')('sockjs-client:receiver:eventsource');
  1892. }
  1893. function EventSourceReceiver(url) {
  1894. debug(url);
  1895. EventEmitter.call(this);
  1896. var self = this;
  1897. var es = this.es = new EventSourceDriver(url);
  1898. es.onmessage = function(e) {
  1899. debug('message', e.data);
  1900. self.emit('message', decodeURI(e.data));
  1901. };
  1902. es.onerror = function(e) {
  1903. debug('error', es.readyState, e);
  1904. // ES on reconnection has readyState = 0 or 1.
  1905. // on network error it's CLOSED = 2
  1906. var reason = (es.readyState !== 2 ? 'network' : 'permanent');
  1907. self._cleanup();
  1908. self._close(reason);
  1909. };
  1910. }
  1911. inherits(EventSourceReceiver, EventEmitter);
  1912. EventSourceReceiver.prototype.abort = function() {
  1913. debug('abort');
  1914. this._cleanup();
  1915. this._close('user');
  1916. };
  1917. EventSourceReceiver.prototype._cleanup = function() {
  1918. debug('cleanup');
  1919. var es = this.es;
  1920. if (es) {
  1921. es.onmessage = es.onerror = null;
  1922. es.close();
  1923. this.es = null;
  1924. }
  1925. };
  1926. EventSourceReceiver.prototype._close = function(reason) {
  1927. debug('close', reason);
  1928. var self = this;
  1929. // Safari and chrome < 15 crash if we close window before
  1930. // waiting for ES cleanup. See:
  1931. // https://code.google.com/p/chromium/issues/detail?id=89155
  1932. setTimeout(function() {
  1933. self.emit('close', null, reason);
  1934. self.removeAllListeners();
  1935. }, 200);
  1936. };
  1937. module.exports = EventSourceReceiver;
  1938. }).call(this,{ env: {} })
  1939. },{"debug":55,"events":3,"eventsource":18,"inherits":57}],30:[function(require,module,exports){
  1940. (function (process,global){
  1941. 'use strict';
  1942. var inherits = require('inherits')
  1943. , iframeUtils = require('../../utils/iframe')
  1944. , urlUtils = require('../../utils/url')
  1945. , EventEmitter = require('events').EventEmitter
  1946. , random = require('../../utils/random')
  1947. ;
  1948. var debug = function() {};
  1949. if (process.env.NODE_ENV !== 'production') {
  1950. debug = require('debug')('sockjs-client:receiver:htmlfile');
  1951. }
  1952. function HtmlfileReceiver(url) {
  1953. debug(url);
  1954. EventEmitter.call(this);
  1955. var self = this;
  1956. iframeUtils.polluteGlobalNamespace();
  1957. this.id = 'a' + random.string(6);
  1958. url = urlUtils.addQuery(url, 'c=' + decodeURIComponent(iframeUtils.WPrefix + '.' + this.id));
  1959. debug('using htmlfile', HtmlfileReceiver.htmlfileEnabled);
  1960. var constructFunc = HtmlfileReceiver.htmlfileEnabled ?
  1961. iframeUtils.createHtmlfile : iframeUtils.createIframe;
  1962. global[iframeUtils.WPrefix][this.id] = {
  1963. start: function() {
  1964. debug('start');
  1965. self.iframeObj.loaded();
  1966. }
  1967. , message: function(data) {
  1968. debug('message', data);
  1969. self.emit('message', data);
  1970. }
  1971. , stop: function() {
  1972. debug('stop');
  1973. self._cleanup();
  1974. self._close('network');
  1975. }
  1976. };
  1977. this.iframeObj = constructFunc(url, function() {
  1978. debug('callback');
  1979. self._cleanup();
  1980. self._close('permanent');
  1981. });
  1982. }
  1983. inherits(HtmlfileReceiver, EventEmitter);
  1984. HtmlfileReceiver.prototype.abort = function() {
  1985. debug('abort');
  1986. this._cleanup();
  1987. this._close('user');
  1988. };
  1989. HtmlfileReceiver.prototype._cleanup = function() {
  1990. debug('_cleanup');
  1991. if (this.iframeObj) {
  1992. this.iframeObj.cleanup();
  1993. this.iframeObj = null;
  1994. }
  1995. delete global[iframeUtils.WPrefix][this.id];
  1996. };
  1997. HtmlfileReceiver.prototype._close = function(reason) {
  1998. debug('_close', reason);
  1999. this.emit('close', null, reason);
  2000. this.removeAllListeners();
  2001. };
  2002. HtmlfileReceiver.htmlfileEnabled = false;
  2003. // obfuscate to avoid firewalls
  2004. var axo = ['Active'].concat('Object').join('X');
  2005. if (axo in global) {
  2006. try {
  2007. HtmlfileReceiver.htmlfileEnabled = !!new global[axo]('htmlfile');
  2008. } catch (x) {
  2009. // intentionally empty
  2010. }
  2011. }
  2012. HtmlfileReceiver.enabled = HtmlfileReceiver.htmlfileEnabled || iframeUtils.iframeEnabled;
  2013. module.exports = HtmlfileReceiver;
  2014. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2015. },{"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],31:[function(require,module,exports){
  2016. (function (process,global){
  2017. 'use strict';
  2018. var utils = require('../../utils/iframe')
  2019. , random = require('../../utils/random')
  2020. , browser = require('../../utils/browser')
  2021. , urlUtils = require('../../utils/url')
  2022. , inherits = require('inherits')
  2023. , EventEmitter = require('events').EventEmitter
  2024. ;
  2025. var debug = function() {};
  2026. if (process.env.NODE_ENV !== 'production') {
  2027. debug = require('debug')('sockjs-client:receiver:jsonp');
  2028. }
  2029. function JsonpReceiver(url) {
  2030. debug(url);
  2031. var self = this;
  2032. EventEmitter.call(this);
  2033. utils.polluteGlobalNamespace();
  2034. this.id = 'a' + random.string(6);
  2035. var urlWithId = urlUtils.addQuery(url, 'c=' + encodeURIComponent(utils.WPrefix + '.' + this.id));
  2036. global[utils.WPrefix][this.id] = this._callback.bind(this);
  2037. this._createScript(urlWithId);
  2038. // Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.
  2039. this.timeoutId = setTimeout(function() {
  2040. debug('timeout');
  2041. self._abort(new Error('JSONP script loaded abnormally (timeout)'));
  2042. }, JsonpReceiver.timeout);
  2043. }
  2044. inherits(JsonpReceiver, EventEmitter);
  2045. JsonpReceiver.prototype.abort = function() {
  2046. debug('abort');
  2047. if (global[utils.WPrefix][this.id]) {
  2048. var err = new Error('JSONP user aborted read');
  2049. err.code = 1000;
  2050. this._abort(err);
  2051. }
  2052. };
  2053. JsonpReceiver.timeout = 35000;
  2054. JsonpReceiver.scriptErrorTimeout = 1000;
  2055. JsonpReceiver.prototype._callback = function(data) {
  2056. debug('_callback', data);
  2057. this._cleanup();
  2058. if (this.aborting) {
  2059. return;
  2060. }
  2061. if (data) {
  2062. debug('message', data);
  2063. this.emit('message', data);
  2064. }
  2065. this.emit('close', null, 'network');
  2066. this.removeAllListeners();
  2067. };
  2068. JsonpReceiver.prototype._abort = function(err) {
  2069. debug('_abort', err);
  2070. this._cleanup();
  2071. this.aborting = true;
  2072. this.emit('close', err.code, err.message);
  2073. this.removeAllListeners();
  2074. };
  2075. JsonpReceiver.prototype._cleanup = function() {
  2076. debug('_cleanup');
  2077. clearTimeout(this.timeoutId);
  2078. if (this.script2) {
  2079. this.script2.parentNode.removeChild(this.script2);
  2080. this.script2 = null;
  2081. }
  2082. if (this.script) {
  2083. var script = this.script;
  2084. // Unfortunately, you can't really abort script loading of
  2085. // the script.
  2086. script.parentNode.removeChild(script);
  2087. script.onreadystatechange = script.onerror =
  2088. script.onload = script.onclick = null;
  2089. this.script = null;
  2090. }
  2091. delete global[utils.WPrefix][this.id];
  2092. };
  2093. JsonpReceiver.prototype._scriptError = function() {
  2094. debug('_scriptError');
  2095. var self = this;
  2096. if (this.errorTimer) {
  2097. return;
  2098. }
  2099. this.errorTimer = setTimeout(function() {
  2100. if (!self.loadedOkay) {
  2101. self._abort(new Error('JSONP script loaded abnormally (onerror)'));
  2102. }
  2103. }, JsonpReceiver.scriptErrorTimeout);
  2104. };
  2105. JsonpReceiver.prototype._createScript = function(url) {
  2106. debug('_createScript', url);
  2107. var self = this;
  2108. var script = this.script = global.document.createElement('script');
  2109. var script2; // Opera synchronous load trick.
  2110. script.id = 'a' + random.string(8);
  2111. script.src = url;
  2112. script.type = 'text/javascript';
  2113. script.charset = 'UTF-8';
  2114. script.onerror = this._scriptError.bind(this);
  2115. script.onload = function() {
  2116. debug('onload');
  2117. self._abort(new Error('JSONP script loaded abnormally (onload)'));
  2118. };
  2119. // IE9 fires 'error' event after onreadystatechange or before, in random order.
  2120. // Use loadedOkay to determine if actually errored
  2121. script.onreadystatechange = function() {
  2122. debug('onreadystatechange', script.readyState);
  2123. if (/loaded|closed/.test(script.readyState)) {
  2124. if (script && script.htmlFor && script.onclick) {
  2125. self.loadedOkay = true;
  2126. try {
  2127. // In IE, actually execute the script.
  2128. script.onclick();
  2129. } catch (x) {
  2130. // intentionally empty
  2131. }
  2132. }
  2133. if (script) {
  2134. self._abort(new Error('JSONP script loaded abnormally (onreadystatechange)'));
  2135. }
  2136. }
  2137. };
  2138. // IE: event/htmlFor/onclick trick.
  2139. // One can't rely on proper order for onreadystatechange. In order to
  2140. // make sure, set a 'htmlFor' and 'event' properties, so that
  2141. // script code will be installed as 'onclick' handler for the
  2142. // script object. Later, onreadystatechange, manually execute this
  2143. // code. FF and Chrome doesn't work with 'event' and 'htmlFor'
  2144. // set. For reference see:
  2145. // http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
  2146. // Also, read on that about script ordering:
  2147. // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
  2148. if (typeof script.async === 'undefined' && global.document.attachEvent) {
  2149. // According to mozilla docs, in recent browsers script.async defaults
  2150. // to 'true', so we may use it to detect a good browser:
  2151. // https://developer.mozilla.org/en/HTML/Element/script
  2152. if (!browser.isOpera()) {
  2153. // Naively assume we're in IE
  2154. try {
  2155. script.htmlFor = script.id;
  2156. script.event = 'onclick';
  2157. } catch (x) {
  2158. // intentionally empty
  2159. }
  2160. script.async = true;
  2161. } else {
  2162. // Opera, second sync script hack
  2163. script2 = this.script2 = global.document.createElement('script');
  2164. script2.text = "try{var a = document.getElementById('" + script.id + "'); if(a)a.onerror();}catch(x){};";
  2165. script.async = script2.async = false;
  2166. }
  2167. }
  2168. if (typeof script.async !== 'undefined') {
  2169. script.async = true;
  2170. }
  2171. var head = global.document.getElementsByTagName('head')[0];
  2172. head.insertBefore(script, head.firstChild);
  2173. if (script2) {
  2174. head.insertBefore(script2, head.firstChild);
  2175. }
  2176. };
  2177. module.exports = JsonpReceiver;
  2178. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2179. },{"../../utils/browser":44,"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],32:[function(require,module,exports){
  2180. (function (process){
  2181. 'use strict';
  2182. var inherits = require('inherits')
  2183. , EventEmitter = require('events').EventEmitter
  2184. ;
  2185. var debug = function() {};
  2186. if (process.env.NODE_ENV !== 'production') {
  2187. debug = require('debug')('sockjs-client:receiver:xhr');
  2188. }
  2189. function XhrReceiver(url, AjaxObject) {
  2190. debug(url);
  2191. EventEmitter.call(this);
  2192. var self = this;
  2193. this.bufferPosition = 0;
  2194. this.xo = new AjaxObject('POST', url, null);
  2195. this.xo.on('chunk', this._chunkHandler.bind(this));
  2196. this.xo.once('finish', function(status, text) {
  2197. debug('finish', status, text);
  2198. self._chunkHandler(status, text);
  2199. self.xo = null;
  2200. var reason = status === 200 ? 'network' : 'permanent';
  2201. debug('close', reason);
  2202. self.emit('close', null, reason);
  2203. self._cleanup();
  2204. });
  2205. }
  2206. inherits(XhrReceiver, EventEmitter);
  2207. XhrReceiver.prototype._chunkHandler = function(status, text) {
  2208. debug('_chunkHandler', status);
  2209. if (status !== 200 || !text) {
  2210. return;
  2211. }
  2212. for (var idx = -1; ; this.bufferPosition += idx + 1) {
  2213. var buf = text.slice(this.bufferPosition);
  2214. idx = buf.indexOf('\n');
  2215. if (idx === -1) {
  2216. break;
  2217. }
  2218. var msg = buf.slice(0, idx);
  2219. if (msg) {
  2220. debug('message', msg);
  2221. this.emit('message', msg);
  2222. }
  2223. }
  2224. };
  2225. XhrReceiver.prototype._cleanup = function() {
  2226. debug('_cleanup');
  2227. this.removeAllListeners();
  2228. };
  2229. XhrReceiver.prototype.abort = function() {
  2230. debug('abort');
  2231. if (this.xo) {
  2232. this.xo.close();
  2233. debug('close');
  2234. this.emit('close', null, 'user');
  2235. this.xo = null;
  2236. }
  2237. this._cleanup();
  2238. };
  2239. module.exports = XhrReceiver;
  2240. }).call(this,{ env: {} })
  2241. },{"debug":55,"events":3,"inherits":57}],33:[function(require,module,exports){
  2242. (function (process,global){
  2243. 'use strict';
  2244. var random = require('../../utils/random')
  2245. , urlUtils = require('../../utils/url')
  2246. ;
  2247. var debug = function() {};
  2248. if (process.env.NODE_ENV !== 'production') {
  2249. debug = require('debug')('sockjs-client:sender:jsonp');
  2250. }
  2251. var form, area;
  2252. function createIframe(id) {
  2253. debug('createIframe', id);
  2254. try {
  2255. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2256. return global.document.createElement('<iframe name="' + id + '">');
  2257. } catch (x) {
  2258. var iframe = global.document.createElement('iframe');
  2259. iframe.name = id;
  2260. return iframe;
  2261. }
  2262. }
  2263. function createForm() {
  2264. debug('createForm');
  2265. form = global.document.createElement('form');
  2266. form.style.display = 'none';
  2267. form.style.position = 'absolute';
  2268. form.method = 'POST';
  2269. form.enctype = 'application/x-www-form-urlencoded';
  2270. form.acceptCharset = 'UTF-8';
  2271. area = global.document.createElement('textarea');
  2272. area.name = 'd';
  2273. form.appendChild(area);
  2274. global.document.body.appendChild(form);
  2275. }
  2276. module.exports = function(url, payload, callback) {
  2277. debug(url, payload);
  2278. if (!form) {
  2279. createForm();
  2280. }
  2281. var id = 'a' + random.string(8);
  2282. form.target = id;
  2283. form.action = urlUtils.addQuery(urlUtils.addPath(url, '/jsonp_send'), 'i=' + id);
  2284. var iframe = createIframe(id);
  2285. iframe.id = id;
  2286. iframe.style.display = 'none';
  2287. form.appendChild(iframe);
  2288. try {
  2289. area.value = payload;
  2290. } catch (e) {
  2291. // seriously broken browsers get here
  2292. }
  2293. form.submit();
  2294. var completed = function(err) {
  2295. debug('completed', id, err);
  2296. if (!iframe.onerror) {
  2297. return;
  2298. }
  2299. iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
  2300. // Opera mini doesn't like if we GC iframe
  2301. // immediately, thus this timeout.
  2302. setTimeout(function() {
  2303. debug('cleaning up', id);
  2304. iframe.parentNode.removeChild(iframe);
  2305. iframe = null;
  2306. }, 500);
  2307. area.value = '';
  2308. // It is not possible to detect if the iframe succeeded or
  2309. // failed to submit our form.
  2310. callback(err);
  2311. };
  2312. iframe.onerror = function() {
  2313. debug('onerror', id);
  2314. completed();
  2315. };
  2316. iframe.onload = function() {
  2317. debug('onload', id);
  2318. completed();
  2319. };
  2320. iframe.onreadystatechange = function(e) {
  2321. debug('onreadystatechange', id, iframe.readyState, e);
  2322. if (iframe.readyState === 'complete') {
  2323. completed();
  2324. }
  2325. };
  2326. return function() {
  2327. debug('aborted', id);
  2328. completed(new Error('Aborted'));
  2329. };
  2330. };
  2331. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2332. },{"../../utils/random":50,"../../utils/url":52,"debug":55}],34:[function(require,module,exports){
  2333. (function (process,global){
  2334. 'use strict';
  2335. var EventEmitter = require('events').EventEmitter
  2336. , inherits = require('inherits')
  2337. , eventUtils = require('../../utils/event')
  2338. , browser = require('../../utils/browser')
  2339. , urlUtils = require('../../utils/url')
  2340. ;
  2341. var debug = function() {};
  2342. if (process.env.NODE_ENV !== 'production') {
  2343. debug = require('debug')('sockjs-client:sender:xdr');
  2344. }
  2345. // References:
  2346. // http://ajaxian.com/archives/100-line-ajax-wrapper
  2347. // http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx
  2348. function XDRObject(method, url, payload) {
  2349. debug(method, url);
  2350. var self = this;
  2351. EventEmitter.call(this);
  2352. setTimeout(function() {
  2353. self._start(method, url, payload);
  2354. }, 0);
  2355. }
  2356. inherits(XDRObject, EventEmitter);
  2357. XDRObject.prototype._start = function(method, url, payload) {
  2358. debug('_start');
  2359. var self = this;
  2360. var xdr = new global.XDomainRequest();
  2361. // IE caches even POSTs
  2362. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  2363. xdr.onerror = function() {
  2364. debug('onerror');
  2365. self._error();
  2366. };
  2367. xdr.ontimeout = function() {
  2368. debug('ontimeout');
  2369. self._error();
  2370. };
  2371. xdr.onprogress = function() {
  2372. debug('progress', xdr.responseText);
  2373. self.emit('chunk', 200, xdr.responseText);
  2374. };
  2375. xdr.onload = function() {
  2376. debug('load');
  2377. self.emit('finish', 200, xdr.responseText);
  2378. self._cleanup(false);
  2379. };
  2380. this.xdr = xdr;
  2381. this.unloadRef = eventUtils.unloadAdd(function() {
  2382. self._cleanup(true);
  2383. });
  2384. try {
  2385. // Fails with AccessDenied if port number is bogus
  2386. this.xdr.open(method, url);
  2387. if (this.timeout) {
  2388. this.xdr.timeout = this.timeout;
  2389. }
  2390. this.xdr.send(payload);
  2391. } catch (x) {
  2392. this._error();
  2393. }
  2394. };
  2395. XDRObject.prototype._error = function() {
  2396. this.emit('finish', 0, '');
  2397. this._cleanup(false);
  2398. };
  2399. XDRObject.prototype._cleanup = function(abort) {
  2400. debug('cleanup', abort);
  2401. if (!this.xdr) {
  2402. return;
  2403. }
  2404. this.removeAllListeners();
  2405. eventUtils.unloadDel(this.unloadRef);
  2406. this.xdr.ontimeout = this.xdr.onerror = this.xdr.onprogress = this.xdr.onload = null;
  2407. if (abort) {
  2408. try {
  2409. this.xdr.abort();
  2410. } catch (x) {
  2411. // intentionally empty
  2412. }
  2413. }
  2414. this.unloadRef = this.xdr = null;
  2415. };
  2416. XDRObject.prototype.close = function() {
  2417. debug('close');
  2418. this._cleanup(true);
  2419. };
  2420. // IE 8/9 if the request target uses the same scheme - #79
  2421. XDRObject.enabled = !!(global.XDomainRequest && browser.hasDomain());
  2422. module.exports = XDRObject;
  2423. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2424. },{"../../utils/browser":44,"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],35:[function(require,module,exports){
  2425. 'use strict';
  2426. var inherits = require('inherits')
  2427. , XhrDriver = require('../driver/xhr')
  2428. ;
  2429. function XHRCorsObject(method, url, payload, opts) {
  2430. XhrDriver.call(this, method, url, payload, opts);
  2431. }
  2432. inherits(XHRCorsObject, XhrDriver);
  2433. XHRCorsObject.enabled = XhrDriver.enabled && XhrDriver.supportsCORS;
  2434. module.exports = XHRCorsObject;
  2435. },{"../driver/xhr":17,"inherits":57}],36:[function(require,module,exports){
  2436. 'use strict';
  2437. var EventEmitter = require('events').EventEmitter
  2438. , inherits = require('inherits')
  2439. ;
  2440. function XHRFake(/* method, url, payload, opts */) {
  2441. var self = this;
  2442. EventEmitter.call(this);
  2443. this.to = setTimeout(function() {
  2444. self.emit('finish', 200, '{}');
  2445. }, XHRFake.timeout);
  2446. }
  2447. inherits(XHRFake, EventEmitter);
  2448. XHRFake.prototype.close = function() {
  2449. clearTimeout(this.to);
  2450. };
  2451. XHRFake.timeout = 2000;
  2452. module.exports = XHRFake;
  2453. },{"events":3,"inherits":57}],37:[function(require,module,exports){
  2454. 'use strict';
  2455. var inherits = require('inherits')
  2456. , XhrDriver = require('../driver/xhr')
  2457. ;
  2458. function XHRLocalObject(method, url, payload /*, opts */) {
  2459. XhrDriver.call(this, method, url, payload, {
  2460. noCredentials: true
  2461. });
  2462. }
  2463. inherits(XHRLocalObject, XhrDriver);
  2464. XHRLocalObject.enabled = XhrDriver.enabled;
  2465. module.exports = XHRLocalObject;
  2466. },{"../driver/xhr":17,"inherits":57}],38:[function(require,module,exports){
  2467. (function (process){
  2468. 'use strict';
  2469. var utils = require('../utils/event')
  2470. , urlUtils = require('../utils/url')
  2471. , inherits = require('inherits')
  2472. , EventEmitter = require('events').EventEmitter
  2473. , WebsocketDriver = require('./driver/websocket')
  2474. ;
  2475. var debug = function() {};
  2476. if (process.env.NODE_ENV !== 'production') {
  2477. debug = require('debug')('sockjs-client:websocket');
  2478. }
  2479. function WebSocketTransport(transUrl, ignore, options) {
  2480. if (!WebSocketTransport.enabled()) {
  2481. throw new Error('Transport created when disabled');
  2482. }
  2483. EventEmitter.call(this);
  2484. debug('constructor', transUrl);
  2485. var self = this;
  2486. var url = urlUtils.addPath(transUrl, '/websocket');
  2487. if (url.slice(0, 5) === 'https') {
  2488. url = 'wss' + url.slice(5);
  2489. } else {
  2490. url = 'ws' + url.slice(4);
  2491. }
  2492. this.url = url;
  2493. this.ws = new WebsocketDriver(this.url, [], options);
  2494. this.ws.onmessage = function(e) {
  2495. debug('message event', e.data);
  2496. self.emit('message', e.data);
  2497. };
  2498. // Firefox has an interesting bug. If a websocket connection is
  2499. // created after onunload, it stays alive even when user
  2500. // navigates away from the page. In such situation let's lie -
  2501. // let's not open the ws connection at all. See:
  2502. // https://github.com/sockjs/sockjs-client/issues/28
  2503. // https://bugzilla.mozilla.org/show_bug.cgi?id=696085
  2504. this.unloadRef = utils.unloadAdd(function() {
  2505. debug('unload');
  2506. self.ws.close();
  2507. });
  2508. this.ws.onclose = function(e) {
  2509. debug('close event', e.code, e.reason);
  2510. self.emit('close', e.code, e.reason);
  2511. self._cleanup();
  2512. };
  2513. this.ws.onerror = function(e) {
  2514. debug('error event', e);
  2515. self.emit('close', 1006, 'WebSocket connection broken');
  2516. self._cleanup();
  2517. };
  2518. }
  2519. inherits(WebSocketTransport, EventEmitter);
  2520. WebSocketTransport.prototype.send = function(data) {
  2521. var msg = '[' + data + ']';
  2522. debug('send', msg);
  2523. this.ws.send(msg);
  2524. };
  2525. WebSocketTransport.prototype.close = function() {
  2526. debug('close');
  2527. var ws = this.ws;
  2528. this._cleanup();
  2529. if (ws) {
  2530. ws.close();
  2531. }
  2532. };
  2533. WebSocketTransport.prototype._cleanup = function() {
  2534. debug('_cleanup');
  2535. var ws = this.ws;
  2536. if (ws) {
  2537. ws.onmessage = ws.onclose = ws.onerror = null;
  2538. }
  2539. utils.unloadDel(this.unloadRef);
  2540. this.unloadRef = this.ws = null;
  2541. this.removeAllListeners();
  2542. };
  2543. WebSocketTransport.enabled = function() {
  2544. debug('enabled');
  2545. return !!WebsocketDriver;
  2546. };
  2547. WebSocketTransport.transportName = 'websocket';
  2548. // In theory, ws should require 1 round trip. But in chrome, this is
  2549. // not very stable over SSL. Most likely a ws connection requires a
  2550. // separate SSL connection, in which case 2 round trips are an
  2551. // absolute minumum.
  2552. WebSocketTransport.roundTrips = 2;
  2553. module.exports = WebSocketTransport;
  2554. }).call(this,{ env: {} })
  2555. },{"../utils/event":46,"../utils/url":52,"./driver/websocket":19,"debug":55,"events":3,"inherits":57}],39:[function(require,module,exports){
  2556. 'use strict';
  2557. var inherits = require('inherits')
  2558. , AjaxBasedTransport = require('./lib/ajax-based')
  2559. , XdrStreamingTransport = require('./xdr-streaming')
  2560. , XhrReceiver = require('./receiver/xhr')
  2561. , XDRObject = require('./sender/xdr')
  2562. ;
  2563. function XdrPollingTransport(transUrl) {
  2564. if (!XDRObject.enabled) {
  2565. throw new Error('Transport created when disabled');
  2566. }
  2567. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XDRObject);
  2568. }
  2569. inherits(XdrPollingTransport, AjaxBasedTransport);
  2570. XdrPollingTransport.enabled = XdrStreamingTransport.enabled;
  2571. XdrPollingTransport.transportName = 'xdr-polling';
  2572. XdrPollingTransport.roundTrips = 2; // preflight, ajax
  2573. module.exports = XdrPollingTransport;
  2574. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"./xdr-streaming":40,"inherits":57}],40:[function(require,module,exports){
  2575. 'use strict';
  2576. var inherits = require('inherits')
  2577. , AjaxBasedTransport = require('./lib/ajax-based')
  2578. , XhrReceiver = require('./receiver/xhr')
  2579. , XDRObject = require('./sender/xdr')
  2580. ;
  2581. // According to:
  2582. // http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests
  2583. // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
  2584. function XdrStreamingTransport(transUrl) {
  2585. if (!XDRObject.enabled) {
  2586. throw new Error('Transport created when disabled');
  2587. }
  2588. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XDRObject);
  2589. }
  2590. inherits(XdrStreamingTransport, AjaxBasedTransport);
  2591. XdrStreamingTransport.enabled = function(info) {
  2592. if (info.cookie_needed || info.nullOrigin) {
  2593. return false;
  2594. }
  2595. return XDRObject.enabled && info.sameScheme;
  2596. };
  2597. XdrStreamingTransport.transportName = 'xdr-streaming';
  2598. XdrStreamingTransport.roundTrips = 2; // preflight, ajax
  2599. module.exports = XdrStreamingTransport;
  2600. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"inherits":57}],41:[function(require,module,exports){
  2601. 'use strict';
  2602. var inherits = require('inherits')
  2603. , AjaxBasedTransport = require('./lib/ajax-based')
  2604. , XhrReceiver = require('./receiver/xhr')
  2605. , XHRCorsObject = require('./sender/xhr-cors')
  2606. , XHRLocalObject = require('./sender/xhr-local')
  2607. ;
  2608. function XhrPollingTransport(transUrl) {
  2609. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2610. throw new Error('Transport created when disabled');
  2611. }
  2612. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XHRCorsObject);
  2613. }
  2614. inherits(XhrPollingTransport, AjaxBasedTransport);
  2615. XhrPollingTransport.enabled = function(info) {
  2616. if (info.nullOrigin) {
  2617. return false;
  2618. }
  2619. if (XHRLocalObject.enabled && info.sameOrigin) {
  2620. return true;
  2621. }
  2622. return XHRCorsObject.enabled;
  2623. };
  2624. XhrPollingTransport.transportName = 'xhr-polling';
  2625. XhrPollingTransport.roundTrips = 2; // preflight, ajax
  2626. module.exports = XhrPollingTransport;
  2627. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],42:[function(require,module,exports){
  2628. (function (global){
  2629. 'use strict';
  2630. var inherits = require('inherits')
  2631. , AjaxBasedTransport = require('./lib/ajax-based')
  2632. , XhrReceiver = require('./receiver/xhr')
  2633. , XHRCorsObject = require('./sender/xhr-cors')
  2634. , XHRLocalObject = require('./sender/xhr-local')
  2635. , browser = require('../utils/browser')
  2636. ;
  2637. function XhrStreamingTransport(transUrl) {
  2638. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2639. throw new Error('Transport created when disabled');
  2640. }
  2641. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XHRCorsObject);
  2642. }
  2643. inherits(XhrStreamingTransport, AjaxBasedTransport);
  2644. XhrStreamingTransport.enabled = function(info) {
  2645. if (info.nullOrigin) {
  2646. return false;
  2647. }
  2648. // Opera doesn't support xhr-streaming #60
  2649. // But it might be able to #92
  2650. if (browser.isOpera()) {
  2651. return false;
  2652. }
  2653. return XHRCorsObject.enabled;
  2654. };
  2655. XhrStreamingTransport.transportName = 'xhr-streaming';
  2656. XhrStreamingTransport.roundTrips = 2; // preflight, ajax
  2657. // Safari gets confused when a streaming ajax request is started
  2658. // before onload. This causes the load indicator to spin indefinetely.
  2659. // Only require body when used in a browser
  2660. XhrStreamingTransport.needBody = !!global.document;
  2661. module.exports = XhrStreamingTransport;
  2662. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2663. },{"../utils/browser":44,"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],43:[function(require,module,exports){
  2664. (function (global){
  2665. 'use strict';
  2666. if (global.crypto && global.crypto.getRandomValues) {
  2667. module.exports.randomBytes = function(length) {
  2668. var bytes = new Uint8Array(length);
  2669. global.crypto.getRandomValues(bytes);
  2670. return bytes;
  2671. };
  2672. } else {
  2673. module.exports.randomBytes = function(length) {
  2674. var bytes = new Array(length);
  2675. for (var i = 0; i < length; i++) {
  2676. bytes[i] = Math.floor(Math.random() * 256);
  2677. }
  2678. return bytes;
  2679. };
  2680. }
  2681. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2682. },{}],44:[function(require,module,exports){
  2683. (function (global){
  2684. 'use strict';
  2685. module.exports = {
  2686. isOpera: function() {
  2687. return global.navigator &&
  2688. /opera/i.test(global.navigator.userAgent);
  2689. }
  2690. , isKonqueror: function() {
  2691. return global.navigator &&
  2692. /konqueror/i.test(global.navigator.userAgent);
  2693. }
  2694. // #187 wrap document.domain in try/catch because of WP8 from file:///
  2695. , hasDomain: function () {
  2696. // non-browser client always has a domain
  2697. if (!global.document) {
  2698. return true;
  2699. }
  2700. try {
  2701. return !!global.document.domain;
  2702. } catch (e) {
  2703. return false;
  2704. }
  2705. }
  2706. };
  2707. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2708. },{}],45:[function(require,module,exports){
  2709. 'use strict';
  2710. var JSON3 = require('json3');
  2711. // Some extra characters that Chrome gets wrong, and substitutes with
  2712. // something else on the wire.
  2713. // eslint-disable-next-line no-control-regex, no-misleading-character-class
  2714. var extraEscapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g
  2715. , extraLookup;
  2716. // This may be quite slow, so let's delay until user actually uses bad
  2717. // characters.
  2718. var unrollLookup = function(escapable) {
  2719. var i;
  2720. var unrolled = {};
  2721. var c = [];
  2722. for (i = 0; i < 65536; i++) {
  2723. c.push( String.fromCharCode(i) );
  2724. }
  2725. escapable.lastIndex = 0;
  2726. c.join('').replace(escapable, function(a) {
  2727. unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  2728. return '';
  2729. });
  2730. escapable.lastIndex = 0;
  2731. return unrolled;
  2732. };
  2733. // Quote string, also taking care of unicode characters that browsers
  2734. // often break. Especially, take care of unicode surrogates:
  2735. // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
  2736. module.exports = {
  2737. quote: function(string) {
  2738. var quoted = JSON3.stringify(string);
  2739. // In most cases this should be very fast and good enough.
  2740. extraEscapable.lastIndex = 0;
  2741. if (!extraEscapable.test(quoted)) {
  2742. return quoted;
  2743. }
  2744. if (!extraLookup) {
  2745. extraLookup = unrollLookup(extraEscapable);
  2746. }
  2747. return quoted.replace(extraEscapable, function(a) {
  2748. return extraLookup[a];
  2749. });
  2750. }
  2751. };
  2752. },{"json3":58}],46:[function(require,module,exports){
  2753. (function (global){
  2754. 'use strict';
  2755. var random = require('./random');
  2756. var onUnload = {}
  2757. , afterUnload = false
  2758. // detect google chrome packaged apps because they don't allow the 'unload' event
  2759. , isChromePackagedApp = global.chrome && global.chrome.app && global.chrome.app.runtime
  2760. ;
  2761. module.exports = {
  2762. attachEvent: function(event, listener) {
  2763. if (typeof global.addEventListener !== 'undefined') {
  2764. global.addEventListener(event, listener, false);
  2765. } else if (global.document && global.attachEvent) {
  2766. // IE quirks.
  2767. // According to: http://stevesouders.com/misc/test-postmessage.php
  2768. // the message gets delivered only to 'document', not 'window'.
  2769. global.document.attachEvent('on' + event, listener);
  2770. // I get 'window' for ie8.
  2771. global.attachEvent('on' + event, listener);
  2772. }
  2773. }
  2774. , detachEvent: function(event, listener) {
  2775. if (typeof global.addEventListener !== 'undefined') {
  2776. global.removeEventListener(event, listener, false);
  2777. } else if (global.document && global.detachEvent) {
  2778. global.document.detachEvent('on' + event, listener);
  2779. global.detachEvent('on' + event, listener);
  2780. }
  2781. }
  2782. , unloadAdd: function(listener) {
  2783. if (isChromePackagedApp) {
  2784. return null;
  2785. }
  2786. var ref = random.string(8);
  2787. onUnload[ref] = listener;
  2788. if (afterUnload) {
  2789. setTimeout(this.triggerUnloadCallbacks, 0);
  2790. }
  2791. return ref;
  2792. }
  2793. , unloadDel: function(ref) {
  2794. if (ref in onUnload) {
  2795. delete onUnload[ref];
  2796. }
  2797. }
  2798. , triggerUnloadCallbacks: function() {
  2799. for (var ref in onUnload) {
  2800. onUnload[ref]();
  2801. delete onUnload[ref];
  2802. }
  2803. }
  2804. };
  2805. var unloadTriggered = function() {
  2806. if (afterUnload) {
  2807. return;
  2808. }
  2809. afterUnload = true;
  2810. module.exports.triggerUnloadCallbacks();
  2811. };
  2812. // 'unload' alone is not reliable in opera within an iframe, but we
  2813. // can't use `beforeunload` as IE fires it on javascript: links.
  2814. if (!isChromePackagedApp) {
  2815. module.exports.attachEvent('unload', unloadTriggered);
  2816. }
  2817. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2818. },{"./random":50}],47:[function(require,module,exports){
  2819. (function (process,global){
  2820. 'use strict';
  2821. var eventUtils = require('./event')
  2822. , JSON3 = require('json3')
  2823. , browser = require('./browser')
  2824. ;
  2825. var debug = function() {};
  2826. if (process.env.NODE_ENV !== 'production') {
  2827. debug = require('debug')('sockjs-client:utils:iframe');
  2828. }
  2829. module.exports = {
  2830. WPrefix: '_jp'
  2831. , currentWindowId: null
  2832. , polluteGlobalNamespace: function() {
  2833. if (!(module.exports.WPrefix in global)) {
  2834. global[module.exports.WPrefix] = {};
  2835. }
  2836. }
  2837. , postMessage: function(type, data) {
  2838. if (global.parent !== global) {
  2839. global.parent.postMessage(JSON3.stringify({
  2840. windowId: module.exports.currentWindowId
  2841. , type: type
  2842. , data: data || ''
  2843. }), '*');
  2844. } else {
  2845. debug('Cannot postMessage, no parent window.', type, data);
  2846. }
  2847. }
  2848. , createIframe: function(iframeUrl, errorCallback) {
  2849. var iframe = global.document.createElement('iframe');
  2850. var tref, unloadRef;
  2851. var unattach = function() {
  2852. debug('unattach');
  2853. clearTimeout(tref);
  2854. // Explorer had problems with that.
  2855. try {
  2856. iframe.onload = null;
  2857. } catch (x) {
  2858. // intentionally empty
  2859. }
  2860. iframe.onerror = null;
  2861. };
  2862. var cleanup = function() {
  2863. debug('cleanup');
  2864. if (iframe) {
  2865. unattach();
  2866. // This timeout makes chrome fire onbeforeunload event
  2867. // within iframe. Without the timeout it goes straight to
  2868. // onunload.
  2869. setTimeout(function() {
  2870. if (iframe) {
  2871. iframe.parentNode.removeChild(iframe);
  2872. }
  2873. iframe = null;
  2874. }, 0);
  2875. eventUtils.unloadDel(unloadRef);
  2876. }
  2877. };
  2878. var onerror = function(err) {
  2879. debug('onerror', err);
  2880. if (iframe) {
  2881. cleanup();
  2882. errorCallback(err);
  2883. }
  2884. };
  2885. var post = function(msg, origin) {
  2886. debug('post', msg, origin);
  2887. setTimeout(function() {
  2888. try {
  2889. // When the iframe is not loaded, IE raises an exception
  2890. // on 'contentWindow'.
  2891. if (iframe && iframe.contentWindow) {
  2892. iframe.contentWindow.postMessage(msg, origin);
  2893. }
  2894. } catch (x) {
  2895. // intentionally empty
  2896. }
  2897. }, 0);
  2898. };
  2899. iframe.src = iframeUrl;
  2900. iframe.style.display = 'none';
  2901. iframe.style.position = 'absolute';
  2902. iframe.onerror = function() {
  2903. onerror('onerror');
  2904. };
  2905. iframe.onload = function() {
  2906. debug('onload');
  2907. // `onload` is triggered before scripts on the iframe are
  2908. // executed. Give it few seconds to actually load stuff.
  2909. clearTimeout(tref);
  2910. tref = setTimeout(function() {
  2911. onerror('onload timeout');
  2912. }, 2000);
  2913. };
  2914. global.document.body.appendChild(iframe);
  2915. tref = setTimeout(function() {
  2916. onerror('timeout');
  2917. }, 15000);
  2918. unloadRef = eventUtils.unloadAdd(cleanup);
  2919. return {
  2920. post: post
  2921. , cleanup: cleanup
  2922. , loaded: unattach
  2923. };
  2924. }
  2925. /* eslint no-undef: "off", new-cap: "off" */
  2926. , createHtmlfile: function(iframeUrl, errorCallback) {
  2927. var axo = ['Active'].concat('Object').join('X');
  2928. var doc = new global[axo]('htmlfile');
  2929. var tref, unloadRef;
  2930. var iframe;
  2931. var unattach = function() {
  2932. clearTimeout(tref);
  2933. iframe.onerror = null;
  2934. };
  2935. var cleanup = function() {
  2936. if (doc) {
  2937. unattach();
  2938. eventUtils.unloadDel(unloadRef);
  2939. iframe.parentNode.removeChild(iframe);
  2940. iframe = doc = null;
  2941. CollectGarbage();
  2942. }
  2943. };
  2944. var onerror = function(r) {
  2945. debug('onerror', r);
  2946. if (doc) {
  2947. cleanup();
  2948. errorCallback(r);
  2949. }
  2950. };
  2951. var post = function(msg, origin) {
  2952. try {
  2953. // When the iframe is not loaded, IE raises an exception
  2954. // on 'contentWindow'.
  2955. setTimeout(function() {
  2956. if (iframe && iframe.contentWindow) {
  2957. iframe.contentWindow.postMessage(msg, origin);
  2958. }
  2959. }, 0);
  2960. } catch (x) {
  2961. // intentionally empty
  2962. }
  2963. };
  2964. doc.open();
  2965. doc.write('<html><s' + 'cript>' +
  2966. 'document.domain="' + global.document.domain + '";' +
  2967. '</s' + 'cript></html>');
  2968. doc.close();
  2969. doc.parentWindow[module.exports.WPrefix] = global[module.exports.WPrefix];
  2970. var c = doc.createElement('div');
  2971. doc.body.appendChild(c);
  2972. iframe = doc.createElement('iframe');
  2973. c.appendChild(iframe);
  2974. iframe.src = iframeUrl;
  2975. iframe.onerror = function() {
  2976. onerror('onerror');
  2977. };
  2978. tref = setTimeout(function() {
  2979. onerror('timeout');
  2980. }, 15000);
  2981. unloadRef = eventUtils.unloadAdd(cleanup);
  2982. return {
  2983. post: post
  2984. , cleanup: cleanup
  2985. , loaded: unattach
  2986. };
  2987. }
  2988. };
  2989. module.exports.iframeEnabled = false;
  2990. if (global.document) {
  2991. // postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with
  2992. // huge delay, or not at all.
  2993. module.exports.iframeEnabled = (typeof global.postMessage === 'function' ||
  2994. typeof global.postMessage === 'object') && (!browser.isKonqueror());
  2995. }
  2996. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2997. },{"./browser":44,"./event":46,"debug":55,"json3":58}],48:[function(require,module,exports){
  2998. (function (global){
  2999. 'use strict';
  3000. var logObject = {};
  3001. ['log', 'debug', 'warn'].forEach(function (level) {
  3002. var levelExists;
  3003. try {
  3004. levelExists = global.console && global.console[level] && global.console[level].apply;
  3005. } catch(e) {
  3006. // do nothing
  3007. }
  3008. logObject[level] = levelExists ? function () {
  3009. return global.console[level].apply(global.console, arguments);
  3010. } : (level === 'log' ? function () {} : logObject.log);
  3011. });
  3012. module.exports = logObject;
  3013. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3014. },{}],49:[function(require,module,exports){
  3015. 'use strict';
  3016. module.exports = {
  3017. isObject: function(obj) {
  3018. var type = typeof obj;
  3019. return type === 'function' || type === 'object' && !!obj;
  3020. }
  3021. , extend: function(obj) {
  3022. if (!this.isObject(obj)) {
  3023. return obj;
  3024. }
  3025. var source, prop;
  3026. for (var i = 1, length = arguments.length; i < length; i++) {
  3027. source = arguments[i];
  3028. for (prop in source) {
  3029. if (Object.prototype.hasOwnProperty.call(source, prop)) {
  3030. obj[prop] = source[prop];
  3031. }
  3032. }
  3033. }
  3034. return obj;
  3035. }
  3036. };
  3037. },{}],50:[function(require,module,exports){
  3038. 'use strict';
  3039. var crypto = require('crypto');
  3040. // This string has length 32, a power of 2, so the modulus doesn't introduce a
  3041. // bias.
  3042. var _randomStringChars = 'abcdefghijklmnopqrstuvwxyz012345';
  3043. module.exports = {
  3044. string: function(length) {
  3045. var max = _randomStringChars.length;
  3046. var bytes = crypto.randomBytes(length);
  3047. var ret = [];
  3048. for (var i = 0; i < length; i++) {
  3049. ret.push(_randomStringChars.substr(bytes[i] % max, 1));
  3050. }
  3051. return ret.join('');
  3052. }
  3053. , number: function(max) {
  3054. return Math.floor(Math.random() * max);
  3055. }
  3056. , numberString: function(max) {
  3057. var t = ('' + (max - 1)).length;
  3058. var p = new Array(t + 1).join('0');
  3059. return (p + this.number(max)).slice(-t);
  3060. }
  3061. };
  3062. },{"crypto":43}],51:[function(require,module,exports){
  3063. (function (process){
  3064. 'use strict';
  3065. var debug = function() {};
  3066. if (process.env.NODE_ENV !== 'production') {
  3067. debug = require('debug')('sockjs-client:utils:transport');
  3068. }
  3069. module.exports = function(availableTransports) {
  3070. return {
  3071. filterToEnabled: function(transportsWhitelist, info) {
  3072. var transports = {
  3073. main: []
  3074. , facade: []
  3075. };
  3076. if (!transportsWhitelist) {
  3077. transportsWhitelist = [];
  3078. } else if (typeof transportsWhitelist === 'string') {
  3079. transportsWhitelist = [transportsWhitelist];
  3080. }
  3081. availableTransports.forEach(function(trans) {
  3082. if (!trans) {
  3083. return;
  3084. }
  3085. if (trans.transportName === 'websocket' && info.websocket === false) {
  3086. debug('disabled from server', 'websocket');
  3087. return;
  3088. }
  3089. if (transportsWhitelist.length &&
  3090. transportsWhitelist.indexOf(trans.transportName) === -1) {
  3091. debug('not in whitelist', trans.transportName);
  3092. return;
  3093. }
  3094. if (trans.enabled(info)) {
  3095. debug('enabled', trans.transportName);
  3096. transports.main.push(trans);
  3097. if (trans.facadeTransport) {
  3098. transports.facade.push(trans.facadeTransport);
  3099. }
  3100. } else {
  3101. debug('disabled', trans.transportName);
  3102. }
  3103. });
  3104. return transports;
  3105. }
  3106. };
  3107. };
  3108. }).call(this,{ env: {} })
  3109. },{"debug":55}],52:[function(require,module,exports){
  3110. (function (process){
  3111. 'use strict';
  3112. var URL = require('url-parse');
  3113. var debug = function() {};
  3114. if (process.env.NODE_ENV !== 'production') {
  3115. debug = require('debug')('sockjs-client:utils:url');
  3116. }
  3117. module.exports = {
  3118. getOrigin: function(url) {
  3119. if (!url) {
  3120. return null;
  3121. }
  3122. var p = new URL(url);
  3123. if (p.protocol === 'file:') {
  3124. return null;
  3125. }
  3126. var port = p.port;
  3127. if (!port) {
  3128. port = (p.protocol === 'https:') ? '443' : '80';
  3129. }
  3130. return p.protocol + '//' + p.hostname + ':' + port;
  3131. }
  3132. , isOriginEqual: function(a, b) {
  3133. var res = this.getOrigin(a) === this.getOrigin(b);
  3134. debug('same', a, b, res);
  3135. return res;
  3136. }
  3137. , isSchemeEqual: function(a, b) {
  3138. return (a.split(':')[0] === b.split(':')[0]);
  3139. }
  3140. , addPath: function (url, path) {
  3141. var qs = url.split('?');
  3142. return qs[0] + path + (qs[1] ? '?' + qs[1] : '');
  3143. }
  3144. , addQuery: function (url, q) {
  3145. return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q));
  3146. }
  3147. , isLoopbackAddr: function (addr) {
  3148. return /^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^\[::1\]$/.test(addr);
  3149. }
  3150. };
  3151. }).call(this,{ env: {} })
  3152. },{"debug":55,"url-parse":61}],53:[function(require,module,exports){
  3153. module.exports = '1.5.1';
  3154. },{}],54:[function(require,module,exports){
  3155. /**
  3156. * Helpers.
  3157. */
  3158. var s = 1000;
  3159. var m = s * 60;
  3160. var h = m * 60;
  3161. var d = h * 24;
  3162. var w = d * 7;
  3163. var y = d * 365.25;
  3164. /**
  3165. * Parse or format the given `val`.
  3166. *
  3167. * Options:
  3168. *
  3169. * - `long` verbose formatting [false]
  3170. *
  3171. * @param {String|Number} val
  3172. * @param {Object} [options]
  3173. * @throws {Error} throw an error if val is not a non-empty string or a number
  3174. * @return {String|Number}
  3175. * @api public
  3176. */
  3177. module.exports = function(val, options) {
  3178. options = options || {};
  3179. var type = typeof val;
  3180. if (type === 'string' && val.length > 0) {
  3181. return parse(val);
  3182. } else if (type === 'number' && isFinite(val)) {
  3183. return options.long ? fmtLong(val) : fmtShort(val);
  3184. }
  3185. throw new Error(
  3186. 'val is not a non-empty string or a valid number. val=' +
  3187. JSON.stringify(val)
  3188. );
  3189. };
  3190. /**
  3191. * Parse the given `str` and return milliseconds.
  3192. *
  3193. * @param {String} str
  3194. * @return {Number}
  3195. * @api private
  3196. */
  3197. function parse(str) {
  3198. str = String(str);
  3199. if (str.length > 100) {
  3200. return;
  3201. }
  3202. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  3203. str
  3204. );
  3205. if (!match) {
  3206. return;
  3207. }
  3208. var n = parseFloat(match[1]);
  3209. var type = (match[2] || 'ms').toLowerCase();
  3210. switch (type) {
  3211. case 'years':
  3212. case 'year':
  3213. case 'yrs':
  3214. case 'yr':
  3215. case 'y':
  3216. return n * y;
  3217. case 'weeks':
  3218. case 'week':
  3219. case 'w':
  3220. return n * w;
  3221. case 'days':
  3222. case 'day':
  3223. case 'd':
  3224. return n * d;
  3225. case 'hours':
  3226. case 'hour':
  3227. case 'hrs':
  3228. case 'hr':
  3229. case 'h':
  3230. return n * h;
  3231. case 'minutes':
  3232. case 'minute':
  3233. case 'mins':
  3234. case 'min':
  3235. case 'm':
  3236. return n * m;
  3237. case 'seconds':
  3238. case 'second':
  3239. case 'secs':
  3240. case 'sec':
  3241. case 's':
  3242. return n * s;
  3243. case 'milliseconds':
  3244. case 'millisecond':
  3245. case 'msecs':
  3246. case 'msec':
  3247. case 'ms':
  3248. return n;
  3249. default:
  3250. return undefined;
  3251. }
  3252. }
  3253. /**
  3254. * Short format for `ms`.
  3255. *
  3256. * @param {Number} ms
  3257. * @return {String}
  3258. * @api private
  3259. */
  3260. function fmtShort(ms) {
  3261. var msAbs = Math.abs(ms);
  3262. if (msAbs >= d) {
  3263. return Math.round(ms / d) + 'd';
  3264. }
  3265. if (msAbs >= h) {
  3266. return Math.round(ms / h) + 'h';
  3267. }
  3268. if (msAbs >= m) {
  3269. return Math.round(ms / m) + 'm';
  3270. }
  3271. if (msAbs >= s) {
  3272. return Math.round(ms / s) + 's';
  3273. }
  3274. return ms + 'ms';
  3275. }
  3276. /**
  3277. * Long format for `ms`.
  3278. *
  3279. * @param {Number} ms
  3280. * @return {String}
  3281. * @api private
  3282. */
  3283. function fmtLong(ms) {
  3284. var msAbs = Math.abs(ms);
  3285. if (msAbs >= d) {
  3286. return plural(ms, msAbs, d, 'day');
  3287. }
  3288. if (msAbs >= h) {
  3289. return plural(ms, msAbs, h, 'hour');
  3290. }
  3291. if (msAbs >= m) {
  3292. return plural(ms, msAbs, m, 'minute');
  3293. }
  3294. if (msAbs >= s) {
  3295. return plural(ms, msAbs, s, 'second');
  3296. }
  3297. return ms + ' ms';
  3298. }
  3299. /**
  3300. * Pluralization helper.
  3301. */
  3302. function plural(ms, msAbs, n, name) {
  3303. var isPlural = msAbs >= n * 1.5;
  3304. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  3305. }
  3306. },{}],55:[function(require,module,exports){
  3307. (function (process){
  3308. "use strict";
  3309. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  3310. /* eslint-env browser */
  3311. /**
  3312. * This is the web browser implementation of `debug()`.
  3313. */
  3314. exports.log = log;
  3315. exports.formatArgs = formatArgs;
  3316. exports.save = save;
  3317. exports.load = load;
  3318. exports.useColors = useColors;
  3319. exports.storage = localstorage();
  3320. /**
  3321. * Colors.
  3322. */
  3323. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  3324. /**
  3325. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3326. * and the Firebug extension (any Firefox version) are known
  3327. * to support "%c" CSS customizations.
  3328. *
  3329. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3330. */
  3331. // eslint-disable-next-line complexity
  3332. function useColors() {
  3333. // NB: In an Electron preload script, document will be defined but not fully
  3334. // initialized. Since we know we're in Chrome, we'll just detect this case
  3335. // explicitly
  3336. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  3337. return true;
  3338. } // Internet Explorer and Edge do not support colors.
  3339. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  3340. return false;
  3341. } // Is webkit? http://stackoverflow.com/a/16459606/376773
  3342. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  3343. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  3344. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  3345. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3346. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  3347. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  3348. }
  3349. /**
  3350. * Colorize log arguments if enabled.
  3351. *
  3352. * @api public
  3353. */
  3354. function formatArgs(args) {
  3355. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  3356. if (!this.useColors) {
  3357. return;
  3358. }
  3359. var c = 'color: ' + this.color;
  3360. args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
  3361. // arguments passed either before or after the %c, so we need to
  3362. // figure out the correct index to insert the CSS into
  3363. var index = 0;
  3364. var lastC = 0;
  3365. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  3366. if (match === '%%') {
  3367. return;
  3368. }
  3369. index++;
  3370. if (match === '%c') {
  3371. // We only are interested in the *last* %c
  3372. // (the user may have provided their own)
  3373. lastC = index;
  3374. }
  3375. });
  3376. args.splice(lastC, 0, c);
  3377. }
  3378. /**
  3379. * Invokes `console.log()` when available.
  3380. * No-op when `console.log` is not a "function".
  3381. *
  3382. * @api public
  3383. */
  3384. function log() {
  3385. var _console;
  3386. // This hackery is required for IE8/9, where
  3387. // the `console.log` function doesn't have 'apply'
  3388. return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  3389. }
  3390. /**
  3391. * Save `namespaces`.
  3392. *
  3393. * @param {String} namespaces
  3394. * @api private
  3395. */
  3396. function save(namespaces) {
  3397. try {
  3398. if (namespaces) {
  3399. exports.storage.setItem('debug', namespaces);
  3400. } else {
  3401. exports.storage.removeItem('debug');
  3402. }
  3403. } catch (error) {// Swallow
  3404. // XXX (@Qix-) should we be logging these?
  3405. }
  3406. }
  3407. /**
  3408. * Load `namespaces`.
  3409. *
  3410. * @return {String} returns the previously persisted debug modes
  3411. * @api private
  3412. */
  3413. function load() {
  3414. var r;
  3415. try {
  3416. r = exports.storage.getItem('debug');
  3417. } catch (error) {} // Swallow
  3418. // XXX (@Qix-) should we be logging these?
  3419. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  3420. if (!r && typeof process !== 'undefined' && 'env' in process) {
  3421. r = process.env.DEBUG;
  3422. }
  3423. return r;
  3424. }
  3425. /**
  3426. * Localstorage attempts to return the localstorage.
  3427. *
  3428. * This is necessary because safari throws
  3429. * when a user disables cookies/localstorage
  3430. * and you attempt to access it.
  3431. *
  3432. * @return {LocalStorage}
  3433. * @api private
  3434. */
  3435. function localstorage() {
  3436. try {
  3437. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  3438. // The Browser also has localStorage in the global context.
  3439. return localStorage;
  3440. } catch (error) {// Swallow
  3441. // XXX (@Qix-) should we be logging these?
  3442. }
  3443. }
  3444. module.exports = require('./common')(exports);
  3445. var formatters = module.exports.formatters;
  3446. /**
  3447. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3448. */
  3449. formatters.j = function (v) {
  3450. try {
  3451. return JSON.stringify(v);
  3452. } catch (error) {
  3453. return '[UnexpectedJSONParseError]: ' + error.message;
  3454. }
  3455. };
  3456. }).call(this,{ env: {} })
  3457. },{"./common":56}],56:[function(require,module,exports){
  3458. "use strict";
  3459. /**
  3460. * This is the common logic for both the Node.js and web browser
  3461. * implementations of `debug()`.
  3462. */
  3463. function setup(env) {
  3464. createDebug.debug = createDebug;
  3465. createDebug.default = createDebug;
  3466. createDebug.coerce = coerce;
  3467. createDebug.disable = disable;
  3468. createDebug.enable = enable;
  3469. createDebug.enabled = enabled;
  3470. createDebug.humanize = require('ms');
  3471. Object.keys(env).forEach(function (key) {
  3472. createDebug[key] = env[key];
  3473. });
  3474. /**
  3475. * Active `debug` instances.
  3476. */
  3477. createDebug.instances = [];
  3478. /**
  3479. * The currently active debug mode names, and names to skip.
  3480. */
  3481. createDebug.names = [];
  3482. createDebug.skips = [];
  3483. /**
  3484. * Map of special "%n" handling functions, for the debug "format" argument.
  3485. *
  3486. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  3487. */
  3488. createDebug.formatters = {};
  3489. /**
  3490. * Selects a color for a debug namespace
  3491. * @param {String} namespace The namespace string for the for the debug instance to be colored
  3492. * @return {Number|String} An ANSI color code for the given namespace
  3493. * @api private
  3494. */
  3495. function selectColor(namespace) {
  3496. var hash = 0;
  3497. for (var i = 0; i < namespace.length; i++) {
  3498. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  3499. hash |= 0; // Convert to 32bit integer
  3500. }
  3501. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  3502. }
  3503. createDebug.selectColor = selectColor;
  3504. /**
  3505. * Create a debugger with the given `namespace`.
  3506. *
  3507. * @param {String} namespace
  3508. * @return {Function}
  3509. * @api public
  3510. */
  3511. function createDebug(namespace) {
  3512. var prevTime;
  3513. function debug() {
  3514. // Disabled?
  3515. if (!debug.enabled) {
  3516. return;
  3517. }
  3518. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3519. args[_key] = arguments[_key];
  3520. }
  3521. var self = debug; // Set `diff` timestamp
  3522. var curr = Number(new Date());
  3523. var ms = curr - (prevTime || curr);
  3524. self.diff = ms;
  3525. self.prev = prevTime;
  3526. self.curr = curr;
  3527. prevTime = curr;
  3528. args[0] = createDebug.coerce(args[0]);
  3529. if (typeof args[0] !== 'string') {
  3530. // Anything else let's inspect with %O
  3531. args.unshift('%O');
  3532. } // Apply any `formatters` transformations
  3533. var index = 0;
  3534. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  3535. // If we encounter an escaped % then don't increase the array index
  3536. if (match === '%%') {
  3537. return match;
  3538. }
  3539. index++;
  3540. var formatter = createDebug.formatters[format];
  3541. if (typeof formatter === 'function') {
  3542. var val = args[index];
  3543. match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  3544. args.splice(index, 1);
  3545. index--;
  3546. }
  3547. return match;
  3548. }); // Apply env-specific formatting (colors, etc.)
  3549. createDebug.formatArgs.call(self, args);
  3550. var logFn = self.log || createDebug.log;
  3551. logFn.apply(self, args);
  3552. }
  3553. debug.namespace = namespace;
  3554. debug.enabled = createDebug.enabled(namespace);
  3555. debug.useColors = createDebug.useColors();
  3556. debug.color = selectColor(namespace);
  3557. debug.destroy = destroy;
  3558. debug.extend = extend; // Debug.formatArgs = formatArgs;
  3559. // debug.rawLog = rawLog;
  3560. // env-specific initialization logic for debug instances
  3561. if (typeof createDebug.init === 'function') {
  3562. createDebug.init(debug);
  3563. }
  3564. createDebug.instances.push(debug);
  3565. return debug;
  3566. }
  3567. function destroy() {
  3568. var index = createDebug.instances.indexOf(this);
  3569. if (index !== -1) {
  3570. createDebug.instances.splice(index, 1);
  3571. return true;
  3572. }
  3573. return false;
  3574. }
  3575. function extend(namespace, delimiter) {
  3576. return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  3577. }
  3578. /**
  3579. * Enables a debug mode by namespaces. This can include modes
  3580. * separated by a colon and wildcards.
  3581. *
  3582. * @param {String} namespaces
  3583. * @api public
  3584. */
  3585. function enable(namespaces) {
  3586. createDebug.save(namespaces);
  3587. createDebug.names = [];
  3588. createDebug.skips = [];
  3589. var i;
  3590. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  3591. var len = split.length;
  3592. for (i = 0; i < len; i++) {
  3593. if (!split[i]) {
  3594. // ignore empty strings
  3595. continue;
  3596. }
  3597. namespaces = split[i].replace(/\*/g, '.*?');
  3598. if (namespaces[0] === '-') {
  3599. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3600. } else {
  3601. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  3602. }
  3603. }
  3604. for (i = 0; i < createDebug.instances.length; i++) {
  3605. var instance = createDebug.instances[i];
  3606. instance.enabled = createDebug.enabled(instance.namespace);
  3607. }
  3608. }
  3609. /**
  3610. * Disable debug output.
  3611. *
  3612. * @api public
  3613. */
  3614. function disable() {
  3615. createDebug.enable('');
  3616. }
  3617. /**
  3618. * Returns true if the given mode name is enabled, false otherwise.
  3619. *
  3620. * @param {String} name
  3621. * @return {Boolean}
  3622. * @api public
  3623. */
  3624. function enabled(name) {
  3625. if (name[name.length - 1] === '*') {
  3626. return true;
  3627. }
  3628. var i;
  3629. var len;
  3630. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  3631. if (createDebug.skips[i].test(name)) {
  3632. return false;
  3633. }
  3634. }
  3635. for (i = 0, len = createDebug.names.length; i < len; i++) {
  3636. if (createDebug.names[i].test(name)) {
  3637. return true;
  3638. }
  3639. }
  3640. return false;
  3641. }
  3642. /**
  3643. * Coerce `val`.
  3644. *
  3645. * @param {Mixed} val
  3646. * @return {Mixed}
  3647. * @api private
  3648. */
  3649. function coerce(val) {
  3650. if (val instanceof Error) {
  3651. return val.stack || val.message;
  3652. }
  3653. return val;
  3654. }
  3655. createDebug.enable(createDebug.load());
  3656. return createDebug;
  3657. }
  3658. module.exports = setup;
  3659. },{"ms":54}],57:[function(require,module,exports){
  3660. if (typeof Object.create === 'function') {
  3661. // implementation from standard node.js 'util' module
  3662. module.exports = function inherits(ctor, superCtor) {
  3663. if (superCtor) {
  3664. ctor.super_ = superCtor
  3665. ctor.prototype = Object.create(superCtor.prototype, {
  3666. constructor: {
  3667. value: ctor,
  3668. enumerable: false,
  3669. writable: true,
  3670. configurable: true
  3671. }
  3672. })
  3673. }
  3674. };
  3675. } else {
  3676. // old school shim for old browsers
  3677. module.exports = function inherits(ctor, superCtor) {
  3678. if (superCtor) {
  3679. ctor.super_ = superCtor
  3680. var TempCtor = function () {}
  3681. TempCtor.prototype = superCtor.prototype
  3682. ctor.prototype = new TempCtor()
  3683. ctor.prototype.constructor = ctor
  3684. }
  3685. }
  3686. }
  3687. },{}],58:[function(require,module,exports){
  3688. (function (global){
  3689. /*! JSON v3.3.2 | https://bestiejs.github.io/json3 | Copyright 2012-2015, Kit Cambridge, Benjamin Tan | http://kit.mit-license.org */
  3690. ;(function () {
  3691. // Detect the `define` function exposed by asynchronous module loaders. The
  3692. // strict `define` check is necessary for compatibility with `r.js`.
  3693. var isLoader = typeof define === "function" && define.amd;
  3694. // A set of types used to distinguish objects from primitives.
  3695. var objectTypes = {
  3696. "function": true,
  3697. "object": true
  3698. };
  3699. // Detect the `exports` object exposed by CommonJS implementations.
  3700. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  3701. // Use the `global` object exposed by Node (including Browserify via
  3702. // `insert-module-globals`), Narwhal, and Ringo as the default context,
  3703. // and the `window` object in browsers. Rhino exports a `global` function
  3704. // instead.
  3705. var root = objectTypes[typeof window] && window || this,
  3706. freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
  3707. if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
  3708. root = freeGlobal;
  3709. }
  3710. // Public: Initializes JSON 3 using the given `context` object, attaching the
  3711. // `stringify` and `parse` functions to the specified `exports` object.
  3712. function runInContext(context, exports) {
  3713. context || (context = root.Object());
  3714. exports || (exports = root.Object());
  3715. // Native constructor aliases.
  3716. var Number = context.Number || root.Number,
  3717. String = context.String || root.String,
  3718. Object = context.Object || root.Object,
  3719. Date = context.Date || root.Date,
  3720. SyntaxError = context.SyntaxError || root.SyntaxError,
  3721. TypeError = context.TypeError || root.TypeError,
  3722. Math = context.Math || root.Math,
  3723. nativeJSON = context.JSON || root.JSON;
  3724. // Delegate to the native `stringify` and `parse` implementations.
  3725. if (typeof nativeJSON == "object" && nativeJSON) {
  3726. exports.stringify = nativeJSON.stringify;
  3727. exports.parse = nativeJSON.parse;
  3728. }
  3729. // Convenience aliases.
  3730. var objectProto = Object.prototype,
  3731. getClass = objectProto.toString,
  3732. isProperty = objectProto.hasOwnProperty,
  3733. undefined;
  3734. // Internal: Contains `try...catch` logic used by other functions.
  3735. // This prevents other functions from being deoptimized.
  3736. function attempt(func, errorFunc) {
  3737. try {
  3738. func();
  3739. } catch (exception) {
  3740. if (errorFunc) {
  3741. errorFunc();
  3742. }
  3743. }
  3744. }
  3745. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  3746. var isExtended = new Date(-3509827334573292);
  3747. attempt(function () {
  3748. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  3749. // results for certain dates in Opera >= 10.53.
  3750. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  3751. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  3752. });
  3753. // Internal: Determines whether the native `JSON.stringify` and `parse`
  3754. // implementations are spec-compliant. Based on work by Ken Snyder.
  3755. function has(name) {
  3756. if (has[name] != null) {
  3757. // Return cached feature test result.
  3758. return has[name];
  3759. }
  3760. var isSupported;
  3761. if (name == "bug-string-char-index") {
  3762. // IE <= 7 doesn't support accessing string characters using square
  3763. // bracket notation. IE 8 only supports this for primitives.
  3764. isSupported = "a"[0] != "a";
  3765. } else if (name == "json") {
  3766. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  3767. // supported.
  3768. isSupported = has("json-stringify") && has("date-serialization") && has("json-parse");
  3769. } else if (name == "date-serialization") {
  3770. // Indicates whether `Date`s can be serialized accurately by `JSON.stringify`.
  3771. isSupported = has("json-stringify") && isExtended;
  3772. if (isSupported) {
  3773. var stringify = exports.stringify;
  3774. attempt(function () {
  3775. isSupported =
  3776. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  3777. // serialize extended years.
  3778. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  3779. // The milliseconds are optional in ES 5, but required in 5.1.
  3780. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  3781. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  3782. // four-digit years instead of six-digit years. Credits: @Yaffle.
  3783. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  3784. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  3785. // values less than 1000. Credits: @Yaffle.
  3786. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  3787. });
  3788. }
  3789. } else {
  3790. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  3791. // Test `JSON.stringify`.
  3792. if (name == "json-stringify") {
  3793. var stringify = exports.stringify, stringifySupported = typeof stringify == "function";
  3794. if (stringifySupported) {
  3795. // A test function object with a custom `toJSON` method.
  3796. (value = function () {
  3797. return 1;
  3798. }).toJSON = value;
  3799. attempt(function () {
  3800. stringifySupported =
  3801. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  3802. // primitives as object literals.
  3803. stringify(0) === "0" &&
  3804. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  3805. // literals.
  3806. stringify(new Number()) === "0" &&
  3807. stringify(new String()) == '""' &&
  3808. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  3809. // does not define a canonical JSON representation (this applies to
  3810. // objects with `toJSON` properties as well, *unless* they are nested
  3811. // within an object or array).
  3812. stringify(getClass) === undefined &&
  3813. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  3814. // FF 3.1b3 pass this test.
  3815. stringify(undefined) === undefined &&
  3816. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  3817. // respectively, if the value is omitted entirely.
  3818. stringify() === undefined &&
  3819. // FF 3.1b1, 2 throw an error if the given value is not a number,
  3820. // string, array, object, Boolean, or `null` literal. This applies to
  3821. // objects with custom `toJSON` methods as well, unless they are nested
  3822. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  3823. // methods entirely.
  3824. stringify(value) === "1" &&
  3825. stringify([value]) == "[1]" &&
  3826. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  3827. // `"[null]"`.
  3828. stringify([undefined]) == "[null]" &&
  3829. // YUI 3.0.0b1 fails to serialize `null` literals.
  3830. stringify(null) == "null" &&
  3831. // FF 3.1b1, 2 halts serialization if an array contains a function:
  3832. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  3833. // elides non-JSON values from objects and arrays, unless they
  3834. // define custom `toJSON` methods.
  3835. stringify([undefined, getClass, null]) == "[null,null,null]" &&
  3836. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  3837. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  3838. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  3839. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  3840. stringify(null, value) === "1" &&
  3841. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]";
  3842. }, function () {
  3843. stringifySupported = false;
  3844. });
  3845. }
  3846. isSupported = stringifySupported;
  3847. }
  3848. // Test `JSON.parse`.
  3849. if (name == "json-parse") {
  3850. var parse = exports.parse, parseSupported;
  3851. if (typeof parse == "function") {
  3852. attempt(function () {
  3853. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  3854. // Conforming implementations should also coerce the initial argument to
  3855. // a string prior to parsing.
  3856. if (parse("0") === 0 && !parse(false)) {
  3857. // Simple parsing test.
  3858. value = parse(serialized);
  3859. parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  3860. if (parseSupported) {
  3861. attempt(function () {
  3862. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  3863. parseSupported = !parse('"\t"');
  3864. });
  3865. if (parseSupported) {
  3866. attempt(function () {
  3867. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  3868. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  3869. // certain octal literals.
  3870. parseSupported = parse("01") !== 1;
  3871. });
  3872. }
  3873. if (parseSupported) {
  3874. attempt(function () {
  3875. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  3876. // points. These environments, along with FF 3.1b1 and 2,
  3877. // also allow trailing commas in JSON objects and arrays.
  3878. parseSupported = parse("1.") !== 1;
  3879. });
  3880. }
  3881. }
  3882. }
  3883. }, function () {
  3884. parseSupported = false;
  3885. });
  3886. }
  3887. isSupported = parseSupported;
  3888. }
  3889. }
  3890. return has[name] = !!isSupported;
  3891. }
  3892. has["bug-string-char-index"] = has["date-serialization"] = has["json"] = has["json-stringify"] = has["json-parse"] = null;
  3893. if (!has("json")) {
  3894. // Common `[[Class]]` name aliases.
  3895. var functionClass = "[object Function]",
  3896. dateClass = "[object Date]",
  3897. numberClass = "[object Number]",
  3898. stringClass = "[object String]",
  3899. arrayClass = "[object Array]",
  3900. booleanClass = "[object Boolean]";
  3901. // Detect incomplete support for accessing string characters by index.
  3902. var charIndexBuggy = has("bug-string-char-index");
  3903. // Internal: Normalizes the `for...in` iteration algorithm across
  3904. // environments. Each enumerated key is yielded to a `callback` function.
  3905. var forOwn = function (object, callback) {
  3906. var size = 0, Properties, dontEnums, property;
  3907. // Tests for bugs in the current environment's `for...in` algorithm. The
  3908. // `valueOf` property inherits the non-enumerable flag from
  3909. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  3910. (Properties = function () {
  3911. this.valueOf = 0;
  3912. }).prototype.valueOf = 0;
  3913. // Iterate over a new instance of the `Properties` class.
  3914. dontEnums = new Properties();
  3915. for (property in dontEnums) {
  3916. // Ignore all properties inherited from `Object.prototype`.
  3917. if (isProperty.call(dontEnums, property)) {
  3918. size++;
  3919. }
  3920. }
  3921. Properties = dontEnums = null;
  3922. // Normalize the iteration algorithm.
  3923. if (!size) {
  3924. // A list of non-enumerable properties inherited from `Object.prototype`.
  3925. dontEnums = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  3926. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  3927. // properties.
  3928. forOwn = function (object, callback) {
  3929. var isFunction = getClass.call(object) == functionClass, property, length;
  3930. var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
  3931. for (property in object) {
  3932. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  3933. // certain conditions; IE does not.
  3934. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  3935. callback(property);
  3936. }
  3937. }
  3938. // Manually invoke the callback for each non-enumerable property.
  3939. for (length = dontEnums.length; property = dontEnums[--length];) {
  3940. if (hasProperty.call(object, property)) {
  3941. callback(property);
  3942. }
  3943. }
  3944. };
  3945. } else {
  3946. // No bugs detected; use the standard `for...in` algorithm.
  3947. forOwn = function (object, callback) {
  3948. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  3949. for (property in object) {
  3950. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  3951. callback(property);
  3952. }
  3953. }
  3954. // Manually invoke the callback for the `constructor` property due to
  3955. // cross-environment inconsistencies.
  3956. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  3957. callback(property);
  3958. }
  3959. };
  3960. }
  3961. return forOwn(object, callback);
  3962. };
  3963. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  3964. // `filter` argument may specify either a function that alters how object and
  3965. // array members are serialized, or an array of strings and numbers that
  3966. // indicates which properties should be serialized. The optional `width`
  3967. // argument may be either a string or number that specifies the indentation
  3968. // level of the output.
  3969. if (!has("json-stringify") && !has("date-serialization")) {
  3970. // Internal: A map of control characters and their escaped equivalents.
  3971. var Escapes = {
  3972. 92: "\\\\",
  3973. 34: '\\"',
  3974. 8: "\\b",
  3975. 12: "\\f",
  3976. 10: "\\n",
  3977. 13: "\\r",
  3978. 9: "\\t"
  3979. };
  3980. // Internal: Converts `value` into a zero-padded string such that its
  3981. // length is at least equal to `width`. The `width` must be <= 6.
  3982. var leadingZeroes = "000000";
  3983. var toPaddedString = function (width, value) {
  3984. // The `|| 0` expression is necessary to work around a bug in
  3985. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  3986. return (leadingZeroes + (value || 0)).slice(-width);
  3987. };
  3988. // Internal: Serializes a date object.
  3989. var serializeDate = function (value) {
  3990. var getData, year, month, date, time, hours, minutes, seconds, milliseconds;
  3991. // Define additional utility methods if the `Date` methods are buggy.
  3992. if (!isExtended) {
  3993. var floor = Math.floor;
  3994. // A mapping between the months of the year and the number of days between
  3995. // January 1st and the first of the respective month.
  3996. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  3997. // Internal: Calculates the number of days between the Unix epoch and the
  3998. // first day of the given month.
  3999. var getDay = function (year, month) {
  4000. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  4001. };
  4002. getData = function (value) {
  4003. // Manually compute the year, month, date, hours, minutes,
  4004. // seconds, and milliseconds if the `getUTC*` methods are
  4005. // buggy. Adapted from @Yaffle's `date-shim` project.
  4006. date = floor(value / 864e5);
  4007. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  4008. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  4009. date = 1 + date - getDay(year, month);
  4010. // The `time` value specifies the time within the day (see ES
  4011. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  4012. // to compute `A modulo B`, as the `%` operator does not
  4013. // correspond to the `modulo` operation for negative numbers.
  4014. time = (value % 864e5 + 864e5) % 864e5;
  4015. // The hours, minutes, seconds, and milliseconds are obtained by
  4016. // decomposing the time within the day. See section 15.9.1.10.
  4017. hours = floor(time / 36e5) % 24;
  4018. minutes = floor(time / 6e4) % 60;
  4019. seconds = floor(time / 1e3) % 60;
  4020. milliseconds = time % 1e3;
  4021. };
  4022. } else {
  4023. getData = function (value) {
  4024. year = value.getUTCFullYear();
  4025. month = value.getUTCMonth();
  4026. date = value.getUTCDate();
  4027. hours = value.getUTCHours();
  4028. minutes = value.getUTCMinutes();
  4029. seconds = value.getUTCSeconds();
  4030. milliseconds = value.getUTCMilliseconds();
  4031. };
  4032. }
  4033. serializeDate = function (value) {
  4034. if (value > -1 / 0 && value < 1 / 0) {
  4035. // Dates are serialized according to the `Date#toJSON` method
  4036. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  4037. // for the ISO 8601 date time string format.
  4038. getData(value);
  4039. // Serialize extended years correctly.
  4040. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  4041. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  4042. // Months, dates, hours, minutes, and seconds should have two
  4043. // digits; milliseconds should have three.
  4044. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  4045. // Milliseconds are optional in ES 5.0, but required in 5.1.
  4046. "." + toPaddedString(3, milliseconds) + "Z";
  4047. year = month = date = hours = minutes = seconds = milliseconds = null;
  4048. } else {
  4049. value = null;
  4050. }
  4051. return value;
  4052. };
  4053. return serializeDate(value);
  4054. };
  4055. // For environments with `JSON.stringify` but buggy date serialization,
  4056. // we override the native `Date#toJSON` implementation with a
  4057. // spec-compliant one.
  4058. if (has("json-stringify") && !has("date-serialization")) {
  4059. // Internal: the `Date#toJSON` implementation used to override the native one.
  4060. function dateToJSON (key) {
  4061. return serializeDate(this);
  4062. }
  4063. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  4064. var nativeStringify = exports.stringify;
  4065. exports.stringify = function (source, filter, width) {
  4066. var nativeToJSON = Date.prototype.toJSON;
  4067. Date.prototype.toJSON = dateToJSON;
  4068. var result = nativeStringify(source, filter, width);
  4069. Date.prototype.toJSON = nativeToJSON;
  4070. return result;
  4071. }
  4072. } else {
  4073. // Internal: Double-quotes a string `value`, replacing all ASCII control
  4074. // characters (characters with code unit values between 0 and 31) with
  4075. // their escaped equivalents. This is an implementation of the
  4076. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  4077. var unicodePrefix = "\\u00";
  4078. var escapeChar = function (character) {
  4079. var charCode = character.charCodeAt(0), escaped = Escapes[charCode];
  4080. if (escaped) {
  4081. return escaped;
  4082. }
  4083. return unicodePrefix + toPaddedString(2, charCode.toString(16));
  4084. };
  4085. var reEscape = /[\x00-\x1f\x22\x5c]/g;
  4086. var quote = function (value) {
  4087. reEscape.lastIndex = 0;
  4088. return '"' +
  4089. (
  4090. reEscape.test(value)
  4091. ? value.replace(reEscape, escapeChar)
  4092. : value
  4093. ) +
  4094. '"';
  4095. };
  4096. // Internal: Recursively serializes an object. Implements the
  4097. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  4098. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  4099. var value, type, className, results, element, index, length, prefix, result;
  4100. attempt(function () {
  4101. // Necessary for host object support.
  4102. value = object[property];
  4103. });
  4104. if (typeof value == "object" && value) {
  4105. if (value.getUTCFullYear && getClass.call(value) == dateClass && value.toJSON === Date.prototype.toJSON) {
  4106. value = serializeDate(value);
  4107. } else if (typeof value.toJSON == "function") {
  4108. value = value.toJSON(property);
  4109. }
  4110. }
  4111. if (callback) {
  4112. // If a replacement function was provided, call it to obtain the value
  4113. // for serialization.
  4114. value = callback.call(object, property, value);
  4115. }
  4116. // Exit early if value is `undefined` or `null`.
  4117. if (value == undefined) {
  4118. return value === undefined ? value : "null";
  4119. }
  4120. type = typeof value;
  4121. // Only call `getClass` if the value is an object.
  4122. if (type == "object") {
  4123. className = getClass.call(value);
  4124. }
  4125. switch (className || type) {
  4126. case "boolean":
  4127. case booleanClass:
  4128. // Booleans are represented literally.
  4129. return "" + value;
  4130. case "number":
  4131. case numberClass:
  4132. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  4133. // `"null"`.
  4134. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  4135. case "string":
  4136. case stringClass:
  4137. // Strings are double-quoted and escaped.
  4138. return quote("" + value);
  4139. }
  4140. // Recursively serialize objects and arrays.
  4141. if (typeof value == "object") {
  4142. // Check for cyclic structures. This is a linear search; performance
  4143. // is inversely proportional to the number of unique nested objects.
  4144. for (length = stack.length; length--;) {
  4145. if (stack[length] === value) {
  4146. // Cyclic structures cannot be serialized by `JSON.stringify`.
  4147. throw TypeError();
  4148. }
  4149. }
  4150. // Add the object to the stack of traversed objects.
  4151. stack.push(value);
  4152. results = [];
  4153. // Save the current indentation level and indent one additional level.
  4154. prefix = indentation;
  4155. indentation += whitespace;
  4156. if (className == arrayClass) {
  4157. // Recursively serialize array elements.
  4158. for (index = 0, length = value.length; index < length; index++) {
  4159. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  4160. results.push(element === undefined ? "null" : element);
  4161. }
  4162. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  4163. } else {
  4164. // Recursively serialize object members. Members are selected from
  4165. // either a user-specified list of property names, or the object
  4166. // itself.
  4167. forOwn(properties || value, function (property) {
  4168. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  4169. if (element !== undefined) {
  4170. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  4171. // is not the empty string, let `member` {quote(property) + ":"}
  4172. // be the concatenation of `member` and the `space` character."
  4173. // The "`space` character" refers to the literal space
  4174. // character, not the `space` {width} argument provided to
  4175. // `JSON.stringify`.
  4176. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  4177. }
  4178. });
  4179. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  4180. }
  4181. // Remove the object from the traversed object stack.
  4182. stack.pop();
  4183. return result;
  4184. }
  4185. };
  4186. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  4187. exports.stringify = function (source, filter, width) {
  4188. var whitespace, callback, properties, className;
  4189. if (objectTypes[typeof filter] && filter) {
  4190. className = getClass.call(filter);
  4191. if (className == functionClass) {
  4192. callback = filter;
  4193. } else if (className == arrayClass) {
  4194. // Convert the property names array into a makeshift set.
  4195. properties = {};
  4196. for (var index = 0, length = filter.length, value; index < length;) {
  4197. value = filter[index++];
  4198. className = getClass.call(value);
  4199. if (className == "[object String]" || className == "[object Number]") {
  4200. properties[value] = 1;
  4201. }
  4202. }
  4203. }
  4204. }
  4205. if (width) {
  4206. className = getClass.call(width);
  4207. if (className == numberClass) {
  4208. // Convert the `width` to an integer and create a string containing
  4209. // `width` number of space characters.
  4210. if ((width -= width % 1) > 0) {
  4211. if (width > 10) {
  4212. width = 10;
  4213. }
  4214. for (whitespace = ""; whitespace.length < width;) {
  4215. whitespace += " ";
  4216. }
  4217. }
  4218. } else if (className == stringClass) {
  4219. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  4220. }
  4221. }
  4222. // Opera <= 7.54u2 discards the values associated with empty string keys
  4223. // (`""`) only if they are used directly within an object member list
  4224. // (e.g., `!("" in { "": 1})`).
  4225. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  4226. };
  4227. }
  4228. }
  4229. // Public: Parses a JSON source string.
  4230. if (!has("json-parse")) {
  4231. var fromCharCode = String.fromCharCode;
  4232. // Internal: A map of escaped control characters and their unescaped
  4233. // equivalents.
  4234. var Unescapes = {
  4235. 92: "\\",
  4236. 34: '"',
  4237. 47: "/",
  4238. 98: "\b",
  4239. 116: "\t",
  4240. 110: "\n",
  4241. 102: "\f",
  4242. 114: "\r"
  4243. };
  4244. // Internal: Stores the parser state.
  4245. var Index, Source;
  4246. // Internal: Resets the parser state and throws a `SyntaxError`.
  4247. var abort = function () {
  4248. Index = Source = null;
  4249. throw SyntaxError();
  4250. };
  4251. // Internal: Returns the next token, or `"$"` if the parser has reached
  4252. // the end of the source string. A token may be a string, number, `null`
  4253. // literal, or Boolean literal.
  4254. var lex = function () {
  4255. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  4256. while (Index < length) {
  4257. charCode = source.charCodeAt(Index);
  4258. switch (charCode) {
  4259. case 9: case 10: case 13: case 32:
  4260. // Skip whitespace tokens, including tabs, carriage returns, line
  4261. // feeds, and space characters.
  4262. Index++;
  4263. break;
  4264. case 123: case 125: case 91: case 93: case 58: case 44:
  4265. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  4266. // the current position.
  4267. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  4268. Index++;
  4269. return value;
  4270. case 34:
  4271. // `"` delimits a JSON string; advance to the next character and
  4272. // begin parsing the string. String tokens are prefixed with the
  4273. // sentinel `@` character to distinguish them from punctuators and
  4274. // end-of-string tokens.
  4275. for (value = "@", Index++; Index < length;) {
  4276. charCode = source.charCodeAt(Index);
  4277. if (charCode < 32) {
  4278. // Unescaped ASCII control characters (those with a code unit
  4279. // less than the space character) are not permitted.
  4280. abort();
  4281. } else if (charCode == 92) {
  4282. // A reverse solidus (`\`) marks the beginning of an escaped
  4283. // control character (including `"`, `\`, and `/`) or Unicode
  4284. // escape sequence.
  4285. charCode = source.charCodeAt(++Index);
  4286. switch (charCode) {
  4287. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  4288. // Revive escaped control characters.
  4289. value += Unescapes[charCode];
  4290. Index++;
  4291. break;
  4292. case 117:
  4293. // `\u` marks the beginning of a Unicode escape sequence.
  4294. // Advance to the first character and validate the
  4295. // four-digit code point.
  4296. begin = ++Index;
  4297. for (position = Index + 4; Index < position; Index++) {
  4298. charCode = source.charCodeAt(Index);
  4299. // A valid sequence comprises four hexdigits (case-
  4300. // insensitive) that form a single hexadecimal value.
  4301. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  4302. // Invalid Unicode escape sequence.
  4303. abort();
  4304. }
  4305. }
  4306. // Revive the escaped character.
  4307. value += fromCharCode("0x" + source.slice(begin, Index));
  4308. break;
  4309. default:
  4310. // Invalid escape sequence.
  4311. abort();
  4312. }
  4313. } else {
  4314. if (charCode == 34) {
  4315. // An unescaped double-quote character marks the end of the
  4316. // string.
  4317. break;
  4318. }
  4319. charCode = source.charCodeAt(Index);
  4320. begin = Index;
  4321. // Optimize for the common case where a string is valid.
  4322. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  4323. charCode = source.charCodeAt(++Index);
  4324. }
  4325. // Append the string as-is.
  4326. value += source.slice(begin, Index);
  4327. }
  4328. }
  4329. if (source.charCodeAt(Index) == 34) {
  4330. // Advance to the next character and return the revived string.
  4331. Index++;
  4332. return value;
  4333. }
  4334. // Unterminated string.
  4335. abort();
  4336. default:
  4337. // Parse numbers and literals.
  4338. begin = Index;
  4339. // Advance past the negative sign, if one is specified.
  4340. if (charCode == 45) {
  4341. isSigned = true;
  4342. charCode = source.charCodeAt(++Index);
  4343. }
  4344. // Parse an integer or floating-point value.
  4345. if (charCode >= 48 && charCode <= 57) {
  4346. // Leading zeroes are interpreted as octal literals.
  4347. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  4348. // Illegal octal literal.
  4349. abort();
  4350. }
  4351. isSigned = false;
  4352. // Parse the integer component.
  4353. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  4354. // Floats cannot contain a leading decimal point; however, this
  4355. // case is already accounted for by the parser.
  4356. if (source.charCodeAt(Index) == 46) {
  4357. position = ++Index;
  4358. // Parse the decimal component.
  4359. for (; position < length; position++) {
  4360. charCode = source.charCodeAt(position);
  4361. if (charCode < 48 || charCode > 57) {
  4362. break;
  4363. }
  4364. }
  4365. if (position == Index) {
  4366. // Illegal trailing decimal.
  4367. abort();
  4368. }
  4369. Index = position;
  4370. }
  4371. // Parse exponents. The `e` denoting the exponent is
  4372. // case-insensitive.
  4373. charCode = source.charCodeAt(Index);
  4374. if (charCode == 101 || charCode == 69) {
  4375. charCode = source.charCodeAt(++Index);
  4376. // Skip past the sign following the exponent, if one is
  4377. // specified.
  4378. if (charCode == 43 || charCode == 45) {
  4379. Index++;
  4380. }
  4381. // Parse the exponential component.
  4382. for (position = Index; position < length; position++) {
  4383. charCode = source.charCodeAt(position);
  4384. if (charCode < 48 || charCode > 57) {
  4385. break;
  4386. }
  4387. }
  4388. if (position == Index) {
  4389. // Illegal empty exponent.
  4390. abort();
  4391. }
  4392. Index = position;
  4393. }
  4394. // Coerce the parsed value to a JavaScript number.
  4395. return +source.slice(begin, Index);
  4396. }
  4397. // A negative sign may only precede numbers.
  4398. if (isSigned) {
  4399. abort();
  4400. }
  4401. // `true`, `false`, and `null` literals.
  4402. var temp = source.slice(Index, Index + 4);
  4403. if (temp == "true") {
  4404. Index += 4;
  4405. return true;
  4406. } else if (temp == "fals" && source.charCodeAt(Index + 4 ) == 101) {
  4407. Index += 5;
  4408. return false;
  4409. } else if (temp == "null") {
  4410. Index += 4;
  4411. return null;
  4412. }
  4413. // Unrecognized token.
  4414. abort();
  4415. }
  4416. }
  4417. // Return the sentinel `$` character if the parser has reached the end
  4418. // of the source string.
  4419. return "$";
  4420. };
  4421. // Internal: Parses a JSON `value` token.
  4422. var get = function (value) {
  4423. var results, hasMembers;
  4424. if (value == "$") {
  4425. // Unexpected end of input.
  4426. abort();
  4427. }
  4428. if (typeof value == "string") {
  4429. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  4430. // Remove the sentinel `@` character.
  4431. return value.slice(1);
  4432. }
  4433. // Parse object and array literals.
  4434. if (value == "[") {
  4435. // Parses a JSON array, returning a new JavaScript array.
  4436. results = [];
  4437. for (;;) {
  4438. value = lex();
  4439. // A closing square bracket marks the end of the array literal.
  4440. if (value == "]") {
  4441. break;
  4442. }
  4443. // If the array literal contains elements, the current token
  4444. // should be a comma separating the previous element from the
  4445. // next.
  4446. if (hasMembers) {
  4447. if (value == ",") {
  4448. value = lex();
  4449. if (value == "]") {
  4450. // Unexpected trailing `,` in array literal.
  4451. abort();
  4452. }
  4453. } else {
  4454. // A `,` must separate each array element.
  4455. abort();
  4456. }
  4457. } else {
  4458. hasMembers = true;
  4459. }
  4460. // Elisions and leading commas are not permitted.
  4461. if (value == ",") {
  4462. abort();
  4463. }
  4464. results.push(get(value));
  4465. }
  4466. return results;
  4467. } else if (value == "{") {
  4468. // Parses a JSON object, returning a new JavaScript object.
  4469. results = {};
  4470. for (;;) {
  4471. value = lex();
  4472. // A closing curly brace marks the end of the object literal.
  4473. if (value == "}") {
  4474. break;
  4475. }
  4476. // If the object literal contains members, the current token
  4477. // should be a comma separator.
  4478. if (hasMembers) {
  4479. if (value == ",") {
  4480. value = lex();
  4481. if (value == "}") {
  4482. // Unexpected trailing `,` in object literal.
  4483. abort();
  4484. }
  4485. } else {
  4486. // A `,` must separate each object member.
  4487. abort();
  4488. }
  4489. } else {
  4490. hasMembers = true;
  4491. }
  4492. // Leading commas are not permitted, object property names must be
  4493. // double-quoted strings, and a `:` must separate each property
  4494. // name and value.
  4495. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  4496. abort();
  4497. }
  4498. results[value.slice(1)] = get(lex());
  4499. }
  4500. return results;
  4501. }
  4502. // Unexpected token encountered.
  4503. abort();
  4504. }
  4505. return value;
  4506. };
  4507. // Internal: Updates a traversed object member.
  4508. var update = function (source, property, callback) {
  4509. var element = walk(source, property, callback);
  4510. if (element === undefined) {
  4511. delete source[property];
  4512. } else {
  4513. source[property] = element;
  4514. }
  4515. };
  4516. // Internal: Recursively traverses a parsed JSON object, invoking the
  4517. // `callback` function for each value. This is an implementation of the
  4518. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  4519. var walk = function (source, property, callback) {
  4520. var value = source[property], length;
  4521. if (typeof value == "object" && value) {
  4522. // `forOwn` can't be used to traverse an array in Opera <= 8.54
  4523. // because its `Object#hasOwnProperty` implementation returns `false`
  4524. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  4525. if (getClass.call(value) == arrayClass) {
  4526. for (length = value.length; length--;) {
  4527. update(getClass, forOwn, value, length, callback);
  4528. }
  4529. } else {
  4530. forOwn(value, function (property) {
  4531. update(value, property, callback);
  4532. });
  4533. }
  4534. }
  4535. return callback.call(source, property, value);
  4536. };
  4537. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  4538. exports.parse = function (source, callback) {
  4539. var result, value;
  4540. Index = 0;
  4541. Source = "" + source;
  4542. result = get(lex());
  4543. // If a JSON string contains multiple tokens, it is invalid.
  4544. if (lex() != "$") {
  4545. abort();
  4546. }
  4547. // Reset the parser state.
  4548. Index = Source = null;
  4549. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  4550. };
  4551. }
  4552. }
  4553. exports.runInContext = runInContext;
  4554. return exports;
  4555. }
  4556. if (freeExports && !isLoader) {
  4557. // Export for CommonJS environments.
  4558. runInContext(root, freeExports);
  4559. } else {
  4560. // Export for web browsers and JavaScript engines.
  4561. var nativeJSON = root.JSON,
  4562. previousJSON = root.JSON3,
  4563. isRestored = false;
  4564. var JSON3 = runInContext(root, (root.JSON3 = {
  4565. // Public: Restores the original value of the global `JSON` object and
  4566. // returns a reference to the `JSON3` object.
  4567. "noConflict": function () {
  4568. if (!isRestored) {
  4569. isRestored = true;
  4570. root.JSON = nativeJSON;
  4571. root.JSON3 = previousJSON;
  4572. nativeJSON = previousJSON = null;
  4573. }
  4574. return JSON3;
  4575. }
  4576. }));
  4577. root.JSON = {
  4578. "parse": JSON3.parse,
  4579. "stringify": JSON3.stringify
  4580. };
  4581. }
  4582. // Export for asynchronous module loaders.
  4583. if (isLoader) {
  4584. define(function () {
  4585. return JSON3;
  4586. });
  4587. }
  4588. }).call(this);
  4589. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4590. },{}],59:[function(require,module,exports){
  4591. 'use strict';
  4592. var has = Object.prototype.hasOwnProperty
  4593. , undef;
  4594. /**
  4595. * Decode a URI encoded string.
  4596. *
  4597. * @param {String} input The URI encoded string.
  4598. * @returns {String|Null} The decoded string.
  4599. * @api private
  4600. */
  4601. function decode(input) {
  4602. try {
  4603. return decodeURIComponent(input.replace(/\+/g, ' '));
  4604. } catch (e) {
  4605. return null;
  4606. }
  4607. }
  4608. /**
  4609. * Attempts to encode a given input.
  4610. *
  4611. * @param {String} input The string that needs to be encoded.
  4612. * @returns {String|Null} The encoded string.
  4613. * @api private
  4614. */
  4615. function encode(input) {
  4616. try {
  4617. return encodeURIComponent(input);
  4618. } catch (e) {
  4619. return null;
  4620. }
  4621. }
  4622. /**
  4623. * Simple query string parser.
  4624. *
  4625. * @param {String} query The query string that needs to be parsed.
  4626. * @returns {Object}
  4627. * @api public
  4628. */
  4629. function querystring(query) {
  4630. var parser = /([^=?&]+)=?([^&]*)/g
  4631. , result = {}
  4632. , part;
  4633. while (part = parser.exec(query)) {
  4634. var key = decode(part[1])
  4635. , value = decode(part[2]);
  4636. //
  4637. // Prevent overriding of existing properties. This ensures that build-in
  4638. // methods like `toString` or __proto__ are not overriden by malicious
  4639. // querystrings.
  4640. //
  4641. // In the case if failed decoding, we want to omit the key/value pairs
  4642. // from the result.
  4643. //
  4644. if (key === null || value === null || key in result) continue;
  4645. result[key] = value;
  4646. }
  4647. return result;
  4648. }
  4649. /**
  4650. * Transform a query string to an object.
  4651. *
  4652. * @param {Object} obj Object that should be transformed.
  4653. * @param {String} prefix Optional prefix.
  4654. * @returns {String}
  4655. * @api public
  4656. */
  4657. function querystringify(obj, prefix) {
  4658. prefix = prefix || '';
  4659. var pairs = []
  4660. , value
  4661. , key;
  4662. //
  4663. // Optionally prefix with a '?' if needed
  4664. //
  4665. if ('string' !== typeof prefix) prefix = '?';
  4666. for (key in obj) {
  4667. if (has.call(obj, key)) {
  4668. value = obj[key];
  4669. //
  4670. // Edge cases where we actually want to encode the value to an empty
  4671. // string instead of the stringified value.
  4672. //
  4673. if (!value && (value === null || value === undef || isNaN(value))) {
  4674. value = '';
  4675. }
  4676. key = encodeURIComponent(key);
  4677. value = encodeURIComponent(value);
  4678. //
  4679. // If we failed to encode the strings, we should bail out as we don't
  4680. // want to add invalid strings to the query.
  4681. //
  4682. if (key === null || value === null) continue;
  4683. pairs.push(key +'='+ value);
  4684. }
  4685. }
  4686. return pairs.length ? prefix + pairs.join('&') : '';
  4687. }
  4688. //
  4689. // Expose the module.
  4690. //
  4691. exports.stringify = querystringify;
  4692. exports.parse = querystring;
  4693. },{}],60:[function(require,module,exports){
  4694. 'use strict';
  4695. /**
  4696. * Check if we're required to add a port number.
  4697. *
  4698. * @see https://url.spec.whatwg.org/#default-port
  4699. * @param {Number|String} port Port number we need to check
  4700. * @param {String} protocol Protocol we need to check against.
  4701. * @returns {Boolean} Is it a default port for the given protocol
  4702. * @api private
  4703. */
  4704. module.exports = function required(port, protocol) {
  4705. protocol = protocol.split(':')[0];
  4706. port = +port;
  4707. if (!port) return false;
  4708. switch (protocol) {
  4709. case 'http':
  4710. case 'ws':
  4711. return port !== 80;
  4712. case 'https':
  4713. case 'wss':
  4714. return port !== 443;
  4715. case 'ftp':
  4716. return port !== 21;
  4717. case 'gopher':
  4718. return port !== 70;
  4719. case 'file':
  4720. return false;
  4721. }
  4722. return port !== 0;
  4723. };
  4724. },{}],61:[function(require,module,exports){
  4725. (function (global){
  4726. 'use strict';
  4727. var required = require('requires-port')
  4728. , qs = require('querystringify')
  4729. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:[\\/]+/
  4730. , protocolre = /^([a-z][a-z0-9.+-]*:)?([\\/]{1,})?([\S\s]*)/i
  4731. , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]'
  4732. , left = new RegExp('^'+ whitespace +'+');
  4733. /**
  4734. * Trim a given string.
  4735. *
  4736. * @param {String} str String to trim.
  4737. * @public
  4738. */
  4739. function trimLeft(str) {
  4740. return (str ? str : '').toString().replace(left, '');
  4741. }
  4742. /**
  4743. * These are the parse rules for the URL parser, it informs the parser
  4744. * about:
  4745. *
  4746. * 0. The char it Needs to parse, if it's a string it should be done using
  4747. * indexOf, RegExp using exec and NaN means set as current value.
  4748. * 1. The property we should set when parsing this value.
  4749. * 2. Indication if it's backwards or forward parsing, when set as number it's
  4750. * the value of extra chars that should be split off.
  4751. * 3. Inherit from location if non existing in the parser.
  4752. * 4. `toLowerCase` the resulting value.
  4753. */
  4754. var rules = [
  4755. ['#', 'hash'], // Extract from the back.
  4756. ['?', 'query'], // Extract from the back.
  4757. function sanitize(address) { // Sanitize what is left of the address
  4758. return address.replace('\\', '/');
  4759. },
  4760. ['/', 'pathname'], // Extract from the back.
  4761. ['@', 'auth', 1], // Extract from the front.
  4762. [NaN, 'host', undefined, 1, 1], // Set left over value.
  4763. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  4764. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  4765. ];
  4766. /**
  4767. * These properties should not be copied or inherited from. This is only needed
  4768. * for all non blob URL's as a blob URL does not include a hash, only the
  4769. * origin.
  4770. *
  4771. * @type {Object}
  4772. * @private
  4773. */
  4774. var ignore = { hash: 1, query: 1 };
  4775. /**
  4776. * The location object differs when your code is loaded through a normal page,
  4777. * Worker or through a worker using a blob. And with the blobble begins the
  4778. * trouble as the location object will contain the URL of the blob, not the
  4779. * location of the page where our code is loaded in. The actual origin is
  4780. * encoded in the `pathname` so we can thankfully generate a good "default"
  4781. * location from it so we can generate proper relative URL's again.
  4782. *
  4783. * @param {Object|String} loc Optional default location object.
  4784. * @returns {Object} lolcation object.
  4785. * @public
  4786. */
  4787. function lolcation(loc) {
  4788. var globalVar;
  4789. if (typeof window !== 'undefined') globalVar = window;
  4790. else if (typeof global !== 'undefined') globalVar = global;
  4791. else if (typeof self !== 'undefined') globalVar = self;
  4792. else globalVar = {};
  4793. var location = globalVar.location || {};
  4794. loc = loc || location;
  4795. var finaldestination = {}
  4796. , type = typeof loc
  4797. , key;
  4798. if ('blob:' === loc.protocol) {
  4799. finaldestination = new Url(unescape(loc.pathname), {});
  4800. } else if ('string' === type) {
  4801. finaldestination = new Url(loc, {});
  4802. for (key in ignore) delete finaldestination[key];
  4803. } else if ('object' === type) {
  4804. for (key in loc) {
  4805. if (key in ignore) continue;
  4806. finaldestination[key] = loc[key];
  4807. }
  4808. if (finaldestination.slashes === undefined) {
  4809. finaldestination.slashes = slashes.test(loc.href);
  4810. }
  4811. }
  4812. return finaldestination;
  4813. }
  4814. /**
  4815. * @typedef ProtocolExtract
  4816. * @type Object
  4817. * @property {String} protocol Protocol matched in the URL, in lowercase.
  4818. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  4819. * @property {String} rest Rest of the URL that is not part of the protocol.
  4820. */
  4821. /**
  4822. * Extract protocol information from a URL with/without double slash ("//").
  4823. *
  4824. * @param {String} address URL we want to extract from.
  4825. * @return {ProtocolExtract} Extracted information.
  4826. * @private
  4827. */
  4828. function extractProtocol(address) {
  4829. address = trimLeft(address);
  4830. var match = protocolre.exec(address)
  4831. , protocol = match[1] ? match[1].toLowerCase() : ''
  4832. , slashes = !!(match[2] && match[2].length >= 2)
  4833. , rest = match[2] && match[2].length === 1 ? '/' + match[3] : match[3];
  4834. return {
  4835. protocol: protocol,
  4836. slashes: slashes,
  4837. rest: rest
  4838. };
  4839. }
  4840. /**
  4841. * Resolve a relative URL pathname against a base URL pathname.
  4842. *
  4843. * @param {String} relative Pathname of the relative URL.
  4844. * @param {String} base Pathname of the base URL.
  4845. * @return {String} Resolved pathname.
  4846. * @private
  4847. */
  4848. function resolve(relative, base) {
  4849. if (relative === '') return base;
  4850. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  4851. , i = path.length
  4852. , last = path[i - 1]
  4853. , unshift = false
  4854. , up = 0;
  4855. while (i--) {
  4856. if (path[i] === '.') {
  4857. path.splice(i, 1);
  4858. } else if (path[i] === '..') {
  4859. path.splice(i, 1);
  4860. up++;
  4861. } else if (up) {
  4862. if (i === 0) unshift = true;
  4863. path.splice(i, 1);
  4864. up--;
  4865. }
  4866. }
  4867. if (unshift) path.unshift('');
  4868. if (last === '.' || last === '..') path.push('');
  4869. return path.join('/');
  4870. }
  4871. /**
  4872. * The actual URL instance. Instead of returning an object we've opted-in to
  4873. * create an actual constructor as it's much more memory efficient and
  4874. * faster and it pleases my OCD.
  4875. *
  4876. * It is worth noting that we should not use `URL` as class name to prevent
  4877. * clashes with the global URL instance that got introduced in browsers.
  4878. *
  4879. * @constructor
  4880. * @param {String} address URL we want to parse.
  4881. * @param {Object|String} [location] Location defaults for relative paths.
  4882. * @param {Boolean|Function} [parser] Parser for the query string.
  4883. * @private
  4884. */
  4885. function Url(address, location, parser) {
  4886. address = trimLeft(address);
  4887. if (!(this instanceof Url)) {
  4888. return new Url(address, location, parser);
  4889. }
  4890. var relative, extracted, parse, instruction, index, key
  4891. , instructions = rules.slice()
  4892. , type = typeof location
  4893. , url = this
  4894. , i = 0;
  4895. //
  4896. // The following if statements allows this module two have compatibility with
  4897. // 2 different API:
  4898. //
  4899. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  4900. // where the boolean indicates that the query string should also be parsed.
  4901. //
  4902. // 2. The `URL` interface of the browser which accepts a URL, object as
  4903. // arguments. The supplied object will be used as default values / fall-back
  4904. // for relative paths.
  4905. //
  4906. if ('object' !== type && 'string' !== type) {
  4907. parser = location;
  4908. location = null;
  4909. }
  4910. if (parser && 'function' !== typeof parser) parser = qs.parse;
  4911. location = lolcation(location);
  4912. //
  4913. // Extract protocol information before running the instructions.
  4914. //
  4915. extracted = extractProtocol(address || '');
  4916. relative = !extracted.protocol && !extracted.slashes;
  4917. url.slashes = extracted.slashes || relative && location.slashes;
  4918. url.protocol = extracted.protocol || location.protocol || '';
  4919. address = extracted.rest;
  4920. //
  4921. // When the authority component is absent the URL starts with a path
  4922. // component.
  4923. //
  4924. if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  4925. for (; i < instructions.length; i++) {
  4926. instruction = instructions[i];
  4927. if (typeof instruction === 'function') {
  4928. address = instruction(address);
  4929. continue;
  4930. }
  4931. parse = instruction[0];
  4932. key = instruction[1];
  4933. if (parse !== parse) {
  4934. url[key] = address;
  4935. } else if ('string' === typeof parse) {
  4936. if (~(index = address.indexOf(parse))) {
  4937. if ('number' === typeof instruction[2]) {
  4938. url[key] = address.slice(0, index);
  4939. address = address.slice(index + instruction[2]);
  4940. } else {
  4941. url[key] = address.slice(index);
  4942. address = address.slice(0, index);
  4943. }
  4944. }
  4945. } else if ((index = parse.exec(address))) {
  4946. url[key] = index[1];
  4947. address = address.slice(0, index.index);
  4948. }
  4949. url[key] = url[key] || (
  4950. relative && instruction[3] ? location[key] || '' : ''
  4951. );
  4952. //
  4953. // Hostname, host and protocol should be lowercased so they can be used to
  4954. // create a proper `origin`.
  4955. //
  4956. if (instruction[4]) url[key] = url[key].toLowerCase();
  4957. }
  4958. //
  4959. // Also parse the supplied query string in to an object. If we're supplied
  4960. // with a custom parser as function use that instead of the default build-in
  4961. // parser.
  4962. //
  4963. if (parser) url.query = parser(url.query);
  4964. //
  4965. // If the URL is relative, resolve the pathname against the base URL.
  4966. //
  4967. if (
  4968. relative
  4969. && location.slashes
  4970. && url.pathname.charAt(0) !== '/'
  4971. && (url.pathname !== '' || location.pathname !== '')
  4972. ) {
  4973. url.pathname = resolve(url.pathname, location.pathname);
  4974. }
  4975. //
  4976. // Default to a / for pathname if none exists. This normalizes the URL
  4977. // to always have a /
  4978. //
  4979. if (url.pathname.charAt(0) !== '/' && url.hostname) {
  4980. url.pathname = '/' + url.pathname;
  4981. }
  4982. //
  4983. // We should not add port numbers if they are already the default port number
  4984. // for a given protocol. As the host also contains the port number we're going
  4985. // override it with the hostname which contains no port number.
  4986. //
  4987. if (!required(url.port, url.protocol)) {
  4988. url.host = url.hostname;
  4989. url.port = '';
  4990. }
  4991. //
  4992. // Parse down the `auth` for the username and password.
  4993. //
  4994. url.username = url.password = '';
  4995. if (url.auth) {
  4996. instruction = url.auth.split(':');
  4997. url.username = instruction[0] || '';
  4998. url.password = instruction[1] || '';
  4999. }
  5000. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  5001. ? url.protocol +'//'+ url.host
  5002. : 'null';
  5003. //
  5004. // The href is just the compiled result.
  5005. //
  5006. url.href = url.toString();
  5007. }
  5008. /**
  5009. * This is convenience method for changing properties in the URL instance to
  5010. * insure that they all propagate correctly.
  5011. *
  5012. * @param {String} part Property we need to adjust.
  5013. * @param {Mixed} value The newly assigned value.
  5014. * @param {Boolean|Function} fn When setting the query, it will be the function
  5015. * used to parse the query.
  5016. * When setting the protocol, double slash will be
  5017. * removed from the final url if it is true.
  5018. * @returns {URL} URL instance for chaining.
  5019. * @public
  5020. */
  5021. function set(part, value, fn) {
  5022. var url = this;
  5023. switch (part) {
  5024. case 'query':
  5025. if ('string' === typeof value && value.length) {
  5026. value = (fn || qs.parse)(value);
  5027. }
  5028. url[part] = value;
  5029. break;
  5030. case 'port':
  5031. url[part] = value;
  5032. if (!required(value, url.protocol)) {
  5033. url.host = url.hostname;
  5034. url[part] = '';
  5035. } else if (value) {
  5036. url.host = url.hostname +':'+ value;
  5037. }
  5038. break;
  5039. case 'hostname':
  5040. url[part] = value;
  5041. if (url.port) value += ':'+ url.port;
  5042. url.host = value;
  5043. break;
  5044. case 'host':
  5045. url[part] = value;
  5046. if (/:\d+$/.test(value)) {
  5047. value = value.split(':');
  5048. url.port = value.pop();
  5049. url.hostname = value.join(':');
  5050. } else {
  5051. url.hostname = value;
  5052. url.port = '';
  5053. }
  5054. break;
  5055. case 'protocol':
  5056. url.protocol = value.toLowerCase();
  5057. url.slashes = !fn;
  5058. break;
  5059. case 'pathname':
  5060. case 'hash':
  5061. if (value) {
  5062. var char = part === 'pathname' ? '/' : '#';
  5063. url[part] = value.charAt(0) !== char ? char + value : value;
  5064. } else {
  5065. url[part] = value;
  5066. }
  5067. break;
  5068. default:
  5069. url[part] = value;
  5070. }
  5071. for (var i = 0; i < rules.length; i++) {
  5072. var ins = rules[i];
  5073. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  5074. }
  5075. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  5076. ? url.protocol +'//'+ url.host
  5077. : 'null';
  5078. url.href = url.toString();
  5079. return url;
  5080. }
  5081. /**
  5082. * Transform the properties back in to a valid and full URL string.
  5083. *
  5084. * @param {Function} stringify Optional query stringify function.
  5085. * @returns {String} Compiled version of the URL.
  5086. * @public
  5087. */
  5088. function toString(stringify) {
  5089. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  5090. var query
  5091. , url = this
  5092. , protocol = url.protocol;
  5093. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  5094. var result = protocol + (url.slashes ? '//' : '');
  5095. if (url.username) {
  5096. result += url.username;
  5097. if (url.password) result += ':'+ url.password;
  5098. result += '@';
  5099. }
  5100. result += url.host + url.pathname;
  5101. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  5102. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  5103. if (url.hash) result += url.hash;
  5104. return result;
  5105. }
  5106. Url.prototype = { set: set, toString: toString };
  5107. //
  5108. // Expose the URL parser and some additional properties that might be useful for
  5109. // others or testing.
  5110. //
  5111. Url.extractProtocol = extractProtocol;
  5112. Url.location = lolcation;
  5113. Url.trimLeft = trimLeft;
  5114. Url.qs = qs;
  5115. module.exports = Url;
  5116. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5117. },{"querystringify":59,"requires-port":60}]},{},[1])(1)
  5118. });
  5119. //# sourceMappingURL=sockjs.js.map