sockjs.js 176 KB

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