sockjs.js 278 KB

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