Ein Projekt das es ermöglicht Beerpong über das Internet von zwei unabhängigen positionen aus zu spielen. Entstehung im Rahmen einer Praktikumsaufgabe im Fach Interaktion.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jade.js 485KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.jade=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. 'use strict';
  3. var nodes = require('./nodes');
  4. var filters = require('./filters');
  5. var doctypes = require('./doctypes');
  6. var runtime = require('./runtime');
  7. var utils = require('./utils');
  8. var selfClosing = require('void-elements');
  9. var parseJSExpression = require('character-parser').parseMax;
  10. var constantinople = require('constantinople');
  11. function isConstant(src) {
  12. return constantinople(src, {jade: runtime, 'jade_interp': undefined});
  13. }
  14. function toConstant(src) {
  15. return constantinople.toConstant(src, {jade: runtime, 'jade_interp': undefined});
  16. }
  17. function errorAtNode(node, error) {
  18. error.line = node.line;
  19. error.filename = node.filename;
  20. return error;
  21. }
  22. /**
  23. * Initialize `Compiler` with the given `node`.
  24. *
  25. * @param {Node} node
  26. * @param {Object} options
  27. * @api public
  28. */
  29. var Compiler = module.exports = function Compiler(node, options) {
  30. this.options = options = options || {};
  31. this.node = node;
  32. this.hasCompiledDoctype = false;
  33. this.hasCompiledTag = false;
  34. this.pp = options.pretty || false;
  35. this.debug = false !== options.compileDebug;
  36. this.indents = 0;
  37. this.parentIndents = 0;
  38. this.terse = false;
  39. this.mixins = {};
  40. this.dynamicMixins = false;
  41. if (options.doctype) this.setDoctype(options.doctype);
  42. };
  43. /**
  44. * Compiler prototype.
  45. */
  46. Compiler.prototype = {
  47. /**
  48. * Compile parse tree to JavaScript.
  49. *
  50. * @api public
  51. */
  52. compile: function(){
  53. this.buf = [];
  54. if (this.pp) this.buf.push("var jade_indent = [];");
  55. this.lastBufferedIdx = -1;
  56. this.visit(this.node);
  57. if (!this.dynamicMixins) {
  58. // if there are no dynamic mixins we can remove any un-used mixins
  59. var mixinNames = Object.keys(this.mixins);
  60. for (var i = 0; i < mixinNames.length; i++) {
  61. var mixin = this.mixins[mixinNames[i]];
  62. if (!mixin.used) {
  63. for (var x = 0; x < mixin.instances.length; x++) {
  64. for (var y = mixin.instances[x].start; y < mixin.instances[x].end; y++) {
  65. this.buf[y] = '';
  66. }
  67. }
  68. }
  69. }
  70. }
  71. return this.buf.join('\n');
  72. },
  73. /**
  74. * Sets the default doctype `name`. Sets terse mode to `true` when
  75. * html 5 is used, causing self-closing tags to end with ">" vs "/>",
  76. * and boolean attributes are not mirrored.
  77. *
  78. * @param {string} name
  79. * @api public
  80. */
  81. setDoctype: function(name){
  82. this.doctype = doctypes[name.toLowerCase()] || '<!DOCTYPE ' + name + '>';
  83. this.terse = this.doctype.toLowerCase() == '<!doctype html>';
  84. this.xml = 0 == this.doctype.indexOf('<?xml');
  85. },
  86. /**
  87. * Buffer the given `str` exactly as is or with interpolation
  88. *
  89. * @param {String} str
  90. * @param {Boolean} interpolate
  91. * @api public
  92. */
  93. buffer: function (str, interpolate) {
  94. var self = this;
  95. if (interpolate) {
  96. var match = /(\\)?([#!]){((?:.|\n)*)$/.exec(str);
  97. if (match) {
  98. this.buffer(str.substr(0, match.index), false);
  99. if (match[1]) { // escape
  100. this.buffer(match[2] + '{', false);
  101. this.buffer(match[3], true);
  102. return;
  103. } else {
  104. var rest = match[3];
  105. var range = parseJSExpression(rest);
  106. var code = ('!' == match[2] ? '' : 'jade.escape') + "((jade_interp = " + range.src + ") == null ? '' : jade_interp)";
  107. this.bufferExpression(code);
  108. this.buffer(rest.substr(range.end + 1), true);
  109. return;
  110. }
  111. }
  112. }
  113. str = JSON.stringify(str);
  114. str = str.substr(1, str.length - 2);
  115. if (this.lastBufferedIdx == this.buf.length) {
  116. if (this.lastBufferedType === 'code') this.lastBuffered += ' + "';
  117. this.lastBufferedType = 'text';
  118. this.lastBuffered += str;
  119. this.buf[this.lastBufferedIdx - 1] = 'buf.push(' + this.bufferStartChar + this.lastBuffered + '");'
  120. } else {
  121. this.buf.push('buf.push("' + str + '");');
  122. this.lastBufferedType = 'text';
  123. this.bufferStartChar = '"';
  124. this.lastBuffered = str;
  125. this.lastBufferedIdx = this.buf.length;
  126. }
  127. },
  128. /**
  129. * Buffer the given `src` so it is evaluated at run time
  130. *
  131. * @param {String} src
  132. * @api public
  133. */
  134. bufferExpression: function (src) {
  135. if (isConstant(src)) {
  136. return this.buffer(toConstant(src) + '', false)
  137. }
  138. if (this.lastBufferedIdx == this.buf.length) {
  139. if (this.lastBufferedType === 'text') this.lastBuffered += '"';
  140. this.lastBufferedType = 'code';
  141. this.lastBuffered += ' + (' + src + ')';
  142. this.buf[this.lastBufferedIdx - 1] = 'buf.push(' + this.bufferStartChar + this.lastBuffered + ');'
  143. } else {
  144. this.buf.push('buf.push(' + src + ');');
  145. this.lastBufferedType = 'code';
  146. this.bufferStartChar = '';
  147. this.lastBuffered = '(' + src + ')';
  148. this.lastBufferedIdx = this.buf.length;
  149. }
  150. },
  151. /**
  152. * Buffer an indent based on the current `indent`
  153. * property and an additional `offset`.
  154. *
  155. * @param {Number} offset
  156. * @param {Boolean} newline
  157. * @api public
  158. */
  159. prettyIndent: function(offset, newline){
  160. offset = offset || 0;
  161. newline = newline ? '\n' : '';
  162. this.buffer(newline + Array(this.indents + offset).join(' '));
  163. if (this.parentIndents)
  164. this.buf.push("buf.push.apply(buf, jade_indent);");
  165. },
  166. /**
  167. * Visit `node`.
  168. *
  169. * @param {Node} node
  170. * @api public
  171. */
  172. visit: function(node){
  173. var debug = this.debug;
  174. if (debug) {
  175. this.buf.push('jade_debug.unshift({ lineno: ' + node.line
  176. + ', filename: ' + (node.filename
  177. ? JSON.stringify(node.filename)
  178. : 'jade_debug[0].filename')
  179. + ' });');
  180. }
  181. // Massive hack to fix our context
  182. // stack for - else[ if] etc
  183. if (false === node.debug && this.debug) {
  184. this.buf.pop();
  185. this.buf.pop();
  186. }
  187. this.visitNode(node);
  188. if (debug) this.buf.push('jade_debug.shift();');
  189. },
  190. /**
  191. * Visit `node`.
  192. *
  193. * @param {Node} node
  194. * @api public
  195. */
  196. visitNode: function(node){
  197. return this['visit' + node.type](node);
  198. },
  199. /**
  200. * Visit case `node`.
  201. *
  202. * @param {Literal} node
  203. * @api public
  204. */
  205. visitCase: function(node){
  206. var _ = this.withinCase;
  207. this.withinCase = true;
  208. this.buf.push('switch (' + node.expr + '){');
  209. this.visit(node.block);
  210. this.buf.push('}');
  211. this.withinCase = _;
  212. },
  213. /**
  214. * Visit when `node`.
  215. *
  216. * @param {Literal} node
  217. * @api public
  218. */
  219. visitWhen: function(node){
  220. if ('default' == node.expr) {
  221. this.buf.push('default:');
  222. } else {
  223. this.buf.push('case ' + node.expr + ':');
  224. }
  225. if (node.block) {
  226. this.visit(node.block);
  227. this.buf.push(' break;');
  228. }
  229. },
  230. /**
  231. * Visit literal `node`.
  232. *
  233. * @param {Literal} node
  234. * @api public
  235. */
  236. visitLiteral: function(node){
  237. this.buffer(node.str);
  238. },
  239. /**
  240. * Visit all nodes in `block`.
  241. *
  242. * @param {Block} block
  243. * @api public
  244. */
  245. visitBlock: function(block){
  246. var len = block.nodes.length
  247. , escape = this.escape
  248. , pp = this.pp
  249. // Pretty print multi-line text
  250. if (pp && len > 1 && !escape && block.nodes[0].isText && block.nodes[1].isText)
  251. this.prettyIndent(1, true);
  252. for (var i = 0; i < len; ++i) {
  253. // Pretty print text
  254. if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText)
  255. this.prettyIndent(1, false);
  256. this.visit(block.nodes[i]);
  257. // Multiple text nodes are separated by newlines
  258. if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText)
  259. this.buffer('\n');
  260. }
  261. },
  262. /**
  263. * Visit a mixin's `block` keyword.
  264. *
  265. * @param {MixinBlock} block
  266. * @api public
  267. */
  268. visitMixinBlock: function(block){
  269. if (this.pp) this.buf.push("jade_indent.push('" + Array(this.indents + 1).join(' ') + "');");
  270. this.buf.push('block && block();');
  271. if (this.pp) this.buf.push("jade_indent.pop();");
  272. },
  273. /**
  274. * Visit `doctype`. Sets terse mode to `true` when html 5
  275. * is used, causing self-closing tags to end with ">" vs "/>",
  276. * and boolean attributes are not mirrored.
  277. *
  278. * @param {Doctype} doctype
  279. * @api public
  280. */
  281. visitDoctype: function(doctype){
  282. if (doctype && (doctype.val || !this.doctype)) {
  283. this.setDoctype(doctype.val || 'default');
  284. }
  285. if (this.doctype) this.buffer(this.doctype);
  286. this.hasCompiledDoctype = true;
  287. },
  288. /**
  289. * Visit `mixin`, generating a function that
  290. * may be called within the template.
  291. *
  292. * @param {Mixin} mixin
  293. * @api public
  294. */
  295. visitMixin: function(mixin){
  296. var name = 'jade_mixins[';
  297. var args = mixin.args || '';
  298. var block = mixin.block;
  299. var attrs = mixin.attrs;
  300. var attrsBlocks = mixin.attributeBlocks;
  301. var pp = this.pp;
  302. var dynamic = mixin.name[0]==='#';
  303. var key = mixin.name;
  304. if (dynamic) this.dynamicMixins = true;
  305. name += (dynamic ? mixin.name.substr(2,mixin.name.length-3):'"'+mixin.name+'"')+']';
  306. this.mixins[key] = this.mixins[key] || {used: false, instances: []};
  307. if (mixin.call) {
  308. this.mixins[key].used = true;
  309. if (pp) this.buf.push("jade_indent.push('" + Array(this.indents + 1).join(' ') + "');")
  310. if (block || attrs.length || attrsBlocks.length) {
  311. this.buf.push(name + '.call({');
  312. if (block) {
  313. this.buf.push('block: function(){');
  314. // Render block with no indents, dynamically added when rendered
  315. this.parentIndents++;
  316. var _indents = this.indents;
  317. this.indents = 0;
  318. this.visit(mixin.block);
  319. this.indents = _indents;
  320. this.parentIndents--;
  321. if (attrs.length || attrsBlocks.length) {
  322. this.buf.push('},');
  323. } else {
  324. this.buf.push('}');
  325. }
  326. }
  327. if (attrsBlocks.length) {
  328. if (attrs.length) {
  329. var val = this.attrs(attrs);
  330. attrsBlocks.unshift(val);
  331. }
  332. this.buf.push('attributes: jade.merge([' + attrsBlocks.join(',') + '])');
  333. } else if (attrs.length) {
  334. var val = this.attrs(attrs);
  335. this.buf.push('attributes: ' + val);
  336. }
  337. if (args) {
  338. this.buf.push('}, ' + args + ');');
  339. } else {
  340. this.buf.push('});');
  341. }
  342. } else {
  343. this.buf.push(name + '(' + args + ');');
  344. }
  345. if (pp) this.buf.push("jade_indent.pop();")
  346. } else {
  347. var mixin_start = this.buf.length;
  348. this.buf.push(name + ' = function(' + args + '){');
  349. this.buf.push('var block = (this && this.block), attributes = (this && this.attributes) || {};');
  350. this.parentIndents++;
  351. this.visit(block);
  352. this.parentIndents--;
  353. this.buf.push('};');
  354. var mixin_end = this.buf.length;
  355. this.mixins[key].instances.push({start: mixin_start, end: mixin_end});
  356. }
  357. },
  358. /**
  359. * Visit `tag` buffering tag markup, generating
  360. * attributes, visiting the `tag`'s code and block.
  361. *
  362. * @param {Tag} tag
  363. * @api public
  364. */
  365. visitTag: function(tag){
  366. this.indents++;
  367. var name = tag.name
  368. , pp = this.pp
  369. , self = this;
  370. function bufferName() {
  371. if (tag.buffer) self.bufferExpression(name);
  372. else self.buffer(name);
  373. }
  374. if ('pre' == tag.name) this.escape = true;
  375. if (!this.hasCompiledTag) {
  376. if (!this.hasCompiledDoctype && 'html' == name) {
  377. this.visitDoctype();
  378. }
  379. this.hasCompiledTag = true;
  380. }
  381. // pretty print
  382. if (pp && !tag.isInline())
  383. this.prettyIndent(0, true);
  384. if (tag.selfClosing || (!this.xml && selfClosing.indexOf(tag.name) !== -1)) {
  385. this.buffer('<');
  386. bufferName();
  387. this.visitAttributes(tag.attrs, tag.attributeBlocks);
  388. this.terse
  389. ? this.buffer('>')
  390. : this.buffer('/>');
  391. // if it is non-empty throw an error
  392. if (tag.block &&
  393. !(tag.block.type === 'Block' && tag.block.nodes.length === 0) &&
  394. tag.block.nodes.some(function (tag) {
  395. return tag.type !== 'Text' || !/^\s*$/.test(tag.val)
  396. })) {
  397. throw errorAtNode(tag, new Error(name + ' is self closing and should not have content.'));
  398. }
  399. } else {
  400. // Optimize attributes buffering
  401. this.buffer('<');
  402. bufferName();
  403. this.visitAttributes(tag.attrs, tag.attributeBlocks);
  404. this.buffer('>');
  405. if (tag.code) this.visitCode(tag.code);
  406. this.visit(tag.block);
  407. // pretty print
  408. if (pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline())
  409. this.prettyIndent(0, true);
  410. this.buffer('</');
  411. bufferName();
  412. this.buffer('>');
  413. }
  414. if ('pre' == tag.name) this.escape = false;
  415. this.indents--;
  416. },
  417. /**
  418. * Visit `filter`, throwing when the filter does not exist.
  419. *
  420. * @param {Filter} filter
  421. * @api public
  422. */
  423. visitFilter: function(filter){
  424. var text = filter.block.nodes.map(
  425. function(node){ return node.val; }
  426. ).join('\n');
  427. filter.attrs.filename = this.options.filename;
  428. try {
  429. this.buffer(filters(filter.name, text, filter.attrs), true);
  430. } catch (err) {
  431. throw errorAtNode(filter, err);
  432. }
  433. },
  434. /**
  435. * Visit `text` node.
  436. *
  437. * @param {Text} text
  438. * @api public
  439. */
  440. visitText: function(text){
  441. this.buffer(text.val, true);
  442. },
  443. /**
  444. * Visit a `comment`, only buffering when the buffer flag is set.
  445. *
  446. * @param {Comment} comment
  447. * @api public
  448. */
  449. visitComment: function(comment){
  450. if (!comment.buffer) return;
  451. if (this.pp) this.prettyIndent(1, true);
  452. this.buffer('<!--' + comment.val + '-->');
  453. },
  454. /**
  455. * Visit a `BlockComment`.
  456. *
  457. * @param {Comment} comment
  458. * @api public
  459. */
  460. visitBlockComment: function(comment){
  461. if (!comment.buffer) return;
  462. if (this.pp) this.prettyIndent(1, true);
  463. this.buffer('<!--' + comment.val);
  464. this.visit(comment.block);
  465. if (this.pp) this.prettyIndent(1, true);
  466. this.buffer('-->');
  467. },
  468. /**
  469. * Visit `code`, respecting buffer / escape flags.
  470. * If the code is followed by a block, wrap it in
  471. * a self-calling function.
  472. *
  473. * @param {Code} code
  474. * @api public
  475. */
  476. visitCode: function(code){
  477. // Wrap code blocks with {}.
  478. // we only wrap unbuffered code blocks ATM
  479. // since they are usually flow control
  480. // Buffer code
  481. if (code.buffer) {
  482. var val = code.val.trimLeft();
  483. val = 'null == (jade_interp = '+val+') ? "" : jade_interp';
  484. if (code.escape) val = 'jade.escape(' + val + ')';
  485. this.bufferExpression(val);
  486. } else {
  487. this.buf.push(code.val);
  488. }
  489. // Block support
  490. if (code.block) {
  491. if (!code.buffer) this.buf.push('{');
  492. this.visit(code.block);
  493. if (!code.buffer) this.buf.push('}');
  494. }
  495. },
  496. /**
  497. * Visit `each` block.
  498. *
  499. * @param {Each} each
  500. * @api public
  501. */
  502. visitEach: function(each){
  503. this.buf.push(''
  504. + '// iterate ' + each.obj + '\n'
  505. + ';(function(){\n'
  506. + ' var $$obj = ' + each.obj + ';\n'
  507. + ' if (\'number\' == typeof $$obj.length) {\n');
  508. if (each.alternative) {
  509. this.buf.push(' if ($$obj.length) {');
  510. }
  511. this.buf.push(''
  512. + ' for (var ' + each.key + ' = 0, $$l = $$obj.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n'
  513. + ' var ' + each.val + ' = $$obj[' + each.key + '];\n');
  514. this.visit(each.block);
  515. this.buf.push(' }\n');
  516. if (each.alternative) {
  517. this.buf.push(' } else {');
  518. this.visit(each.alternative);
  519. this.buf.push(' }');
  520. }
  521. this.buf.push(''
  522. + ' } else {\n'
  523. + ' var $$l = 0;\n'
  524. + ' for (var ' + each.key + ' in $$obj) {\n'
  525. + ' $$l++;'
  526. + ' var ' + each.val + ' = $$obj[' + each.key + '];\n');
  527. this.visit(each.block);
  528. this.buf.push(' }\n');
  529. if (each.alternative) {
  530. this.buf.push(' if ($$l === 0) {');
  531. this.visit(each.alternative);
  532. this.buf.push(' }');
  533. }
  534. this.buf.push(' }\n}).call(this);\n');
  535. },
  536. /**
  537. * Visit `attrs`.
  538. *
  539. * @param {Array} attrs
  540. * @api public
  541. */
  542. visitAttributes: function(attrs, attributeBlocks){
  543. if (attributeBlocks.length) {
  544. if (attrs.length) {
  545. var val = this.attrs(attrs);
  546. attributeBlocks.unshift(val);
  547. }
  548. this.bufferExpression('jade.attrs(jade.merge([' + attributeBlocks.join(',') + ']), ' + JSON.stringify(this.terse) + ')');
  549. } else if (attrs.length) {
  550. this.attrs(attrs, true);
  551. }
  552. },
  553. /**
  554. * Compile attributes.
  555. */
  556. attrs: function(attrs, buffer){
  557. var buf = [];
  558. var classes = [];
  559. var classEscaping = [];
  560. attrs.forEach(function(attr){
  561. var key = attr.name;
  562. var escaped = attr.escaped;
  563. if (key === 'class') {
  564. classes.push(attr.val);
  565. classEscaping.push(attr.escaped);
  566. } else if (isConstant(attr.val)) {
  567. if (buffer) {
  568. this.buffer(runtime.attr(key, toConstant(attr.val), escaped, this.terse));
  569. } else {
  570. var val = toConstant(attr.val);
  571. if (escaped && !(key.indexOf('data') === 0 && typeof val !== 'string')) {
  572. val = runtime.escape(val);
  573. }
  574. buf.push(JSON.stringify(key) + ': ' + JSON.stringify(val));
  575. }
  576. } else {
  577. if (buffer) {
  578. this.bufferExpression('jade.attr("' + key + '", ' + attr.val + ', ' + JSON.stringify(escaped) + ', ' + JSON.stringify(this.terse) + ')');
  579. } else {
  580. var val = attr.val;
  581. if (escaped && !(key.indexOf('data') === 0)) {
  582. val = 'jade.escape(' + val + ')';
  583. } else if (escaped) {
  584. val = '(typeof (jade_interp = ' + val + ') == "string" ? jade.escape(jade_interp) : jade_interp)';
  585. }
  586. buf.push(JSON.stringify(key) + ': ' + val);
  587. }
  588. }
  589. }.bind(this));
  590. if (buffer) {
  591. if (classes.every(isConstant)) {
  592. this.buffer(runtime.cls(classes.map(toConstant), classEscaping));
  593. } else {
  594. this.bufferExpression('jade.cls([' + classes.join(',') + '], ' + JSON.stringify(classEscaping) + ')');
  595. }
  596. } else if (classes.length) {
  597. if (classes.every(isConstant)) {
  598. classes = JSON.stringify(runtime.joinClasses(classes.map(toConstant).map(runtime.joinClasses).map(function (cls, i) {
  599. return classEscaping[i] ? runtime.escape(cls) : cls;
  600. })));
  601. } else {
  602. classes = '(jade_interp = ' + JSON.stringify(classEscaping) + ',' +
  603. ' jade.joinClasses([' + classes.join(',') + '].map(jade.joinClasses).map(function (cls, i) {' +
  604. ' return jade_interp[i] ? jade.escape(cls) : cls' +
  605. ' }))' +
  606. ')';
  607. }
  608. if (classes.length)
  609. buf.push('"class": ' + classes);
  610. }
  611. return '{' + buf.join(',') + '}';
  612. }
  613. };
  614. },{"./doctypes":2,"./filters":3,"./nodes":16,"./runtime":24,"./utils":25,"character-parser":32,"constantinople":33,"void-elements":45}],2:[function(require,module,exports){
  615. 'use strict';
  616. module.exports = {
  617. 'default': '<!DOCTYPE html>'
  618. , 'xml': '<?xml version="1.0" encoding="utf-8" ?>'
  619. , 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
  620. , 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
  621. , 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">'
  622. , '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
  623. , 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">'
  624. , 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">'
  625. };
  626. },{}],3:[function(require,module,exports){
  627. 'use strict';
  628. module.exports = filter;
  629. function filter(name, str, options) {
  630. if (typeof filter[name] === 'function') {
  631. return filter[name](str, options);
  632. } else {
  633. throw new Error('unknown filter ":' + name + '"');
  634. }
  635. }
  636. },{}],4:[function(require,module,exports){
  637. 'use strict';
  638. module.exports = [
  639. 'a'
  640. , 'abbr'
  641. , 'acronym'
  642. , 'b'
  643. , 'br'
  644. , 'code'
  645. , 'em'
  646. , 'font'
  647. , 'i'
  648. , 'img'
  649. , 'ins'
  650. , 'kbd'
  651. , 'map'
  652. , 'samp'
  653. , 'small'
  654. , 'span'
  655. , 'strong'
  656. , 'sub'
  657. , 'sup'
  658. ];
  659. },{}],5:[function(require,module,exports){
  660. 'use strict';
  661. /*!
  662. * Jade
  663. * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
  664. * MIT Licensed
  665. */
  666. /**
  667. * Module dependencies.
  668. */
  669. var Parser = require('./parser')
  670. , Lexer = require('./lexer')
  671. , Compiler = require('./compiler')
  672. , runtime = require('./runtime')
  673. , addWith = require('with')
  674. , fs = require('fs');
  675. /**
  676. * Expose self closing tags.
  677. */
  678. exports.selfClosing = require('void-elements');
  679. /**
  680. * Default supported doctypes.
  681. */
  682. exports.doctypes = require('./doctypes');
  683. /**
  684. * Text filters.
  685. */
  686. exports.filters = require('./filters');
  687. /**
  688. * Utilities.
  689. */
  690. exports.utils = require('./utils');
  691. /**
  692. * Expose `Compiler`.
  693. */
  694. exports.Compiler = Compiler;
  695. /**
  696. * Expose `Parser`.
  697. */
  698. exports.Parser = Parser;
  699. /**
  700. * Expose `Lexer`.
  701. */
  702. exports.Lexer = Lexer;
  703. /**
  704. * Nodes.
  705. */
  706. exports.nodes = require('./nodes');
  707. /**
  708. * Jade runtime helpers.
  709. */
  710. exports.runtime = runtime;
  711. /**
  712. * Template function cache.
  713. */
  714. exports.cache = {};
  715. /**
  716. * Parse the given `str` of jade and return a function body.
  717. *
  718. * @param {String} str
  719. * @param {Object} options
  720. * @return {Object}
  721. * @api private
  722. */
  723. function parse(str, options){
  724. // Parse
  725. var parser = new (options.parser || Parser)(str, options.filename, options);
  726. var tokens;
  727. try {
  728. // Parse
  729. tokens = parser.parse();
  730. } catch (err) {
  731. parser = parser.context();
  732. runtime.rethrow(err, parser.filename, parser.lexer.lineno, parser.input);
  733. }
  734. // Compile
  735. var compiler = new (options.compiler || Compiler)(tokens, options);
  736. var js;
  737. try {
  738. js = compiler.compile();
  739. } catch (err) {
  740. if (err.line && (err.filename || !options.filename)) {
  741. runtime.rethrow(err, err.filename, err.line, parser.input);
  742. }
  743. }
  744. // Debug compiler
  745. if (options.debug) {
  746. console.error('\nCompiled Function:\n\n\u001b[90m%s\u001b[0m', js.replace(/^/gm, ' '));
  747. }
  748. var globals = [];
  749. globals.push('jade');
  750. globals.push('jade_mixins');
  751. globals.push('jade_interp');
  752. globals.push('jade_debug');
  753. globals.push('buf');
  754. var body = ''
  755. + 'var buf = [];\n'
  756. + 'var jade_mixins = {};\n'
  757. + 'var jade_interp;\n'
  758. + (options.self
  759. ? 'var self = locals || {};\n' + js
  760. : addWith('locals || {}', '\n' + js, globals)) + ';'
  761. + 'return buf.join("");';
  762. return {body: body, dependencies: parser.dependencies};
  763. }
  764. /**
  765. * Compile a `Function` representation of the given jade `str`.
  766. *
  767. * Options:
  768. *
  769. * - `compileDebug` when `false` debugging code is stripped from the compiled
  770. template, when it is explicitly `true`, the source code is included in
  771. the compiled template for better accuracy.
  772. * - `filename` used to improve errors when `compileDebug` is not `false` and to resolve imports/extends
  773. *
  774. * @param {String} str
  775. * @param {Options} options
  776. * @return {Function}
  777. * @api public
  778. */
  779. exports.compile = function(str, options){
  780. var options = options || {}
  781. , filename = options.filename
  782. ? JSON.stringify(options.filename)
  783. : 'undefined'
  784. , fn;
  785. str = String(str);
  786. var parsed = parse(str, options);
  787. if (options.compileDebug !== false) {
  788. fn = [
  789. 'var jade_debug = [{ lineno: 1, filename: ' + filename + ' }];'
  790. , 'try {'
  791. , parsed.body
  792. , '} catch (err) {'
  793. , ' jade.rethrow(err, jade_debug[0].filename, jade_debug[0].lineno' + (options.compileDebug === true ? ',' + JSON.stringify(str) : '') + ');'
  794. , '}'
  795. ].join('\n');
  796. } else {
  797. fn = parsed.body;
  798. }
  799. fn = new Function('locals, jade', fn)
  800. var res = function(locals){ return fn(locals, Object.create(runtime)) };
  801. if (options.client) {
  802. res.toString = function () {
  803. var err = new Error('The `client` option is deprecated, use the `jade.compileClient` method instead');
  804. err.name = 'Warning';
  805. console.error(err.stack || err.message);
  806. return exports.compileClient(str, options);
  807. };
  808. }
  809. res.dependencies = parsed.dependencies;
  810. return res;
  811. };
  812. /**
  813. * Compile a JavaScript source representation of the given jade `str`.
  814. *
  815. * Options:
  816. *
  817. * - `compileDebug` When it is `true`, the source code is included in
  818. * the compiled template for better error messages.
  819. * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends
  820. * - `name` the name of the resulting function (defaults to "template")
  821. *
  822. * @param {String} str
  823. * @param {Options} options
  824. * @return {String}
  825. * @api public
  826. */
  827. exports.compileClient = function(str, options){
  828. var options = options || {};
  829. var name = options.name || 'template';
  830. var filename = options.filename ? JSON.stringify(options.filename) : 'undefined';
  831. var fn;
  832. str = String(str);
  833. if (options.compileDebug) {
  834. options.compileDebug = true;
  835. fn = [
  836. 'var jade_debug = [{ lineno: 1, filename: ' + filename + ' }];'
  837. , 'try {'
  838. , parse(str, options).body
  839. , '} catch (err) {'
  840. , ' jade.rethrow(err, jade_debug[0].filename, jade_debug[0].lineno, ' + JSON.stringify(str) + ');'
  841. , '}'
  842. ].join('\n');
  843. } else {
  844. options.compileDebug = false;
  845. fn = parse(str, options).body;
  846. }
  847. return 'function ' + name + '(locals) {\n' + fn + '\n}';
  848. };
  849. /**
  850. * Compile a `Function` representation of the given jade file.
  851. *
  852. * Options:
  853. *
  854. * - `compileDebug` when `false` debugging code is stripped from the compiled
  855. template, when it is explicitly `true`, the source code is included in
  856. the compiled template for better accuracy.
  857. *
  858. * @param {String} path
  859. * @param {Options} options
  860. * @return {Function}
  861. * @api public
  862. */
  863. exports.compileFile = function (path, options) {
  864. options = options || {};
  865. var key = path + ':string';
  866. options.filename = path;
  867. var str = options.cache
  868. ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8'))
  869. : fs.readFileSync(path, 'utf8');
  870. return options.cache
  871. ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options))
  872. : exports.compile(str, options);
  873. };
  874. /**
  875. * Render the given `str` of jade.
  876. *
  877. * Options:
  878. *
  879. * - `cache` enable template caching
  880. * - `filename` filename required for `include` / `extends` and caching
  881. *
  882. * @param {String} str
  883. * @param {Object|Function} options or fn
  884. * @param {Function|undefined} fn
  885. * @returns {String}
  886. * @api public
  887. */
  888. exports.render = function(str, options, fn){
  889. // support callback API
  890. if ('function' == typeof options) {
  891. fn = options, options = undefined;
  892. }
  893. if (typeof fn === 'function') {
  894. var res
  895. try {
  896. res = exports.render(str, options);
  897. } catch (ex) {
  898. return fn(ex);
  899. }
  900. return fn(null, res);
  901. }
  902. options = options || {};
  903. // cache requires .filename
  904. if (options.cache && !options.filename) {
  905. throw new Error('the "filename" option is required for caching');
  906. }
  907. var path = options.filename;
  908. var tmpl = options.cache
  909. ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options))
  910. : exports.compile(str, options);
  911. return tmpl(options);
  912. };
  913. /**
  914. * Render a Jade file at the given `path`.
  915. *
  916. * @param {String} path
  917. * @param {Object|Function} options or callback
  918. * @param {Function|undefined} fn
  919. * @returns {String}
  920. * @api public
  921. */
  922. exports.renderFile = function(path, options, fn){
  923. // support callback API
  924. if ('function' == typeof options) {
  925. fn = options, options = undefined;
  926. }
  927. if (typeof fn === 'function') {
  928. var res
  929. try {
  930. res = exports.renderFile(path, options);
  931. } catch (ex) {
  932. return fn(ex);
  933. }
  934. return fn(null, res);
  935. }
  936. options = options || {};
  937. var key = path + ':string';
  938. options.filename = path;
  939. var str = options.cache
  940. ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8'))
  941. : fs.readFileSync(path, 'utf8');
  942. return exports.render(str, options);
  943. };
  944. /**
  945. * Compile a Jade file at the given `path` for use on the client.
  946. *
  947. * @param {String} path
  948. * @param {Object} options
  949. * @returns {String}
  950. * @api public
  951. */
  952. exports.compileFileClient = function(path, options){
  953. options = options || {};
  954. var key = path + ':string';
  955. options.filename = path;
  956. var str = options.cache
  957. ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8'))
  958. : fs.readFileSync(path, 'utf8');
  959. return exports.compileClient(str, options);
  960. };
  961. /**
  962. * Express support.
  963. */
  964. exports.__express = exports.renderFile;
  965. },{"./compiler":1,"./doctypes":2,"./filters":3,"./lexer":6,"./nodes":16,"./parser":23,"./runtime":24,"./utils":25,"fs":26,"void-elements":45,"with":46}],6:[function(require,module,exports){
  966. 'use strict';
  967. var utils = require('./utils');
  968. var characterParser = require('character-parser');
  969. /**
  970. * Initialize `Lexer` with the given `str`.
  971. *
  972. * @param {String} str
  973. * @param {String} filename
  974. * @api private
  975. */
  976. var Lexer = module.exports = function Lexer(str, filename) {
  977. this.input = str.replace(/\r\n|\r/g, '\n');
  978. this.filename = filename;
  979. this.deferredTokens = [];
  980. this.lastIndents = 0;
  981. this.lineno = 1;
  982. this.stash = [];
  983. this.indentStack = [];
  984. this.indentRe = null;
  985. this.pipeless = false;
  986. };
  987. function assertExpression(exp) {
  988. //this verifies that a JavaScript expression is valid
  989. Function('', 'return (' + exp + ')');
  990. }
  991. function assertNestingCorrect(exp) {
  992. //this verifies that code is properly nested, but allows
  993. //invalid JavaScript such as the contents of `attributes`
  994. var res = characterParser(exp)
  995. if (res.isNesting()) {
  996. throw new Error('Nesting must match on expression `' + exp + '`')
  997. }
  998. }
  999. /**
  1000. * Lexer prototype.
  1001. */
  1002. Lexer.prototype = {
  1003. /**
  1004. * Construct a token with the given `type` and `val`.
  1005. *
  1006. * @param {String} type
  1007. * @param {String} val
  1008. * @return {Object}
  1009. * @api private
  1010. */
  1011. tok: function(type, val){
  1012. return {
  1013. type: type
  1014. , line: this.lineno
  1015. , val: val
  1016. }
  1017. },
  1018. /**
  1019. * Consume the given `len` of input.
  1020. *
  1021. * @param {Number} len
  1022. * @api private
  1023. */
  1024. consume: function(len){
  1025. this.input = this.input.substr(len);
  1026. },
  1027. /**
  1028. * Scan for `type` with the given `regexp`.
  1029. *
  1030. * @param {String} type
  1031. * @param {RegExp} regexp
  1032. * @return {Object}
  1033. * @api private
  1034. */
  1035. scan: function(regexp, type){
  1036. var captures;
  1037. if (captures = regexp.exec(this.input)) {
  1038. this.consume(captures[0].length);
  1039. return this.tok(type, captures[1]);
  1040. }
  1041. },
  1042. /**
  1043. * Defer the given `tok`.
  1044. *
  1045. * @param {Object} tok
  1046. * @api private
  1047. */
  1048. defer: function(tok){
  1049. this.deferredTokens.push(tok);
  1050. },
  1051. /**
  1052. * Lookahead `n` tokens.
  1053. *
  1054. * @param {Number} n
  1055. * @return {Object}
  1056. * @api private
  1057. */
  1058. lookahead: function(n){
  1059. var fetch = n - this.stash.length;
  1060. while (fetch-- > 0) this.stash.push(this.next());
  1061. return this.stash[--n];
  1062. },
  1063. /**
  1064. * Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters.
  1065. *
  1066. * @return {Number}
  1067. * @api private
  1068. */
  1069. bracketExpression: function(skip){
  1070. skip = skip || 0;
  1071. var start = this.input[skip];
  1072. if (start != '(' && start != '{' && start != '[') throw new Error('unrecognized start character');
  1073. var end = ({'(': ')', '{': '}', '[': ']'})[start];
  1074. var range = characterParser.parseMax(this.input, {start: skip + 1});
  1075. if (this.input[range.end] !== end) throw new Error('start character ' + start + ' does not match end character ' + this.input[range.end]);
  1076. return range;
  1077. },
  1078. /**
  1079. * Stashed token.
  1080. */
  1081. stashed: function() {
  1082. return this.stash.length
  1083. && this.stash.shift();
  1084. },
  1085. /**
  1086. * Deferred token.
  1087. */
  1088. deferred: function() {
  1089. return this.deferredTokens.length
  1090. && this.deferredTokens.shift();
  1091. },
  1092. /**
  1093. * end-of-source.
  1094. */
  1095. eos: function() {
  1096. if (this.input.length) return;
  1097. if (this.indentStack.length) {
  1098. this.indentStack.shift();
  1099. return this.tok('outdent');
  1100. } else {
  1101. return this.tok('eos');
  1102. }
  1103. },
  1104. /**
  1105. * Blank line.
  1106. */
  1107. blank: function() {
  1108. var captures;
  1109. if (captures = /^\n *\n/.exec(this.input)) {
  1110. this.consume(captures[0].length - 1);
  1111. ++this.lineno;
  1112. if (this.pipeless) return this.tok('text', '');
  1113. return this.next();
  1114. }
  1115. },
  1116. /**
  1117. * Comment.
  1118. */
  1119. comment: function() {
  1120. var captures;
  1121. if (captures = /^\/\/(-)?([^\n]*)/.exec(this.input)) {
  1122. this.consume(captures[0].length);
  1123. var tok = this.tok('comment', captures[2]);
  1124. tok.buffer = '-' != captures[1];
  1125. this.pipeless = true;
  1126. return tok;
  1127. }
  1128. },
  1129. /**
  1130. * Interpolated tag.
  1131. */
  1132. interpolation: function() {
  1133. if (/^#\{/.test(this.input)) {
  1134. var match;
  1135. try {
  1136. match = this.bracketExpression(1);
  1137. } catch (ex) {
  1138. return;//not an interpolation expression, just an unmatched open interpolation
  1139. }
  1140. this.consume(match.end + 1);
  1141. return this.tok('interpolation', match.src);
  1142. }
  1143. },
  1144. /**
  1145. * Tag.
  1146. */
  1147. tag: function() {
  1148. var captures;
  1149. if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) {
  1150. this.consume(captures[0].length);
  1151. var tok, name = captures[1];
  1152. if (':' == name[name.length - 1]) {
  1153. name = name.slice(0, -1);
  1154. tok = this.tok('tag', name);
  1155. this.defer(this.tok(':'));
  1156. while (' ' == this.input[0]) this.input = this.input.substr(1);
  1157. } else {
  1158. tok = this.tok('tag', name);
  1159. }
  1160. tok.selfClosing = !!captures[2];
  1161. return tok;
  1162. }
  1163. },
  1164. /**
  1165. * Filter.
  1166. */
  1167. filter: function() {
  1168. var tok = this.scan(/^:([\w\-]+)/, 'filter');
  1169. if (tok) {
  1170. this.pipeless = true;
  1171. return tok;
  1172. }
  1173. },
  1174. /**
  1175. * Doctype.
  1176. */
  1177. doctype: function() {
  1178. if (this.scan(/^!!! *([^\n]+)?/, 'doctype')) {
  1179. throw new Error('`!!!` is deprecated, you must now use `doctype`');
  1180. }
  1181. var node = this.scan(/^(?:doctype) *([^\n]+)?/, 'doctype');
  1182. if (node && node.val && node.val.trim() === '5') {
  1183. throw new Error('`doctype 5` is deprecated, you must now use `doctype html`');
  1184. }
  1185. return node;
  1186. },
  1187. /**
  1188. * Id.
  1189. */
  1190. id: function() {
  1191. return this.scan(/^#([\w-]+)/, 'id');
  1192. },
  1193. /**
  1194. * Class.
  1195. */
  1196. className: function() {
  1197. return this.scan(/^\.([\w-]+)/, 'class');
  1198. },
  1199. /**
  1200. * Text.
  1201. */
  1202. text: function() {
  1203. return this.scan(/^(?:\| ?| )([^\n]+)/, 'text') ||
  1204. this.scan(/^\|?( )/, 'text') ||
  1205. this.scan(/^(<[^\n]*)/, 'text');
  1206. },
  1207. textFail: function () {
  1208. var tok;
  1209. if (tok = this.scan(/^([^\.\n][^\n]+)/, 'text')) {
  1210. console.warn('Warning: missing space before text for line ' + this.lineno +
  1211. ' of jade file "' + this.filename + '"');
  1212. return tok;
  1213. }
  1214. },
  1215. /**
  1216. * Dot.
  1217. */
  1218. dot: function() {
  1219. var match;
  1220. if (match = this.scan(/^\./, 'dot')) {
  1221. this.pipeless = true;
  1222. return match;
  1223. }
  1224. },
  1225. /**
  1226. * Extends.
  1227. */
  1228. "extends": function() {
  1229. return this.scan(/^extends? +([^\n]+)/, 'extends');
  1230. },
  1231. /**
  1232. * Block prepend.
  1233. */
  1234. prepend: function() {
  1235. var captures;
  1236. if (captures = /^prepend +([^\n]+)/.exec(this.input)) {
  1237. this.consume(captures[0].length);
  1238. var mode = 'prepend'
  1239. , name = captures[1]
  1240. , tok = this.tok('block', name);
  1241. tok.mode = mode;
  1242. return tok;
  1243. }
  1244. },
  1245. /**
  1246. * Block append.
  1247. */
  1248. append: function() {
  1249. var captures;
  1250. if (captures = /^append +([^\n]+)/.exec(this.input)) {
  1251. this.consume(captures[0].length);
  1252. var mode = 'append'
  1253. , name = captures[1]
  1254. , tok = this.tok('block', name);
  1255. tok.mode = mode;
  1256. return tok;
  1257. }
  1258. },
  1259. /**
  1260. * Block.
  1261. */
  1262. block: function() {
  1263. var captures;
  1264. if (captures = /^block\b *(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) {
  1265. this.consume(captures[0].length);
  1266. var mode = captures[1] || 'replace'
  1267. , name = captures[2]
  1268. , tok = this.tok('block', name);
  1269. tok.mode = mode;
  1270. return tok;
  1271. }
  1272. },
  1273. /**
  1274. * Mixin Block.
  1275. */
  1276. mixinBlock: function() {
  1277. var captures;
  1278. if (captures = /^block[ \t]*(\n|$)/.exec(this.input)) {
  1279. this.consume(captures[0].length - captures[1].length);
  1280. return this.tok('mixin-block');
  1281. }
  1282. },
  1283. /**
  1284. * Yield.
  1285. */
  1286. 'yield': function() {
  1287. return this.scan(/^yield */, 'yield');
  1288. },
  1289. /**
  1290. * Include.
  1291. */
  1292. include: function() {
  1293. return this.scan(/^include +([^\n]+)/, 'include');
  1294. },
  1295. /**
  1296. * Include with filter
  1297. */
  1298. includeFiltered: function() {
  1299. var captures;
  1300. if (captures = /^include:([\w\-]+)([\( ])/.exec(this.input)) {
  1301. this.consume(captures[0].length - 1);
  1302. var filter = captures[1];
  1303. var attrs = captures[2] === '(' ? this.attrs() : null;
  1304. if (!(captures[2] === ' ' || this.input[0] === ' ')) {
  1305. throw new Error('expected space after include:filter but got ' + JSON.stringify(this.input[0]));
  1306. }
  1307. captures = /^ *([^\n]+)/.exec(this.input);
  1308. if (!captures || captures[1].trim() === '') {
  1309. throw new Error('missing path for include:filter');
  1310. }
  1311. this.consume(captures[0].length);
  1312. var path = captures[1];
  1313. var tok = this.tok('include', path);
  1314. tok.filter = filter;
  1315. tok.attrs = attrs;
  1316. return tok;
  1317. }
  1318. },
  1319. /**
  1320. * Case.
  1321. */
  1322. "case": function() {
  1323. return this.scan(/^case +([^\n]+)/, 'case');
  1324. },
  1325. /**
  1326. * When.
  1327. */
  1328. when: function() {
  1329. return this.scan(/^when +([^:\n]+)/, 'when');
  1330. },
  1331. /**
  1332. * Default.
  1333. */
  1334. "default": function() {
  1335. return this.scan(/^default */, 'default');
  1336. },
  1337. /**
  1338. * Call mixin.
  1339. */
  1340. call: function(){
  1341. var tok, captures;
  1342. if (captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input)) {
  1343. // try to consume simple or interpolated call
  1344. if (captures[3]) {
  1345. // simple call
  1346. this.consume(captures[0].length);
  1347. tok = this.tok('call', captures[3]);
  1348. } else {
  1349. // interpolated call
  1350. var match;
  1351. try {
  1352. match = this.bracketExpression(2 + captures[1].length);
  1353. } catch (ex) {
  1354. return;//not an interpolation expression, just an unmatched open interpolation
  1355. }
  1356. this.consume(match.end + 1);
  1357. assertExpression(match.src);
  1358. tok = this.tok('call', '#{'+match.src+'}');
  1359. }
  1360. // Check for args (not attributes)
  1361. if (captures = /^ *\(/.exec(this.input)) {
  1362. try {
  1363. var range = this.bracketExpression(captures[0].length - 1);
  1364. if (!/^\s*[-\w]+ *=/.test(range.src)) { // not attributes
  1365. this.consume(range.end + 1);
  1366. tok.args = range.src;
  1367. }
  1368. } catch (ex) {
  1369. //not a bracket expcetion, just unmatched open parens
  1370. }
  1371. }
  1372. return tok;
  1373. }
  1374. },
  1375. /**
  1376. * Mixin.
  1377. */
  1378. mixin: function(){
  1379. var captures;
  1380. if (captures = /^mixin +([-\w]+)(?: *\((.*)\))? */.exec(this.input)) {
  1381. this.consume(captures[0].length);
  1382. var tok = this.tok('mixin', captures[1]);
  1383. tok.args = captures[2];
  1384. return tok;
  1385. }
  1386. },
  1387. /**
  1388. * Conditional.
  1389. */
  1390. conditional: function() {
  1391. var captures;
  1392. if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
  1393. this.consume(captures[0].length);
  1394. var type = captures[1]
  1395. var js = captures[2];
  1396. var isIf = false;
  1397. var isElse = false;
  1398. switch (type) {
  1399. case 'if':
  1400. assertExpression(js)
  1401. js = 'if (' + js + ')';
  1402. isIf = true;
  1403. break;
  1404. case 'unless':
  1405. assertExpression(js)
  1406. js = 'if (!(' + js + '))';
  1407. isIf = true;
  1408. break;
  1409. case 'else if':
  1410. assertExpression(js)
  1411. js = 'else if (' + js + ')';
  1412. isIf = true;
  1413. isElse = true;
  1414. break;
  1415. case 'else':
  1416. if (js && js.trim()) {
  1417. throw new Error('`else` cannot have a condition, perhaps you meant `else if`');
  1418. }
  1419. js = 'else';
  1420. isElse = true;
  1421. break;
  1422. }
  1423. var tok = this.tok('code', js);
  1424. tok.isElse = isElse;
  1425. tok.isIf = isIf;
  1426. tok.requiresBlock = true;
  1427. return tok;
  1428. }
  1429. },
  1430. /**
  1431. * While.
  1432. */
  1433. "while": function() {
  1434. var captures;
  1435. if (captures = /^while +([^\n]+)/.exec(this.input)) {
  1436. this.consume(captures[0].length);
  1437. assertExpression(captures[1])
  1438. var tok = this.tok('code', 'while (' + captures[1] + ')');
  1439. tok.requiresBlock = true;
  1440. return tok;
  1441. }
  1442. },
  1443. /**
  1444. * Each.
  1445. */
  1446. each: function() {
  1447. var captures;
  1448. if (captures = /^(?:- *)?(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec(this.input)) {
  1449. this.consume(captures[0].length);
  1450. var tok = this.tok('each', captures[1]);
  1451. tok.key = captures[2] || '$index';
  1452. assertExpression(captures[3])
  1453. tok.code = captures[3];
  1454. return tok;
  1455. }
  1456. },
  1457. /**
  1458. * Code.
  1459. */
  1460. code: function() {
  1461. var captures;
  1462. if (captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input)) {
  1463. this.consume(captures[0].length);
  1464. var flags = captures[1];
  1465. captures[1] = captures[2];
  1466. var tok = this.tok('code', captures[1]);
  1467. tok.escape = flags.charAt(0) === '=';
  1468. tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '=';
  1469. if (tok.buffer) assertExpression(captures[1])
  1470. return tok;
  1471. }
  1472. },
  1473. /**
  1474. * Attributes.
  1475. */
  1476. attrs: function() {
  1477. if ('(' == this.input.charAt(0)) {
  1478. var index = this.bracketExpression().end
  1479. , str = this.input.substr(1, index-1)
  1480. , tok = this.tok('attrs');
  1481. assertNestingCorrect(str);
  1482. var quote = '';
  1483. var interpolate = function (attr) {
  1484. return attr.replace(/(\\)?#\{(.+)/g, function(_, escape, expr){
  1485. if (escape) return _;
  1486. try {
  1487. var range = characterParser.parseMax(expr);
  1488. if (expr[range.end] !== '}') return _.substr(0, 2) + interpolate(_.substr(2));
  1489. assertExpression(range.src)
  1490. return quote + " + (" + range.src + ") + " + quote + interpolate(expr.substr(range.end + 1));
  1491. } catch (ex) {
  1492. return _.substr(0, 2) + interpolate(_.substr(2));
  1493. }
  1494. });
  1495. }
  1496. this.consume(index + 1);
  1497. tok.attrs = [];
  1498. var escapedAttr = true
  1499. var key = '';
  1500. var val = '';
  1501. var interpolatable = '';
  1502. var state = characterParser.defaultState();
  1503. var loc = 'key';
  1504. var isEndOfAttribute = function (i) {
  1505. if (key.trim() === '') return false;
  1506. if (i === str.length) return true;
  1507. if (loc === 'key') {
  1508. if (str[i] === ' ' || str[i] === '\n') {
  1509. for (var x = i; x < str.length; x++) {
  1510. if (str[x] != ' ' && str[x] != '\n') {
  1511. if (str[x] === '=' || str[x] === '!' || str[x] === ',') return false;
  1512. else return true;
  1513. }
  1514. }
  1515. }
  1516. return str[i] === ','
  1517. } else if (loc === 'value' && !state.isNesting()) {
  1518. try {
  1519. Function('', 'return (' + val + ');');
  1520. if (str[i] === ' ' || str[i] === '\n') {
  1521. for (var x = i; x < str.length; x++) {
  1522. if (str[x] != ' ' && str[x] != '\n') {
  1523. if (characterParser.isPunctuator(str[x]) && str[x] != '"' && str[x] != "'") return false;
  1524. else return true;
  1525. }
  1526. }
  1527. }
  1528. return str[i] === ',';
  1529. } catch (ex) {
  1530. return false;
  1531. }
  1532. }
  1533. }
  1534. this.lineno += str.split("\n").length - 1;
  1535. for (var i = 0; i <= str.length; i++) {
  1536. if (isEndOfAttribute(i)) {
  1537. val = val.trim();
  1538. if (val) assertExpression(val)
  1539. key = key.trim();
  1540. key = key.replace(/^['"]|['"]$/g, '');
  1541. tok.attrs.push({
  1542. name: key,
  1543. val: '' == val ? true : val,
  1544. escaped: escapedAttr
  1545. });
  1546. key = val = '';
  1547. loc = 'key';
  1548. escapedAttr = false;
  1549. } else {
  1550. switch (loc) {
  1551. case 'key-char':
  1552. if (str[i] === quote) {
  1553. loc = 'key';
  1554. if (i + 1 < str.length && [' ', ',', '!', '=', '\n'].indexOf(str[i + 1]) === -1)
  1555. throw new Error('Unexpected character ' + str[i + 1] + ' expected ` `, `\\n`, `,`, `!` or `=`');
  1556. } else {
  1557. key += str[i];
  1558. }
  1559. break;
  1560. case 'key':
  1561. if (key === '' && (str[i] === '"' || str[i] === "'")) {
  1562. loc = 'key-char';
  1563. quote = str[i];
  1564. } else if (str[i] === '!' || str[i] === '=') {
  1565. escapedAttr = str[i] !== '!';
  1566. if (str[i] === '!') i++;
  1567. if (str[i] !== '=') throw new Error('Unexpected character ' + str[i] + ' expected `=`');
  1568. loc = 'value';
  1569. state = characterParser.defaultState();
  1570. } else {
  1571. key += str[i]
  1572. }
  1573. break;
  1574. case 'value':
  1575. state = characterParser.parseChar(str[i], state);
  1576. if (state.isString()) {
  1577. loc = 'string';
  1578. quote = str[i];
  1579. interpolatable = str[i];
  1580. } else {
  1581. val += str[i];
  1582. }
  1583. break;
  1584. case 'string':
  1585. state = characterParser.parseChar(str[i], state);
  1586. interpolatable += str[i];
  1587. if (!state.isString()) {
  1588. loc = 'value';
  1589. val += interpolate(interpolatable);
  1590. }
  1591. break;
  1592. }
  1593. }
  1594. }
  1595. if ('/' == this.input.charAt(0)) {
  1596. this.consume(1);
  1597. tok.selfClosing = true;
  1598. }
  1599. return tok;
  1600. }
  1601. },
  1602. /**
  1603. * &attributes block
  1604. */
  1605. attributesBlock: function () {
  1606. var captures;
  1607. if (/^&attributes\b/.test(this.input)) {
  1608. this.consume(11);
  1609. var args = this.bracketExpression();
  1610. this.consume(args.end + 1);
  1611. return this.tok('&attributes', args.src);
  1612. }
  1613. },
  1614. /**
  1615. * Indent | Outdent | Newline.
  1616. */
  1617. indent: function() {
  1618. var captures, re;
  1619. // established regexp
  1620. if (this.indentRe) {
  1621. captures = this.indentRe.exec(this.input);
  1622. // determine regexp
  1623. } else {
  1624. // tabs
  1625. re = /^\n(\t*) */;
  1626. captures = re.exec(this.input);
  1627. // spaces
  1628. if (captures && !captures[1].length) {
  1629. re = /^\n( *)/;
  1630. captures = re.exec(this.input);
  1631. }
  1632. // established
  1633. if (captures && captures[1].length) this.indentRe = re;
  1634. }
  1635. if (captures) {
  1636. var tok
  1637. , indents = captures[1].length;
  1638. ++this.lineno;
  1639. this.consume(indents + 1);
  1640. if (' ' == this.input[0] || '\t' == this.input[0]) {
  1641. throw new Error('Invalid indentation, you can use tabs or spaces but not both');
  1642. }
  1643. // blank line
  1644. if ('\n' == this.input[0]) {
  1645. this.pipeless = false;
  1646. return this.tok('newline');
  1647. }
  1648. // outdent
  1649. if (this.indentStack.length && indents < this.indentStack[0]) {
  1650. while (this.indentStack.length && this.indentStack[0] > indents) {
  1651. this.stash.push(this.tok('outdent'));
  1652. this.indentStack.shift();
  1653. }
  1654. tok = this.stash.pop();
  1655. // indent
  1656. } else if (indents && indents != this.indentStack[0]) {
  1657. this.indentStack.unshift(indents);
  1658. tok = this.tok('indent', indents);
  1659. // newline
  1660. } else {
  1661. tok = this.tok('newline');
  1662. }
  1663. this.pipeless = false;
  1664. return tok;
  1665. }
  1666. },
  1667. /**
  1668. * Pipe-less text consumed only when
  1669. * pipeless is true;
  1670. */
  1671. pipelessText: function() {
  1672. if (!this.pipeless) return;
  1673. var captures, re;
  1674. // established regexp
  1675. if (this.indentRe) {
  1676. captures = this.indentRe.exec(this.input);
  1677. // determine regexp
  1678. } else {
  1679. // tabs
  1680. re = /^\n(\t*) */;
  1681. captures = re.exec(this.input);
  1682. // spaces
  1683. if (captures && !captures[1].length) {
  1684. re = /^\n( *)/;
  1685. captures = re.exec(this.input);
  1686. }
  1687. // established
  1688. if (captures && captures[1].length) this.indentRe = re;
  1689. }
  1690. var indents = captures && captures[1].length;
  1691. if (indents && (this.indentStack.length === 0 || indents > this.indentStack[0])) {
  1692. var indent = captures[1];
  1693. var line;
  1694. var tokens = [];
  1695. var isMatch;
  1696. do {
  1697. // text has `\n` as a prefix
  1698. var i = this.input.substr(1).indexOf('\n');
  1699. if (-1 == i) i = this.input.length - 1;
  1700. var str = this.input.substr(1, i);
  1701. isMatch = str.substr(0, indent.length) === indent || !str.trim();
  1702. if (isMatch) {
  1703. // consume test along with `\n` prefix if match
  1704. this.consume(str.length + 1);
  1705. tokens.push(str.substr(indent.length));
  1706. }
  1707. } while(this.input.length && isMatch);
  1708. while (this.input.length === 0 && tokens[tokens.length - 1] === '') tokens.pop();
  1709. return this.tok('pipeless-text', tokens);
  1710. }
  1711. },
  1712. /**
  1713. * ':'
  1714. */
  1715. colon: function() {
  1716. return this.scan(/^: */, ':');
  1717. },
  1718. fail: function () {
  1719. throw new Error('unexpected text ' + this.input.substr(0, 5));
  1720. },
  1721. /**
  1722. * Return the next token object, or those
  1723. * previously stashed by lookahead.
  1724. *
  1725. * @return {Object}
  1726. * @api private
  1727. */
  1728. advance: function(){
  1729. return this.stashed()
  1730. || this.next();
  1731. },
  1732. /**
  1733. * Return the next token object.
  1734. *
  1735. * @return {Object}
  1736. * @api private
  1737. */
  1738. next: function() {
  1739. return this.deferred()
  1740. || this.blank()
  1741. || this.eos()
  1742. || this.pipelessText()
  1743. || this.yield()
  1744. || this.doctype()
  1745. || this.interpolation()
  1746. || this["case"]()
  1747. || this.when()
  1748. || this["default"]()
  1749. || this["extends"]()
  1750. || this.append()
  1751. || this.prepend()
  1752. || this.block()
  1753. || this.mixinBlock()
  1754. || this.include()
  1755. || this.includeFiltered()
  1756. || this.mixin()
  1757. || this.call()
  1758. || this.conditional()
  1759. || this.each()
  1760. || this["while"]()
  1761. || this.tag()
  1762. || this.filter()
  1763. || this.code()
  1764. || this.id()
  1765. || this.className()
  1766. || this.attrs()
  1767. || this.attributesBlock()
  1768. || this.indent()
  1769. || this.text()
  1770. || this.comment()
  1771. || this.colon()
  1772. || this.dot()
  1773. || this.textFail()
  1774. || this.fail();
  1775. }
  1776. };
  1777. },{"./utils":25,"character-parser":32}],7:[function(require,module,exports){
  1778. 'use strict';
  1779. var Node = require('./node');
  1780. /**
  1781. * Initialize a `Attrs` node.
  1782. *
  1783. * @api public
  1784. */
  1785. var Attrs = module.exports = function Attrs() {
  1786. this.attributeNames = [];
  1787. this.attrs = [];
  1788. this.attributeBlocks = [];
  1789. };
  1790. // Inherit from `Node`.
  1791. Attrs.prototype = Object.create(Node.prototype);
  1792. Attrs.prototype.constructor = Attrs;
  1793. Attrs.prototype.type = 'Attrs';
  1794. /**
  1795. * Set attribute `name` to `val`, keep in mind these become
  1796. * part of a raw js object literal, so to quote a value you must
  1797. * '"quote me"', otherwise or example 'user.name' is literal JavaScript.
  1798. *
  1799. * @param {String} name
  1800. * @param {String} val
  1801. * @param {Boolean} escaped
  1802. * @return {Tag} for chaining
  1803. * @api public
  1804. */
  1805. Attrs.prototype.setAttribute = function(name, val, escaped){
  1806. if (name !== 'class' && this.attributeNames.indexOf(name) !== -1) {
  1807. throw new Error('Duplicate attribute "' + name + '" is not allowed.');
  1808. }
  1809. this.attributeNames.push(name);
  1810. this.attrs.push({ name: name, val: val, escaped: escaped });
  1811. return this;
  1812. };
  1813. /**
  1814. * Remove attribute `name` when present.
  1815. *
  1816. * @param {String} name
  1817. * @api public
  1818. */
  1819. Attrs.prototype.removeAttribute = function(name){
  1820. var err = new Error('attrs.removeAttribute is deprecated and will be removed in v2.0.0');
  1821. console.warn(err.stack);
  1822. for (var i = 0, len = this.attrs.length; i < len; ++i) {
  1823. if (this.attrs[i] && this.attrs[i].name == name) {
  1824. delete this.attrs[i];
  1825. }
  1826. }
  1827. };
  1828. /**
  1829. * Get attribute value by `name`.
  1830. *
  1831. * @param {String} name
  1832. * @return {String}
  1833. * @api public
  1834. */
  1835. Attrs.prototype.getAttribute = function(name){
  1836. var err = new Error('attrs.getAttribute is deprecated and will be removed in v2.0.0');
  1837. console.warn(err.stack);
  1838. for (var i = 0, len = this.attrs.length; i < len; ++i) {
  1839. if (this.attrs[i] && this.attrs[i].name == name) {
  1840. return this.attrs[i].val;
  1841. }
  1842. }
  1843. };
  1844. Attrs.prototype.addAttributes = function (src) {
  1845. this.attributeBlocks.push(src);
  1846. };
  1847. },{"./node":20}],8:[function(require,module,exports){
  1848. 'use strict';
  1849. var Node = require('./node');
  1850. /**
  1851. * Initialize a `BlockComment` with the given `block`.
  1852. *
  1853. * @param {String} val
  1854. * @param {Block} block
  1855. * @param {Boolean} buffer
  1856. * @api public
  1857. */
  1858. var BlockComment = module.exports = function BlockComment(val, block, buffer) {
  1859. this.block = block;
  1860. this.val = val;
  1861. this.buffer = buffer;
  1862. };
  1863. // Inherit from `Node`.
  1864. BlockComment.prototype = Object.create(Node.prototype);
  1865. BlockComment.prototype.constructor = BlockComment;
  1866. BlockComment.prototype.type = 'BlockComment';
  1867. },{"./node":20}],9:[function(require,module,exports){
  1868. 'use strict';
  1869. var Node = require('./node');
  1870. /**
  1871. * Initialize a new `Block` with an optional `node`.
  1872. *
  1873. * @param {Node} node
  1874. * @api public
  1875. */
  1876. var Block = module.exports = function Block(node){
  1877. this.nodes = [];
  1878. if (node) this.push(node);
  1879. };
  1880. // Inherit from `Node`.
  1881. Block.prototype = Object.create(Node.prototype);
  1882. Block.prototype.constructor = Block;
  1883. Block.prototype.type = 'Block';
  1884. /**
  1885. * Block flag.
  1886. */
  1887. Block.prototype.isBlock = true;
  1888. /**
  1889. * Replace the nodes in `other` with the nodes
  1890. * in `this` block.
  1891. *
  1892. * @param {Block} other
  1893. * @api private
  1894. */
  1895. Block.prototype.replace = function(other){
  1896. var err = new Error('block.replace is deprecated and will be removed in v2.0.0');
  1897. console.warn(err.stack);
  1898. other.nodes = this.nodes;
  1899. };
  1900. /**
  1901. * Push the given `node`.
  1902. *
  1903. * @param {Node} node
  1904. * @return {Number}
  1905. * @api public
  1906. */
  1907. Block.prototype.push = function(node){
  1908. return this.nodes.push(node);
  1909. };
  1910. /**
  1911. * Check if this block is empty.
  1912. *
  1913. * @return {Boolean}
  1914. * @api public
  1915. */
  1916. Block.prototype.isEmpty = function(){
  1917. return 0 == this.nodes.length;
  1918. };
  1919. /**
  1920. * Unshift the given `node`.
  1921. *
  1922. * @param {Node} node
  1923. * @return {Number}
  1924. * @api public
  1925. */
  1926. Block.prototype.unshift = function(node){
  1927. return this.nodes.unshift(node);
  1928. };
  1929. /**
  1930. * Return the "last" block, or the first `yield` node.
  1931. *
  1932. * @return {Block}
  1933. * @api private
  1934. */
  1935. Block.prototype.includeBlock = function(){
  1936. var ret = this
  1937. , node;
  1938. for (var i = 0, len = this.nodes.length; i < len; ++i) {
  1939. node = this.nodes[i];
  1940. if (node.yield) return node;
  1941. else if (node.textOnly) continue;
  1942. else if (node.includeBlock) ret = node.includeBlock();
  1943. else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock();
  1944. if (ret.yield) return ret;
  1945. }
  1946. return ret;
  1947. };
  1948. /**
  1949. * Return a clone of this block.
  1950. *
  1951. * @return {Block}
  1952. * @api private
  1953. */
  1954. Block.prototype.clone = function(){
  1955. var err = new Error('block.clone is deprecated and will be removed in v2.0.0');
  1956. console.warn(err.stack);
  1957. var clone = new Block;
  1958. for (var i = 0, len = this.nodes.length; i < len; ++i) {
  1959. clone.push(this.nodes[i].clone());
  1960. }
  1961. return clone;
  1962. };
  1963. },{"./node":20}],10:[function(require,module,exports){
  1964. 'use strict';
  1965. var Node = require('./node');
  1966. /**
  1967. * Initialize a new `Case` with `expr`.
  1968. *
  1969. * @param {String} expr
  1970. * @api public
  1971. */
  1972. var Case = exports = module.exports = function Case(expr, block){
  1973. this.expr = expr;
  1974. this.block = block;
  1975. };
  1976. // Inherit from `Node`.
  1977. Case.prototype = Object.create(Node.prototype);
  1978. Case.prototype.constructor = Case;
  1979. Case.prototype.type = 'Case';
  1980. var When = exports.When = function When(expr, block){
  1981. this.expr = expr;
  1982. this.block = block;
  1983. this.debug = false;
  1984. };
  1985. // Inherit from `Node`.
  1986. When.prototype = Object.create(Node.prototype);
  1987. When.prototype.constructor = When;
  1988. When.prototype.type = 'When';
  1989. },{"./node":20}],11:[function(require,module,exports){
  1990. 'use strict';
  1991. var Node = require('./node');
  1992. /**
  1993. * Initialize a `Code` node with the given code `val`.
  1994. * Code may also be optionally buffered and escaped.
  1995. *
  1996. * @param {String} val
  1997. * @param {Boolean} buffer
  1998. * @param {Boolean} escape
  1999. * @api public
  2000. */
  2001. var Code = module.exports = function Code(val, buffer, escape) {
  2002. this.val = val;
  2003. this.buffer = buffer;
  2004. this.escape = escape;
  2005. if (val.match(/^ *else/)) this.debug = false;
  2006. };
  2007. // Inherit from `Node`.
  2008. Code.prototype = Object.create(Node.prototype);
  2009. Code.prototype.constructor = Code;
  2010. Code.prototype.type = 'Code'; // prevent the minifiers removing this
  2011. },{"./node":20}],12:[function(require,module,exports){
  2012. 'use strict';
  2013. var Node = require('./node');
  2014. /**
  2015. * Initialize a `Comment` with the given `val`, optionally `buffer`,
  2016. * otherwise the comment may render in the output.
  2017. *
  2018. * @param {String} val
  2019. * @param {Boolean} buffer
  2020. * @api public
  2021. */
  2022. var Comment = module.exports = function Comment(val, buffer) {
  2023. this.val = val;
  2024. this.buffer = buffer;
  2025. };
  2026. // Inherit from `Node`.
  2027. Comment.prototype = Object.create(Node.prototype);
  2028. Comment.prototype.constructor = Comment;
  2029. Comment.prototype.type = 'Comment';
  2030. },{"./node":20}],13:[function(require,module,exports){
  2031. 'use strict';
  2032. var Node = require('./node');
  2033. /**
  2034. * Initialize a `Doctype` with the given `val`.
  2035. *
  2036. * @param {String} val
  2037. * @api public
  2038. */
  2039. var Doctype = module.exports = function Doctype(val) {
  2040. this.val = val;
  2041. };
  2042. // Inherit from `Node`.
  2043. Doctype.prototype = Object.create(Node.prototype);
  2044. Doctype.prototype.constructor = Doctype;
  2045. Doctype.prototype.type = 'Doctype';
  2046. },{"./node":20}],14:[function(require,module,exports){
  2047. 'use strict';
  2048. var Node = require('./node');
  2049. /**
  2050. * Initialize an `Each` node, representing iteration
  2051. *
  2052. * @param {String} obj
  2053. * @param {String} val
  2054. * @param {String} key
  2055. * @param {Block} block
  2056. * @api public
  2057. */
  2058. var Each = module.exports = function Each(obj, val, key, block) {
  2059. this.obj = obj;
  2060. this.val = val;
  2061. this.key = key;
  2062. this.block = block;
  2063. };
  2064. // Inherit from `Node`.
  2065. Each.prototype = Object.create(Node.prototype);
  2066. Each.prototype.constructor = Each;
  2067. Each.prototype.type = 'Each';
  2068. },{"./node":20}],15:[function(require,module,exports){
  2069. 'use strict';
  2070. var Node = require('./node');
  2071. /**
  2072. * Initialize a `Filter` node with the given
  2073. * filter `name` and `block`.
  2074. *
  2075. * @param {String} name
  2076. * @param {Block|Node} block
  2077. * @api public
  2078. */
  2079. var Filter = module.exports = function Filter(name, block, attrs) {
  2080. this.name = name;
  2081. this.block = block;
  2082. this.attrs = attrs;
  2083. };
  2084. // Inherit from `Node`.
  2085. Filter.prototype = Object.create(Node.prototype);
  2086. Filter.prototype.constructor = Filter;
  2087. Filter.prototype.type = 'Filter';
  2088. },{"./node":20}],16:[function(require,module,exports){
  2089. 'use strict';
  2090. exports.Node = require('./node');
  2091. exports.Tag = require('./tag');
  2092. exports.Code = require('./code');
  2093. exports.Each = require('./each');
  2094. exports.Case = require('./case');
  2095. exports.Text = require('./text');
  2096. exports.Block = require('./block');
  2097. exports.MixinBlock = require('./mixin-block');
  2098. exports.Mixin = require('./mixin');
  2099. exports.Filter = require('./filter');
  2100. exports.Comment = require('./comment');
  2101. exports.Literal = require('./literal');
  2102. exports.BlockComment = require('./block-comment');
  2103. exports.Doctype = require('./doctype');
  2104. },{"./block":9,"./block-comment":8,"./case":10,"./code":11,"./comment":12,"./doctype":13,"./each":14,"./filter":15,"./literal":17,"./mixin":19,"./mixin-block":18,"./node":20,"./tag":21,"./text":22}],17:[function(require,module,exports){
  2105. 'use strict';
  2106. var Node = require('./node');
  2107. /**
  2108. * Initialize a `Literal` node with the given `str.
  2109. *
  2110. * @param {String} str
  2111. * @api public
  2112. */
  2113. var Literal = module.exports = function Literal(str) {
  2114. this.str = str;
  2115. };
  2116. // Inherit from `Node`.
  2117. Literal.prototype = Object.create(Node.prototype);
  2118. Literal.prototype.constructor = Literal;
  2119. Literal.prototype.type = 'Literal';
  2120. },{"./node":20}],18:[function(require,module,exports){
  2121. 'use strict';
  2122. var Node = require('./node');
  2123. /**
  2124. * Initialize a new `Block` with an optional `node`.
  2125. *
  2126. * @param {Node} node
  2127. * @api public
  2128. */
  2129. var MixinBlock = module.exports = function MixinBlock(){};
  2130. // Inherit from `Node`.
  2131. MixinBlock.prototype = Object.create(Node.prototype);
  2132. MixinBlock.prototype.constructor = MixinBlock;
  2133. MixinBlock.prototype.type = 'MixinBlock';
  2134. },{"./node":20}],19:[function(require,module,exports){
  2135. 'use strict';
  2136. var Attrs = require('./attrs');
  2137. /**
  2138. * Initialize a new `Mixin` with `name` and `block`.
  2139. *
  2140. * @param {String} name
  2141. * @param {String} args
  2142. * @param {Block} block
  2143. * @api public
  2144. */
  2145. var Mixin = module.exports = function Mixin(name, args, block, call){
  2146. Attrs.call(this);
  2147. this.name = name;
  2148. this.args = args;
  2149. this.block = block;
  2150. this.call = call;
  2151. };
  2152. // Inherit from `Attrs`.
  2153. Mixin.prototype = Object.create(Attrs.prototype);
  2154. Mixin.prototype.constructor = Mixin;
  2155. Mixin.prototype.type = 'Mixin';
  2156. },{"./attrs":7}],20:[function(require,module,exports){
  2157. 'use strict';
  2158. var Node = module.exports = function Node(){};
  2159. /**
  2160. * Clone this node (return itself)
  2161. *
  2162. * @return {Node}
  2163. * @api private
  2164. */
  2165. Node.prototype.clone = function(){
  2166. var err = new Error('node.clone is deprecated and will be removed in v2.0.0');
  2167. console.warn(err.stack);
  2168. return this;
  2169. };
  2170. Node.prototype.type = '';
  2171. },{}],21:[function(require,module,exports){
  2172. 'use strict';
  2173. var Attrs = require('./attrs');
  2174. var Block = require('./block');
  2175. var inlineTags = require('../inline-tags');
  2176. /**
  2177. * Initialize a `Tag` node with the given tag `name` and optional `block`.
  2178. *
  2179. * @param {String} name
  2180. * @param {Block} block
  2181. * @api public
  2182. */
  2183. var Tag = module.exports = function Tag(name, block) {
  2184. Attrs.call(this);
  2185. this.name = name;
  2186. this.block = block || new Block;
  2187. };
  2188. // Inherit from `Attrs`.
  2189. Tag.prototype = Object.create(Attrs.prototype);
  2190. Tag.prototype.constructor = Tag;
  2191. Tag.prototype.type = 'Tag';
  2192. /**
  2193. * Clone this tag.
  2194. *
  2195. * @return {Tag}
  2196. * @api private
  2197. */
  2198. Tag.prototype.clone = function(){
  2199. var err = new Error('tag.clone is deprecated and will be removed in v2.0.0');
  2200. console.warn(err.stack);
  2201. var clone = new Tag(this.name, this.block.clone());
  2202. clone.line = this.line;
  2203. clone.attrs = this.attrs;
  2204. clone.textOnly = this.textOnly;
  2205. return clone;
  2206. };
  2207. /**
  2208. * Check if this tag is an inline tag.
  2209. *
  2210. * @return {Boolean}
  2211. * @api private
  2212. */
  2213. Tag.prototype.isInline = function(){
  2214. return ~inlineTags.indexOf(this.name);
  2215. };
  2216. /**
  2217. * Check if this tag's contents can be inlined. Used for pretty printing.
  2218. *
  2219. * @return {Boolean}
  2220. * @api private
  2221. */
  2222. Tag.prototype.canInline = function(){
  2223. var nodes = this.block.nodes;
  2224. function isInline(node){
  2225. // Recurse if the node is a block
  2226. if (node.isBlock) return node.nodes.every(isInline);
  2227. return node.isText || (node.isInline && node.isInline());
  2228. }
  2229. // Empty tag
  2230. if (!nodes.length) return true;
  2231. // Text-only or inline-only tag
  2232. if (1 == nodes.length) return isInline(nodes[0]);
  2233. // Multi-line inline-only tag
  2234. if (this.block.nodes.every(isInline)) {
  2235. for (var i = 1, len = nodes.length; i < len; ++i) {
  2236. if (nodes[i-1].isText && nodes[i].isText)
  2237. return false;
  2238. }
  2239. return true;
  2240. }
  2241. // Mixed tag
  2242. return false;
  2243. };
  2244. },{"../inline-tags":4,"./attrs":7,"./block":9}],22:[function(require,module,exports){
  2245. 'use strict';
  2246. var Node = require('./node');
  2247. /**
  2248. * Initialize a `Text` node with optional `line`.
  2249. *
  2250. * @param {String} line
  2251. * @api public
  2252. */
  2253. var Text = module.exports = function Text(line) {
  2254. this.val = line;
  2255. };
  2256. // Inherit from `Node`.
  2257. Text.prototype = Object.create(Node.prototype);
  2258. Text.prototype.constructor = Text;
  2259. Text.prototype.type = 'Text';
  2260. /**
  2261. * Flag as text.
  2262. */
  2263. Text.prototype.isText = true;
  2264. },{"./node":20}],23:[function(require,module,exports){
  2265. 'use strict';
  2266. var Lexer = require('./lexer');
  2267. var nodes = require('./nodes');
  2268. var utils = require('./utils');
  2269. var filters = require('./filters');
  2270. var path = require('path');
  2271. var constantinople = require('constantinople');
  2272. var parseJSExpression = require('character-parser').parseMax;
  2273. var extname = path.extname;
  2274. /**
  2275. * Initialize `Parser` with the given input `str` and `filename`.
  2276. *
  2277. * @param {String} str
  2278. * @param {String} filename
  2279. * @param {Object} options
  2280. * @api public
  2281. */
  2282. var Parser = exports = module.exports = function Parser(str, filename, options){
  2283. //Strip any UTF-8 BOM off of the start of `str`, if it exists.
  2284. this.input = str.replace(/^\uFEFF/, '');
  2285. this.lexer = new Lexer(this.input, filename);
  2286. this.filename = filename;
  2287. this.blocks = {};
  2288. this.mixins = {};
  2289. this.options = options;
  2290. this.contexts = [this];
  2291. this.inMixin = false;
  2292. this.dependencies = [];
  2293. this.inBlock = 0;
  2294. };
  2295. /**
  2296. * Parser prototype.
  2297. */
  2298. Parser.prototype = {
  2299. /**
  2300. * Save original constructor
  2301. */
  2302. constructor: Parser,
  2303. /**
  2304. * Push `parser` onto the context stack,
  2305. * or pop and return a `Parser`.
  2306. */
  2307. context: function(parser){
  2308. if (parser) {
  2309. this.contexts.push(parser);
  2310. } else {
  2311. return this.contexts.pop();
  2312. }
  2313. },
  2314. /**
  2315. * Return the next token object.
  2316. *
  2317. * @return {Object}
  2318. * @api private
  2319. */
  2320. advance: function(){
  2321. return this.lexer.advance();
  2322. },
  2323. /**
  2324. * Single token lookahead.
  2325. *
  2326. * @return {Object}
  2327. * @api private
  2328. */
  2329. peek: function() {
  2330. return this.lookahead(1);
  2331. },
  2332. /**
  2333. * Return lexer lineno.
  2334. *
  2335. * @return {Number}
  2336. * @api private
  2337. */
  2338. line: function() {
  2339. return this.lexer.lineno;
  2340. },
  2341. /**
  2342. * `n` token lookahead.
  2343. *
  2344. * @param {Number} n
  2345. * @return {Object}
  2346. * @api private
  2347. */
  2348. lookahead: function(n){
  2349. return this.lexer.lookahead(n);
  2350. },
  2351. /**
  2352. * Parse input returning a string of js for evaluation.
  2353. *
  2354. * @return {String}
  2355. * @api public
  2356. */
  2357. parse: function(){
  2358. var block = new nodes.Block, parser;
  2359. block.line = 0;
  2360. block.filename = this.filename;
  2361. while ('eos' != this.peek().type) {
  2362. if ('newline' == this.peek().type) {
  2363. this.advance();
  2364. } else {
  2365. var next = this.peek();
  2366. var expr = this.parseExpr();
  2367. expr.filename = expr.filename || this.filename;
  2368. expr.line = next.line;
  2369. block.push(expr);
  2370. }
  2371. }
  2372. if (parser = this.extending) {
  2373. this.context(parser);
  2374. var ast = parser.parse();
  2375. this.context();
  2376. // hoist mixins
  2377. for (var name in this.mixins)
  2378. ast.unshift(this.mixins[name]);
  2379. return ast;
  2380. }
  2381. if (!this.extending && !this.included && Object.keys(this.blocks).length){
  2382. var blocks = [];
  2383. utils.walkAST(block, function (node) {
  2384. if (node.type === 'Block' && node.name) {
  2385. blocks.push(node.name);
  2386. }
  2387. });
  2388. Object.keys(this.blocks).forEach(function (name) {
  2389. if (blocks.indexOf(name) === -1 && !this.blocks[name].isSubBlock) {
  2390. console.warn('Warning: Unexpected block "'
  2391. + name
  2392. + '" '
  2393. + ' on line '
  2394. + this.blocks[name].line
  2395. + ' of '
  2396. + (this.blocks[name].filename)
  2397. + '. This block is never used. This warning will be an error in v2.0.0');
  2398. }
  2399. }.bind(this));
  2400. }
  2401. return block;
  2402. },
  2403. /**
  2404. * Expect the given type, or throw an exception.
  2405. *
  2406. * @param {String} type
  2407. * @api private
  2408. */
  2409. expect: function(type){
  2410. if (this.peek().type === type) {
  2411. return this.advance();
  2412. } else {
  2413. throw new Error('expected "' + type + '", but got "' + this.peek().type + '"');
  2414. }
  2415. },
  2416. /**
  2417. * Accept the given `type`.
  2418. *
  2419. * @param {String} type
  2420. * @api private
  2421. */
  2422. accept: function(type){
  2423. if (this.peek().type === type) {
  2424. return this.advance();
  2425. }
  2426. },
  2427. /**
  2428. * tag
  2429. * | doctype
  2430. * | mixin
  2431. * | include
  2432. * | filter
  2433. * | comment
  2434. * | text
  2435. * | each
  2436. * | code
  2437. * | yield
  2438. * | id
  2439. * | class
  2440. * | interpolation
  2441. */
  2442. parseExpr: function(){
  2443. switch (this.peek().type) {
  2444. case 'tag':
  2445. return this.parseTag();
  2446. case 'mixin':
  2447. return this.parseMixin();
  2448. case 'block':
  2449. return this.parseBlock();
  2450. case 'mixin-block':
  2451. return this.parseMixinBlock();
  2452. case 'case':
  2453. return this.parseCase();
  2454. case 'extends':
  2455. return this.parseExtends();
  2456. case 'include':
  2457. return this.parseInclude();
  2458. case 'doctype':
  2459. return this.parseDoctype();
  2460. case 'filter':
  2461. return this.parseFilter();
  2462. case 'comment':
  2463. return this.parseComment();
  2464. case 'text':
  2465. return this.parseText();
  2466. case 'each':
  2467. return this.parseEach();
  2468. case 'code':
  2469. return this.parseCode();
  2470. case 'call':
  2471. return this.parseCall();
  2472. case 'interpolation':
  2473. return this.parseInterpolation();
  2474. case 'yield':
  2475. this.advance();
  2476. var block = new nodes.Block;
  2477. block.yield = true;
  2478. return block;
  2479. case 'id':
  2480. case 'class':
  2481. var tok = this.advance();
  2482. this.lexer.defer(this.lexer.tok('tag', 'div'));
  2483. this.lexer.defer(tok);
  2484. return this.parseExpr();
  2485. default:
  2486. throw new Error('unexpected token "' + this.peek().type + '"');
  2487. }
  2488. },
  2489. /**
  2490. * Text
  2491. */
  2492. parseText: function(){
  2493. var tok = this.expect('text');
  2494. var tokens = this.parseInlineTagsInText(tok.val);
  2495. if (tokens.length === 1) return tokens[0];
  2496. var node = new nodes.Block;
  2497. for (var i = 0; i < tokens.length; i++) {
  2498. node.push(tokens[i]);
  2499. };
  2500. return node;
  2501. },
  2502. /**
  2503. * ':' expr
  2504. * | block
  2505. */
  2506. parseBlockExpansion: function(){
  2507. if (':' == this.peek().type) {
  2508. this.advance();
  2509. return new nodes.Block(this.parseExpr());
  2510. } else {
  2511. return this.block();
  2512. }
  2513. },
  2514. /**
  2515. * case
  2516. */
  2517. parseCase: function(){
  2518. var val = this.expect('case').val;
  2519. var node = new nodes.Case(val);
  2520. node.line = this.line();
  2521. var block = new nodes.Block;
  2522. block.line = this.line();
  2523. block.filename = this.filename;
  2524. this.expect('indent');
  2525. while ('outdent' != this.peek().type) {
  2526. switch (this.peek().type) {
  2527. case 'newline':
  2528. this.advance();
  2529. break;
  2530. case 'when':
  2531. block.push(this.parseWhen());
  2532. break;
  2533. case 'default':
  2534. block.push(this.parseDefault());
  2535. break;
  2536. default:
  2537. throw new Error('Unexpected token "' + this.peek().type
  2538. + '", expected "when", "default" or "newline"');
  2539. }
  2540. }
  2541. this.expect('outdent');
  2542. node.block = block;
  2543. return node;
  2544. },
  2545. /**
  2546. * when
  2547. */
  2548. parseWhen: function(){
  2549. var val = this.expect('when').val;
  2550. if (this.peek().type !== 'newline')
  2551. return new nodes.Case.When(val, this.parseBlockExpansion());
  2552. else
  2553. return new nodes.Case.When(val);
  2554. },
  2555. /**
  2556. * default
  2557. */
  2558. parseDefault: function(){
  2559. this.expect('default');
  2560. return new nodes.Case.When('default', this.parseBlockExpansion());
  2561. },
  2562. /**
  2563. * code
  2564. */
  2565. parseCode: function(afterIf){
  2566. var tok = this.expect('code');
  2567. var node = new nodes.Code(tok.val, tok.buffer, tok.escape);
  2568. var block;
  2569. node.line = this.line();
  2570. // throw an error if an else does not have an if
  2571. if (tok.isElse && !tok.hasIf) {
  2572. throw new Error('Unexpected else without if');
  2573. }
  2574. // handle block
  2575. block = 'indent' == this.peek().type;
  2576. if (block) {
  2577. node.block = this.block();
  2578. }
  2579. // handle missing block
  2580. if (tok.requiresBlock && !block) {
  2581. node.block = new nodes.Block();
  2582. }
  2583. // mark presense of if for future elses
  2584. if (tok.isIf && this.peek().isElse) {
  2585. this.peek().hasIf = true;
  2586. } else if (tok.isIf && this.peek().type === 'newline' && this.lookahead(2).isElse) {
  2587. this.lookahead(2).hasIf = true;
  2588. }
  2589. return node;
  2590. },
  2591. /**
  2592. * comment
  2593. */
  2594. parseComment: function(){
  2595. var tok = this.expect('comment');
  2596. var node;
  2597. var block;
  2598. if (block = this.parseTextBlock()) {
  2599. node = new nodes.BlockComment(tok.val, block, tok.buffer);
  2600. } else {
  2601. node = new nodes.Comment(tok.val, tok.buffer);
  2602. }
  2603. node.line = this.line();
  2604. return node;
  2605. },
  2606. /**
  2607. * doctype
  2608. */
  2609. parseDoctype: function(){
  2610. var tok = this.expect('doctype');
  2611. var node = new nodes.Doctype(tok.val);
  2612. node.line = this.line();
  2613. return node;
  2614. },
  2615. /**
  2616. * filter attrs? text-block
  2617. */
  2618. parseFilter: function(){
  2619. var tok = this.expect('filter');
  2620. var attrs = this.accept('attrs');
  2621. var block;
  2622. block = this.parseTextBlock() || new nodes.Block();
  2623. var options = {};
  2624. if (attrs) {
  2625. attrs.attrs.forEach(function (attribute) {
  2626. options[attribute.name] = constantinople.toConstant(attribute.val);
  2627. });
  2628. }
  2629. var node = new nodes.Filter(tok.val, block, options);
  2630. node.line = this.line();
  2631. return node;
  2632. },
  2633. /**
  2634. * each block
  2635. */
  2636. parseEach: function(){
  2637. var tok = this.expect('each');
  2638. var node = new nodes.Each(tok.code, tok.val, tok.key);
  2639. node.line = this.line();
  2640. node.block = this.block();
  2641. if (this.peek().type == 'code' && this.peek().val == 'else') {
  2642. this.advance();
  2643. node.alternative = this.block();
  2644. }
  2645. return node;
  2646. },
  2647. /**
  2648. * Resolves a path relative to the template for use in
  2649. * includes and extends
  2650. *
  2651. * @param {String} path
  2652. * @param {String} purpose Used in error messages.
  2653. * @return {String}
  2654. * @api private
  2655. */
  2656. resolvePath: function (path, purpose) {
  2657. var p = require('path');
  2658. var dirname = p.dirname;
  2659. var basename = p.basename;
  2660. var join = p.join;
  2661. if (path[0] !== '/' && !this.filename)
  2662. throw new Error('the "filename" option is required to use "' + purpose + '" with "relative" paths');
  2663. if (path[0] === '/' && !this.options.basedir)
  2664. throw new Error('the "basedir" option is required to use "' + purpose + '" with "absolute" paths');
  2665. path = join(path[0] === '/' ? this.options.basedir : dirname(this.filename), path);
  2666. if (basename(path).indexOf('.') === -1) path += '.jade';
  2667. return path;
  2668. },
  2669. /**
  2670. * 'extends' name
  2671. */
  2672. parseExtends: function(){
  2673. var fs = require('fs');
  2674. var path = this.resolvePath(this.expect('extends').val.trim(), 'extends');
  2675. if ('.jade' != path.substr(-5)) path += '.jade';
  2676. this.dependencies.push(path);
  2677. var str = fs.readFileSync(path, 'utf8');
  2678. var parser = new this.constructor(str, path, this.options);
  2679. parser.dependencies = this.dependencies;
  2680. parser.blocks = this.blocks;
  2681. parser.included = this.included;
  2682. parser.contexts = this.contexts;
  2683. this.extending = parser;
  2684. // TODO: null node
  2685. return new nodes.Literal('');
  2686. },
  2687. /**
  2688. * 'block' name block
  2689. */
  2690. parseBlock: function(){
  2691. var block = this.expect('block');
  2692. var mode = block.mode;
  2693. var name = block.val.trim();
  2694. var line = block.line;
  2695. this.inBlock++;
  2696. block = 'indent' == this.peek().type
  2697. ? this.block()
  2698. : new nodes.Block(new nodes.Literal(''));
  2699. this.inBlock--;
  2700. block.name = name;
  2701. block.line = line;
  2702. var prev = this.blocks[name] || {prepended: [], appended: []}
  2703. if (prev.mode === 'replace') return this.blocks[name] = prev;
  2704. var allNodes = prev.prepended.concat(block.nodes).concat(prev.appended);
  2705. switch (mode) {
  2706. case 'append':
  2707. prev.appended = prev.parser === this ?
  2708. prev.appended.concat(block.nodes) :
  2709. block.nodes.concat(prev.appended);
  2710. break;
  2711. case 'prepend':
  2712. prev.prepended = prev.parser === this ?
  2713. block.nodes.concat(prev.prepended) :
  2714. prev.prepended.concat(block.nodes);
  2715. break;
  2716. }
  2717. block.nodes = allNodes;
  2718. block.appended = prev.appended;
  2719. block.prepended = prev.prepended;
  2720. block.mode = mode;
  2721. block.parser = this;
  2722. block.isSubBlock = this.inBlock > 0;
  2723. return this.blocks[name] = block;
  2724. },
  2725. parseMixinBlock: function () {
  2726. var block = this.expect('mixin-block');
  2727. if (!this.inMixin) {
  2728. throw new Error('Anonymous blocks are not allowed unless they are part of a mixin.');
  2729. }
  2730. return new nodes.MixinBlock();
  2731. },
  2732. /**
  2733. * include block?
  2734. */
  2735. parseInclude: function(){
  2736. var fs = require('fs');
  2737. var tok = this.expect('include');
  2738. var path = this.resolvePath(tok.val.trim(), 'include');
  2739. this.dependencies.push(path);
  2740. // has-filter
  2741. if (tok.filter) {
  2742. var str = fs.readFileSync(path, 'utf8').replace(/\r/g, '');
  2743. var options = {filename: path};
  2744. if (tok.attrs) {
  2745. tok.attrs.attrs.forEach(function (attribute) {
  2746. options[attribute.name] = constantinople.toConstant(attribute.val);
  2747. });
  2748. }
  2749. str = filters(tok.filter, str, options);
  2750. return new nodes.Literal(str);
  2751. }
  2752. // non-jade
  2753. if ('.jade' != path.substr(-5)) {
  2754. var str = fs.readFileSync(path, 'utf8').replace(/\r/g, '');
  2755. return new nodes.Literal(str);
  2756. }
  2757. var str = fs.readFileSync(path, 'utf8');
  2758. var parser = new this.constructor(str, path, this.options);
  2759. parser.dependencies = this.dependencies;
  2760. parser.blocks = utils.merge({}, this.blocks);
  2761. parser.included = true;
  2762. parser.mixins = this.mixins;
  2763. this.context(parser);
  2764. var ast = parser.parse();
  2765. this.context();
  2766. ast.filename = path;
  2767. if ('indent' == this.peek().type) {
  2768. ast.includeBlock().push(this.block());
  2769. }
  2770. return ast;
  2771. },
  2772. /**
  2773. * call ident block
  2774. */
  2775. parseCall: function(){
  2776. var tok = this.expect('call');
  2777. var name = tok.val;
  2778. var args = tok.args;
  2779. var mixin = new nodes.Mixin(name, args, new nodes.Block, true);
  2780. this.tag(mixin);
  2781. if (mixin.code) {
  2782. mixin.block.push(mixin.code);
  2783. mixin.code = null;
  2784. }
  2785. if (mixin.block.isEmpty()) mixin.block = null;
  2786. return mixin;
  2787. },
  2788. /**
  2789. * mixin block
  2790. */
  2791. parseMixin: function(){
  2792. var tok = this.expect('mixin');
  2793. var name = tok.val;
  2794. var args = tok.args;
  2795. var mixin;
  2796. // definition
  2797. if ('indent' == this.peek().type) {
  2798. this.inMixin = true;
  2799. mixin = new nodes.Mixin(name, args, this.block(), false);
  2800. this.mixins[name] = mixin;
  2801. this.inMixin = false;
  2802. return mixin;
  2803. // call
  2804. } else {
  2805. return new nodes.Mixin(name, args, null, true);
  2806. }
  2807. },
  2808. parseInlineTagsInText: function (str) {
  2809. var line = this.line();
  2810. var match = /(\\)?#\[((?:.|\n)*)$/.exec(str);
  2811. if (match) {
  2812. if (match[1]) { // escape
  2813. var text = new nodes.Text(str.substr(0, match.index) + '#[');
  2814. text.line = line;
  2815. var rest = this.parseInlineTagsInText(match[2]);
  2816. if (rest[0].type === 'Text') {
  2817. text.val += rest[0].val;
  2818. rest.shift();
  2819. }
  2820. return [text].concat(rest);
  2821. } else {
  2822. var text = new nodes.Text(str.substr(0, match.index));
  2823. text.line = line;
  2824. var buffer = [text];
  2825. var rest = match[2];
  2826. var range = parseJSExpression(rest);
  2827. var inner = new Parser(range.src, this.filename, this.options);
  2828. buffer.push(inner.parse());
  2829. return buffer.concat(this.parseInlineTagsInText(rest.substr(range.end + 1)));
  2830. }
  2831. } else {
  2832. var text = new nodes.Text(str);
  2833. text.line = line;
  2834. return [text];
  2835. }
  2836. },
  2837. /**
  2838. * indent (text | newline)* outdent
  2839. */
  2840. parseTextBlock: function(){
  2841. var block = new nodes.Block;
  2842. block.line = this.line();
  2843. var body = this.peek();
  2844. if (body.type !== 'pipeless-text') return;
  2845. this.advance();
  2846. block.nodes = body.val.reduce(function (accumulator, text) {
  2847. return accumulator.concat(this.parseInlineTagsInText(text));
  2848. }.bind(this), []);
  2849. return block;
  2850. },
  2851. /**
  2852. * indent expr* outdent
  2853. */
  2854. block: function(){
  2855. var block = new nodes.Block;
  2856. block.line = this.line();
  2857. block.filename = this.filename;
  2858. this.expect('indent');
  2859. while ('outdent' != this.peek().type) {
  2860. if ('newline' == this.peek().type) {
  2861. this.advance();
  2862. } else {
  2863. var expr = this.parseExpr();
  2864. expr.filename = this.filename;
  2865. block.push(expr);
  2866. }
  2867. }
  2868. this.expect('outdent');
  2869. return block;
  2870. },
  2871. /**
  2872. * interpolation (attrs | class | id)* (text | code | ':')? newline* block?
  2873. */
  2874. parseInterpolation: function(){
  2875. var tok = this.advance();
  2876. var tag = new nodes.Tag(tok.val);
  2877. tag.buffer = true;
  2878. return this.tag(tag);
  2879. },
  2880. /**
  2881. * tag (attrs | class | id)* (text | code | ':')? newline* block?
  2882. */
  2883. parseTag: function(){
  2884. var tok = this.advance();
  2885. var tag = new nodes.Tag(tok.val);
  2886. tag.selfClosing = tok.selfClosing;
  2887. return this.tag(tag);
  2888. },
  2889. /**
  2890. * Parse tag.
  2891. */
  2892. tag: function(tag){
  2893. tag.line = this.line();
  2894. var seenAttrs = false;
  2895. // (attrs | class | id)*
  2896. out:
  2897. while (true) {
  2898. switch (this.peek().type) {
  2899. case 'id':
  2900. case 'class':
  2901. var tok = this.advance();
  2902. tag.setAttribute(tok.type, "'" + tok.val + "'");
  2903. continue;
  2904. case 'attrs':
  2905. if (seenAttrs) {
  2906. console.warn(this.filename + ', line ' + this.peek().line + ':\nYou should not have jade tags with multiple attributes.');
  2907. }
  2908. seenAttrs = true;
  2909. var tok = this.advance();
  2910. var attrs = tok.attrs;
  2911. if (tok.selfClosing) tag.selfClosing = true;
  2912. for (var i = 0; i < attrs.length; i++) {
  2913. tag.setAttribute(attrs[i].name, attrs[i].val, attrs[i].escaped);
  2914. }
  2915. continue;
  2916. case '&attributes':
  2917. var tok = this.advance();
  2918. tag.addAttributes(tok.val);
  2919. break;
  2920. default:
  2921. break out;
  2922. }
  2923. }
  2924. // check immediate '.'
  2925. if ('dot' == this.peek().type) {
  2926. tag.textOnly = true;
  2927. this.advance();
  2928. }
  2929. // (text | code | ':')?
  2930. switch (this.peek().type) {
  2931. case 'text':
  2932. tag.block.push(this.parseText());
  2933. break;
  2934. case 'code':
  2935. tag.code = this.parseCode();
  2936. break;
  2937. case ':':
  2938. this.advance();
  2939. tag.block = new nodes.Block;
  2940. tag.block.push(this.parseExpr());
  2941. break;
  2942. case 'newline':
  2943. case 'indent':
  2944. case 'outdent':
  2945. case 'eos':
  2946. case 'pipeless-text':
  2947. break;
  2948. default:
  2949. throw new Error('Unexpected token `' + this.peek().type + '` expected `text`, `code`, `:`, `newline` or `eos`')
  2950. }
  2951. // newline*
  2952. while ('newline' == this.peek().type) this.advance();
  2953. // block?
  2954. if (tag.textOnly) {
  2955. tag.block = this.parseTextBlock();
  2956. } else if ('indent' == this.peek().type) {
  2957. var block = this.block();
  2958. for (var i = 0, len = block.nodes.length; i < len; ++i) {
  2959. tag.block.push(block.nodes[i]);
  2960. }
  2961. }
  2962. return tag;
  2963. }
  2964. };
  2965. },{"./filters":3,"./lexer":6,"./nodes":16,"./utils":25,"character-parser":32,"constantinople":33,"fs":26,"path":28}],24:[function(require,module,exports){
  2966. 'use strict';
  2967. /**
  2968. * Merge two attribute objects giving precedence
  2969. * to values in object `b`. Classes are special-cased
  2970. * allowing for arrays and merging/joining appropriately
  2971. * resulting in a string.
  2972. *
  2973. * @param {Object} a
  2974. * @param {Object} b
  2975. * @return {Object} a
  2976. * @api private
  2977. */
  2978. exports.merge = function merge(a, b) {
  2979. if (arguments.length === 1) {
  2980. var attrs = a[0];
  2981. for (var i = 1; i < a.length; i++) {
  2982. attrs = merge(attrs, a[i]);
  2983. }
  2984. return attrs;
  2985. }
  2986. var ac = a['class'];
  2987. var bc = b['class'];
  2988. if (ac || bc) {
  2989. ac = ac || [];
  2990. bc = bc || [];
  2991. if (!Array.isArray(ac)) ac = [ac];
  2992. if (!Array.isArray(bc)) bc = [bc];
  2993. a['class'] = ac.concat(bc).filter(nulls);
  2994. }
  2995. for (var key in b) {
  2996. if (key != 'class') {
  2997. a[key] = b[key];
  2998. }
  2999. }
  3000. return a;
  3001. };
  3002. /**
  3003. * Filter null `val`s.
  3004. *
  3005. * @param {*} val
  3006. * @return {Boolean}
  3007. * @api private
  3008. */
  3009. function nulls(val) {
  3010. return val != null && val !== '';
  3011. }
  3012. /**
  3013. * join array as classes.
  3014. *
  3015. * @param {*} val
  3016. * @return {String}
  3017. */
  3018. exports.joinClasses = joinClasses;
  3019. function joinClasses(val) {
  3020. return Array.isArray(val) ? val.map(joinClasses).filter(nulls).join(' ') : val;
  3021. }
  3022. /**
  3023. * Render the given classes.
  3024. *
  3025. * @param {Array} classes
  3026. * @param {Array.<Boolean>} escaped
  3027. * @return {String}
  3028. */
  3029. exports.cls = function cls(classes, escaped) {
  3030. var buf = [];
  3031. for (var i = 0; i < classes.length; i++) {
  3032. if (escaped && escaped[i]) {
  3033. buf.push(exports.escape(joinClasses([classes[i]])));
  3034. } else {
  3035. buf.push(joinClasses(classes[i]));
  3036. }
  3037. }
  3038. var text = joinClasses(buf);
  3039. if (text.length) {
  3040. return ' class="' + text + '"';
  3041. } else {
  3042. return '';
  3043. }
  3044. };
  3045. /**
  3046. * Render the given attribute.
  3047. *
  3048. * @param {String} key
  3049. * @param {String} val
  3050. * @param {Boolean} escaped
  3051. * @param {Boolean} terse
  3052. * @return {String}
  3053. */
  3054. exports.attr = function attr(key, val, escaped, terse) {
  3055. if ('boolean' == typeof val || null == val) {
  3056. if (val) {
  3057. return ' ' + (terse ? key : key + '="' + key + '"');
  3058. } else {
  3059. return '';
  3060. }
  3061. } else if (0 == key.indexOf('data') && 'string' != typeof val) {
  3062. return ' ' + key + "='" + JSON.stringify(val).replace(/'/g, '&apos;') + "'";
  3063. } else if (escaped) {
  3064. return ' ' + key + '="' + exports.escape(val) + '"';
  3065. } else {
  3066. return ' ' + key + '="' + val + '"';
  3067. }
  3068. };
  3069. /**
  3070. * Render the given attributes object.
  3071. *
  3072. * @param {Object} obj
  3073. * @param {Object} escaped
  3074. * @return {String}
  3075. */
  3076. exports.attrs = function attrs(obj, terse){
  3077. var buf = [];
  3078. var keys = Object.keys(obj);
  3079. if (keys.length) {
  3080. for (var i = 0; i < keys.length; ++i) {
  3081. var key = keys[i]
  3082. , val = obj[key];
  3083. if ('class' == key) {
  3084. if (val = joinClasses(val)) {
  3085. buf.push(' ' + key + '="' + val + '"');
  3086. }
  3087. } else {
  3088. buf.push(exports.attr(key, val, false, terse));
  3089. }
  3090. }
  3091. }
  3092. return buf.join('');
  3093. };
  3094. /**
  3095. * Escape the given string of `html`.
  3096. *
  3097. * @param {String} html
  3098. * @return {String}
  3099. * @api private
  3100. */
  3101. exports.escape = function escape(html){
  3102. var result = String(html)
  3103. .replace(/&/g, '&amp;')
  3104. .replace(/</g, '&lt;')
  3105. .replace(/>/g, '&gt;')
  3106. .replace(/"/g, '&quot;');
  3107. if (result === '' + html) return html;
  3108. else return result;
  3109. };
  3110. /**
  3111. * Re-throw the given `err` in context to the
  3112. * the jade in `filename` at the given `lineno`.
  3113. *
  3114. * @param {Error} err
  3115. * @param {String} filename
  3116. * @param {String} lineno
  3117. * @api private
  3118. */
  3119. exports.rethrow = function rethrow(err, filename, lineno, str){
  3120. if (!(err instanceof Error)) throw err;
  3121. if ((typeof window != 'undefined' || !filename) && !str) {
  3122. err.message += ' on line ' + lineno;
  3123. throw err;
  3124. }
  3125. try {
  3126. str = str || require('fs').readFileSync(filename, 'utf8')
  3127. } catch (ex) {
  3128. rethrow(err, null, lineno)
  3129. }
  3130. var context = 3
  3131. , lines = str.split('\n')
  3132. , start = Math.max(lineno - context, 0)
  3133. , end = Math.min(lines.length, lineno + context);
  3134. // Error context
  3135. var context = lines.slice(start, end).map(function(line, i){
  3136. var curr = i + start + 1;
  3137. return (curr == lineno ? ' > ' : ' ')
  3138. + curr
  3139. + '| '
  3140. + line;
  3141. }).join('\n');
  3142. // Alter exception message
  3143. err.path = filename;
  3144. err.message = (filename || 'Jade') + ':' + lineno
  3145. + '\n' + context + '\n\n' + err.message;
  3146. throw err;
  3147. };
  3148. },{"fs":26}],25:[function(require,module,exports){
  3149. 'use strict';
  3150. /**
  3151. * Merge `b` into `a`.
  3152. *
  3153. * @param {Object} a
  3154. * @param {Object} b
  3155. * @return {Object}
  3156. * @api public
  3157. */
  3158. exports.merge = function(a, b) {
  3159. for (var key in b) a[key] = b[key];
  3160. return a;
  3161. };
  3162. exports.walkAST = function walkAST(ast, before, after) {
  3163. before && before(ast);
  3164. switch (ast.type) {
  3165. case 'Block':
  3166. ast.nodes.forEach(function (node) {
  3167. walkAST(node, before, after);
  3168. });
  3169. break;
  3170. case 'Case':
  3171. case 'Each':
  3172. case 'Mixin':
  3173. case 'Tag':
  3174. case 'When':
  3175. case 'Code':
  3176. ast.block && walkAST(ast.block, before, after);
  3177. break;
  3178. case 'Attrs':
  3179. case 'BlockComment':
  3180. case 'Comment':
  3181. case 'Doctype':
  3182. case 'Filter':
  3183. case 'Literal':
  3184. case 'MixinBlock':
  3185. case 'Text':
  3186. break;
  3187. default:
  3188. throw new Error('Unexpected node type ' + ast.type);
  3189. break;
  3190. }
  3191. after && after(ast);
  3192. };
  3193. },{}],26:[function(require,module,exports){
  3194. },{}],27:[function(require,module,exports){
  3195. if (typeof Object.create === 'function') {
  3196. // implementation from standard node.js 'util' module
  3197. module.exports = function inherits(ctor, superCtor) {
  3198. ctor.super_ = superCtor
  3199. ctor.prototype = Object.create(superCtor.prototype, {
  3200. constructor: {
  3201. value: ctor,
  3202. enumerable: false,
  3203. writable: true,
  3204. configurable: true
  3205. }
  3206. });
  3207. };
  3208. } else {
  3209. // old school shim for old browsers
  3210. module.exports = function inherits(ctor, superCtor) {
  3211. ctor.super_ = superCtor
  3212. var TempCtor = function () {}
  3213. TempCtor.prototype = superCtor.prototype
  3214. ctor.prototype = new TempCtor()
  3215. ctor.prototype.constructor = ctor
  3216. }
  3217. }
  3218. },{}],28:[function(require,module,exports){
  3219. (function (process){
  3220. // Copyright Joyent, Inc. and other Node contributors.
  3221. //
  3222. // Permission is hereby granted, free of charge, to any person obtaining a
  3223. // copy of this software and associated documentation files (the
  3224. // "Software"), to deal in the Software without restriction, including
  3225. // without limitation the rights to use, copy, modify, merge, publish,
  3226. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3227. // persons to whom the Software is furnished to do so, subject to the
  3228. // following conditions:
  3229. //
  3230. // The above copyright notice and this permission notice shall be included
  3231. // in all copies or substantial portions of the Software.
  3232. //
  3233. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3234. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3235. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3236. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3237. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3238. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3239. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3240. // resolves . and .. elements in a path array with directory names there
  3241. // must be no slashes, empty elements, or device names (c:\) in the array
  3242. // (so also no leading and trailing slashes - it does not distinguish
  3243. // relative and absolute paths)
  3244. function normalizeArray(parts, allowAboveRoot) {
  3245. // if the path tries to go above the root, `up` ends up > 0
  3246. var up = 0;
  3247. for (var i = parts.length - 1; i >= 0; i--) {
  3248. var last = parts[i];
  3249. if (last === '.') {
  3250. parts.splice(i, 1);
  3251. } else if (last === '..') {
  3252. parts.splice(i, 1);
  3253. up++;
  3254. } else if (up) {
  3255. parts.splice(i, 1);
  3256. up--;
  3257. }
  3258. }
  3259. // if the path is allowed to go above the root, restore leading ..s
  3260. if (allowAboveRoot) {
  3261. for (; up--; up) {
  3262. parts.unshift('..');
  3263. }
  3264. }
  3265. return parts;
  3266. }
  3267. // Split a filename into [root, dir, basename, ext], unix version
  3268. // 'root' is just a slash, or nothing.
  3269. var splitPathRe =
  3270. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  3271. var splitPath = function(filename) {
  3272. return splitPathRe.exec(filename).slice(1);
  3273. };
  3274. // path.resolve([from ...], to)
  3275. // posix version
  3276. exports.resolve = function() {
  3277. var resolvedPath = '',
  3278. resolvedAbsolute = false;
  3279. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  3280. var path = (i >= 0) ? arguments[i] : process.cwd();
  3281. // Skip empty and invalid entries
  3282. if (typeof path !== 'string') {
  3283. throw new TypeError('Arguments to path.resolve must be strings');
  3284. } else if (!path) {
  3285. continue;
  3286. }
  3287. resolvedPath = path + '/' + resolvedPath;
  3288. resolvedAbsolute = path.charAt(0) === '/';
  3289. }
  3290. // At this point the path should be resolved to a full absolute path, but
  3291. // handle relative paths to be safe (might happen when process.cwd() fails)
  3292. // Normalize the path
  3293. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  3294. return !!p;
  3295. }), !resolvedAbsolute).join('/');
  3296. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  3297. };
  3298. // path.normalize(path)
  3299. // posix version
  3300. exports.normalize = function(path) {
  3301. var isAbsolute = exports.isAbsolute(path),
  3302. trailingSlash = substr(path, -1) === '/';
  3303. // Normalize the path
  3304. path = normalizeArray(filter(path.split('/'), function(p) {
  3305. return !!p;
  3306. }), !isAbsolute).join('/');
  3307. if (!path && !isAbsolute) {
  3308. path = '.';
  3309. }
  3310. if (path && trailingSlash) {
  3311. path += '/';
  3312. }
  3313. return (isAbsolute ? '/' : '') + path;
  3314. };
  3315. // posix version
  3316. exports.isAbsolute = function(path) {
  3317. return path.charAt(0) === '/';
  3318. };
  3319. // posix version
  3320. exports.join = function() {
  3321. var paths = Array.prototype.slice.call(arguments, 0);
  3322. return exports.normalize(filter(paths, function(p, index) {
  3323. if (typeof p !== 'string') {
  3324. throw new TypeError('Arguments to path.join must be strings');
  3325. }
  3326. return p;
  3327. }).join('/'));
  3328. };
  3329. // path.relative(from, to)
  3330. // posix version
  3331. exports.relative = function(from, to) {
  3332. from = exports.resolve(from).substr(1);
  3333. to = exports.resolve(to).substr(1);
  3334. function trim(arr) {
  3335. var start = 0;
  3336. for (; start < arr.length; start++) {
  3337. if (arr[start] !== '') break;
  3338. }
  3339. var end = arr.length - 1;
  3340. for (; end >= 0; end--) {
  3341. if (arr[end] !== '') break;
  3342. }
  3343. if (start > end) return [];
  3344. return arr.slice(start, end - start + 1);
  3345. }
  3346. var fromParts = trim(from.split('/'));
  3347. var toParts = trim(to.split('/'));
  3348. var length = Math.min(fromParts.length, toParts.length);
  3349. var samePartsLength = length;
  3350. for (var i = 0; i < length; i++) {
  3351. if (fromParts[i] !== toParts[i]) {
  3352. samePartsLength = i;
  3353. break;
  3354. }
  3355. }
  3356. var outputParts = [];
  3357. for (var i = samePartsLength; i < fromParts.length; i++) {
  3358. outputParts.push('..');
  3359. }
  3360. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  3361. return outputParts.join('/');
  3362. };
  3363. exports.sep = '/';
  3364. exports.delimiter = ':';
  3365. exports.dirname = function(path) {
  3366. var result = splitPath(path),
  3367. root = result[0],
  3368. dir = result[1];
  3369. if (!root && !dir) {
  3370. // No dirname whatsoever
  3371. return '.';
  3372. }
  3373. if (dir) {
  3374. // It has a dirname, strip trailing slash
  3375. dir = dir.substr(0, dir.length - 1);
  3376. }
  3377. return root + dir;
  3378. };
  3379. exports.basename = function(path, ext) {
  3380. var f = splitPath(path)[2];
  3381. // TODO: make this comparison case-insensitive on windows?
  3382. if (ext && f.substr(-1 * ext.length) === ext) {
  3383. f = f.substr(0, f.length - ext.length);
  3384. }
  3385. return f;
  3386. };
  3387. exports.extname = function(path) {
  3388. return splitPath(path)[3];
  3389. };
  3390. function filter (xs, f) {
  3391. if (xs.filter) return xs.filter(f);
  3392. var res = [];
  3393. for (var i = 0; i < xs.length; i++) {
  3394. if (f(xs[i], i, xs)) res.push(xs[i]);
  3395. }
  3396. return res;
  3397. }
  3398. // String.prototype.substr - negative index don't work in IE8
  3399. var substr = 'ab'.substr(-1) === 'b'
  3400. ? function (str, start, len) { return str.substr(start, len) }
  3401. : function (str, start, len) {
  3402. if (start < 0) start = str.length + start;
  3403. return str.substr(start, len);
  3404. }
  3405. ;
  3406. }).call(this,require('_process'))
  3407. },{"_process":29}],29:[function(require,module,exports){
  3408. // shim for using process in browser
  3409. var process = module.exports = {};
  3410. process.nextTick = (function () {
  3411. var canSetImmediate = typeof window !== 'undefined'
  3412. && window.setImmediate;
  3413. var canPost = typeof window !== 'undefined'
  3414. && window.postMessage && window.addEventListener
  3415. ;
  3416. if (canSetImmediate) {
  3417. return function (f) { return window.setImmediate(f) };
  3418. }
  3419. if (canPost) {
  3420. var queue = [];
  3421. window.addEventListener('message', function (ev) {
  3422. var source = ev.source;
  3423. if ((source === window || source === null) && ev.data === 'process-tick') {
  3424. ev.stopPropagation();
  3425. if (queue.length > 0) {
  3426. var fn = queue.shift();
  3427. fn();
  3428. }
  3429. }
  3430. }, true);
  3431. return function nextTick(fn) {
  3432. queue.push(fn);
  3433. window.postMessage('process-tick', '*');
  3434. };
  3435. }
  3436. return function nextTick(fn) {
  3437. setTimeout(fn, 0);
  3438. };
  3439. })();
  3440. process.title = 'browser';
  3441. process.browser = true;
  3442. process.env = {};
  3443. process.argv = [];
  3444. function noop() {}
  3445. process.on = noop;
  3446. process.addListener = noop;
  3447. process.once = noop;
  3448. process.off = noop;
  3449. process.removeListener = noop;
  3450. process.removeAllListeners = noop;
  3451. process.emit = noop;
  3452. process.binding = function (name) {
  3453. throw new Error('process.binding is not supported');
  3454. }
  3455. // TODO(shtylman)
  3456. process.cwd = function () { return '/' };
  3457. process.chdir = function (dir) {
  3458. throw new Error('process.chdir is not supported');
  3459. };
  3460. },{}],30:[function(require,module,exports){
  3461. module.exports = function isBuffer(arg) {
  3462. return arg && typeof arg === 'object'
  3463. && typeof arg.copy === 'function'
  3464. && typeof arg.fill === 'function'
  3465. && typeof arg.readUInt8 === 'function';
  3466. }
  3467. },{}],31:[function(require,module,exports){
  3468. (function (process,global){
  3469. // Copyright Joyent, Inc. and other Node contributors.
  3470. //
  3471. // Permission is hereby granted, free of charge, to any person obtaining a
  3472. // copy of this software and associated documentation files (the
  3473. // "Software"), to deal in the Software without restriction, including
  3474. // without limitation the rights to use, copy, modify, merge, publish,
  3475. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3476. // persons to whom the Software is furnished to do so, subject to the
  3477. // following conditions:
  3478. //
  3479. // The above copyright notice and this permission notice shall be included
  3480. // in all copies or substantial portions of the Software.
  3481. //
  3482. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3483. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3484. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3485. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3486. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3487. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3488. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3489. var formatRegExp = /%[sdj%]/g;
  3490. exports.format = function(f) {
  3491. if (!isString(f)) {
  3492. var objects = [];
  3493. for (var i = 0; i < arguments.length; i++) {
  3494. objects.push(inspect(arguments[i]));
  3495. }
  3496. return objects.join(' ');
  3497. }
  3498. var i = 1;
  3499. var args = arguments;
  3500. var len = args.length;
  3501. var str = String(f).replace(formatRegExp, function(x) {
  3502. if (x === '%%') return '%';
  3503. if (i >= len) return x;
  3504. switch (x) {
  3505. case '%s': return String(args[i++]);
  3506. case '%d': return Number(args[i++]);
  3507. case '%j':
  3508. try {
  3509. return JSON.stringify(args[i++]);
  3510. } catch (_) {
  3511. return '[Circular]';
  3512. }
  3513. default:
  3514. return x;
  3515. }
  3516. });
  3517. for (var x = args[i]; i < len; x = args[++i]) {
  3518. if (isNull(x) || !isObject(x)) {
  3519. str += ' ' + x;
  3520. } else {
  3521. str += ' ' + inspect(x);
  3522. }
  3523. }
  3524. return str;
  3525. };
  3526. // Mark that a method should not be used.
  3527. // Returns a modified function which warns once by default.
  3528. // If --no-deprecation is set, then it is a no-op.
  3529. exports.deprecate = function(fn, msg) {
  3530. // Allow for deprecating things in the process of starting up.
  3531. if (isUndefined(global.process)) {
  3532. return function() {
  3533. return exports.deprecate(fn, msg).apply(this, arguments);
  3534. };
  3535. }
  3536. if (process.noDeprecation === true) {
  3537. return fn;
  3538. }
  3539. var warned = false;
  3540. function deprecated() {
  3541. if (!warned) {
  3542. if (process.throwDeprecation) {
  3543. throw new Error(msg);
  3544. } else if (process.traceDeprecation) {
  3545. console.trace(msg);
  3546. } else {
  3547. console.error(msg);
  3548. }
  3549. warned = true;
  3550. }
  3551. return fn.apply(this, arguments);
  3552. }
  3553. return deprecated;
  3554. };
  3555. var debugs = {};
  3556. var debugEnviron;
  3557. exports.debuglog = function(set) {
  3558. if (isUndefined(debugEnviron))
  3559. debugEnviron = process.env.NODE_DEBUG || '';
  3560. set = set.toUpperCase();
  3561. if (!debugs[set]) {
  3562. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  3563. var pid = process.pid;
  3564. debugs[set] = function() {
  3565. var msg = exports.format.apply(exports, arguments);
  3566. console.error('%s %d: %s', set, pid, msg);
  3567. };
  3568. } else {
  3569. debugs[set] = function() {};
  3570. }
  3571. }
  3572. return debugs[set];
  3573. };
  3574. /**
  3575. * Echos the value of a value. Trys to print the value out
  3576. * in the best way possible given the different types.
  3577. *
  3578. * @param {Object} obj The object to print out.
  3579. * @param {Object} opts Optional options object that alters the output.
  3580. */
  3581. /* legacy: obj, showHidden, depth, colors*/
  3582. function inspect(obj, opts) {
  3583. // default options
  3584. var ctx = {
  3585. seen: [],
  3586. stylize: stylizeNoColor
  3587. };
  3588. // legacy...
  3589. if (arguments.length >= 3) ctx.depth = arguments[2];
  3590. if (arguments.length >= 4) ctx.colors = arguments[3];
  3591. if (isBoolean(opts)) {
  3592. // legacy...
  3593. ctx.showHidden = opts;
  3594. } else if (opts) {
  3595. // got an "options" object
  3596. exports._extend(ctx, opts);
  3597. }
  3598. // set default options
  3599. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  3600. if (isUndefined(ctx.depth)) ctx.depth = 2;
  3601. if (isUndefined(ctx.colors)) ctx.colors = false;
  3602. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  3603. if (ctx.colors) ctx.stylize = stylizeWithColor;
  3604. return formatValue(ctx, obj, ctx.depth);
  3605. }
  3606. exports.inspect = inspect;
  3607. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  3608. inspect.colors = {
  3609. 'bold' : [1, 22],
  3610. 'italic' : [3, 23],
  3611. 'underline' : [4, 24],
  3612. 'inverse' : [7, 27],
  3613. 'white' : [37, 39],
  3614. 'grey' : [90, 39],
  3615. 'black' : [30, 39],
  3616. 'blue' : [34, 39],
  3617. 'cyan' : [36, 39],
  3618. 'green' : [32, 39],
  3619. 'magenta' : [35, 39],
  3620. 'red' : [31, 39],
  3621. 'yellow' : [33, 39]
  3622. };
  3623. // Don't use 'blue' not visible on cmd.exe
  3624. inspect.styles = {
  3625. 'special': 'cyan',
  3626. 'number': 'yellow',
  3627. 'boolean': 'yellow',
  3628. 'undefined': 'grey',
  3629. 'null': 'bold',
  3630. 'string': 'green',
  3631. 'date': 'magenta',
  3632. // "name": intentionally not styling
  3633. 'regexp': 'red'
  3634. };
  3635. function stylizeWithColor(str, styleType) {
  3636. var style = inspect.styles[styleType];
  3637. if (style) {
  3638. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  3639. '\u001b[' + inspect.colors[style][1] + 'm';
  3640. } else {
  3641. return str;
  3642. }
  3643. }
  3644. function stylizeNoColor(str, styleType) {
  3645. return str;
  3646. }
  3647. function arrayToHash(array) {
  3648. var hash = {};
  3649. array.forEach(function(val, idx) {
  3650. hash[val] = true;
  3651. });
  3652. return hash;
  3653. }
  3654. function formatValue(ctx, value, recurseTimes) {
  3655. // Provide a hook for user-specified inspect functions.
  3656. // Check that value is an object with an inspect function on it
  3657. if (ctx.customInspect &&
  3658. value &&
  3659. isFunction(value.inspect) &&
  3660. // Filter out the util module, it's inspect function is special
  3661. value.inspect !== exports.inspect &&
  3662. // Also filter out any prototype objects using the circular check.
  3663. !(value.constructor && value.constructor.prototype === value)) {
  3664. var ret = value.inspect(recurseTimes, ctx);
  3665. if (!isString(ret)) {
  3666. ret = formatValue(ctx, ret, recurseTimes);
  3667. }
  3668. return ret;
  3669. }
  3670. // Primitive types cannot have properties
  3671. var primitive = formatPrimitive(ctx, value);
  3672. if (primitive) {
  3673. return primitive;
  3674. }
  3675. // Look up the keys of the object.
  3676. var keys = Object.keys(value);
  3677. var visibleKeys = arrayToHash(keys);
  3678. if (ctx.showHidden) {
  3679. keys = Object.getOwnPropertyNames(value);
  3680. }
  3681. // IE doesn't make error fields non-enumerable
  3682. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  3683. if (isError(value)
  3684. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  3685. return formatError(value);
  3686. }
  3687. // Some type of object without properties can be shortcutted.
  3688. if (keys.length === 0) {
  3689. if (isFunction(value)) {
  3690. var name = value.name ? ': ' + value.name : '';
  3691. return ctx.stylize('[Function' + name + ']', 'special');
  3692. }
  3693. if (isRegExp(value)) {
  3694. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  3695. }
  3696. if (isDate(value)) {
  3697. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  3698. }
  3699. if (isError(value)) {
  3700. return formatError(value);
  3701. }
  3702. }
  3703. var base = '', array = false, braces = ['{', '}'];
  3704. // Make Array say that they are Array
  3705. if (isArray(value)) {
  3706. array = true;
  3707. braces = ['[', ']'];
  3708. }
  3709. // Make functions say that they are functions
  3710. if (isFunction(value)) {
  3711. var n = value.name ? ': ' + value.name : '';
  3712. base = ' [Function' + n + ']';
  3713. }
  3714. // Make RegExps say that they are RegExps
  3715. if (isRegExp(value)) {
  3716. base = ' ' + RegExp.prototype.toString.call(value);
  3717. }
  3718. // Make dates with properties first say the date
  3719. if (isDate(value)) {
  3720. base = ' ' + Date.prototype.toUTCString.call(value);
  3721. }
  3722. // Make error with message first say the error
  3723. if (isError(value)) {
  3724. base = ' ' + formatError(value);
  3725. }
  3726. if (keys.length === 0 && (!array || value.length == 0)) {
  3727. return braces[0] + base + braces[1];
  3728. }
  3729. if (recurseTimes < 0) {
  3730. if (isRegExp(value)) {
  3731. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  3732. } else {
  3733. return ctx.stylize('[Object]', 'special');
  3734. }
  3735. }
  3736. ctx.seen.push(value);
  3737. var output;
  3738. if (array) {
  3739. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  3740. } else {
  3741. output = keys.map(function(key) {
  3742. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  3743. });
  3744. }
  3745. ctx.seen.pop();
  3746. return reduceToSingleString(output, base, braces);
  3747. }
  3748. function formatPrimitive(ctx, value) {
  3749. if (isUndefined(value))
  3750. return ctx.stylize('undefined', 'undefined');
  3751. if (isString(value)) {
  3752. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  3753. .replace(/'/g, "\\'")
  3754. .replace(/\\"/g, '"') + '\'';
  3755. return ctx.stylize(simple, 'string');
  3756. }
  3757. if (isNumber(value))
  3758. return ctx.stylize('' + value, 'number');
  3759. if (isBoolean(value))
  3760. return ctx.stylize('' + value, 'boolean');
  3761. // For some reason typeof null is "object", so special case here.
  3762. if (isNull(value))
  3763. return ctx.stylize('null', 'null');
  3764. }
  3765. function formatError(value) {
  3766. return '[' + Error.prototype.toString.call(value) + ']';
  3767. }
  3768. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  3769. var output = [];
  3770. for (var i = 0, l = value.length; i < l; ++i) {
  3771. if (hasOwnProperty(value, String(i))) {
  3772. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  3773. String(i), true));
  3774. } else {
  3775. output.push('');
  3776. }
  3777. }
  3778. keys.forEach(function(key) {
  3779. if (!key.match(/^\d+$/)) {
  3780. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  3781. key, true));
  3782. }
  3783. });
  3784. return output;
  3785. }
  3786. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  3787. var name, str, desc;
  3788. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  3789. if (desc.get) {
  3790. if (desc.set) {
  3791. str = ctx.stylize('[Getter/Setter]', 'special');
  3792. } else {
  3793. str = ctx.stylize('[Getter]', 'special');
  3794. }
  3795. } else {
  3796. if (desc.set) {
  3797. str = ctx.stylize('[Setter]', 'special');
  3798. }
  3799. }
  3800. if (!hasOwnProperty(visibleKeys, key)) {
  3801. name = '[' + key + ']';
  3802. }
  3803. if (!str) {
  3804. if (ctx.seen.indexOf(desc.value) < 0) {
  3805. if (isNull(recurseTimes)) {
  3806. str = formatValue(ctx, desc.value, null);
  3807. } else {
  3808. str = formatValue(ctx, desc.value, recurseTimes - 1);
  3809. }
  3810. if (str.indexOf('\n') > -1) {
  3811. if (array) {
  3812. str = str.split('\n').map(function(line) {
  3813. return ' ' + line;
  3814. }).join('\n').substr(2);
  3815. } else {
  3816. str = '\n' + str.split('\n').map(function(line) {
  3817. return ' ' + line;
  3818. }).join('\n');
  3819. }
  3820. }
  3821. } else {
  3822. str = ctx.stylize('[Circular]', 'special');
  3823. }
  3824. }
  3825. if (isUndefined(name)) {
  3826. if (array && key.match(/^\d+$/)) {
  3827. return str;
  3828. }
  3829. name = JSON.stringify('' + key);
  3830. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  3831. name = name.substr(1, name.length - 2);
  3832. name = ctx.stylize(name, 'name');
  3833. } else {
  3834. name = name.replace(/'/g, "\\'")
  3835. .replace(/\\"/g, '"')
  3836. .replace(/(^"|"$)/g, "'");
  3837. name = ctx.stylize(name, 'string');
  3838. }
  3839. }
  3840. return name + ': ' + str;
  3841. }
  3842. function reduceToSingleString(output, base, braces) {
  3843. var numLinesEst = 0;
  3844. var length = output.reduce(function(prev, cur) {
  3845. numLinesEst++;
  3846. if (cur.indexOf('\n') >= 0) numLinesEst++;
  3847. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  3848. }, 0);
  3849. if (length > 60) {
  3850. return braces[0] +
  3851. (base === '' ? '' : base + '\n ') +
  3852. ' ' +
  3853. output.join(',\n ') +
  3854. ' ' +
  3855. braces[1];
  3856. }
  3857. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  3858. }
  3859. // NOTE: These type checking functions intentionally don't use `instanceof`
  3860. // because it is fragile and can be easily faked with `Object.create()`.
  3861. function isArray(ar) {
  3862. return Array.isArray(ar);
  3863. }
  3864. exports.isArray = isArray;
  3865. function isBoolean(arg) {
  3866. return typeof arg === 'boolean';
  3867. }
  3868. exports.isBoolean = isBoolean;
  3869. function isNull(arg) {
  3870. return arg === null;
  3871. }
  3872. exports.isNull = isNull;
  3873. function isNullOrUndefined(arg) {
  3874. return arg == null;
  3875. }
  3876. exports.isNullOrUndefined = isNullOrUndefined;
  3877. function isNumber(arg) {
  3878. return typeof arg === 'number';
  3879. }
  3880. exports.isNumber = isNumber;
  3881. function isString(arg) {
  3882. return typeof arg === 'string';
  3883. }
  3884. exports.isString = isString;
  3885. function isSymbol(arg) {
  3886. return typeof arg === 'symbol';
  3887. }
  3888. exports.isSymbol = isSymbol;
  3889. function isUndefined(arg) {
  3890. return arg === void 0;
  3891. }
  3892. exports.isUndefined = isUndefined;
  3893. function isRegExp(re) {
  3894. return isObject(re) && objectToString(re) === '[object RegExp]';
  3895. }
  3896. exports.isRegExp = isRegExp;
  3897. function isObject(arg) {
  3898. return typeof arg === 'object' && arg !== null;
  3899. }
  3900. exports.isObject = isObject;
  3901. function isDate(d) {
  3902. return isObject(d) && objectToString(d) === '[object Date]';
  3903. }
  3904. exports.isDate = isDate;
  3905. function isError(e) {
  3906. return isObject(e) &&
  3907. (objectToString(e) === '[object Error]' || e instanceof Error);
  3908. }
  3909. exports.isError = isError;
  3910. function isFunction(arg) {
  3911. return typeof arg === 'function';
  3912. }
  3913. exports.isFunction = isFunction;
  3914. function isPrimitive(arg) {
  3915. return arg === null ||
  3916. typeof arg === 'boolean' ||
  3917. typeof arg === 'number' ||
  3918. typeof arg === 'string' ||
  3919. typeof arg === 'symbol' || // ES6 symbol
  3920. typeof arg === 'undefined';
  3921. }
  3922. exports.isPrimitive = isPrimitive;
  3923. exports.isBuffer = require('./support/isBuffer');
  3924. function objectToString(o) {
  3925. return Object.prototype.toString.call(o);
  3926. }
  3927. function pad(n) {
  3928. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  3929. }
  3930. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  3931. 'Oct', 'Nov', 'Dec'];
  3932. // 26 Feb 16:19:34
  3933. function timestamp() {
  3934. var d = new Date();
  3935. var time = [pad(d.getHours()),
  3936. pad(d.getMinutes()),
  3937. pad(d.getSeconds())].join(':');
  3938. return [d.getDate(), months[d.getMonth()], time].join(' ');
  3939. }
  3940. // log is just a thin wrapper to console.log that prepends a timestamp
  3941. exports.log = function() {
  3942. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  3943. };
  3944. /**
  3945. * Inherit the prototype methods from one constructor into another.
  3946. *
  3947. * The Function.prototype.inherits from lang.js rewritten as a standalone
  3948. * function (not on Function.prototype). NOTE: If this file is to be loaded
  3949. * during bootstrapping this function needs to be rewritten using some native
  3950. * functions as prototype setup using normal JavaScript does not work as
  3951. * expected during bootstrapping (see mirror.js in r114903).
  3952. *
  3953. * @param {function} ctor Constructor function which needs to inherit the
  3954. * prototype.
  3955. * @param {function} superCtor Constructor function to inherit prototype from.
  3956. */
  3957. exports.inherits = require('inherits');
  3958. exports._extend = function(origin, add) {
  3959. // Don't do anything if add isn't an object
  3960. if (!add || !isObject(add)) return origin;
  3961. var keys = Object.keys(add);
  3962. var i = keys.length;
  3963. while (i--) {
  3964. origin[keys[i]] = add[keys[i]];
  3965. }
  3966. return origin;
  3967. };
  3968. function hasOwnProperty(obj, prop) {
  3969. return Object.prototype.hasOwnProperty.call(obj, prop);
  3970. }
  3971. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3972. },{"./support/isBuffer":30,"_process":29,"inherits":27}],32:[function(require,module,exports){
  3973. exports = (module.exports = parse);
  3974. exports.parse = parse;
  3975. function parse(src, state, options) {
  3976. options = options || {};
  3977. state = state || exports.defaultState();
  3978. var start = options.start || 0;
  3979. var end = options.end || src.length;
  3980. var index = start;
  3981. while (index < end) {
  3982. if (state.roundDepth < 0 || state.curlyDepth < 0 || state.squareDepth < 0) {
  3983. throw new SyntaxError('Mismatched Bracket: ' + src[index - 1]);
  3984. }
  3985. exports.parseChar(src[index++], state);
  3986. }
  3987. return state;
  3988. }
  3989. exports.parseMax = parseMax;
  3990. function parseMax(src, options) {
  3991. options = options || {};
  3992. var start = options.start || 0;
  3993. var index = start;
  3994. var state = exports.defaultState();
  3995. while (state.roundDepth >= 0 && state.curlyDepth >= 0 && state.squareDepth >= 0) {
  3996. if (index >= src.length) {
  3997. throw new Error('The end of the string was reached with no closing bracket found.');
  3998. }
  3999. exports.parseChar(src[index++], state);
  4000. }
  4001. var end = index - 1;
  4002. return {
  4003. start: start,
  4004. end: end,
  4005. src: src.substring(start, end)
  4006. };
  4007. }
  4008. exports.parseUntil = parseUntil;
  4009. function parseUntil(src, delimiter, options) {
  4010. options = options || {};
  4011. var includeLineComment = options.includeLineComment || false;
  4012. var start = options.start || 0;
  4013. var index = start;
  4014. var state = exports.defaultState();
  4015. while (state.isString() || state.regexp || state.blockComment ||
  4016. (!includeLineComment && state.lineComment) || !startsWith(src, delimiter, index)) {
  4017. exports.parseChar(src[index++], state);
  4018. }
  4019. var end = index;
  4020. return {
  4021. start: start,
  4022. end: end,
  4023. src: src.substring(start, end)
  4024. };
  4025. }
  4026. exports.parseChar = parseChar;
  4027. function parseChar(character, state) {
  4028. if (character.length !== 1) throw new Error('Character must be a string of length 1');
  4029. state = state || exports.defaultState();
  4030. var wasComment = state.blockComment || state.lineComment;
  4031. var lastChar = state.history ? state.history[0] : '';
  4032. if (state.lineComment) {
  4033. if (character === '\n') {
  4034. state.lineComment = false;
  4035. }
  4036. } else if (state.blockComment) {
  4037. if (state.lastChar === '*' && character === '/') {
  4038. state.blockComment = false;
  4039. }
  4040. } else if (state.singleQuote) {
  4041. if (character === '\'' && !state.escaped) {
  4042. state.singleQuote = false;
  4043. } else if (character === '\\' && !state.escaped) {
  4044. state.escaped = true;
  4045. } else {
  4046. state.escaped = false;
  4047. }
  4048. } else if (state.doubleQuote) {
  4049. if (character === '"' && !state.escaped) {
  4050. state.doubleQuote = false;
  4051. } else if (character === '\\' && !state.escaped) {
  4052. state.escaped = true;
  4053. } else {
  4054. state.escaped = false;
  4055. }
  4056. } else if (state.regexp) {
  4057. if (character === '/' && !state.escaped) {
  4058. state.regexp = false;
  4059. } else if (character === '\\' && !state.escaped) {
  4060. state.escaped = true;
  4061. } else {
  4062. state.escaped = false;
  4063. }
  4064. } else if (lastChar === '/' && character === '/') {
  4065. state.history = state.history.substr(1);
  4066. state.lineComment = true;
  4067. } else if (lastChar === '/' && character === '*') {
  4068. state.history = state.history.substr(1);
  4069. state.blockComment = true;
  4070. } else if (character === '/' && isRegexp(state.history)) {
  4071. state.regexp = true;
  4072. } else if (character === '\'') {
  4073. state.singleQuote = true;
  4074. } else if (character === '"') {
  4075. state.doubleQuote = true;
  4076. } else if (character === '(') {
  4077. state.roundDepth++;
  4078. } else if (character === ')') {
  4079. state.roundDepth--;
  4080. } else if (character === '{') {
  4081. state.curlyDepth++;
  4082. } else if (character === '}') {
  4083. state.curlyDepth--;
  4084. } else if (character === '[') {
  4085. state.squareDepth++;
  4086. } else if (character === ']') {
  4087. state.squareDepth--;
  4088. }
  4089. if (!state.blockComment && !state.lineComment && !wasComment) state.history = character + state.history;
  4090. return state;
  4091. }
  4092. exports.defaultState = function () { return new State() };
  4093. function State() {
  4094. this.lineComment = false;
  4095. this.blockComment = false;
  4096. this.singleQuote = false;
  4097. this.doubleQuote = false;
  4098. this.regexp = false;
  4099. this.escaped = false;
  4100. this.roundDepth = 0;
  4101. this.curlyDepth = 0;
  4102. this.squareDepth = 0;
  4103. this.history = ''
  4104. }
  4105. State.prototype.isString = function () {
  4106. return this.singleQuote || this.doubleQuote;
  4107. }
  4108. State.prototype.isComment = function () {
  4109. return this.lineComment || this.blockComment;
  4110. }
  4111. State.prototype.isNesting = function () {
  4112. return this.isString() || this.isComment() || this.regexp || this.roundDepth > 0 || this.curlyDepth > 0 || this.squareDepth > 0
  4113. }
  4114. function startsWith(str, start, i) {
  4115. return str.substr(i || 0, start.length) === start;
  4116. }
  4117. exports.isPunctuator = isPunctuator
  4118. function isPunctuator(c) {
  4119. var code = c.charCodeAt(0)
  4120. switch (code) {
  4121. case 46: // . dot
  4122. case 40: // ( open bracket
  4123. case 41: // ) close bracket
  4124. case 59: // ; semicolon
  4125. case 44: // , comma
  4126. case 123: // { open curly brace
  4127. case 125: // } close curly brace
  4128. case 91: // [
  4129. case 93: // ]
  4130. case 58: // :
  4131. case 63: // ?
  4132. case 126: // ~
  4133. case 37: // %
  4134. case 38: // &
  4135. case 42: // *:
  4136. case 43: // +
  4137. case 45: // -
  4138. case 47: // /
  4139. case 60: // <
  4140. case 62: // >
  4141. case 94: // ^
  4142. case 124: // |
  4143. case 33: // !
  4144. case 61: // =
  4145. return true;
  4146. default:
  4147. return false;
  4148. }
  4149. }
  4150. exports.isKeyword = isKeyword
  4151. function isKeyword(id) {
  4152. return (id === 'if') || (id === 'in') || (id === 'do') || (id === 'var') || (id === 'for') || (id === 'new') ||
  4153. (id === 'try') || (id === 'let') || (id === 'this') || (id === 'else') || (id === 'case') ||
  4154. (id === 'void') || (id === 'with') || (id === 'enum') || (id === 'while') || (id === 'break') || (id === 'catch') ||
  4155. (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super') ||
  4156. (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') ||
  4157. (id === 'import') || (id === 'default') || (id === 'finally') || (id === 'extends') || (id === 'function') ||
  4158. (id === 'continue') || (id === 'debugger') || (id === 'package') || (id === 'private') || (id === 'interface') ||
  4159. (id === 'instanceof') || (id === 'implements') || (id === 'protected') || (id === 'public') || (id === 'static') ||
  4160. (id === 'yield') || (id === 'let');
  4161. }
  4162. function isRegexp(history) {
  4163. //could be start of regexp or divide sign
  4164. history = history.replace(/^\s*/, '');
  4165. //unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide
  4166. if (history[0] === ')') return false;
  4167. //unless it's a function expression, it's a regexp, so we assume it's a regexp
  4168. if (history[0] === '}') return true;
  4169. //any punctuation means it's a regexp
  4170. if (isPunctuator(history[0])) return true;
  4171. //if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`)
  4172. if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0].split('').reverse().join(''))) return true;
  4173. return false;
  4174. }
  4175. },{}],33:[function(require,module,exports){
  4176. 'use strict'
  4177. var uglify = require('uglify-js')
  4178. var lastSRC = '(null)'
  4179. var lastRes = true
  4180. var lastConstants = undefined;
  4181. module.exports = isConstant
  4182. function isConstant(src, constants) {
  4183. src = '(' + src + ')'
  4184. if (lastSRC === src && lastConstants === constants) return lastRes
  4185. lastSRC = src
  4186. try {
  4187. return lastRes = (detect(src).filter(function (key) {
  4188. return !constants || !(key in constants)
  4189. }).length === 0)
  4190. } catch (ex) {
  4191. return lastRes = false
  4192. }
  4193. }
  4194. isConstant.isConstant = isConstant
  4195. isConstant.toConstant = toConstant
  4196. function toConstant(src, constants) {
  4197. if (!isConstant(src, constants)) throw new Error(JSON.stringify(src) + ' is not constant.')
  4198. return Function(Object.keys(constants || {}).join(','), 'return (' + src + ')').apply(null, Object.keys(constants || {}).map(function (key) {
  4199. return constants[key];
  4200. }));
  4201. }
  4202. function detect(src) {
  4203. var ast = uglify.parse(src.toString())
  4204. ast.figure_out_scope()
  4205. var globals = ast.globals
  4206. .map(function (node, name) {
  4207. return name
  4208. })
  4209. // Walk the AST tree in search for `this`
  4210. // Add a fake "this" global when found
  4211. var has_this = false;
  4212. var walker = new uglify.TreeWalker(function(node) {
  4213. if (node instanceof uglify.AST_This) {
  4214. has_this = true;
  4215. }
  4216. });
  4217. ast.walk(walker);
  4218. if (has_this) {
  4219. globals.push('this')
  4220. }
  4221. return globals
  4222. }
  4223. },{"uglify-js":44}],34:[function(require,module,exports){
  4224. /*
  4225. * Copyright 2009-2011 Mozilla Foundation and contributors
  4226. * Licensed under the New BSD license. See LICENSE.txt or:
  4227. * http://opensource.org/licenses/BSD-3-Clause
  4228. */
  4229. exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
  4230. exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
  4231. exports.SourceNode = require('./source-map/source-node').SourceNode;
  4232. },{"./source-map/source-map-consumer":39,"./source-map/source-map-generator":40,"./source-map/source-node":41}],35:[function(require,module,exports){
  4233. /* -*- Mode: js; js-indent-level: 2; -*- */
  4234. /*
  4235. * Copyright 2011 Mozilla Foundation and contributors
  4236. * Licensed under the New BSD license. See LICENSE or:
  4237. * http://opensource.org/licenses/BSD-3-Clause
  4238. */
  4239. if (typeof define !== 'function') {
  4240. var define = require('amdefine')(module, require);
  4241. }
  4242. define(function (require, exports, module) {
  4243. var util = require('./util');
  4244. /**
  4245. * A data structure which is a combination of an array and a set. Adding a new
  4246. * member is O(1), testing for membership is O(1), and finding the index of an
  4247. * element is O(1). Removing elements from the set is not supported. Only
  4248. * strings are supported for membership.
  4249. */
  4250. function ArraySet() {
  4251. this._array = [];
  4252. this._set = {};
  4253. }
  4254. /**
  4255. * Static method for creating ArraySet instances from an existing array.
  4256. */
  4257. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  4258. var set = new ArraySet();
  4259. for (var i = 0, len = aArray.length; i < len; i++) {
  4260. set.add(aArray[i], aAllowDuplicates);
  4261. }
  4262. return set;
  4263. };
  4264. /**
  4265. * Add the given string to this set.
  4266. *
  4267. * @param String aStr
  4268. */
  4269. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  4270. var isDuplicate = this.has(aStr);
  4271. var idx = this._array.length;
  4272. if (!isDuplicate || aAllowDuplicates) {
  4273. this._array.push(aStr);
  4274. }
  4275. if (!isDuplicate) {
  4276. this._set[util.toSetString(aStr)] = idx;
  4277. }
  4278. };
  4279. /**
  4280. * Is the given string a member of this set?
  4281. *
  4282. * @param String aStr
  4283. */
  4284. ArraySet.prototype.has = function ArraySet_has(aStr) {
  4285. return Object.prototype.hasOwnProperty.call(this._set,
  4286. util.toSetString(aStr));
  4287. };
  4288. /**
  4289. * What is the index of the given string in the array?
  4290. *
  4291. * @param String aStr
  4292. */
  4293. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  4294. if (this.has(aStr)) {
  4295. return this._set[util.toSetString(aStr)];
  4296. }
  4297. throw new Error('"' + aStr + '" is not in the set.');
  4298. };
  4299. /**
  4300. * What is the element at the given index?
  4301. *
  4302. * @param Number aIdx
  4303. */
  4304. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  4305. if (aIdx >= 0 && aIdx < this._array.length) {
  4306. return this._array[aIdx];
  4307. }
  4308. throw new Error('No element indexed by ' + aIdx);
  4309. };
  4310. /**
  4311. * Returns the array representation of this set (which has the proper indices
  4312. * indicated by indexOf). Note that this is a copy of the internal array used
  4313. * for storing the members so that no one can mess with internal state.
  4314. */
  4315. ArraySet.prototype.toArray = function ArraySet_toArray() {
  4316. return this._array.slice();
  4317. };
  4318. exports.ArraySet = ArraySet;
  4319. });
  4320. },{"./util":42,"amdefine":43}],36:[function(require,module,exports){
  4321. /* -*- Mode: js; js-indent-level: 2; -*- */
  4322. /*
  4323. * Copyright 2011 Mozilla Foundation and contributors
  4324. * Licensed under the New BSD license. See LICENSE or:
  4325. * http://opensource.org/licenses/BSD-3-Clause
  4326. *
  4327. * Based on the Base 64 VLQ implementation in Closure Compiler:
  4328. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  4329. *
  4330. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  4331. * Redistribution and use in source and binary forms, with or without
  4332. * modification, are permitted provided that the following conditions are
  4333. * met:
  4334. *
  4335. * * Redistributions of source code must retain the above copyright
  4336. * notice, this list of conditions and the following disclaimer.
  4337. * * Redistributions in binary form must reproduce the above
  4338. * copyright notice, this list of conditions and the following
  4339. * disclaimer in the documentation and/or other materials provided
  4340. * with the distribution.
  4341. * * Neither the name of Google Inc. nor the names of its
  4342. * contributors may be used to endorse or promote products derived
  4343. * from this software without specific prior written permission.
  4344. *
  4345. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4346. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4347. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4348. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4349. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4350. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4351. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4352. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4353. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4354. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4355. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4356. */
  4357. if (typeof define !== 'function') {
  4358. var define = require('amdefine')(module, require);
  4359. }
  4360. define(function (require, exports, module) {
  4361. var base64 = require('./base64');
  4362. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  4363. // length quantities we use in the source map spec, the first bit is the sign,
  4364. // the next four bits are the actual value, and the 6th bit is the
  4365. // continuation bit. The continuation bit tells us whether there are more
  4366. // digits in this value following this digit.
  4367. //
  4368. // Continuation
  4369. // | Sign
  4370. // | |
  4371. // V V
  4372. // 101011
  4373. var VLQ_BASE_SHIFT = 5;
  4374. // binary: 100000
  4375. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  4376. // binary: 011111
  4377. var VLQ_BASE_MASK = VLQ_BASE - 1;
  4378. // binary: 100000
  4379. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  4380. /**
  4381. * Converts from a two-complement value to a value where the sign bit is
  4382. * is placed in the least significant bit. For example, as decimals:
  4383. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  4384. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  4385. */
  4386. function toVLQSigned(aValue) {
  4387. return aValue < 0
  4388. ? ((-aValue) << 1) + 1
  4389. : (aValue << 1) + 0;
  4390. }
  4391. /**
  4392. * Converts to a two-complement value from a value where the sign bit is
  4393. * is placed in the least significant bit. For example, as decimals:
  4394. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  4395. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  4396. */
  4397. function fromVLQSigned(aValue) {
  4398. var isNegative = (aValue & 1) === 1;
  4399. var shifted = aValue >> 1;
  4400. return isNegative
  4401. ? -shifted
  4402. : shifted;
  4403. }
  4404. /**
  4405. * Returns the base 64 VLQ encoded value.
  4406. */
  4407. exports.encode = function base64VLQ_encode(aValue) {
  4408. var encoded = "";
  4409. var digit;
  4410. var vlq = toVLQSigned(aValue);
  4411. do {
  4412. digit = vlq & VLQ_BASE_MASK;
  4413. vlq >>>= VLQ_BASE_SHIFT;
  4414. if (vlq > 0) {
  4415. // There are still more digits in this value, so we must make sure the
  4416. // continuation bit is marked.
  4417. digit |= VLQ_CONTINUATION_BIT;
  4418. }
  4419. encoded += base64.encode(digit);
  4420. } while (vlq > 0);
  4421. return encoded;
  4422. };
  4423. /**
  4424. * Decodes the next base 64 VLQ value from the given string and returns the
  4425. * value and the rest of the string.
  4426. */
  4427. exports.decode = function base64VLQ_decode(aStr) {
  4428. var i = 0;
  4429. var strLen = aStr.length;
  4430. var result = 0;
  4431. var shift = 0;
  4432. var continuation, digit;
  4433. do {
  4434. if (i >= strLen) {
  4435. throw new Error("Expected more digits in base 64 VLQ value.");
  4436. }
  4437. digit = base64.decode(aStr.charAt(i++));
  4438. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  4439. digit &= VLQ_BASE_MASK;
  4440. result = result + (digit << shift);
  4441. shift += VLQ_BASE_SHIFT;
  4442. } while (continuation);
  4443. return {
  4444. value: fromVLQSigned(result),
  4445. rest: aStr.slice(i)
  4446. };
  4447. };
  4448. });
  4449. },{"./base64":37,"amdefine":43}],37:[function(require,module,exports){
  4450. /* -*- Mode: js; js-indent-level: 2; -*- */
  4451. /*
  4452. * Copyright 2011 Mozilla Foundation and contributors
  4453. * Licensed under the New BSD license. See LICENSE or:
  4454. * http://opensource.org/licenses/BSD-3-Clause
  4455. */
  4456. if (typeof define !== 'function') {
  4457. var define = require('amdefine')(module, require);
  4458. }
  4459. define(function (require, exports, module) {
  4460. var charToIntMap = {};
  4461. var intToCharMap = {};
  4462. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  4463. .split('')
  4464. .forEach(function (ch, index) {
  4465. charToIntMap[ch] = index;
  4466. intToCharMap[index] = ch;
  4467. });
  4468. /**
  4469. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  4470. */
  4471. exports.encode = function base64_encode(aNumber) {
  4472. if (aNumber in intToCharMap) {
  4473. return intToCharMap[aNumber];
  4474. }
  4475. throw new TypeError("Must be between 0 and 63: " + aNumber);
  4476. };
  4477. /**
  4478. * Decode a single base 64 digit to an integer.
  4479. */
  4480. exports.decode = function base64_decode(aChar) {
  4481. if (aChar in charToIntMap) {
  4482. return charToIntMap[aChar];
  4483. }
  4484. throw new TypeError("Not a valid base 64 digit: " + aChar);
  4485. };
  4486. });
  4487. },{"amdefine":43}],38:[function(require,module,exports){
  4488. /* -*- Mode: js; js-indent-level: 2; -*- */
  4489. /*
  4490. * Copyright 2011 Mozilla Foundation and contributors
  4491. * Licensed under the New BSD license. See LICENSE or:
  4492. * http://opensource.org/licenses/BSD-3-Clause
  4493. */
  4494. if (typeof define !== 'function') {
  4495. var define = require('amdefine')(module, require);
  4496. }
  4497. define(function (require, exports, module) {
  4498. /**
  4499. * Recursive implementation of binary search.
  4500. *
  4501. * @param aLow Indices here and lower do not contain the needle.
  4502. * @param aHigh Indices here and higher do not contain the needle.
  4503. * @param aNeedle The element being searched for.
  4504. * @param aHaystack The non-empty array being searched.
  4505. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  4506. */
  4507. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
  4508. // This function terminates when one of the following is true:
  4509. //
  4510. // 1. We find the exact element we are looking for.
  4511. //
  4512. // 2. We did not find the exact element, but we can return the next
  4513. // closest element that is less than that element.
  4514. //
  4515. // 3. We did not find the exact element, and there is no next-closest
  4516. // element which is less than the one we are searching for, so we
  4517. // return null.
  4518. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  4519. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  4520. if (cmp === 0) {
  4521. // Found the element we are looking for.
  4522. return aHaystack[mid];
  4523. }
  4524. else if (cmp > 0) {
  4525. // aHaystack[mid] is greater than our needle.
  4526. if (aHigh - mid > 1) {
  4527. // The element is in the upper half.
  4528. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
  4529. }
  4530. // We did not find an exact match, return the next closest one
  4531. // (termination case 2).
  4532. return aHaystack[mid];
  4533. }
  4534. else {
  4535. // aHaystack[mid] is less than our needle.
  4536. if (mid - aLow > 1) {
  4537. // The element is in the lower half.
  4538. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
  4539. }
  4540. // The exact needle element was not found in this haystack. Determine if
  4541. // we are in termination case (2) or (3) and return the appropriate thing.
  4542. return aLow < 0
  4543. ? null
  4544. : aHaystack[aLow];
  4545. }
  4546. }
  4547. /**
  4548. * This is an implementation of binary search which will always try and return
  4549. * the next lowest value checked if there is no exact hit. This is because
  4550. * mappings between original and generated line/col pairs are single points,
  4551. * and there is an implicit region between each of them, so a miss just means
  4552. * that you aren't on the very start of a region.
  4553. *
  4554. * @param aNeedle The element you are looking for.
  4555. * @param aHaystack The array that is being searched.
  4556. * @param aCompare A function which takes the needle and an element in the
  4557. * array and returns -1, 0, or 1 depending on whether the needle is less
  4558. * than, equal to, or greater than the element, respectively.
  4559. */
  4560. exports.search = function search(aNeedle, aHaystack, aCompare) {
  4561. return aHaystack.length > 0
  4562. ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
  4563. : null;
  4564. };
  4565. });
  4566. },{"amdefine":43}],39:[function(require,module,exports){
  4567. /* -*- Mode: js; js-indent-level: 2; -*- */
  4568. /*
  4569. * Copyright 2011 Mozilla Foundation and contributors
  4570. * Licensed under the New BSD license. See LICENSE or:
  4571. * http://opensource.org/licenses/BSD-3-Clause
  4572. */
  4573. if (typeof define !== 'function') {
  4574. var define = require('amdefine')(module, require);
  4575. }
  4576. define(function (require, exports, module) {
  4577. var util = require('./util');
  4578. var binarySearch = require('./binary-search');
  4579. var ArraySet = require('./array-set').ArraySet;
  4580. var base64VLQ = require('./base64-vlq');
  4581. /**
  4582. * A SourceMapConsumer instance represents a parsed source map which we can
  4583. * query for information about the original file positions by giving it a file
  4584. * position in the generated source.
  4585. *
  4586. * The only parameter is the raw source map (either as a JSON string, or
  4587. * already parsed to an object). According to the spec, source maps have the
  4588. * following attributes:
  4589. *
  4590. * - version: Which version of the source map spec this map is following.
  4591. * - sources: An array of URLs to the original source files.
  4592. * - names: An array of identifiers which can be referrenced by individual mappings.
  4593. * - sourceRoot: Optional. The URL root from which all sources are relative.
  4594. * - sourcesContent: Optional. An array of contents of the original source files.
  4595. * - mappings: A string of base64 VLQs which contain the actual mappings.
  4596. * - file: Optional. The generated file this source map is associated with.
  4597. *
  4598. * Here is an example source map, taken from the source map spec[0]:
  4599. *
  4600. * {
  4601. * version : 3,
  4602. * file: "out.js",
  4603. * sourceRoot : "",
  4604. * sources: ["foo.js", "bar.js"],
  4605. * names: ["src", "maps", "are", "fun"],
  4606. * mappings: "AA,AB;;ABCDE;"
  4607. * }
  4608. *
  4609. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  4610. */
  4611. function SourceMapConsumer(aSourceMap) {
  4612. var sourceMap = aSourceMap;
  4613. if (typeof aSourceMap === 'string') {
  4614. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  4615. }
  4616. var version = util.getArg(sourceMap, 'version');
  4617. var sources = util.getArg(sourceMap, 'sources');
  4618. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  4619. // requires the array) to play nice here.
  4620. var names = util.getArg(sourceMap, 'names', []);
  4621. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  4622. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  4623. var mappings = util.getArg(sourceMap, 'mappings');
  4624. var file = util.getArg(sourceMap, 'file', null);
  4625. // Once again, Sass deviates from the spec and supplies the version as a
  4626. // string rather than a number, so we use loose equality checking here.
  4627. if (version != this._version) {
  4628. throw new Error('Unsupported version: ' + version);
  4629. }
  4630. // Pass `true` below to allow duplicate names and sources. While source maps
  4631. // are intended to be compressed and deduplicated, the TypeScript compiler
  4632. // sometimes generates source maps with duplicates in them. See Github issue
  4633. // #72 and bugzil.la/889492.
  4634. this._names = ArraySet.fromArray(names, true);
  4635. this._sources = ArraySet.fromArray(sources, true);
  4636. this.sourceRoot = sourceRoot;
  4637. this.sourcesContent = sourcesContent;
  4638. this._mappings = mappings;
  4639. this.file = file;
  4640. }
  4641. /**
  4642. * Create a SourceMapConsumer from a SourceMapGenerator.
  4643. *
  4644. * @param SourceMapGenerator aSourceMap
  4645. * The source map that will be consumed.
  4646. * @returns SourceMapConsumer
  4647. */
  4648. SourceMapConsumer.fromSourceMap =
  4649. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  4650. var smc = Object.create(SourceMapConsumer.prototype);
  4651. smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  4652. smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  4653. smc.sourceRoot = aSourceMap._sourceRoot;
  4654. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  4655. smc.sourceRoot);
  4656. smc.file = aSourceMap._file;
  4657. smc.__generatedMappings = aSourceMap._mappings.slice()
  4658. .sort(util.compareByGeneratedPositions);
  4659. smc.__originalMappings = aSourceMap._mappings.slice()
  4660. .sort(util.compareByOriginalPositions);
  4661. return smc;
  4662. };
  4663. /**
  4664. * The version of the source mapping spec that we are consuming.
  4665. */
  4666. SourceMapConsumer.prototype._version = 3;
  4667. /**
  4668. * The list of original sources.
  4669. */
  4670. Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
  4671. get: function () {
  4672. return this._sources.toArray().map(function (s) {
  4673. return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
  4674. }, this);
  4675. }
  4676. });
  4677. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  4678. // parsed mapping coordinates from the source map's "mappings" attribute. They
  4679. // are lazily instantiated, accessed via the `_generatedMappings` and
  4680. // `_originalMappings` getters respectively, and we only parse the mappings
  4681. // and create these arrays once queried for a source location. We jump through
  4682. // these hoops because there can be many thousands of mappings, and parsing
  4683. // them is expensive, so we only want to do it if we must.
  4684. //
  4685. // Each object in the arrays is of the form:
  4686. //
  4687. // {
  4688. // generatedLine: The line number in the generated code,
  4689. // generatedColumn: The column number in the generated code,
  4690. // source: The path to the original source file that generated this
  4691. // chunk of code,
  4692. // originalLine: The line number in the original source that
  4693. // corresponds to this chunk of generated code,
  4694. // originalColumn: The column number in the original source that
  4695. // corresponds to this chunk of generated code,
  4696. // name: The name of the original symbol which generated this chunk of
  4697. // code.
  4698. // }
  4699. //
  4700. // All properties except for `generatedLine` and `generatedColumn` can be
  4701. // `null`.
  4702. //
  4703. // `_generatedMappings` is ordered by the generated positions.
  4704. //
  4705. // `_originalMappings` is ordered by the original positions.
  4706. SourceMapConsumer.prototype.__generatedMappings = null;
  4707. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  4708. get: function () {
  4709. if (!this.__generatedMappings) {
  4710. this.__generatedMappings = [];
  4711. this.__originalMappings = [];
  4712. this._parseMappings(this._mappings, this.sourceRoot);
  4713. }
  4714. return this.__generatedMappings;
  4715. }
  4716. });
  4717. SourceMapConsumer.prototype.__originalMappings = null;
  4718. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  4719. get: function () {
  4720. if (!this.__originalMappings) {
  4721. this.__generatedMappings = [];
  4722. this.__originalMappings = [];
  4723. this._parseMappings(this._mappings, this.sourceRoot);
  4724. }
  4725. return this.__originalMappings;
  4726. }
  4727. });
  4728. /**
  4729. * Parse the mappings in a string in to a data structure which we can easily
  4730. * query (the ordered arrays in the `this.__generatedMappings` and
  4731. * `this.__originalMappings` properties).
  4732. */
  4733. SourceMapConsumer.prototype._parseMappings =
  4734. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  4735. var generatedLine = 1;
  4736. var previousGeneratedColumn = 0;
  4737. var previousOriginalLine = 0;
  4738. var previousOriginalColumn = 0;
  4739. var previousSource = 0;
  4740. var previousName = 0;
  4741. var mappingSeparator = /^[,;]/;
  4742. var str = aStr;
  4743. var mapping;
  4744. var temp;
  4745. while (str.length > 0) {
  4746. if (str.charAt(0) === ';') {
  4747. generatedLine++;
  4748. str = str.slice(1);
  4749. previousGeneratedColumn = 0;
  4750. }
  4751. else if (str.charAt(0) === ',') {
  4752. str = str.slice(1);
  4753. }
  4754. else {
  4755. mapping = {};
  4756. mapping.generatedLine = generatedLine;
  4757. // Generated column.
  4758. temp = base64VLQ.decode(str);
  4759. mapping.generatedColumn = previousGeneratedColumn + temp.value;
  4760. previousGeneratedColumn = mapping.generatedColumn;
  4761. str = temp.rest;
  4762. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  4763. // Original source.
  4764. temp = base64VLQ.decode(str);
  4765. mapping.source = this._sources.at(previousSource + temp.value);
  4766. previousSource += temp.value;
  4767. str = temp.rest;
  4768. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  4769. throw new Error('Found a source, but no line and column');
  4770. }
  4771. // Original line.
  4772. temp = base64VLQ.decode(str);
  4773. mapping.originalLine = previousOriginalLine + temp.value;
  4774. previousOriginalLine = mapping.originalLine;
  4775. // Lines are stored 0-based
  4776. mapping.originalLine += 1;
  4777. str = temp.rest;
  4778. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  4779. throw new Error('Found a source and line, but no column');
  4780. }
  4781. // Original column.
  4782. temp = base64VLQ.decode(str);
  4783. mapping.originalColumn = previousOriginalColumn + temp.value;
  4784. previousOriginalColumn = mapping.originalColumn;
  4785. str = temp.rest;
  4786. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  4787. // Original name.
  4788. temp = base64VLQ.decode(str);
  4789. mapping.name = this._names.at(previousName + temp.value);
  4790. previousName += temp.value;
  4791. str = temp.rest;
  4792. }
  4793. }
  4794. this.__generatedMappings.push(mapping);
  4795. if (typeof mapping.originalLine === 'number') {
  4796. this.__originalMappings.push(mapping);
  4797. }
  4798. }
  4799. }
  4800. this.__generatedMappings.sort(util.compareByGeneratedPositions);
  4801. this.__originalMappings.sort(util.compareByOriginalPositions);
  4802. };
  4803. /**
  4804. * Find the mapping that best matches the hypothetical "needle" mapping that
  4805. * we are searching for in the given "haystack" of mappings.
  4806. */
  4807. SourceMapConsumer.prototype._findMapping =
  4808. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  4809. aColumnName, aComparator) {
  4810. // To return the position we are searching for, we must first find the
  4811. // mapping for the given position and then return the opposite position it
  4812. // points to. Because the mappings are sorted, we can use binary search to
  4813. // find the best mapping.
  4814. if (aNeedle[aLineName] <= 0) {
  4815. throw new TypeError('Line must be greater than or equal to 1, got '
  4816. + aNeedle[aLineName]);
  4817. }
  4818. if (aNeedle[aColumnName] < 0) {
  4819. throw new TypeError('Column must be greater than or equal to 0, got '
  4820. + aNeedle[aColumnName]);
  4821. }
  4822. return binarySearch.search(aNeedle, aMappings, aComparator);
  4823. };
  4824. /**
  4825. * Returns the original source, line, and column information for the generated
  4826. * source's line and column positions provided. The only argument is an object
  4827. * with the following properties:
  4828. *
  4829. * - line: The line number in the generated source.
  4830. * - column: The column number in the generated source.
  4831. *
  4832. * and an object is returned with the following properties:
  4833. *
  4834. * - source: The original source file, or null.
  4835. * - line: The line number in the original source, or null.
  4836. * - column: The column number in the original source, or null.
  4837. * - name: The original identifier, or null.
  4838. */
  4839. SourceMapConsumer.prototype.originalPositionFor =
  4840. function SourceMapConsumer_originalPositionFor(aArgs) {
  4841. var needle = {
  4842. generatedLine: util.getArg(aArgs, 'line'),
  4843. generatedColumn: util.getArg(aArgs, 'column')
  4844. };
  4845. var mapping = this._findMapping(needle,
  4846. this._generatedMappings,
  4847. "generatedLine",
  4848. "generatedColumn",
  4849. util.compareByGeneratedPositions);
  4850. if (mapping && mapping.generatedLine === needle.generatedLine) {
  4851. var source = util.getArg(mapping, 'source', null);
  4852. if (source && this.sourceRoot) {
  4853. source = util.join(this.sourceRoot, source);
  4854. }
  4855. return {
  4856. source: source,
  4857. line: util.getArg(mapping, 'originalLine', null),
  4858. column: util.getArg(mapping, 'originalColumn', null),
  4859. name: util.getArg(mapping, 'name', null)
  4860. };
  4861. }
  4862. return {
  4863. source: null,
  4864. line: null,
  4865. column: null,
  4866. name: null
  4867. };
  4868. };
  4869. /**
  4870. * Returns the original source content. The only argument is the url of the
  4871. * original source file. Returns null if no original source content is
  4872. * availible.
  4873. */
  4874. SourceMapConsumer.prototype.sourceContentFor =
  4875. function SourceMapConsumer_sourceContentFor(aSource) {
  4876. if (!this.sourcesContent) {
  4877. return null;
  4878. }
  4879. if (this.sourceRoot) {
  4880. aSource = util.relative(this.sourceRoot, aSource);
  4881. }
  4882. if (this._sources.has(aSource)) {
  4883. return this.sourcesContent[this._sources.indexOf(aSource)];
  4884. }
  4885. var url;
  4886. if (this.sourceRoot
  4887. && (url = util.urlParse(this.sourceRoot))) {
  4888. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  4889. // many users. We can help them out when they expect file:// URIs to
  4890. // behave like it would if they were running a local HTTP server. See
  4891. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  4892. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  4893. if (url.scheme == "file"
  4894. && this._sources.has(fileUriAbsPath)) {
  4895. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  4896. }
  4897. if ((!url.path || url.path == "/")
  4898. && this._sources.has("/" + aSource)) {
  4899. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  4900. }
  4901. }
  4902. throw new Error('"' + aSource + '" is not in the SourceMap.');
  4903. };
  4904. /**
  4905. * Returns the generated line and column information for the original source,
  4906. * line, and column positions provided. The only argument is an object with
  4907. * the following properties:
  4908. *
  4909. * - source: The filename of the original source.
  4910. * - line: The line number in the original source.
  4911. * - column: The column number in the original source.
  4912. *
  4913. * and an object is returned with the following properties:
  4914. *
  4915. * - line: The line number in the generated source, or null.
  4916. * - column: The column number in the generated source, or null.
  4917. */
  4918. SourceMapConsumer.prototype.generatedPositionFor =
  4919. function SourceMapConsumer_generatedPositionFor(aArgs) {
  4920. var needle = {
  4921. source: util.getArg(aArgs, 'source'),
  4922. originalLine: util.getArg(aArgs, 'line'),
  4923. originalColumn: util.getArg(aArgs, 'column')
  4924. };
  4925. if (this.sourceRoot) {
  4926. needle.source = util.relative(this.sourceRoot, needle.source);
  4927. }
  4928. var mapping = this._findMapping(needle,
  4929. this._originalMappings,
  4930. "originalLine",
  4931. "originalColumn",
  4932. util.compareByOriginalPositions);
  4933. if (mapping) {
  4934. return {
  4935. line: util.getArg(mapping, 'generatedLine', null),
  4936. column: util.getArg(mapping, 'generatedColumn', null)
  4937. };
  4938. }
  4939. return {
  4940. line: null,
  4941. column: null
  4942. };
  4943. };
  4944. SourceMapConsumer.GENERATED_ORDER = 1;
  4945. SourceMapConsumer.ORIGINAL_ORDER = 2;
  4946. /**
  4947. * Iterate over each mapping between an original source/line/column and a
  4948. * generated line/column in this source map.
  4949. *
  4950. * @param Function aCallback
  4951. * The function that is called with each mapping.
  4952. * @param Object aContext
  4953. * Optional. If specified, this object will be the value of `this` every
  4954. * time that `aCallback` is called.
  4955. * @param aOrder
  4956. * Either `SourceMapConsumer.GENERATED_ORDER` or
  4957. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  4958. * iterate over the mappings sorted by the generated file's line/column
  4959. * order or the original's source/line/column order, respectively. Defaults to
  4960. * `SourceMapConsumer.GENERATED_ORDER`.
  4961. */
  4962. SourceMapConsumer.prototype.eachMapping =
  4963. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  4964. var context = aContext || null;
  4965. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  4966. var mappings;
  4967. switch (order) {
  4968. case SourceMapConsumer.GENERATED_ORDER:
  4969. mappings = this._generatedMappings;
  4970. break;
  4971. case SourceMapConsumer.ORIGINAL_ORDER:
  4972. mappings = this._originalMappings;
  4973. break;
  4974. default:
  4975. throw new Error("Unknown order of iteration.");
  4976. }
  4977. var sourceRoot = this.sourceRoot;
  4978. mappings.map(function (mapping) {
  4979. var source = mapping.source;
  4980. if (source && sourceRoot) {
  4981. source = util.join(sourceRoot, source);
  4982. }
  4983. return {
  4984. source: source,
  4985. generatedLine: mapping.generatedLine,
  4986. generatedColumn: mapping.generatedColumn,
  4987. originalLine: mapping.originalLine,
  4988. originalColumn: mapping.originalColumn,
  4989. name: mapping.name
  4990. };
  4991. }).forEach(aCallback, context);
  4992. };
  4993. exports.SourceMapConsumer = SourceMapConsumer;
  4994. });
  4995. },{"./array-set":35,"./base64-vlq":36,"./binary-search":38,"./util":42,"amdefine":43}],40:[function(require,module,exports){
  4996. /* -*- Mode: js; js-indent-level: 2; -*- */
  4997. /*
  4998. * Copyright 2011 Mozilla Foundation and contributors
  4999. * Licensed under the New BSD license. See LICENSE or:
  5000. * http://opensource.org/licenses/BSD-3-Clause
  5001. */
  5002. if (typeof define !== 'function') {
  5003. var define = require('amdefine')(module, require);
  5004. }
  5005. define(function (require, exports, module) {
  5006. var base64VLQ = require('./base64-vlq');
  5007. var util = require('./util');
  5008. var ArraySet = require('./array-set').ArraySet;
  5009. /**
  5010. * An instance of the SourceMapGenerator represents a source map which is
  5011. * being built incrementally. You may pass an object with the following
  5012. * properties:
  5013. *
  5014. * - file: The filename of the generated source.
  5015. * - sourceRoot: A root for all relative URLs in this source map.
  5016. */
  5017. function SourceMapGenerator(aArgs) {
  5018. if (!aArgs) {
  5019. aArgs = {};
  5020. }
  5021. this._file = util.getArg(aArgs, 'file', null);
  5022. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  5023. this._sources = new ArraySet();
  5024. this._names = new ArraySet();
  5025. this._mappings = [];
  5026. this._sourcesContents = null;
  5027. }
  5028. SourceMapGenerator.prototype._version = 3;
  5029. /**
  5030. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  5031. *
  5032. * @param aSourceMapConsumer The SourceMap.
  5033. */
  5034. SourceMapGenerator.fromSourceMap =
  5035. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  5036. var sourceRoot = aSourceMapConsumer.sourceRoot;
  5037. var generator = new SourceMapGenerator({
  5038. file: aSourceMapConsumer.file,
  5039. sourceRoot: sourceRoot
  5040. });
  5041. aSourceMapConsumer.eachMapping(function (mapping) {
  5042. var newMapping = {
  5043. generated: {
  5044. line: mapping.generatedLine,
  5045. column: mapping.generatedColumn
  5046. }
  5047. };
  5048. if (mapping.source) {
  5049. newMapping.source = mapping.source;
  5050. if (sourceRoot) {
  5051. newMapping.source = util.relative(sourceRoot, newMapping.source);
  5052. }
  5053. newMapping.original = {
  5054. line: mapping.originalLine,
  5055. column: mapping.originalColumn
  5056. };
  5057. if (mapping.name) {
  5058. newMapping.name = mapping.name;
  5059. }
  5060. }
  5061. generator.addMapping(newMapping);
  5062. });
  5063. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  5064. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  5065. if (content) {
  5066. generator.setSourceContent(sourceFile, content);
  5067. }
  5068. });
  5069. return generator;
  5070. };
  5071. /**
  5072. * Add a single mapping from original source line and column to the generated
  5073. * source's line and column for this source map being created. The mapping
  5074. * object should have the following properties:
  5075. *
  5076. * - generated: An object with the generated line and column positions.
  5077. * - original: An object with the original line and column positions.
  5078. * - source: The original source file (relative to the sourceRoot).
  5079. * - name: An optional original token name for this mapping.
  5080. */
  5081. SourceMapGenerator.prototype.addMapping =
  5082. function SourceMapGenerator_addMapping(aArgs) {
  5083. var generated = util.getArg(aArgs, 'generated');
  5084. var original = util.getArg(aArgs, 'original', null);
  5085. var source = util.getArg(aArgs, 'source', null);
  5086. var name = util.getArg(aArgs, 'name', null);
  5087. this._validateMapping(generated, original, source, name);
  5088. if (source && !this._sources.has(source)) {
  5089. this._sources.add(source);
  5090. }
  5091. if (name && !this._names.has(name)) {
  5092. this._names.add(name);
  5093. }
  5094. this._mappings.push({
  5095. generatedLine: generated.line,
  5096. generatedColumn: generated.column,
  5097. originalLine: original != null && original.line,
  5098. originalColumn: original != null && original.column,
  5099. source: source,
  5100. name: name
  5101. });
  5102. };
  5103. /**
  5104. * Set the source content for a source file.
  5105. */
  5106. SourceMapGenerator.prototype.setSourceContent =
  5107. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  5108. var source = aSourceFile;
  5109. if (this._sourceRoot) {
  5110. source = util.relative(this._sourceRoot, source);
  5111. }
  5112. if (aSourceContent !== null) {
  5113. // Add the source content to the _sourcesContents map.
  5114. // Create a new _sourcesContents map if the property is null.
  5115. if (!this._sourcesContents) {
  5116. this._sourcesContents = {};
  5117. }
  5118. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  5119. } else {
  5120. // Remove the source file from the _sourcesContents map.
  5121. // If the _sourcesContents map is empty, set the property to null.
  5122. delete this._sourcesContents[util.toSetString(source)];
  5123. if (Object.keys(this._sourcesContents).length === 0) {
  5124. this._sourcesContents = null;
  5125. }
  5126. }
  5127. };
  5128. /**
  5129. * Applies the mappings of a sub-source-map for a specific source file to the
  5130. * source map being generated. Each mapping to the supplied source file is
  5131. * rewritten using the supplied source map. Note: The resolution for the
  5132. * resulting mappings is the minimium of this map and the supplied map.
  5133. *
  5134. * @param aSourceMapConsumer The source map to be applied.
  5135. * @param aSourceFile Optional. The filename of the source file.
  5136. * If omitted, SourceMapConsumer's file property will be used.
  5137. * @param aSourceMapPath Optional. The dirname of the path to the source map
  5138. * to be applied. If relative, it is relative to the SourceMapConsumer.
  5139. * This parameter is needed when the two source maps aren't in the same
  5140. * directory, and the source map to be applied contains relative source
  5141. * paths. If so, those relative source paths need to be rewritten
  5142. * relative to the SourceMapGenerator.
  5143. */
  5144. SourceMapGenerator.prototype.applySourceMap =
  5145. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  5146. // If aSourceFile is omitted, we will use the file property of the SourceMap
  5147. if (!aSourceFile) {
  5148. if (!aSourceMapConsumer.file) {
  5149. throw new Error(
  5150. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  5151. 'or the source map\'s "file" property. Both were omitted.'
  5152. );
  5153. }
  5154. aSourceFile = aSourceMapConsumer.file;
  5155. }
  5156. var sourceRoot = this._sourceRoot;
  5157. // Make "aSourceFile" relative if an absolute Url is passed.
  5158. if (sourceRoot) {
  5159. aSourceFile = util.relative(sourceRoot, aSourceFile);
  5160. }
  5161. // Applying the SourceMap can add and remove items from the sources and
  5162. // the names array.
  5163. var newSources = new ArraySet();
  5164. var newNames = new ArraySet();
  5165. // Find mappings for the "aSourceFile"
  5166. this._mappings.forEach(function (mapping) {
  5167. if (mapping.source === aSourceFile && mapping.originalLine) {
  5168. // Check if it can be mapped by the source map, then update the mapping.
  5169. var original = aSourceMapConsumer.originalPositionFor({
  5170. line: mapping.originalLine,
  5171. column: mapping.originalColumn
  5172. });
  5173. if (original.source !== null) {
  5174. // Copy mapping
  5175. mapping.source = original.source;
  5176. if (aSourceMapPath) {
  5177. mapping.source = util.join(aSourceMapPath, mapping.source)
  5178. }
  5179. if (sourceRoot) {
  5180. mapping.source = util.relative(sourceRoot, mapping.source);
  5181. }
  5182. mapping.originalLine = original.line;
  5183. mapping.originalColumn = original.column;
  5184. if (original.name !== null && mapping.name !== null) {
  5185. // Only use the identifier name if it's an identifier
  5186. // in both SourceMaps
  5187. mapping.name = original.name;
  5188. }
  5189. }
  5190. }
  5191. var source = mapping.source;
  5192. if (source && !newSources.has(source)) {
  5193. newSources.add(source);
  5194. }
  5195. var name = mapping.name;
  5196. if (name && !newNames.has(name)) {
  5197. newNames.add(name);
  5198. }
  5199. }, this);
  5200. this._sources = newSources;
  5201. this._names = newNames;
  5202. // Copy sourcesContents of applied map.
  5203. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  5204. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  5205. if (content) {
  5206. if (aSourceMapPath) {
  5207. sourceFile = util.join(aSourceMapPath, sourceFile);
  5208. }
  5209. if (sourceRoot) {
  5210. sourceFile = util.relative(sourceRoot, sourceFile);
  5211. }
  5212. this.setSourceContent(sourceFile, content);
  5213. }
  5214. }, this);
  5215. };
  5216. /**
  5217. * A mapping can have one of the three levels of data:
  5218. *
  5219. * 1. Just the generated position.
  5220. * 2. The Generated position, original position, and original source.
  5221. * 3. Generated and original position, original source, as well as a name
  5222. * token.
  5223. *
  5224. * To maintain consistency, we validate that any new mapping being added falls
  5225. * in to one of these categories.
  5226. */
  5227. SourceMapGenerator.prototype._validateMapping =
  5228. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  5229. aName) {
  5230. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  5231. && aGenerated.line > 0 && aGenerated.column >= 0
  5232. && !aOriginal && !aSource && !aName) {
  5233. // Case 1.
  5234. return;
  5235. }
  5236. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  5237. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  5238. && aGenerated.line > 0 && aGenerated.column >= 0
  5239. && aOriginal.line > 0 && aOriginal.column >= 0
  5240. && aSource) {
  5241. // Cases 2 and 3.
  5242. return;
  5243. }
  5244. else {
  5245. throw new Error('Invalid mapping: ' + JSON.stringify({
  5246. generated: aGenerated,
  5247. source: aSource,
  5248. original: aOriginal,
  5249. name: aName
  5250. }));
  5251. }
  5252. };
  5253. /**
  5254. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  5255. * specified by the source map format.
  5256. */
  5257. SourceMapGenerator.prototype._serializeMappings =
  5258. function SourceMapGenerator_serializeMappings() {
  5259. var previousGeneratedColumn = 0;
  5260. var previousGeneratedLine = 1;
  5261. var previousOriginalColumn = 0;
  5262. var previousOriginalLine = 0;
  5263. var previousName = 0;
  5264. var previousSource = 0;
  5265. var result = '';
  5266. var mapping;
  5267. // The mappings must be guaranteed to be in sorted order before we start
  5268. // serializing them or else the generated line numbers (which are defined
  5269. // via the ';' separators) will be all messed up. Note: it might be more
  5270. // performant to maintain the sorting as we insert them, rather than as we
  5271. // serialize them, but the big O is the same either way.
  5272. this._mappings.sort(util.compareByGeneratedPositions);
  5273. for (var i = 0, len = this._mappings.length; i < len; i++) {
  5274. mapping = this._mappings[i];
  5275. if (mapping.generatedLine !== previousGeneratedLine) {
  5276. previousGeneratedColumn = 0;
  5277. while (mapping.generatedLine !== previousGeneratedLine) {
  5278. result += ';';
  5279. previousGeneratedLine++;
  5280. }
  5281. }
  5282. else {
  5283. if (i > 0) {
  5284. if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
  5285. continue;
  5286. }
  5287. result += ',';
  5288. }
  5289. }
  5290. result += base64VLQ.encode(mapping.generatedColumn
  5291. - previousGeneratedColumn);
  5292. previousGeneratedColumn = mapping.generatedColumn;
  5293. if (mapping.source) {
  5294. result += base64VLQ.encode(this._sources.indexOf(mapping.source)
  5295. - previousSource);
  5296. previousSource = this._sources.indexOf(mapping.source);
  5297. // lines are stored 0-based in SourceMap spec version 3
  5298. result += base64VLQ.encode(mapping.originalLine - 1
  5299. - previousOriginalLine);
  5300. previousOriginalLine = mapping.originalLine - 1;
  5301. result += base64VLQ.encode(mapping.originalColumn
  5302. - previousOriginalColumn);
  5303. previousOriginalColumn = mapping.originalColumn;
  5304. if (mapping.name) {
  5305. result += base64VLQ.encode(this._names.indexOf(mapping.name)
  5306. - previousName);
  5307. previousName = this._names.indexOf(mapping.name);
  5308. }
  5309. }
  5310. }
  5311. return result;
  5312. };
  5313. SourceMapGenerator.prototype._generateSourcesContent =
  5314. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  5315. return aSources.map(function (source) {
  5316. if (!this._sourcesContents) {
  5317. return null;
  5318. }
  5319. if (aSourceRoot) {
  5320. source = util.relative(aSourceRoot, source);
  5321. }
  5322. var key = util.toSetString(source);
  5323. return Object.prototype.hasOwnProperty.call(this._sourcesContents,
  5324. key)
  5325. ? this._sourcesContents[key]
  5326. : null;
  5327. }, this);
  5328. };
  5329. /**
  5330. * Externalize the source map.
  5331. */
  5332. SourceMapGenerator.prototype.toJSON =
  5333. function SourceMapGenerator_toJSON() {
  5334. var map = {
  5335. version: this._version,
  5336. file: this._file,
  5337. sources: this._sources.toArray(),
  5338. names: this._names.toArray(),
  5339. mappings: this._serializeMappings()
  5340. };
  5341. if (this._sourceRoot) {
  5342. map.sourceRoot = this._sourceRoot;
  5343. }
  5344. if (this._sourcesContents) {
  5345. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  5346. }
  5347. return map;
  5348. };
  5349. /**
  5350. * Render the source map being generated to a string.
  5351. */
  5352. SourceMapGenerator.prototype.toString =
  5353. function SourceMapGenerator_toString() {
  5354. return JSON.stringify(this);
  5355. };
  5356. exports.SourceMapGenerator = SourceMapGenerator;
  5357. });
  5358. },{"./array-set":35,"./base64-vlq":36,"./util":42,"amdefine":43}],41:[function(require,module,exports){
  5359. /* -*- Mode: js; js-indent-level: 2; -*- */
  5360. /*
  5361. * Copyright 2011 Mozilla Foundation and contributors
  5362. * Licensed under the New BSD license. See LICENSE or:
  5363. * http://opensource.org/licenses/BSD-3-Clause
  5364. */
  5365. if (typeof define !== 'function') {
  5366. var define = require('amdefine')(module, require);
  5367. }
  5368. define(function (require, exports, module) {
  5369. var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
  5370. var util = require('./util');
  5371. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  5372. // operating systems these days (capturing the result).
  5373. var REGEX_NEWLINE = /(\r?\n)/g;
  5374. // Matches a Windows-style newline, or any character.
  5375. var REGEX_CHARACTER = /\r\n|[\s\S]/g;
  5376. /**
  5377. * SourceNodes provide a way to abstract over interpolating/concatenating
  5378. * snippets of generated JavaScript source code while maintaining the line and
  5379. * column information associated with the original source code.
  5380. *
  5381. * @param aLine The original line number.
  5382. * @param aColumn The original column number.
  5383. * @param aSource The original source's filename.
  5384. * @param aChunks Optional. An array of strings which are snippets of
  5385. * generated JS, or other SourceNodes.
  5386. * @param aName The original identifier.
  5387. */
  5388. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  5389. this.children = [];
  5390. this.sourceContents = {};
  5391. this.line = aLine === undefined ? null : aLine;
  5392. this.column = aColumn === undefined ? null : aColumn;
  5393. this.source = aSource === undefined ? null : aSource;
  5394. this.name = aName === undefined ? null : aName;
  5395. if (aChunks != null) this.add(aChunks);
  5396. }
  5397. /**
  5398. * Creates a SourceNode from generated code and a SourceMapConsumer.
  5399. *
  5400. * @param aGeneratedCode The generated code
  5401. * @param aSourceMapConsumer The SourceMap for the generated code
  5402. */
  5403. SourceNode.fromStringWithSourceMap =
  5404. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
  5405. // The SourceNode we want to fill with the generated code
  5406. // and the SourceMap
  5407. var node = new SourceNode();
  5408. // All even indices of this array are one line of the generated code,
  5409. // while all odd indices are the newlines between two adjacent lines
  5410. // (since `REGEX_NEWLINE` captures its match).
  5411. // Processed fragments are removed from this array, by calling `shiftNextLine`.
  5412. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  5413. var shiftNextLine = function() {
  5414. var lineContents = remainingLines.shift();
  5415. // The last line of a file might not have a newline.
  5416. var newLine = remainingLines.shift() || "";
  5417. return lineContents + newLine;
  5418. };
  5419. // We need to remember the position of "remainingLines"
  5420. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  5421. // The generate SourceNodes we need a code range.
  5422. // To extract it current and last mapping is used.
  5423. // Here we store the last mapping.
  5424. var lastMapping = null;
  5425. aSourceMapConsumer.eachMapping(function (mapping) {
  5426. if (lastMapping !== null) {
  5427. // We add the code from "lastMapping" to "mapping":
  5428. // First check if there is a new line in between.
  5429. if (lastGeneratedLine < mapping.generatedLine) {
  5430. var code = "";
  5431. // Associate first line with "lastMapping"
  5432. addMappingWithCode(lastMapping, shiftNextLine());
  5433. lastGeneratedLine++;
  5434. lastGeneratedColumn = 0;
  5435. // The remaining code is added without mapping
  5436. } else {
  5437. // There is no new line in between.
  5438. // Associate the code between "lastGeneratedColumn" and
  5439. // "mapping.generatedColumn" with "lastMapping"
  5440. var nextLine = remainingLines[0];
  5441. var code = nextLine.substr(0, mapping.generatedColumn -
  5442. lastGeneratedColumn);
  5443. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  5444. lastGeneratedColumn);
  5445. lastGeneratedColumn = mapping.generatedColumn;
  5446. addMappingWithCode(lastMapping, code);
  5447. // No more remaining code, continue
  5448. lastMapping = mapping;
  5449. return;
  5450. }
  5451. }
  5452. // We add the generated code until the first mapping
  5453. // to the SourceNode without any mapping.
  5454. // Each line is added as separate string.
  5455. while (lastGeneratedLine < mapping.generatedLine) {
  5456. node.add(shiftNextLine());
  5457. lastGeneratedLine++;
  5458. }
  5459. if (lastGeneratedColumn < mapping.generatedColumn) {
  5460. var nextLine = remainingLines[0];
  5461. node.add(nextLine.substr(0, mapping.generatedColumn));
  5462. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  5463. lastGeneratedColumn = mapping.generatedColumn;
  5464. }
  5465. lastMapping = mapping;
  5466. }, this);
  5467. // We have processed all mappings.
  5468. if (remainingLines.length > 0) {
  5469. if (lastMapping) {
  5470. // Associate the remaining code in the current line with "lastMapping"
  5471. addMappingWithCode(lastMapping, shiftNextLine());
  5472. }
  5473. // and add the remaining lines without any mapping
  5474. node.add(remainingLines.join(""));
  5475. }
  5476. // Copy sourcesContent into SourceNode
  5477. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  5478. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  5479. if (content) {
  5480. node.setSourceContent(sourceFile, content);
  5481. }
  5482. });
  5483. return node;
  5484. function addMappingWithCode(mapping, code) {
  5485. if (mapping === null || mapping.source === undefined) {
  5486. node.add(code);
  5487. } else {
  5488. node.add(new SourceNode(mapping.originalLine,
  5489. mapping.originalColumn,
  5490. mapping.source,
  5491. code,
  5492. mapping.name));
  5493. }
  5494. }
  5495. };
  5496. /**
  5497. * Add a chunk of generated JS to this source node.
  5498. *
  5499. * @param aChunk A string snippet of generated JS code, another instance of
  5500. * SourceNode, or an array where each member is one of those things.
  5501. */
  5502. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  5503. if (Array.isArray(aChunk)) {
  5504. aChunk.forEach(function (chunk) {
  5505. this.add(chunk);
  5506. }, this);
  5507. }
  5508. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  5509. if (aChunk) {
  5510. this.children.push(aChunk);
  5511. }
  5512. }
  5513. else {
  5514. throw new TypeError(
  5515. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  5516. );
  5517. }
  5518. return this;
  5519. };
  5520. /**
  5521. * Add a chunk of generated JS to the beginning of this source node.
  5522. *
  5523. * @param aChunk A string snippet of generated JS code, another instance of
  5524. * SourceNode, or an array where each member is one of those things.
  5525. */
  5526. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  5527. if (Array.isArray(aChunk)) {
  5528. for (var i = aChunk.length-1; i >= 0; i--) {
  5529. this.prepend(aChunk[i]);
  5530. }
  5531. }
  5532. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  5533. this.children.unshift(aChunk);
  5534. }
  5535. else {
  5536. throw new TypeError(
  5537. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  5538. );
  5539. }
  5540. return this;
  5541. };
  5542. /**
  5543. * Walk over the tree of JS snippets in this node and its children. The
  5544. * walking function is called once for each snippet of JS and is passed that
  5545. * snippet and the its original associated source's line/column location.
  5546. *
  5547. * @param aFn The traversal function.
  5548. */
  5549. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  5550. var chunk;
  5551. for (var i = 0, len = this.children.length; i < len; i++) {
  5552. chunk = this.children[i];
  5553. if (chunk instanceof SourceNode) {
  5554. chunk.walk(aFn);
  5555. }
  5556. else {
  5557. if (chunk !== '') {
  5558. aFn(chunk, { source: this.source,
  5559. line: this.line,
  5560. column: this.column,
  5561. name: this.name });
  5562. }
  5563. }
  5564. }
  5565. };
  5566. /**
  5567. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  5568. * each of `this.children`.
  5569. *
  5570. * @param aSep The separator.
  5571. */
  5572. SourceNode.prototype.join = function SourceNode_join(aSep) {
  5573. var newChildren;
  5574. var i;
  5575. var len = this.children.length;
  5576. if (len > 0) {
  5577. newChildren = [];
  5578. for (i = 0; i < len-1; i++) {
  5579. newChildren.push(this.children[i]);
  5580. newChildren.push(aSep);
  5581. }
  5582. newChildren.push(this.children[i]);
  5583. this.children = newChildren;
  5584. }
  5585. return this;
  5586. };
  5587. /**
  5588. * Call String.prototype.replace on the very right-most source snippet. Useful
  5589. * for trimming whitespace from the end of a source node, etc.
  5590. *
  5591. * @param aPattern The pattern to replace.
  5592. * @param aReplacement The thing to replace the pattern with.
  5593. */
  5594. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  5595. var lastChild = this.children[this.children.length - 1];
  5596. if (lastChild instanceof SourceNode) {
  5597. lastChild.replaceRight(aPattern, aReplacement);
  5598. }
  5599. else if (typeof lastChild === 'string') {
  5600. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  5601. }
  5602. else {
  5603. this.children.push(''.replace(aPattern, aReplacement));
  5604. }
  5605. return this;
  5606. };
  5607. /**
  5608. * Set the source content for a source file. This will be added to the SourceMapGenerator
  5609. * in the sourcesContent field.
  5610. *
  5611. * @param aSourceFile The filename of the source file
  5612. * @param aSourceContent The content of the source file
  5613. */
  5614. SourceNode.prototype.setSourceContent =
  5615. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  5616. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  5617. };
  5618. /**
  5619. * Walk over the tree of SourceNodes. The walking function is called for each
  5620. * source file content and is passed the filename and source content.
  5621. *
  5622. * @param aFn The traversal function.
  5623. */
  5624. SourceNode.prototype.walkSourceContents =
  5625. function SourceNode_walkSourceContents(aFn) {
  5626. for (var i = 0, len = this.children.length; i < len; i++) {
  5627. if (this.children[i] instanceof SourceNode) {
  5628. this.children[i].walkSourceContents(aFn);
  5629. }
  5630. }
  5631. var sources = Object.keys(this.sourceContents);
  5632. for (var i = 0, len = sources.length; i < len; i++) {
  5633. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  5634. }
  5635. };
  5636. /**
  5637. * Return the string representation of this source node. Walks over the tree
  5638. * and concatenates all the various snippets together to one string.
  5639. */
  5640. SourceNode.prototype.toString = function SourceNode_toString() {
  5641. var str = "";
  5642. this.walk(function (chunk) {
  5643. str += chunk;
  5644. });
  5645. return str;
  5646. };
  5647. /**
  5648. * Returns the string representation of this source node along with a source
  5649. * map.
  5650. */
  5651. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  5652. var generated = {
  5653. code: "",
  5654. line: 1,
  5655. column: 0
  5656. };
  5657. var map = new SourceMapGenerator(aArgs);
  5658. var sourceMappingActive = false;
  5659. var lastOriginalSource = null;
  5660. var lastOriginalLine = null;
  5661. var lastOriginalColumn = null;
  5662. var lastOriginalName = null;
  5663. this.walk(function (chunk, original) {
  5664. generated.code += chunk;
  5665. if (original.source !== null
  5666. && original.line !== null
  5667. && original.column !== null) {
  5668. if(lastOriginalSource !== original.source
  5669. || lastOriginalLine !== original.line
  5670. || lastOriginalColumn !== original.column
  5671. || lastOriginalName !== original.name) {
  5672. map.addMapping({
  5673. source: original.source,
  5674. original: {
  5675. line: original.line,
  5676. column: original.column
  5677. },
  5678. generated: {
  5679. line: generated.line,
  5680. column: generated.column
  5681. },
  5682. name: original.name
  5683. });
  5684. }
  5685. lastOriginalSource = original.source;
  5686. lastOriginalLine = original.line;
  5687. lastOriginalColumn = original.column;
  5688. lastOriginalName = original.name;
  5689. sourceMappingActive = true;
  5690. } else if (sourceMappingActive) {
  5691. map.addMapping({
  5692. generated: {
  5693. line: generated.line,
  5694. column: generated.column
  5695. }
  5696. });
  5697. lastOriginalSource = null;
  5698. sourceMappingActive = false;
  5699. }
  5700. chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) {
  5701. if (REGEX_NEWLINE.test(ch)) {
  5702. generated.line++;
  5703. generated.column = 0;
  5704. // Mappings end at eol
  5705. if (idx + 1 === array.length) {
  5706. lastOriginalSource = null;
  5707. sourceMappingActive = false;
  5708. } else if (sourceMappingActive) {
  5709. map.addMapping({
  5710. source: original.source,
  5711. original: {
  5712. line: original.line,
  5713. column: original.column
  5714. },
  5715. generated: {
  5716. line: generated.line,
  5717. column: generated.column
  5718. },
  5719. name: original.name
  5720. });
  5721. }
  5722. } else {
  5723. generated.column += ch.length;
  5724. }
  5725. });
  5726. });
  5727. this.walkSourceContents(function (sourceFile, sourceContent) {
  5728. map.setSourceContent(sourceFile, sourceContent);
  5729. });
  5730. return { code: generated.code, map: map };
  5731. };
  5732. exports.SourceNode = SourceNode;
  5733. });
  5734. },{"./source-map-generator":40,"./util":42,"amdefine":43}],42:[function(require,module,exports){
  5735. /* -*- Mode: js; js-indent-level: 2; -*- */
  5736. /*
  5737. * Copyright 2011 Mozilla Foundation and contributors
  5738. * Licensed under the New BSD license. See LICENSE or:
  5739. * http://opensource.org/licenses/BSD-3-Clause
  5740. */
  5741. if (typeof define !== 'function') {
  5742. var define = require('amdefine')(module, require);
  5743. }
  5744. define(function (require, exports, module) {
  5745. /**
  5746. * This is a helper function for getting values from parameter/options
  5747. * objects.
  5748. *
  5749. * @param args The object we are extracting values from
  5750. * @param name The name of the property we are getting.
  5751. * @param defaultValue An optional value to return if the property is missing
  5752. * from the object. If this is not specified and the property is missing, an
  5753. * error will be thrown.
  5754. */
  5755. function getArg(aArgs, aName, aDefaultValue) {
  5756. if (aName in aArgs) {
  5757. return aArgs[aName];
  5758. } else if (arguments.length === 3) {
  5759. return aDefaultValue;
  5760. } else {
  5761. throw new Error('"' + aName + '" is a required argument.');
  5762. }
  5763. }
  5764. exports.getArg = getArg;
  5765. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  5766. var dataUrlRegexp = /^data:.+\,.+$/;
  5767. function urlParse(aUrl) {
  5768. var match = aUrl.match(urlRegexp);
  5769. if (!match) {
  5770. return null;
  5771. }
  5772. return {
  5773. scheme: match[1],
  5774. auth: match[2],
  5775. host: match[3],
  5776. port: match[4],
  5777. path: match[5]
  5778. };
  5779. }
  5780. exports.urlParse = urlParse;
  5781. function urlGenerate(aParsedUrl) {
  5782. var url = '';
  5783. if (aParsedUrl.scheme) {
  5784. url += aParsedUrl.scheme + ':';
  5785. }
  5786. url += '//';
  5787. if (aParsedUrl.auth) {
  5788. url += aParsedUrl.auth + '@';
  5789. }
  5790. if (aParsedUrl.host) {
  5791. url += aParsedUrl.host;
  5792. }
  5793. if (aParsedUrl.port) {
  5794. url += ":" + aParsedUrl.port
  5795. }
  5796. if (aParsedUrl.path) {
  5797. url += aParsedUrl.path;
  5798. }
  5799. return url;
  5800. }
  5801. exports.urlGenerate = urlGenerate;
  5802. /**
  5803. * Normalizes a path, or the path portion of a URL:
  5804. *
  5805. * - Replaces consequtive slashes with one slash.
  5806. * - Removes unnecessary '.' parts.
  5807. * - Removes unnecessary '<dir>/..' parts.
  5808. *
  5809. * Based on code in the Node.js 'path' core module.
  5810. *
  5811. * @param aPath The path or url to normalize.
  5812. */
  5813. function normalize(aPath) {
  5814. var path = aPath;
  5815. var url = urlParse(aPath);
  5816. if (url) {
  5817. if (!url.path) {
  5818. return aPath;
  5819. }
  5820. path = url.path;
  5821. }
  5822. var isAbsolute = (path.charAt(0) === '/');
  5823. var parts = path.split(/\/+/);
  5824. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  5825. part = parts[i];
  5826. if (part === '.') {
  5827. parts.splice(i, 1);
  5828. } else if (part === '..') {
  5829. up++;
  5830. } else if (up > 0) {
  5831. if (part === '') {
  5832. // The first part is blank if the path is absolute. Trying to go
  5833. // above the root is a no-op. Therefore we can remove all '..' parts
  5834. // directly after the root.
  5835. parts.splice(i + 1, up);
  5836. up = 0;
  5837. } else {
  5838. parts.splice(i, 2);
  5839. up--;
  5840. }
  5841. }
  5842. }
  5843. path = parts.join('/');
  5844. if (path === '') {
  5845. path = isAbsolute ? '/' : '.';
  5846. }
  5847. if (url) {
  5848. url.path = path;
  5849. return urlGenerate(url);
  5850. }
  5851. return path;
  5852. }
  5853. exports.normalize = normalize;
  5854. /**
  5855. * Joins two paths/URLs.
  5856. *
  5857. * @param aRoot The root path or URL.
  5858. * @param aPath The path or URL to be joined with the root.
  5859. *
  5860. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  5861. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  5862. * first.
  5863. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  5864. * is updated with the result and aRoot is returned. Otherwise the result
  5865. * is returned.
  5866. * - If aPath is absolute, the result is aPath.
  5867. * - Otherwise the two paths are joined with a slash.
  5868. * - Joining for example 'http://' and 'www.example.com' is also supported.
  5869. */
  5870. function join(aRoot, aPath) {
  5871. var aPathUrl = urlParse(aPath);
  5872. var aRootUrl = urlParse(aRoot);
  5873. if (aRootUrl) {
  5874. aRoot = aRootUrl.path || '/';
  5875. }
  5876. // `join(foo, '//www.example.org')`
  5877. if (aPathUrl && !aPathUrl.scheme) {
  5878. if (aRootUrl) {
  5879. aPathUrl.scheme = aRootUrl.scheme;
  5880. }
  5881. return urlGenerate(aPathUrl);
  5882. }
  5883. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  5884. return aPath;
  5885. }
  5886. // `join('http://', 'www.example.com')`
  5887. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  5888. aRootUrl.host = aPath;
  5889. return urlGenerate(aRootUrl);
  5890. }
  5891. var joined = aPath.charAt(0) === '/'
  5892. ? aPath
  5893. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  5894. if (aRootUrl) {
  5895. aRootUrl.path = joined;
  5896. return urlGenerate(aRootUrl);
  5897. }
  5898. return joined;
  5899. }
  5900. exports.join = join;
  5901. /**
  5902. * Because behavior goes wacky when you set `__proto__` on objects, we
  5903. * have to prefix all the strings in our set with an arbitrary character.
  5904. *
  5905. * See https://github.com/mozilla/source-map/pull/31 and
  5906. * https://github.com/mozilla/source-map/issues/30
  5907. *
  5908. * @param String aStr
  5909. */
  5910. function toSetString(aStr) {
  5911. return '$' + aStr;
  5912. }
  5913. exports.toSetString = toSetString;
  5914. function fromSetString(aStr) {
  5915. return aStr.substr(1);
  5916. }
  5917. exports.fromSetString = fromSetString;
  5918. function relative(aRoot, aPath) {
  5919. aRoot = aRoot.replace(/\/$/, '');
  5920. var url = urlParse(aRoot);
  5921. if (aPath.charAt(0) == "/" && url && url.path == "/") {
  5922. return aPath.slice(1);
  5923. }
  5924. return aPath.indexOf(aRoot + '/') === 0
  5925. ? aPath.substr(aRoot.length + 1)
  5926. : aPath;
  5927. }
  5928. exports.relative = relative;
  5929. function strcmp(aStr1, aStr2) {
  5930. var s1 = aStr1 || "";
  5931. var s2 = aStr2 || "";
  5932. return (s1 > s2) - (s1 < s2);
  5933. }
  5934. /**
  5935. * Comparator between two mappings where the original positions are compared.
  5936. *
  5937. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  5938. * mappings with the same original source/line/column, but different generated
  5939. * line and column the same. Useful when searching for a mapping with a
  5940. * stubbed out mapping.
  5941. */
  5942. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  5943. var cmp;
  5944. cmp = strcmp(mappingA.source, mappingB.source);
  5945. if (cmp) {
  5946. return cmp;
  5947. }
  5948. cmp = mappingA.originalLine - mappingB.originalLine;
  5949. if (cmp) {
  5950. return cmp;
  5951. }
  5952. cmp = mappingA.originalColumn - mappingB.originalColumn;
  5953. if (cmp || onlyCompareOriginal) {
  5954. return cmp;
  5955. }
  5956. cmp = strcmp(mappingA.name, mappingB.name);
  5957. if (cmp) {
  5958. return cmp;
  5959. }
  5960. cmp = mappingA.generatedLine - mappingB.generatedLine;
  5961. if (cmp) {
  5962. return cmp;
  5963. }
  5964. return mappingA.generatedColumn - mappingB.generatedColumn;
  5965. };
  5966. exports.compareByOriginalPositions = compareByOriginalPositions;
  5967. /**
  5968. * Comparator between two mappings where the generated positions are
  5969. * compared.
  5970. *
  5971. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  5972. * mappings with the same generated line and column, but different
  5973. * source/name/original line and column the same. Useful when searching for a
  5974. * mapping with a stubbed out mapping.
  5975. */
  5976. function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
  5977. var cmp;
  5978. cmp = mappingA.generatedLine - mappingB.generatedLine;
  5979. if (cmp) {
  5980. return cmp;
  5981. }
  5982. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  5983. if (cmp || onlyCompareGenerated) {
  5984. return cmp;
  5985. }
  5986. cmp = strcmp(mappingA.source, mappingB.source);
  5987. if (cmp) {
  5988. return cmp;
  5989. }
  5990. cmp = mappingA.originalLine - mappingB.originalLine;
  5991. if (cmp) {
  5992. return cmp;
  5993. }
  5994. cmp = mappingA.originalColumn - mappingB.originalColumn;
  5995. if (cmp) {
  5996. return cmp;
  5997. }
  5998. return strcmp(mappingA.name, mappingB.name);
  5999. };
  6000. exports.compareByGeneratedPositions = compareByGeneratedPositions;
  6001. });
  6002. },{"amdefine":43}],43:[function(require,module,exports){
  6003. (function (process,__filename){
  6004. /** vim: et:ts=4:sw=4:sts=4
  6005. * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
  6006. * Available via the MIT or new BSD license.
  6007. * see: http://github.com/jrburke/amdefine for details
  6008. */
  6009. /*jslint node: true */
  6010. /*global module, process */
  6011. 'use strict';
  6012. /**
  6013. * Creates a define for node.
  6014. * @param {Object} module the "module" object that is defined by Node for the
  6015. * current module.
  6016. * @param {Function} [requireFn]. Node's require function for the current module.
  6017. * It only needs to be passed in Node versions before 0.5, when module.require
  6018. * did not exist.
  6019. * @returns {Function} a define function that is usable for the current node
  6020. * module.
  6021. */
  6022. function amdefine(module, requireFn) {
  6023. 'use strict';
  6024. var defineCache = {},
  6025. loaderCache = {},
  6026. alreadyCalled = false,
  6027. path = require('path'),
  6028. makeRequire, stringRequire;
  6029. /**
  6030. * Trims the . and .. from an array of path segments.
  6031. * It will keep a leading path segment if a .. will become
  6032. * the first path segment, to help with module name lookups,
  6033. * which act like paths, but can be remapped. But the end result,
  6034. * all paths that use this function should look normalized.
  6035. * NOTE: this method MODIFIES the input array.
  6036. * @param {Array} ary the array of path segments.
  6037. */
  6038. function trimDots(ary) {
  6039. var i, part;
  6040. for (i = 0; ary[i]; i+= 1) {
  6041. part = ary[i];
  6042. if (part === '.') {
  6043. ary.splice(i, 1);
  6044. i -= 1;
  6045. } else if (part === '..') {
  6046. if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
  6047. //End of the line. Keep at least one non-dot
  6048. //path segment at the front so it can be mapped
  6049. //correctly to disk. Otherwise, there is likely
  6050. //no path mapping for a path starting with '..'.
  6051. //This can still fail, but catches the most reasonable
  6052. //uses of ..
  6053. break;
  6054. } else if (i > 0) {
  6055. ary.splice(i - 1, 2);
  6056. i -= 2;
  6057. }
  6058. }
  6059. }
  6060. }
  6061. function normalize(name, baseName) {
  6062. var baseParts;
  6063. //Adjust any relative paths.
  6064. if (name && name.charAt(0) === '.') {
  6065. //If have a base name, try to normalize against it,
  6066. //otherwise, assume it is a top-level require that will
  6067. //be relative to baseUrl in the end.
  6068. if (baseName) {
  6069. baseParts = baseName.split('/');
  6070. baseParts = baseParts.slice(0, baseParts.length - 1);
  6071. baseParts = baseParts.concat(name.split('/'));
  6072. trimDots(baseParts);
  6073. name = baseParts.join('/');
  6074. }
  6075. }
  6076. return name;
  6077. }
  6078. /**
  6079. * Create the normalize() function passed to a loader plugin's
  6080. * normalize method.
  6081. */
  6082. function makeNormalize(relName) {
  6083. return function (name) {
  6084. return normalize(name, relName);
  6085. };
  6086. }
  6087. function makeLoad(id) {
  6088. function load(value) {
  6089. loaderCache[id] = value;
  6090. }
  6091. load.fromText = function (id, text) {
  6092. //This one is difficult because the text can/probably uses
  6093. //define, and any relative paths and requires should be relative
  6094. //to that id was it would be found on disk. But this would require
  6095. //bootstrapping a module/require fairly deeply from node core.
  6096. //Not sure how best to go about that yet.
  6097. throw new Error('amdefine does not implement load.fromText');
  6098. };
  6099. return load;
  6100. }
  6101. makeRequire = function (systemRequire, exports, module, relId) {
  6102. function amdRequire(deps, callback) {
  6103. if (typeof deps === 'string') {
  6104. //Synchronous, single module require('')
  6105. return stringRequire(systemRequire, exports, module, deps, relId);
  6106. } else {
  6107. //Array of dependencies with a callback.
  6108. //Convert the dependencies to modules.
  6109. deps = deps.map(function (depName) {
  6110. return stringRequire(systemRequire, exports, module, depName, relId);
  6111. });
  6112. //Wait for next tick to call back the require call.
  6113. process.nextTick(function () {
  6114. callback.apply(null, deps);
  6115. });
  6116. }
  6117. }
  6118. amdRequire.toUrl = function (filePath) {
  6119. if (filePath.indexOf('.') === 0) {
  6120. return normalize(filePath, path.dirname(module.filename));
  6121. } else {
  6122. return filePath;
  6123. }
  6124. };
  6125. return amdRequire;
  6126. };
  6127. //Favor explicit value, passed in if the module wants to support Node 0.4.
  6128. requireFn = requireFn || function req() {
  6129. return module.require.apply(module, arguments);
  6130. };
  6131. function runFactory(id, deps, factory) {
  6132. var r, e, m, result;
  6133. if (id) {
  6134. e = loaderCache[id] = {};
  6135. m = {
  6136. id: id,
  6137. uri: __filename,
  6138. exports: e
  6139. };
  6140. r = makeRequire(requireFn, e, m, id);
  6141. } else {
  6142. //Only support one define call per file
  6143. if (alreadyCalled) {
  6144. throw new Error('amdefine with no module ID cannot be called more than once per file.');
  6145. }
  6146. alreadyCalled = true;
  6147. //Use the real variables from node
  6148. //Use module.exports for exports, since
  6149. //the exports in here is amdefine exports.
  6150. e = module.exports;
  6151. m = module;
  6152. r = makeRequire(requireFn, e, m, module.id);
  6153. }
  6154. //If there are dependencies, they are strings, so need
  6155. //to convert them to dependency values.
  6156. if (deps) {
  6157. deps = deps.map(function (depName) {
  6158. return r(depName);
  6159. });
  6160. }
  6161. //Call the factory with the right dependencies.
  6162. if (typeof factory === 'function') {
  6163. result = factory.apply(m.exports, deps);
  6164. } else {
  6165. result = factory;
  6166. }
  6167. if (result !== undefined) {
  6168. m.exports = result;
  6169. if (id) {
  6170. loaderCache[id] = m.exports;
  6171. }
  6172. }
  6173. }
  6174. stringRequire = function (systemRequire, exports, module, id, relId) {
  6175. //Split the ID by a ! so that
  6176. var index = id.indexOf('!'),
  6177. originalId = id,
  6178. prefix, plugin;
  6179. if (index === -1) {
  6180. id = normalize(id, relId);
  6181. //Straight module lookup. If it is one of the special dependencies,
  6182. //deal with it, otherwise, delegate to node.
  6183. if (id === 'require') {
  6184. return makeRequire(systemRequire, exports, module, relId);
  6185. } else if (id === 'exports') {
  6186. return exports;
  6187. } else if (id === 'module') {
  6188. return module;
  6189. } else if (loaderCache.hasOwnProperty(id)) {
  6190. return loaderCache[id];
  6191. } else if (defineCache[id]) {
  6192. runFactory.apply(null, defineCache[id]);
  6193. return loaderCache[id];
  6194. } else {
  6195. if(systemRequire) {
  6196. return systemRequire(originalId);
  6197. } else {
  6198. throw new Error('No module with ID: ' + id);
  6199. }
  6200. }
  6201. } else {
  6202. //There is a plugin in play.
  6203. prefix = id.substring(0, index);
  6204. id = id.substring(index + 1, id.length);
  6205. plugin = stringRequire(systemRequire, exports, module, prefix, relId);
  6206. if (plugin.normalize) {
  6207. id = plugin.normalize(id, makeNormalize(relId));
  6208. } else {
  6209. //Normalize the ID normally.
  6210. id = normalize(id, relId);
  6211. }
  6212. if (loaderCache[id]) {
  6213. return loaderCache[id];
  6214. } else {
  6215. plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
  6216. return loaderCache[id];
  6217. }
  6218. }
  6219. };
  6220. //Create a define function specific to the module asking for amdefine.
  6221. function define(id, deps, factory) {
  6222. if (Array.isArray(id)) {
  6223. factory = deps;
  6224. deps = id;
  6225. id = undefined;
  6226. } else if (typeof id !== 'string') {
  6227. factory = id;
  6228. id = deps = undefined;
  6229. }
  6230. if (deps && !Array.isArray(deps)) {
  6231. factory = deps;
  6232. deps = undefined;
  6233. }
  6234. if (!deps) {
  6235. deps = ['require', 'exports', 'module'];
  6236. }
  6237. //Set up properties for this module. If an ID, then use
  6238. //internal cache. If no ID, then use the external variables
  6239. //for this node module.
  6240. if (id) {
  6241. //Put the module in deep freeze until there is a
  6242. //require call for it.
  6243. defineCache[id] = [id, deps, factory];
  6244. } else {
  6245. runFactory(id, deps, factory);
  6246. }
  6247. }
  6248. //define.require, which has access to all the values in the
  6249. //cache. Useful for AMD modules that all have IDs in the file,
  6250. //but need to finally export a value to node based on one of those
  6251. //IDs.
  6252. define.require = function (id) {
  6253. if (loaderCache[id]) {
  6254. return loaderCache[id];
  6255. }
  6256. if (defineCache[id]) {
  6257. runFactory.apply(null, defineCache[id]);
  6258. return loaderCache[id];
  6259. }
  6260. };
  6261. define.amd = {};
  6262. return define;
  6263. }
  6264. module.exports = amdefine;
  6265. }).call(this,require('_process'),"/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js")
  6266. },{"_process":29,"path":28}],44:[function(require,module,exports){
  6267. var sys = require("util");
  6268. var MOZ_SourceMap = require("source-map");
  6269. var UglifyJS = exports;
  6270. /***********************************************************************
  6271. A JavaScript tokenizer / parser / beautifier / compressor.
  6272. https://github.com/mishoo/UglifyJS2
  6273. -------------------------------- (C) ---------------------------------
  6274. Author: Mihai Bazon
  6275. <mihai.bazon@gmail.com>
  6276. http://mihai.bazon.net/blog
  6277. Distributed under the BSD license:
  6278. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  6279. Redistribution and use in source and binary forms, with or without
  6280. modification, are permitted provided that the following conditions
  6281. are met:
  6282. * Redistributions of source code must retain the above
  6283. copyright notice, this list of conditions and the following
  6284. disclaimer.
  6285. * Redistributions in binary form must reproduce the above
  6286. copyright notice, this list of conditions and the following
  6287. disclaimer in the documentation and/or other materials
  6288. provided with the distribution.
  6289. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  6290. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6291. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  6292. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  6293. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  6294. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  6295. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  6296. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6297. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  6298. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  6299. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6300. SUCH DAMAGE.
  6301. ***********************************************************************/
  6302. "use strict";
  6303. function array_to_hash(a) {
  6304. var ret = Object.create(null);
  6305. for (var i = 0; i < a.length; ++i)
  6306. ret[a[i]] = true;
  6307. return ret;
  6308. };
  6309. function slice(a, start) {
  6310. return Array.prototype.slice.call(a, start || 0);
  6311. };
  6312. function characters(str) {
  6313. return str.split("");
  6314. };
  6315. function member(name, array) {
  6316. for (var i = array.length; --i >= 0;)
  6317. if (array[i] == name)
  6318. return true;
  6319. return false;
  6320. };
  6321. function find_if(func, array) {
  6322. for (var i = 0, n = array.length; i < n; ++i) {
  6323. if (func(array[i]))
  6324. return array[i];
  6325. }
  6326. };
  6327. function repeat_string(str, i) {
  6328. if (i <= 0) return "";
  6329. if (i == 1) return str;
  6330. var d = repeat_string(str, i >> 1);
  6331. d += d;
  6332. if (i & 1) d += str;
  6333. return d;
  6334. };
  6335. function DefaultsError(msg, defs) {
  6336. Error.call(this, msg);
  6337. this.msg = msg;
  6338. this.defs = defs;
  6339. };
  6340. DefaultsError.prototype = Object.create(Error.prototype);
  6341. DefaultsError.prototype.constructor = DefaultsError;
  6342. DefaultsError.croak = function(msg, defs) {
  6343. throw new DefaultsError(msg, defs);
  6344. };
  6345. function defaults(args, defs, croak) {
  6346. if (args === true)
  6347. args = {};
  6348. var ret = args || {};
  6349. if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
  6350. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  6351. for (var i in defs) if (defs.hasOwnProperty(i)) {
  6352. ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
  6353. }
  6354. return ret;
  6355. };
  6356. function merge(obj, ext) {
  6357. for (var i in ext) if (ext.hasOwnProperty(i)) {
  6358. obj[i] = ext[i];
  6359. }
  6360. return obj;
  6361. };
  6362. function noop() {};
  6363. var MAP = (function(){
  6364. function MAP(a, f, backwards) {
  6365. var ret = [], top = [], i;
  6366. function doit() {
  6367. var val = f(a[i], i);
  6368. var is_last = val instanceof Last;
  6369. if (is_last) val = val.v;
  6370. if (val instanceof AtTop) {
  6371. val = val.v;
  6372. if (val instanceof Splice) {
  6373. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  6374. } else {
  6375. top.push(val);
  6376. }
  6377. }
  6378. else if (val !== skip) {
  6379. if (val instanceof Splice) {
  6380. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  6381. } else {
  6382. ret.push(val);
  6383. }
  6384. }
  6385. return is_last;
  6386. };
  6387. if (a instanceof Array) {
  6388. if (backwards) {
  6389. for (i = a.length; --i >= 0;) if (doit()) break;
  6390. ret.reverse();
  6391. top.reverse();
  6392. } else {
  6393. for (i = 0; i < a.length; ++i) if (doit()) break;
  6394. }
  6395. }
  6396. else {
  6397. for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
  6398. }
  6399. return top.concat(ret);
  6400. };
  6401. MAP.at_top = function(val) { return new AtTop(val) };
  6402. MAP.splice = function(val) { return new Splice(val) };
  6403. MAP.last = function(val) { return new Last(val) };
  6404. var skip = MAP.skip = {};
  6405. function AtTop(val) { this.v = val };
  6406. function Splice(val) { this.v = val };
  6407. function Last(val) { this.v = val };
  6408. return MAP;
  6409. })();
  6410. function push_uniq(array, el) {
  6411. if (array.indexOf(el) < 0)
  6412. array.push(el);
  6413. };
  6414. function string_template(text, props) {
  6415. return text.replace(/\{(.+?)\}/g, function(str, p){
  6416. return props[p];
  6417. });
  6418. };
  6419. function remove(array, el) {
  6420. for (var i = array.length; --i >= 0;) {
  6421. if (array[i] === el) array.splice(i, 1);
  6422. }
  6423. };
  6424. function mergeSort(array, cmp) {
  6425. if (array.length < 2) return array.slice();
  6426. function merge(a, b) {
  6427. var r = [], ai = 0, bi = 0, i = 0;
  6428. while (ai < a.length && bi < b.length) {
  6429. cmp(a[ai], b[bi]) <= 0
  6430. ? r[i++] = a[ai++]
  6431. : r[i++] = b[bi++];
  6432. }
  6433. if (ai < a.length) r.push.apply(r, a.slice(ai));
  6434. if (bi < b.length) r.push.apply(r, b.slice(bi));
  6435. return r;
  6436. };
  6437. function _ms(a) {
  6438. if (a.length <= 1)
  6439. return a;
  6440. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  6441. left = _ms(left);
  6442. right = _ms(right);
  6443. return merge(left, right);
  6444. };
  6445. return _ms(array);
  6446. };
  6447. function set_difference(a, b) {
  6448. return a.filter(function(el){
  6449. return b.indexOf(el) < 0;
  6450. });
  6451. };
  6452. function set_intersection(a, b) {
  6453. return a.filter(function(el){
  6454. return b.indexOf(el) >= 0;
  6455. });
  6456. };
  6457. // this function is taken from Acorn [1], written by Marijn Haverbeke
  6458. // [1] https://github.com/marijnh/acorn
  6459. function makePredicate(words) {
  6460. if (!(words instanceof Array)) words = words.split(" ");
  6461. var f = "", cats = [];
  6462. out: for (var i = 0; i < words.length; ++i) {
  6463. for (var j = 0; j < cats.length; ++j)
  6464. if (cats[j][0].length == words[i].length) {
  6465. cats[j].push(words[i]);
  6466. continue out;
  6467. }
  6468. cats.push([words[i]]);
  6469. }
  6470. function compareTo(arr) {
  6471. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  6472. f += "switch(str){";
  6473. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  6474. f += "return true}return false;";
  6475. }
  6476. // When there are more than three length categories, an outer
  6477. // switch first dispatches on the lengths, to save on comparisons.
  6478. if (cats.length > 3) {
  6479. cats.sort(function(a, b) {return b.length - a.length;});
  6480. f += "switch(str.length){";
  6481. for (var i = 0; i < cats.length; ++i) {
  6482. var cat = cats[i];
  6483. f += "case " + cat[0].length + ":";
  6484. compareTo(cat);
  6485. }
  6486. f += "}";
  6487. // Otherwise, simply generate a flat `switch` statement.
  6488. } else {
  6489. compareTo(words);
  6490. }
  6491. return new Function("str", f);
  6492. };
  6493. function all(array, predicate) {
  6494. for (var i = array.length; --i >= 0;)
  6495. if (!predicate(array[i]))
  6496. return false;
  6497. return true;
  6498. };
  6499. function Dictionary() {
  6500. this._values = Object.create(null);
  6501. this._size = 0;
  6502. };
  6503. Dictionary.prototype = {
  6504. set: function(key, val) {
  6505. if (!this.has(key)) ++this._size;
  6506. this._values["$" + key] = val;
  6507. return this;
  6508. },
  6509. add: function(key, val) {
  6510. if (this.has(key)) {
  6511. this.get(key).push(val);
  6512. } else {
  6513. this.set(key, [ val ]);
  6514. }
  6515. return this;
  6516. },
  6517. get: function(key) { return this._values["$" + key] },
  6518. del: function(key) {
  6519. if (this.has(key)) {
  6520. --this._size;
  6521. delete this._values["$" + key];
  6522. }
  6523. return this;
  6524. },
  6525. has: function(key) { return ("$" + key) in this._values },
  6526. each: function(f) {
  6527. for (var i in this._values)
  6528. f(this._values[i], i.substr(1));
  6529. },
  6530. size: function() {
  6531. return this._size;
  6532. },
  6533. map: function(f) {
  6534. var ret = [];
  6535. for (var i in this._values)
  6536. ret.push(f(this._values[i], i.substr(1)));
  6537. return ret;
  6538. }
  6539. };
  6540. /***********************************************************************
  6541. A JavaScript tokenizer / parser / beautifier / compressor.
  6542. https://github.com/mishoo/UglifyJS2
  6543. -------------------------------- (C) ---------------------------------
  6544. Author: Mihai Bazon
  6545. <mihai.bazon@gmail.com>
  6546. http://mihai.bazon.net/blog
  6547. Distributed under the BSD license:
  6548. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  6549. Redistribution and use in source and binary forms, with or without
  6550. modification, are permitted provided that the following conditions
  6551. are met:
  6552. * Redistributions of source code must retain the above
  6553. copyright notice, this list of conditions and the following
  6554. disclaimer.
  6555. * Redistributions in binary form must reproduce the above
  6556. copyright notice, this list of conditions and the following
  6557. disclaimer in the documentation and/or other materials
  6558. provided with the distribution.
  6559. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  6560. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6561. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  6562. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  6563. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  6564. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  6565. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  6566. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6567. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  6568. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  6569. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6570. SUCH DAMAGE.
  6571. ***********************************************************************/
  6572. "use strict";
  6573. function DEFNODE(type, props, methods, base) {
  6574. if (arguments.length < 4) base = AST_Node;
  6575. if (!props) props = [];
  6576. else props = props.split(/\s+/);
  6577. var self_props = props;
  6578. if (base && base.PROPS)
  6579. props = props.concat(base.PROPS);
  6580. var code = "return function AST_" + type + "(props){ if (props) { ";
  6581. for (var i = props.length; --i >= 0;) {
  6582. code += "this." + props[i] + " = props." + props[i] + ";";
  6583. }
  6584. var proto = base && new base;
  6585. if (proto && proto.initialize || (methods && methods.initialize))
  6586. code += "this.initialize();";
  6587. code += "}}";
  6588. var ctor = new Function(code)();
  6589. if (proto) {
  6590. ctor.prototype = proto;
  6591. ctor.BASE = base;
  6592. }
  6593. if (base) base.SUBCLASSES.push(ctor);
  6594. ctor.prototype.CTOR = ctor;
  6595. ctor.PROPS = props || null;
  6596. ctor.SELF_PROPS = self_props;
  6597. ctor.SUBCLASSES = [];
  6598. if (type) {
  6599. ctor.prototype.TYPE = ctor.TYPE = type;
  6600. }
  6601. if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
  6602. if (/^\$/.test(i)) {
  6603. ctor[i.substr(1)] = methods[i];
  6604. } else {
  6605. ctor.prototype[i] = methods[i];
  6606. }
  6607. }
  6608. ctor.DEFMETHOD = function(name, method) {
  6609. this.prototype[name] = method;
  6610. };
  6611. return ctor;
  6612. };
  6613. var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
  6614. }, null);
  6615. var AST_Node = DEFNODE("Node", "start end", {
  6616. clone: function() {
  6617. return new this.CTOR(this);
  6618. },
  6619. $documentation: "Base class of all AST nodes",
  6620. $propdoc: {
  6621. start: "[AST_Token] The first token of this node",
  6622. end: "[AST_Token] The last token of this node"
  6623. },
  6624. _walk: function(visitor) {
  6625. return visitor._visit(this);
  6626. },
  6627. walk: function(visitor) {
  6628. return this._walk(visitor); // not sure the indirection will be any help
  6629. }
  6630. }, null);
  6631. AST_Node.warn_function = null;
  6632. AST_Node.warn = function(txt, props) {
  6633. if (AST_Node.warn_function)
  6634. AST_Node.warn_function(string_template(txt, props));
  6635. };
  6636. /* -----[ statements ]----- */
  6637. var AST_Statement = DEFNODE("Statement", null, {
  6638. $documentation: "Base class of all statements",
  6639. });
  6640. var AST_Debugger = DEFNODE("Debugger", null, {
  6641. $documentation: "Represents a debugger statement",
  6642. }, AST_Statement);
  6643. var AST_Directive = DEFNODE("Directive", "value scope", {
  6644. $documentation: "Represents a directive, like \"use strict\";",
  6645. $propdoc: {
  6646. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  6647. scope: "[AST_Scope/S] The scope that this directive affects"
  6648. },
  6649. }, AST_Statement);
  6650. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  6651. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  6652. $propdoc: {
  6653. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  6654. },
  6655. _walk: function(visitor) {
  6656. return visitor._visit(this, function(){
  6657. this.body._walk(visitor);
  6658. });
  6659. }
  6660. }, AST_Statement);
  6661. function walk_body(node, visitor) {
  6662. if (node.body instanceof AST_Statement) {
  6663. node.body._walk(visitor);
  6664. }
  6665. else node.body.forEach(function(stat){
  6666. stat._walk(visitor);
  6667. });
  6668. };
  6669. var AST_Block = DEFNODE("Block", "body", {
  6670. $documentation: "A body of statements (usually bracketed)",
  6671. $propdoc: {
  6672. body: "[AST_Statement*] an array of statements"
  6673. },
  6674. _walk: function(visitor) {
  6675. return visitor._visit(this, function(){
  6676. walk_body(this, visitor);
  6677. });
  6678. }
  6679. }, AST_Statement);
  6680. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  6681. $documentation: "A block statement",
  6682. }, AST_Block);
  6683. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  6684. $documentation: "The empty statement (empty block or simply a semicolon)",
  6685. _walk: function(visitor) {
  6686. return visitor._visit(this);
  6687. }
  6688. }, AST_Statement);
  6689. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  6690. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  6691. $propdoc: {
  6692. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  6693. },
  6694. _walk: function(visitor) {
  6695. return visitor._visit(this, function(){
  6696. this.body._walk(visitor);
  6697. });
  6698. }
  6699. }, AST_Statement);
  6700. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  6701. $documentation: "Statement with a label",
  6702. $propdoc: {
  6703. label: "[AST_Label] a label definition"
  6704. },
  6705. _walk: function(visitor) {
  6706. return visitor._visit(this, function(){
  6707. this.label._walk(visitor);
  6708. this.body._walk(visitor);
  6709. });
  6710. }
  6711. }, AST_StatementWithBody);
  6712. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  6713. $documentation: "Internal class. All loops inherit from it."
  6714. }, AST_StatementWithBody);
  6715. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  6716. $documentation: "Base class for do/while statements",
  6717. $propdoc: {
  6718. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  6719. },
  6720. _walk: function(visitor) {
  6721. return visitor._visit(this, function(){
  6722. this.condition._walk(visitor);
  6723. this.body._walk(visitor);
  6724. });
  6725. }
  6726. }, AST_IterationStatement);
  6727. var AST_Do = DEFNODE("Do", null, {
  6728. $documentation: "A `do` statement",
  6729. }, AST_DWLoop);
  6730. var AST_While = DEFNODE("While", null, {
  6731. $documentation: "A `while` statement",
  6732. }, AST_DWLoop);
  6733. var AST_For = DEFNODE("For", "init condition step", {
  6734. $documentation: "A `for` statement",
  6735. $propdoc: {
  6736. init: "[AST_Node?] the `for` initialization code, or null if empty",
  6737. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  6738. step: "[AST_Node?] the `for` update clause, or null if empty"
  6739. },
  6740. _walk: function(visitor) {
  6741. return visitor._visit(this, function(){
  6742. if (this.init) this.init._walk(visitor);
  6743. if (this.condition) this.condition._walk(visitor);
  6744. if (this.step) this.step._walk(visitor);
  6745. this.body._walk(visitor);
  6746. });
  6747. }
  6748. }, AST_IterationStatement);
  6749. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  6750. $documentation: "A `for ... in` statement",
  6751. $propdoc: {
  6752. init: "[AST_Node] the `for/in` initialization code",
  6753. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  6754. object: "[AST_Node] the object that we're looping through"
  6755. },
  6756. _walk: function(visitor) {
  6757. return visitor._visit(this, function(){
  6758. this.init._walk(visitor);
  6759. this.object._walk(visitor);
  6760. this.body._walk(visitor);
  6761. });
  6762. }
  6763. }, AST_IterationStatement);
  6764. var AST_With = DEFNODE("With", "expression", {
  6765. $documentation: "A `with` statement",
  6766. $propdoc: {
  6767. expression: "[AST_Node] the `with` expression"
  6768. },
  6769. _walk: function(visitor) {
  6770. return visitor._visit(this, function(){
  6771. this.expression._walk(visitor);
  6772. this.body._walk(visitor);
  6773. });
  6774. }
  6775. }, AST_StatementWithBody);
  6776. /* -----[ scope and functions ]----- */
  6777. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  6778. $documentation: "Base class for all statements introducing a lexical scope",
  6779. $propdoc: {
  6780. directives: "[string*/S] an array of directives declared in this scope",
  6781. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  6782. functions: "[Object/S] like `variables`, but only lists function declarations",
  6783. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  6784. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  6785. parent_scope: "[AST_Scope?/S] link to the parent scope",
  6786. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  6787. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  6788. },
  6789. }, AST_Block);
  6790. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  6791. $documentation: "The toplevel scope",
  6792. $propdoc: {
  6793. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  6794. },
  6795. wrap_enclose: function(arg_parameter_pairs) {
  6796. var self = this;
  6797. var args = [];
  6798. var parameters = [];
  6799. arg_parameter_pairs.forEach(function(pair) {
  6800. var splitAt = pair.lastIndexOf(":");
  6801. args.push(pair.substr(0, splitAt));
  6802. parameters.push(pair.substr(splitAt + 1));
  6803. });
  6804. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  6805. wrapped_tl = parse(wrapped_tl);
  6806. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  6807. if (node instanceof AST_Directive && node.value == "$ORIG") {
  6808. return MAP.splice(self.body);
  6809. }
  6810. }));
  6811. return wrapped_tl;
  6812. },
  6813. wrap_commonjs: function(name, export_all) {
  6814. var self = this;
  6815. var to_export = [];
  6816. if (export_all) {
  6817. self.figure_out_scope();
  6818. self.walk(new TreeWalker(function(node){
  6819. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  6820. if (!find_if(function(n){ return n.name == node.name }, to_export))
  6821. to_export.push(node);
  6822. }
  6823. }));
  6824. }
  6825. var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
  6826. wrapped_tl = parse(wrapped_tl);
  6827. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  6828. if (node instanceof AST_SimpleStatement) {
  6829. node = node.body;
  6830. if (node instanceof AST_String) switch (node.getValue()) {
  6831. case "$ORIG":
  6832. return MAP.splice(self.body);
  6833. case "$EXPORTS":
  6834. var body = [];
  6835. to_export.forEach(function(sym){
  6836. body.push(new AST_SimpleStatement({
  6837. body: new AST_Assign({
  6838. left: new AST_Sub({
  6839. expression: new AST_SymbolRef({ name: "exports" }),
  6840. property: new AST_String({ value: sym.name }),
  6841. }),
  6842. operator: "=",
  6843. right: new AST_SymbolRef(sym),
  6844. }),
  6845. }));
  6846. });
  6847. return MAP.splice(body);
  6848. }
  6849. }
  6850. }));
  6851. return wrapped_tl;
  6852. }
  6853. }, AST_Scope);
  6854. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  6855. $documentation: "Base class for functions",
  6856. $propdoc: {
  6857. name: "[AST_SymbolDeclaration?] the name of this function",
  6858. argnames: "[AST_SymbolFunarg*] array of function arguments",
  6859. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  6860. },
  6861. _walk: function(visitor) {
  6862. return visitor._visit(this, function(){
  6863. if (this.name) this.name._walk(visitor);
  6864. this.argnames.forEach(function(arg){
  6865. arg._walk(visitor);
  6866. });
  6867. walk_body(this, visitor);
  6868. });
  6869. }
  6870. }, AST_Scope);
  6871. var AST_Accessor = DEFNODE("Accessor", null, {
  6872. $documentation: "A setter/getter function. The `name` property is always null."
  6873. }, AST_Lambda);
  6874. var AST_Function = DEFNODE("Function", null, {
  6875. $documentation: "A function expression"
  6876. }, AST_Lambda);
  6877. var AST_Defun = DEFNODE("Defun", null, {
  6878. $documentation: "A function definition"
  6879. }, AST_Lambda);
  6880. /* -----[ JUMPS ]----- */
  6881. var AST_Jump = DEFNODE("Jump", null, {
  6882. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  6883. }, AST_Statement);
  6884. var AST_Exit = DEFNODE("Exit", "value", {
  6885. $documentation: "Base class for “exits” (`return` and `throw`)",
  6886. $propdoc: {
  6887. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  6888. },
  6889. _walk: function(visitor) {
  6890. return visitor._visit(this, this.value && function(){
  6891. this.value._walk(visitor);
  6892. });
  6893. }
  6894. }, AST_Jump);
  6895. var AST_Return = DEFNODE("Return", null, {
  6896. $documentation: "A `return` statement"
  6897. }, AST_Exit);
  6898. var AST_Throw = DEFNODE("Throw", null, {
  6899. $documentation: "A `throw` statement"
  6900. }, AST_Exit);
  6901. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  6902. $documentation: "Base class for loop control statements (`break` and `continue`)",
  6903. $propdoc: {
  6904. label: "[AST_LabelRef?] the label, or null if none",
  6905. },
  6906. _walk: function(visitor) {
  6907. return visitor._visit(this, this.label && function(){
  6908. this.label._walk(visitor);
  6909. });
  6910. }
  6911. }, AST_Jump);
  6912. var AST_Break = DEFNODE("Break", null, {
  6913. $documentation: "A `break` statement"
  6914. }, AST_LoopControl);
  6915. var AST_Continue = DEFNODE("Continue", null, {
  6916. $documentation: "A `continue` statement"
  6917. }, AST_LoopControl);
  6918. /* -----[ IF ]----- */
  6919. var AST_If = DEFNODE("If", "condition alternative", {
  6920. $documentation: "A `if` statement",
  6921. $propdoc: {
  6922. condition: "[AST_Node] the `if` condition",
  6923. alternative: "[AST_Statement?] the `else` part, or null if not present"
  6924. },
  6925. _walk: function(visitor) {
  6926. return visitor._visit(this, function(){
  6927. this.condition._walk(visitor);
  6928. this.body._walk(visitor);
  6929. if (this.alternative) this.alternative._walk(visitor);
  6930. });
  6931. }
  6932. }, AST_StatementWithBody);
  6933. /* -----[ SWITCH ]----- */
  6934. var AST_Switch = DEFNODE("Switch", "expression", {
  6935. $documentation: "A `switch` statement",
  6936. $propdoc: {
  6937. expression: "[AST_Node] the `switch` “discriminant”"
  6938. },
  6939. _walk: function(visitor) {
  6940. return visitor._visit(this, function(){
  6941. this.expression._walk(visitor);
  6942. walk_body(this, visitor);
  6943. });
  6944. }
  6945. }, AST_Block);
  6946. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  6947. $documentation: "Base class for `switch` branches",
  6948. }, AST_Block);
  6949. var AST_Default = DEFNODE("Default", null, {
  6950. $documentation: "A `default` switch branch",
  6951. }, AST_SwitchBranch);
  6952. var AST_Case = DEFNODE("Case", "expression", {
  6953. $documentation: "A `case` switch branch",
  6954. $propdoc: {
  6955. expression: "[AST_Node] the `case` expression"
  6956. },
  6957. _walk: function(visitor) {
  6958. return visitor._visit(this, function(){
  6959. this.expression._walk(visitor);
  6960. walk_body(this, visitor);
  6961. });
  6962. }
  6963. }, AST_SwitchBranch);
  6964. /* -----[ EXCEPTIONS ]----- */
  6965. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  6966. $documentation: "A `try` statement",
  6967. $propdoc: {
  6968. bcatch: "[AST_Catch?] the catch block, or null if not present",
  6969. bfinally: "[AST_Finally?] the finally block, or null if not present"
  6970. },
  6971. _walk: function(visitor) {
  6972. return visitor._visit(this, function(){
  6973. walk_body(this, visitor);
  6974. if (this.bcatch) this.bcatch._walk(visitor);
  6975. if (this.bfinally) this.bfinally._walk(visitor);
  6976. });
  6977. }
  6978. }, AST_Block);
  6979. var AST_Catch = DEFNODE("Catch", "argname", {
  6980. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  6981. $propdoc: {
  6982. argname: "[AST_SymbolCatch] symbol for the exception"
  6983. },
  6984. _walk: function(visitor) {
  6985. return visitor._visit(this, function(){
  6986. this.argname._walk(visitor);
  6987. walk_body(this, visitor);
  6988. });
  6989. }
  6990. }, AST_Block);
  6991. var AST_Finally = DEFNODE("Finally", null, {
  6992. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  6993. }, AST_Block);
  6994. /* -----[ VAR/CONST ]----- */
  6995. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  6996. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  6997. $propdoc: {
  6998. definitions: "[AST_VarDef*] array of variable definitions"
  6999. },
  7000. _walk: function(visitor) {
  7001. return visitor._visit(this, function(){
  7002. this.definitions.forEach(function(def){
  7003. def._walk(visitor);
  7004. });
  7005. });
  7006. }
  7007. }, AST_Statement);
  7008. var AST_Var = DEFNODE("Var", null, {
  7009. $documentation: "A `var` statement"
  7010. }, AST_Definitions);
  7011. var AST_Const = DEFNODE("Const", null, {
  7012. $documentation: "A `const` statement"
  7013. }, AST_Definitions);
  7014. var AST_VarDef = DEFNODE("VarDef", "name value", {
  7015. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  7016. $propdoc: {
  7017. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  7018. value: "[AST_Node?] initializer, or null of there's no initializer"
  7019. },
  7020. _walk: function(visitor) {
  7021. return visitor._visit(this, function(){
  7022. this.name._walk(visitor);
  7023. if (this.value) this.value._walk(visitor);
  7024. });
  7025. }
  7026. });
  7027. /* -----[ OTHER ]----- */
  7028. var AST_Call = DEFNODE("Call", "expression args", {
  7029. $documentation: "A function call expression",
  7030. $propdoc: {
  7031. expression: "[AST_Node] expression to invoke as function",
  7032. args: "[AST_Node*] array of arguments"
  7033. },
  7034. _walk: function(visitor) {
  7035. return visitor._visit(this, function(){
  7036. this.expression._walk(visitor);
  7037. this.args.forEach(function(arg){
  7038. arg._walk(visitor);
  7039. });
  7040. });
  7041. }
  7042. });
  7043. var AST_New = DEFNODE("New", null, {
  7044. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  7045. }, AST_Call);
  7046. var AST_Seq = DEFNODE("Seq", "car cdr", {
  7047. $documentation: "A sequence expression (two comma-separated expressions)",
  7048. $propdoc: {
  7049. car: "[AST_Node] first element in sequence",
  7050. cdr: "[AST_Node] second element in sequence"
  7051. },
  7052. $cons: function(x, y) {
  7053. var seq = new AST_Seq(x);
  7054. seq.car = x;
  7055. seq.cdr = y;
  7056. return seq;
  7057. },
  7058. $from_array: function(array) {
  7059. if (array.length == 0) return null;
  7060. if (array.length == 1) return array[0].clone();
  7061. var list = null;
  7062. for (var i = array.length; --i >= 0;) {
  7063. list = AST_Seq.cons(array[i], list);
  7064. }
  7065. var p = list;
  7066. while (p) {
  7067. if (p.cdr && !p.cdr.cdr) {
  7068. p.cdr = p.cdr.car;
  7069. break;
  7070. }
  7071. p = p.cdr;
  7072. }
  7073. return list;
  7074. },
  7075. to_array: function() {
  7076. var p = this, a = [];
  7077. while (p) {
  7078. a.push(p.car);
  7079. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  7080. a.push(p.cdr);
  7081. break;
  7082. }
  7083. p = p.cdr;
  7084. }
  7085. return a;
  7086. },
  7087. add: function(node) {
  7088. var p = this;
  7089. while (p) {
  7090. if (!(p.cdr instanceof AST_Seq)) {
  7091. var cell = AST_Seq.cons(p.cdr, node);
  7092. return p.cdr = cell;
  7093. }
  7094. p = p.cdr;
  7095. }
  7096. },
  7097. _walk: function(visitor) {
  7098. return visitor._visit(this, function(){
  7099. this.car._walk(visitor);
  7100. if (this.cdr) this.cdr._walk(visitor);
  7101. });
  7102. }
  7103. });
  7104. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  7105. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  7106. $propdoc: {
  7107. expression: "[AST_Node] the “container” expression",
  7108. property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
  7109. }
  7110. });
  7111. var AST_Dot = DEFNODE("Dot", null, {
  7112. $documentation: "A dotted property access expression",
  7113. _walk: function(visitor) {
  7114. return visitor._visit(this, function(){
  7115. this.expression._walk(visitor);
  7116. });
  7117. }
  7118. }, AST_PropAccess);
  7119. var AST_Sub = DEFNODE("Sub", null, {
  7120. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  7121. _walk: function(visitor) {
  7122. return visitor._visit(this, function(){
  7123. this.expression._walk(visitor);
  7124. this.property._walk(visitor);
  7125. });
  7126. }
  7127. }, AST_PropAccess);
  7128. var AST_Unary = DEFNODE("Unary", "operator expression", {
  7129. $documentation: "Base class for unary expressions",
  7130. $propdoc: {
  7131. operator: "[string] the operator",
  7132. expression: "[AST_Node] expression that this unary operator applies to"
  7133. },
  7134. _walk: function(visitor) {
  7135. return visitor._visit(this, function(){
  7136. this.expression._walk(visitor);
  7137. });
  7138. }
  7139. });
  7140. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  7141. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  7142. }, AST_Unary);
  7143. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  7144. $documentation: "Unary postfix expression, i.e. `i++`"
  7145. }, AST_Unary);
  7146. var AST_Binary = DEFNODE("Binary", "left operator right", {
  7147. $documentation: "Binary expression, i.e. `a + b`",
  7148. $propdoc: {
  7149. left: "[AST_Node] left-hand side expression",
  7150. operator: "[string] the operator",
  7151. right: "[AST_Node] right-hand side expression"
  7152. },
  7153. _walk: function(visitor) {
  7154. return visitor._visit(this, function(){
  7155. this.left._walk(visitor);
  7156. this.right._walk(visitor);
  7157. });
  7158. }
  7159. });
  7160. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  7161. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  7162. $propdoc: {
  7163. condition: "[AST_Node]",
  7164. consequent: "[AST_Node]",
  7165. alternative: "[AST_Node]"
  7166. },
  7167. _walk: function(visitor) {
  7168. return visitor._visit(this, function(){
  7169. this.condition._walk(visitor);
  7170. this.consequent._walk(visitor);
  7171. this.alternative._walk(visitor);
  7172. });
  7173. }
  7174. });
  7175. var AST_Assign = DEFNODE("Assign", null, {
  7176. $documentation: "An assignment expression — `a = b + 5`",
  7177. }, AST_Binary);
  7178. /* -----[ LITERALS ]----- */
  7179. var AST_Array = DEFNODE("Array", "elements", {
  7180. $documentation: "An array literal",
  7181. $propdoc: {
  7182. elements: "[AST_Node*] array of elements"
  7183. },
  7184. _walk: function(visitor) {
  7185. return visitor._visit(this, function(){
  7186. this.elements.forEach(function(el){
  7187. el._walk(visitor);
  7188. });
  7189. });
  7190. }
  7191. });
  7192. var AST_Object = DEFNODE("Object", "properties", {
  7193. $documentation: "An object literal",
  7194. $propdoc: {
  7195. properties: "[AST_ObjectProperty*] array of properties"
  7196. },
  7197. _walk: function(visitor) {
  7198. return visitor._visit(this, function(){
  7199. this.properties.forEach(function(prop){
  7200. prop._walk(visitor);
  7201. });
  7202. });
  7203. }
  7204. });
  7205. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  7206. $documentation: "Base class for literal object properties",
  7207. $propdoc: {
  7208. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
  7209. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  7210. },
  7211. _walk: function(visitor) {
  7212. return visitor._visit(this, function(){
  7213. this.value._walk(visitor);
  7214. });
  7215. }
  7216. });
  7217. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
  7218. $documentation: "A key: value object property",
  7219. }, AST_ObjectProperty);
  7220. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  7221. $documentation: "An object setter property",
  7222. }, AST_ObjectProperty);
  7223. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  7224. $documentation: "An object getter property",
  7225. }, AST_ObjectProperty);
  7226. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  7227. $propdoc: {
  7228. name: "[string] name of this symbol",
  7229. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  7230. thedef: "[SymbolDef/S] the definition of this symbol"
  7231. },
  7232. $documentation: "Base class for all symbols",
  7233. });
  7234. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  7235. $documentation: "The name of a property accessor (setter/getter function)"
  7236. }, AST_Symbol);
  7237. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  7238. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  7239. $propdoc: {
  7240. init: "[AST_Node*/S] array of initializers for this declaration."
  7241. }
  7242. }, AST_Symbol);
  7243. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  7244. $documentation: "Symbol defining a variable",
  7245. }, AST_SymbolDeclaration);
  7246. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  7247. $documentation: "A constant declaration"
  7248. }, AST_SymbolDeclaration);
  7249. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  7250. $documentation: "Symbol naming a function argument",
  7251. }, AST_SymbolVar);
  7252. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  7253. $documentation: "Symbol defining a function",
  7254. }, AST_SymbolDeclaration);
  7255. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  7256. $documentation: "Symbol naming a function expression",
  7257. }, AST_SymbolDeclaration);
  7258. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  7259. $documentation: "Symbol naming the exception in catch",
  7260. }, AST_SymbolDeclaration);
  7261. var AST_Label = DEFNODE("Label", "references", {
  7262. $documentation: "Symbol naming a label (declaration)",
  7263. $propdoc: {
  7264. references: "[AST_LoopControl*] a list of nodes referring to this label"
  7265. },
  7266. initialize: function() {
  7267. this.references = [];
  7268. this.thedef = this;
  7269. }
  7270. }, AST_Symbol);
  7271. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  7272. $documentation: "Reference to some symbol (not definition/declaration)",
  7273. }, AST_Symbol);
  7274. var AST_LabelRef = DEFNODE("LabelRef", null, {
  7275. $documentation: "Reference to a label symbol",
  7276. }, AST_Symbol);
  7277. var AST_This = DEFNODE("This", null, {
  7278. $documentation: "The `this` symbol",
  7279. }, AST_Symbol);
  7280. var AST_Constant = DEFNODE("Constant", null, {
  7281. $documentation: "Base class for all constants",
  7282. getValue: function() {
  7283. return this.value;
  7284. }
  7285. });
  7286. var AST_String = DEFNODE("String", "value", {
  7287. $documentation: "A string literal",
  7288. $propdoc: {
  7289. value: "[string] the contents of this string"
  7290. }
  7291. }, AST_Constant);
  7292. var AST_Number = DEFNODE("Number", "value", {
  7293. $documentation: "A number literal",
  7294. $propdoc: {
  7295. value: "[number] the numeric value"
  7296. }
  7297. }, AST_Constant);
  7298. var AST_RegExp = DEFNODE("RegExp", "value", {
  7299. $documentation: "A regexp literal",
  7300. $propdoc: {
  7301. value: "[RegExp] the actual regexp"
  7302. }
  7303. }, AST_Constant);
  7304. var AST_Atom = DEFNODE("Atom", null, {
  7305. $documentation: "Base class for atoms",
  7306. }, AST_Constant);
  7307. var AST_Null = DEFNODE("Null", null, {
  7308. $documentation: "The `null` atom",
  7309. value: null
  7310. }, AST_Atom);
  7311. var AST_NaN = DEFNODE("NaN", null, {
  7312. $documentation: "The impossible value",
  7313. value: 0/0
  7314. }, AST_Atom);
  7315. var AST_Undefined = DEFNODE("Undefined", null, {
  7316. $documentation: "The `undefined` value",
  7317. value: (function(){}())
  7318. }, AST_Atom);
  7319. var AST_Hole = DEFNODE("Hole", null, {
  7320. $documentation: "A hole in an array",
  7321. value: (function(){}())
  7322. }, AST_Atom);
  7323. var AST_Infinity = DEFNODE("Infinity", null, {
  7324. $documentation: "The `Infinity` value",
  7325. value: 1/0
  7326. }, AST_Atom);
  7327. var AST_Boolean = DEFNODE("Boolean", null, {
  7328. $documentation: "Base class for booleans",
  7329. }, AST_Atom);
  7330. var AST_False = DEFNODE("False", null, {
  7331. $documentation: "The `false` atom",
  7332. value: false
  7333. }, AST_Boolean);
  7334. var AST_True = DEFNODE("True", null, {
  7335. $documentation: "The `true` atom",
  7336. value: true
  7337. }, AST_Boolean);
  7338. /* -----[ TreeWalker ]----- */
  7339. function TreeWalker(callback) {
  7340. this.visit = callback;
  7341. this.stack = [];
  7342. };
  7343. TreeWalker.prototype = {
  7344. _visit: function(node, descend) {
  7345. this.stack.push(node);
  7346. var ret = this.visit(node, descend ? function(){
  7347. descend.call(node);
  7348. } : noop);
  7349. if (!ret && descend) {
  7350. descend.call(node);
  7351. }
  7352. this.stack.pop();
  7353. return ret;
  7354. },
  7355. parent: function(n) {
  7356. return this.stack[this.stack.length - 2 - (n || 0)];
  7357. },
  7358. push: function (node) {
  7359. this.stack.push(node);
  7360. },
  7361. pop: function() {
  7362. return this.stack.pop();
  7363. },
  7364. self: function() {
  7365. return this.stack[this.stack.length - 1];
  7366. },
  7367. find_parent: function(type) {
  7368. var stack = this.stack;
  7369. for (var i = stack.length; --i >= 0;) {
  7370. var x = stack[i];
  7371. if (x instanceof type) return x;
  7372. }
  7373. },
  7374. has_directive: function(type) {
  7375. return this.find_parent(AST_Scope).has_directive(type);
  7376. },
  7377. in_boolean_context: function() {
  7378. var stack = this.stack;
  7379. var i = stack.length, self = stack[--i];
  7380. while (i > 0) {
  7381. var p = stack[--i];
  7382. if ((p instanceof AST_If && p.condition === self) ||
  7383. (p instanceof AST_Conditional && p.condition === self) ||
  7384. (p instanceof AST_DWLoop && p.condition === self) ||
  7385. (p instanceof AST_For && p.condition === self) ||
  7386. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  7387. {
  7388. return true;
  7389. }
  7390. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  7391. return false;
  7392. self = p;
  7393. }
  7394. },
  7395. loopcontrol_target: function(label) {
  7396. var stack = this.stack;
  7397. if (label) for (var i = stack.length; --i >= 0;) {
  7398. var x = stack[i];
  7399. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  7400. return x.body;
  7401. }
  7402. } else for (var i = stack.length; --i >= 0;) {
  7403. var x = stack[i];
  7404. if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
  7405. return x;
  7406. }
  7407. }
  7408. };
  7409. /***********************************************************************
  7410. A JavaScript tokenizer / parser / beautifier / compressor.
  7411. https://github.com/mishoo/UglifyJS2
  7412. -------------------------------- (C) ---------------------------------
  7413. Author: Mihai Bazon
  7414. <mihai.bazon@gmail.com>
  7415. http://mihai.bazon.net/blog
  7416. Distributed under the BSD license:
  7417. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  7418. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  7419. Redistribution and use in source and binary forms, with or without
  7420. modification, are permitted provided that the following conditions
  7421. are met:
  7422. * Redistributions of source code must retain the above
  7423. copyright notice, this list of conditions and the following
  7424. disclaimer.
  7425. * Redistributions in binary form must reproduce the above
  7426. copyright notice, this list of conditions and the following
  7427. disclaimer in the documentation and/or other materials
  7428. provided with the distribution.
  7429. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  7430. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  7431. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  7432. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  7433. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  7434. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  7435. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  7436. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7437. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  7438. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  7439. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  7440. SUCH DAMAGE.
  7441. ***********************************************************************/
  7442. "use strict";
  7443. var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with';
  7444. var KEYWORDS_ATOM = 'false null true';
  7445. var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield'
  7446. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  7447. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  7448. KEYWORDS = makePredicate(KEYWORDS);
  7449. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  7450. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  7451. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  7452. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  7453. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  7454. var RE_OCT_NUMBER = /^0[0-7]+$/;
  7455. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  7456. var OPERATORS = makePredicate([
  7457. "in",
  7458. "instanceof",
  7459. "typeof",
  7460. "new",
  7461. "void",
  7462. "delete",
  7463. "++",
  7464. "--",
  7465. "+",
  7466. "-",
  7467. "!",
  7468. "~",
  7469. "&",
  7470. "|",
  7471. "^",
  7472. "*",
  7473. "/",
  7474. "%",
  7475. ">>",
  7476. "<<",
  7477. ">>>",
  7478. "<",
  7479. ">",
  7480. "<=",
  7481. ">=",
  7482. "==",
  7483. "===",
  7484. "!=",
  7485. "!==",
  7486. "?",
  7487. "=",
  7488. "+=",
  7489. "-=",
  7490. "/=",
  7491. "*=",
  7492. "%=",
  7493. ">>=",
  7494. "<<=",
  7495. ">>>=",
  7496. "|=",
  7497. "^=",
  7498. "&=",
  7499. "&&",
  7500. "||"
  7501. ]);
  7502. var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
  7503. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  7504. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  7505. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  7506. /* -----[ Tokenizer ]----- */
  7507. // regexps adapted from http://xregexp.com/plugins/#unicode
  7508. var UNICODE = {
  7509. letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
  7510. non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  7511. space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
  7512. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  7513. };
  7514. function is_letter(code) {
  7515. return (code >= 97 && code <= 122)
  7516. || (code >= 65 && code <= 90)
  7517. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  7518. };
  7519. function is_digit(code) {
  7520. return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
  7521. };
  7522. function is_alphanumeric_char(code) {
  7523. return is_digit(code) || is_letter(code);
  7524. };
  7525. function is_unicode_combining_mark(ch) {
  7526. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  7527. };
  7528. function is_unicode_connector_punctuation(ch) {
  7529. return UNICODE.connector_punctuation.test(ch);
  7530. };
  7531. function is_identifier(name) {
  7532. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  7533. };
  7534. function is_identifier_start(code) {
  7535. return code == 36 || code == 95 || is_letter(code);
  7536. };
  7537. function is_identifier_char(ch) {
  7538. var code = ch.charCodeAt(0);
  7539. return is_identifier_start(code)
  7540. || is_digit(code)
  7541. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  7542. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  7543. || is_unicode_combining_mark(ch)
  7544. || is_unicode_connector_punctuation(ch)
  7545. ;
  7546. };
  7547. function is_identifier_string(str){
  7548. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  7549. };
  7550. function parse_js_number(num) {
  7551. if (RE_HEX_NUMBER.test(num)) {
  7552. return parseInt(num.substr(2), 16);
  7553. } else if (RE_OCT_NUMBER.test(num)) {
  7554. return parseInt(num.substr(1), 8);
  7555. } else if (RE_DEC_NUMBER.test(num)) {
  7556. return parseFloat(num);
  7557. }
  7558. };
  7559. function JS_Parse_Error(message, line, col, pos) {
  7560. this.message = message;
  7561. this.line = line;
  7562. this.col = col;
  7563. this.pos = pos;
  7564. this.stack = new Error().stack;
  7565. };
  7566. JS_Parse_Error.prototype.toString = function() {
  7567. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  7568. };
  7569. function js_error(message, filename, line, col, pos) {
  7570. throw new JS_Parse_Error(message, line, col, pos);
  7571. };
  7572. function is_token(token, type, val) {
  7573. return token.type == type && (val == null || token.value == val);
  7574. };
  7575. var EX_EOF = {};
  7576. function tokenizer($TEXT, filename, html5_comments) {
  7577. var S = {
  7578. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''),
  7579. filename : filename,
  7580. pos : 0,
  7581. tokpos : 0,
  7582. line : 1,
  7583. tokline : 0,
  7584. col : 0,
  7585. tokcol : 0,
  7586. newline_before : false,
  7587. regex_allowed : false,
  7588. comments_before : []
  7589. };
  7590. function peek() { return S.text.charAt(S.pos); };
  7591. function next(signal_eof, in_string) {
  7592. var ch = S.text.charAt(S.pos++);
  7593. if (signal_eof && !ch)
  7594. throw EX_EOF;
  7595. if (ch == "\n") {
  7596. S.newline_before = S.newline_before || !in_string;
  7597. ++S.line;
  7598. S.col = 0;
  7599. } else {
  7600. ++S.col;
  7601. }
  7602. return ch;
  7603. };
  7604. function forward(i) {
  7605. while (i-- > 0) next();
  7606. };
  7607. function looking_at(str) {
  7608. return S.text.substr(S.pos, str.length) == str;
  7609. };
  7610. function find(what, signal_eof) {
  7611. var pos = S.text.indexOf(what, S.pos);
  7612. if (signal_eof && pos == -1) throw EX_EOF;
  7613. return pos;
  7614. };
  7615. function start_token() {
  7616. S.tokline = S.line;
  7617. S.tokcol = S.col;
  7618. S.tokpos = S.pos;
  7619. };
  7620. var prev_was_dot = false;
  7621. function token(type, value, is_comment) {
  7622. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  7623. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  7624. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  7625. prev_was_dot = (type == "punc" && value == ".");
  7626. var ret = {
  7627. type : type,
  7628. value : value,
  7629. line : S.tokline,
  7630. col : S.tokcol,
  7631. pos : S.tokpos,
  7632. endpos : S.pos,
  7633. nlb : S.newline_before,
  7634. file : filename
  7635. };
  7636. if (!is_comment) {
  7637. ret.comments_before = S.comments_before;
  7638. S.comments_before = [];
  7639. // make note of any newlines in the comments that came before
  7640. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  7641. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  7642. }
  7643. }
  7644. S.newline_before = false;
  7645. return new AST_Token(ret);
  7646. };
  7647. function skip_whitespace() {
  7648. while (WHITESPACE_CHARS(peek()))
  7649. next();
  7650. };
  7651. function read_while(pred) {
  7652. var ret = "", ch, i = 0;
  7653. while ((ch = peek()) && pred(ch, i++))
  7654. ret += next();
  7655. return ret;
  7656. };
  7657. function parse_error(err) {
  7658. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  7659. };
  7660. function read_num(prefix) {
  7661. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  7662. var num = read_while(function(ch, i){
  7663. var code = ch.charCodeAt(0);
  7664. switch (code) {
  7665. case 120: case 88: // xX
  7666. return has_x ? false : (has_x = true);
  7667. case 101: case 69: // eE
  7668. return has_x ? true : has_e ? false : (has_e = after_e = true);
  7669. case 45: // -
  7670. return after_e || (i == 0 && !prefix);
  7671. case 43: // +
  7672. return after_e;
  7673. case (after_e = false, 46): // .
  7674. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  7675. }
  7676. return is_alphanumeric_char(code);
  7677. });
  7678. if (prefix) num = prefix + num;
  7679. var valid = parse_js_number(num);
  7680. if (!isNaN(valid)) {
  7681. return token("num", valid);
  7682. } else {
  7683. parse_error("Invalid syntax: " + num);
  7684. }
  7685. };
  7686. function read_escaped_char(in_string) {
  7687. var ch = next(true, in_string);
  7688. switch (ch.charCodeAt(0)) {
  7689. case 110 : return "\n";
  7690. case 114 : return "\r";
  7691. case 116 : return "\t";
  7692. case 98 : return "\b";
  7693. case 118 : return "\u000b"; // \v
  7694. case 102 : return "\f";
  7695. case 48 : return "\0";
  7696. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  7697. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  7698. case 10 : return ""; // newline
  7699. default : return ch;
  7700. }
  7701. };
  7702. function hex_bytes(n) {
  7703. var num = 0;
  7704. for (; n > 0; --n) {
  7705. var digit = parseInt(next(true), 16);
  7706. if (isNaN(digit))
  7707. parse_error("Invalid hex-character pattern in string");
  7708. num = (num << 4) | digit;
  7709. }
  7710. return num;
  7711. };
  7712. var read_string = with_eof_error("Unterminated string constant", function(){
  7713. var quote = next(), ret = "";
  7714. for (;;) {
  7715. var ch = next(true);
  7716. if (ch == "\\") {
  7717. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  7718. // https://github.com/mishoo/UglifyJS/issues/178
  7719. var octal_len = 0, first = null;
  7720. ch = read_while(function(ch){
  7721. if (ch >= "0" && ch <= "7") {
  7722. if (!first) {
  7723. first = ch;
  7724. return ++octal_len;
  7725. }
  7726. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  7727. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  7728. }
  7729. return false;
  7730. });
  7731. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  7732. else ch = read_escaped_char(true);
  7733. }
  7734. else if (ch == quote) break;
  7735. ret += ch;
  7736. }
  7737. return token("string", ret);
  7738. });
  7739. function skip_line_comment(type) {
  7740. var regex_allowed = S.regex_allowed;
  7741. var i = find("\n"), ret;
  7742. if (i == -1) {
  7743. ret = S.text.substr(S.pos);
  7744. S.pos = S.text.length;
  7745. } else {
  7746. ret = S.text.substring(S.pos, i);
  7747. S.pos = i;
  7748. }
  7749. S.comments_before.push(token(type, ret, true));
  7750. S.regex_allowed = regex_allowed;
  7751. return next_token();
  7752. };
  7753. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
  7754. var regex_allowed = S.regex_allowed;
  7755. var i = find("*/", true);
  7756. var text = S.text.substring(S.pos, i);
  7757. var a = text.split("\n"), n = a.length;
  7758. // update stream position
  7759. S.pos = i + 2;
  7760. S.line += n - 1;
  7761. if (n > 1) S.col = a[n - 1].length;
  7762. else S.col += a[n - 1].length;
  7763. S.col += 2;
  7764. var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  7765. S.comments_before.push(token("comment2", text, true));
  7766. S.regex_allowed = regex_allowed;
  7767. S.newline_before = nlb;
  7768. return next_token();
  7769. });
  7770. function read_name() {
  7771. var backslash = false, name = "", ch, escaped = false, hex;
  7772. while ((ch = peek()) != null) {
  7773. if (!backslash) {
  7774. if (ch == "\\") escaped = backslash = true, next();
  7775. else if (is_identifier_char(ch)) name += next();
  7776. else break;
  7777. }
  7778. else {
  7779. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  7780. ch = read_escaped_char();
  7781. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  7782. name += ch;
  7783. backslash = false;
  7784. }
  7785. }
  7786. if (KEYWORDS(name) && escaped) {
  7787. hex = name.charCodeAt(0).toString(16).toUpperCase();
  7788. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  7789. }
  7790. return name;
  7791. };
  7792. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
  7793. var prev_backslash = false, ch, in_class = false;
  7794. while ((ch = next(true))) if (prev_backslash) {
  7795. regexp += "\\" + ch;
  7796. prev_backslash = false;
  7797. } else if (ch == "[") {
  7798. in_class = true;
  7799. regexp += ch;
  7800. } else if (ch == "]" && in_class) {
  7801. in_class = false;
  7802. regexp += ch;
  7803. } else if (ch == "/" && !in_class) {
  7804. break;
  7805. } else if (ch == "\\") {
  7806. prev_backslash = true;
  7807. } else {
  7808. regexp += ch;
  7809. }
  7810. var mods = read_name();
  7811. return token("regexp", new RegExp(regexp, mods));
  7812. });
  7813. function read_operator(prefix) {
  7814. function grow(op) {
  7815. if (!peek()) return op;
  7816. var bigger = op + peek();
  7817. if (OPERATORS(bigger)) {
  7818. next();
  7819. return grow(bigger);
  7820. } else {
  7821. return op;
  7822. }
  7823. };
  7824. return token("operator", grow(prefix || next()));
  7825. };
  7826. function handle_slash() {
  7827. next();
  7828. switch (peek()) {
  7829. case "/":
  7830. next();
  7831. return skip_line_comment("comment1");
  7832. case "*":
  7833. next();
  7834. return skip_multiline_comment();
  7835. }
  7836. return S.regex_allowed ? read_regexp("") : read_operator("/");
  7837. };
  7838. function handle_dot() {
  7839. next();
  7840. return is_digit(peek().charCodeAt(0))
  7841. ? read_num(".")
  7842. : token("punc", ".");
  7843. };
  7844. function read_word() {
  7845. var word = read_name();
  7846. if (prev_was_dot) return token("name", word);
  7847. return KEYWORDS_ATOM(word) ? token("atom", word)
  7848. : !KEYWORDS(word) ? token("name", word)
  7849. : OPERATORS(word) ? token("operator", word)
  7850. : token("keyword", word);
  7851. };
  7852. function with_eof_error(eof_error, cont) {
  7853. return function(x) {
  7854. try {
  7855. return cont(x);
  7856. } catch(ex) {
  7857. if (ex === EX_EOF) parse_error(eof_error);
  7858. else throw ex;
  7859. }
  7860. };
  7861. };
  7862. function next_token(force_regexp) {
  7863. if (force_regexp != null)
  7864. return read_regexp(force_regexp);
  7865. skip_whitespace();
  7866. start_token();
  7867. if (html5_comments) {
  7868. if (looking_at("<!--")) {
  7869. forward(4);
  7870. return skip_line_comment("comment3");
  7871. }
  7872. if (looking_at("-->") && S.newline_before) {
  7873. forward(3);
  7874. return skip_line_comment("comment4");
  7875. }
  7876. }
  7877. var ch = peek();
  7878. if (!ch) return token("eof");
  7879. var code = ch.charCodeAt(0);
  7880. switch (code) {
  7881. case 34: case 39: return read_string();
  7882. case 46: return handle_dot();
  7883. case 47: return handle_slash();
  7884. }
  7885. if (is_digit(code)) return read_num();
  7886. if (PUNC_CHARS(ch)) return token("punc", next());
  7887. if (OPERATOR_CHARS(ch)) return read_operator();
  7888. if (code == 92 || is_identifier_start(code)) return read_word();
  7889. parse_error("Unexpected character '" + ch + "'");
  7890. };
  7891. next_token.context = function(nc) {
  7892. if (nc) S = nc;
  7893. return S;
  7894. };
  7895. return next_token;
  7896. };
  7897. /* -----[ Parser (constants) ]----- */
  7898. var UNARY_PREFIX = makePredicate([
  7899. "typeof",
  7900. "void",
  7901. "delete",
  7902. "--",
  7903. "++",
  7904. "!",
  7905. "~",
  7906. "-",
  7907. "+"
  7908. ]);
  7909. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  7910. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  7911. var PRECEDENCE = (function(a, ret){
  7912. for (var i = 0; i < a.length; ++i) {
  7913. var b = a[i];
  7914. for (var j = 0; j < b.length; ++j) {
  7915. ret[b[j]] = i + 1;
  7916. }
  7917. }
  7918. return ret;
  7919. })(
  7920. [
  7921. ["||"],
  7922. ["&&"],
  7923. ["|"],
  7924. ["^"],
  7925. ["&"],
  7926. ["==", "===", "!=", "!=="],
  7927. ["<", ">", "<=", ">=", "in", "instanceof"],
  7928. [">>", "<<", ">>>"],
  7929. ["+", "-"],
  7930. ["*", "/", "%"]
  7931. ],
  7932. {}
  7933. );
  7934. var STATEMENTS_WITH_LABELS = array_to_hash([ "fo" + "r", "do", "while", "switch" ]);
  7935. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  7936. /* -----[ Parser ]----- */
  7937. function parse($TEXT, options) {
  7938. options = defaults(options, {
  7939. strict : false,
  7940. filename : null,
  7941. toplevel : null,
  7942. expression : false,
  7943. html5_comments : true,
  7944. });
  7945. var S = {
  7946. input : (typeof $TEXT == "string"
  7947. ? tokenizer($TEXT, options.filename,
  7948. options.html5_comments)
  7949. : $TEXT),
  7950. token : null,
  7951. prev : null,
  7952. peeked : null,
  7953. in_function : 0,
  7954. in_directives : true,
  7955. in_loop : 0,
  7956. labels : []
  7957. };
  7958. S.token = next();
  7959. function is(type, value) {
  7960. return is_token(S.token, type, value);
  7961. };
  7962. function peek() { return S.peeked || (S.peeked = S.input()); };
  7963. function next() {
  7964. S.prev = S.token;
  7965. if (S.peeked) {
  7966. S.token = S.peeked;
  7967. S.peeked = null;
  7968. } else {
  7969. S.token = S.input();
  7970. }
  7971. S.in_directives = S.in_directives && (
  7972. S.token.type == "string" || is("punc", ";")
  7973. );
  7974. return S.token;
  7975. };
  7976. function prev() {
  7977. return S.prev;
  7978. };
  7979. function croak(msg, line, col, pos) {
  7980. var ctx = S.input.context();
  7981. js_error(msg,
  7982. ctx.filename,
  7983. line != null ? line : ctx.tokline,
  7984. col != null ? col : ctx.tokcol,
  7985. pos != null ? pos : ctx.tokpos);
  7986. };
  7987. function token_error(token, msg) {
  7988. croak(msg, token.line, token.col);
  7989. };
  7990. function unexpected(token) {
  7991. if (token == null)
  7992. token = S.token;
  7993. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  7994. };
  7995. function expect_token(type, val) {
  7996. if (is(type, val)) {
  7997. return next();
  7998. }
  7999. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  8000. };
  8001. function expect(punc) { return expect_token("punc", punc); };
  8002. function can_insert_semicolon() {
  8003. return !options.strict && (
  8004. S.token.nlb || is("eof") || is("punc", "}")
  8005. );
  8006. };
  8007. function semicolon() {
  8008. if (is("punc", ";")) next();
  8009. else if (!can_insert_semicolon()) unexpected();
  8010. };
  8011. function parenthesised() {
  8012. expect("(");
  8013. var exp = expression(true);
  8014. expect(")");
  8015. return exp;
  8016. };
  8017. function embed_tokens(parser) {
  8018. return function() {
  8019. var start = S.token;
  8020. var expr = parser();
  8021. var end = prev();
  8022. expr.start = start;
  8023. expr.end = end;
  8024. return expr;
  8025. };
  8026. };
  8027. function handle_regexp() {
  8028. if (is("operator", "/") || is("operator", "/=")) {
  8029. S.peeked = null;
  8030. S.token = S.input(S.token.value.substr(1)); // force regexp
  8031. }
  8032. };
  8033. var statement = embed_tokens(function() {
  8034. var tmp;
  8035. handle_regexp();
  8036. switch (S.token.type) {
  8037. case "string":
  8038. var dir = S.in_directives, stat = simple_statement();
  8039. // XXXv2: decide how to fix directives
  8040. if (dir && stat.body instanceof AST_String && !is("punc", ","))
  8041. return new AST_Directive({ value: stat.body.value });
  8042. return stat;
  8043. case "num":
  8044. case "regexp":
  8045. case "operator":
  8046. case "atom":
  8047. return simple_statement();
  8048. case "name":
  8049. return is_token(peek(), "punc", ":")
  8050. ? labeled_statement()
  8051. : simple_statement();
  8052. case "punc":
  8053. switch (S.token.value) {
  8054. case "{":
  8055. return new AST_BlockStatement({
  8056. start : S.token,
  8057. body : block_(),
  8058. end : prev()
  8059. });
  8060. case "[":
  8061. case "(":
  8062. return simple_statement();
  8063. case ";":
  8064. next();
  8065. return new AST_EmptyStatement();
  8066. default:
  8067. unexpected();
  8068. }
  8069. case "keyword":
  8070. switch (tmp = S.token.value, next(), tmp) {
  8071. case "break":
  8072. return break_cont(AST_Break);
  8073. case "continue":
  8074. return break_cont(AST_Continue);
  8075. case "debugger":
  8076. semicolon();
  8077. return new AST_Debugger();
  8078. case "do":
  8079. return new AST_Do({
  8080. body : in_loop(statement),
  8081. condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
  8082. });
  8083. case "while":
  8084. return new AST_While({
  8085. condition : parenthesised(),
  8086. body : in_loop(statement)
  8087. });
  8088. case "fo" + "r":
  8089. return for_();
  8090. case "function":
  8091. return function_(AST_Defun);
  8092. case "if":
  8093. return if_();
  8094. case "return":
  8095. if (S.in_function == 0)
  8096. croak("'return' outside of function");
  8097. return new AST_Return({
  8098. value: ( is("punc", ";")
  8099. ? (next(), null)
  8100. : can_insert_semicolon()
  8101. ? null
  8102. : (tmp = expression(true), semicolon(), tmp) )
  8103. });
  8104. case "switch":
  8105. return new AST_Switch({
  8106. expression : parenthesised(),
  8107. body : in_loop(switch_body_)
  8108. });
  8109. case "throw":
  8110. if (S.token.nlb)
  8111. croak("Illegal newline after 'throw'");
  8112. return new AST_Throw({
  8113. value: (tmp = expression(true), semicolon(), tmp)
  8114. });
  8115. case "try":
  8116. return try_();
  8117. case "var":
  8118. return tmp = var_(), semicolon(), tmp;
  8119. case "const":
  8120. return tmp = const_(), semicolon(), tmp;
  8121. case "with":
  8122. return new AST_With({
  8123. expression : parenthesised(),
  8124. body : statement()
  8125. });
  8126. default:
  8127. unexpected();
  8128. }
  8129. }
  8130. });
  8131. function labeled_statement() {
  8132. var label = as_symbol(AST_Label);
  8133. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  8134. // ECMA-262, 12.12: An ECMAScript program is considered
  8135. // syntactically incorrect if it contains a
  8136. // LabelledStatement that is enclosed by a
  8137. // LabelledStatement with the same Identifier as label.
  8138. croak("Label " + label.name + " defined twice");
  8139. }
  8140. expect(":");
  8141. S.labels.push(label);
  8142. var stat = statement();
  8143. S.labels.pop();
  8144. if (!(stat instanceof AST_IterationStatement)) {
  8145. // check for `continue` that refers to this label.
  8146. // those should be reported as syntax errors.
  8147. // https://github.com/mishoo/UglifyJS2/issues/287
  8148. label.references.forEach(function(ref){
  8149. if (ref instanceof AST_Continue) {
  8150. ref = ref.label.start;
  8151. croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
  8152. ref.line, ref.col, ref.pos);
  8153. }
  8154. });
  8155. }
  8156. return new AST_LabeledStatement({ body: stat, label: label });
  8157. };
  8158. function simple_statement(tmp) {
  8159. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  8160. };
  8161. function break_cont(type) {
  8162. var label = null, ldef;
  8163. if (!can_insert_semicolon()) {
  8164. label = as_symbol(AST_LabelRef, true);
  8165. }
  8166. if (label != null) {
  8167. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  8168. if (!ldef)
  8169. croak("Undefined label " + label.name);
  8170. label.thedef = ldef;
  8171. }
  8172. else if (S.in_loop == 0)
  8173. croak(type.TYPE + " not inside a loop or switch");
  8174. semicolon();
  8175. var stat = new type({ label: label });
  8176. if (ldef) ldef.references.push(stat);
  8177. return stat;
  8178. };
  8179. function for_() {
  8180. expect("(");
  8181. var init = null;
  8182. if (!is("punc", ";")) {
  8183. init = is("keyword", "var")
  8184. ? (next(), var_(true))
  8185. : expression(true, true);
  8186. if (is("operator", "in")) {
  8187. if (init instanceof AST_Var && init.definitions.length > 1)
  8188. croak("Only one variable declaration allowed in for..in loop");
  8189. next();
  8190. return for_in(init);
  8191. }
  8192. }
  8193. return regular_for(init);
  8194. };
  8195. function regular_for(init) {
  8196. expect(";");
  8197. var test = is("punc", ";") ? null : expression(true);
  8198. expect(";");
  8199. var step = is("punc", ")") ? null : expression(true);
  8200. expect(")");
  8201. return new AST_For({
  8202. init : init,
  8203. condition : test,
  8204. step : step,
  8205. body : in_loop(statement)
  8206. });
  8207. };
  8208. function for_in(init) {
  8209. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  8210. var obj = expression(true);
  8211. expect(")");
  8212. return new AST_ForIn({
  8213. init : init,
  8214. name : lhs,
  8215. object : obj,
  8216. body : in_loop(statement)
  8217. });
  8218. };
  8219. var function_ = function(ctor) {
  8220. var in_statement = ctor === AST_Defun;
  8221. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  8222. if (in_statement && !name)
  8223. unexpected();
  8224. expect("(");
  8225. return new ctor({
  8226. name: name,
  8227. argnames: (function(first, a){
  8228. while (!is("punc", ")")) {
  8229. if (first) first = false; else expect(",");
  8230. a.push(as_symbol(AST_SymbolFunarg));
  8231. }
  8232. next();
  8233. return a;
  8234. })(true, []),
  8235. body: (function(loop, labels){
  8236. ++S.in_function;
  8237. S.in_directives = true;
  8238. S.in_loop = 0;
  8239. S.labels = [];
  8240. var a = block_();
  8241. --S.in_function;
  8242. S.in_loop = loop;
  8243. S.labels = labels;
  8244. return a;
  8245. })(S.in_loop, S.labels)
  8246. });
  8247. };
  8248. function if_() {
  8249. var cond = parenthesised(), body = statement(), belse = null;
  8250. if (is("keyword", "else")) {
  8251. next();
  8252. belse = statement();
  8253. }
  8254. return new AST_If({
  8255. condition : cond,
  8256. body : body,
  8257. alternative : belse
  8258. });
  8259. };
  8260. function block_() {
  8261. expect("{");
  8262. var a = [];
  8263. while (!is("punc", "}")) {
  8264. if (is("eof")) unexpected();
  8265. a.push(statement());
  8266. }
  8267. next();
  8268. return a;
  8269. };
  8270. function switch_body_() {
  8271. expect("{");
  8272. var a = [], cur = null, branch = null, tmp;
  8273. while (!is("punc", "}")) {
  8274. if (is("eof")) unexpected();
  8275. if (is("keyword", "case")) {
  8276. if (branch) branch.end = prev();
  8277. cur = [];
  8278. branch = new AST_Case({
  8279. start : (tmp = S.token, next(), tmp),
  8280. expression : expression(true),
  8281. body : cur
  8282. });
  8283. a.push(branch);
  8284. expect(":");
  8285. }
  8286. else if (is("keyword", "default")) {
  8287. if (branch) branch.end = prev();
  8288. cur = [];
  8289. branch = new AST_Default({
  8290. start : (tmp = S.token, next(), expect(":"), tmp),
  8291. body : cur
  8292. });
  8293. a.push(branch);
  8294. }
  8295. else {
  8296. if (!cur) unexpected();
  8297. cur.push(statement());
  8298. }
  8299. }
  8300. if (branch) branch.end = prev();
  8301. next();
  8302. return a;
  8303. };
  8304. function try_() {
  8305. var body = block_(), bcatch = null, bfinally = null;
  8306. if (is("keyword", "catch")) {
  8307. var start = S.token;
  8308. next();
  8309. expect("(");
  8310. var name = as_symbol(AST_SymbolCatch);
  8311. expect(")");
  8312. bcatch = new AST_Catch({
  8313. start : start,
  8314. argname : name,
  8315. body : block_(),
  8316. end : prev()
  8317. });
  8318. }
  8319. if (is("keyword", "finally")) {
  8320. var start = S.token;
  8321. next();
  8322. bfinally = new AST_Finally({
  8323. start : start,
  8324. body : block_(),
  8325. end : prev()
  8326. });
  8327. }
  8328. if (!bcatch && !bfinally)
  8329. croak("Missing catch/finally blocks");
  8330. return new AST_Try({
  8331. body : body,
  8332. bcatch : bcatch,
  8333. bfinally : bfinally
  8334. });
  8335. };
  8336. function vardefs(no_in, in_const) {
  8337. var a = [];
  8338. for (;;) {
  8339. a.push(new AST_VarDef({
  8340. start : S.token,
  8341. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  8342. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  8343. end : prev()
  8344. }));
  8345. if (!is("punc", ","))
  8346. break;
  8347. next();
  8348. }
  8349. return a;
  8350. };
  8351. var var_ = function(no_in) {
  8352. return new AST_Var({
  8353. start : prev(),
  8354. definitions : vardefs(no_in, false),
  8355. end : prev()
  8356. });
  8357. };
  8358. var const_ = function() {
  8359. return new AST_Const({
  8360. start : prev(),
  8361. definitions : vardefs(false, true),
  8362. end : prev()
  8363. });
  8364. };
  8365. var new_ = function() {
  8366. var start = S.token;
  8367. expect_token("operator", "new");
  8368. var newexp = expr_atom(false), args;
  8369. if (is("punc", "(")) {
  8370. next();
  8371. args = expr_list(")");
  8372. } else {
  8373. args = [];
  8374. }
  8375. return subscripts(new AST_New({
  8376. start : start,
  8377. expression : newexp,
  8378. args : args,
  8379. end : prev()
  8380. }), true);
  8381. };
  8382. function as_atom_node() {
  8383. var tok = S.token, ret;
  8384. switch (tok.type) {
  8385. case "name":
  8386. case "keyword":
  8387. ret = _make_symbol(AST_SymbolRef);
  8388. break;
  8389. case "num":
  8390. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  8391. break;
  8392. case "string":
  8393. ret = new AST_String({ start: tok, end: tok, value: tok.value });
  8394. break;
  8395. case "regexp":
  8396. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  8397. break;
  8398. case "atom":
  8399. switch (tok.value) {
  8400. case "false":
  8401. ret = new AST_False({ start: tok, end: tok });
  8402. break;
  8403. case "true":
  8404. ret = new AST_True({ start: tok, end: tok });
  8405. break;
  8406. case "null":
  8407. ret = new AST_Null({ start: tok, end: tok });
  8408. break;
  8409. }
  8410. break;
  8411. }
  8412. next();
  8413. return ret;
  8414. };
  8415. var expr_atom = function(allow_calls) {
  8416. if (is("operator", "new")) {
  8417. return new_();
  8418. }
  8419. var start = S.token;
  8420. if (is("punc")) {
  8421. switch (start.value) {
  8422. case "(":
  8423. next();
  8424. var ex = expression(true);
  8425. ex.start = start;
  8426. ex.end = S.token;
  8427. expect(")");
  8428. return subscripts(ex, allow_calls);
  8429. case "[":
  8430. return subscripts(array_(), allow_calls);
  8431. case "{":
  8432. return subscripts(object_(), allow_calls);
  8433. }
  8434. unexpected();
  8435. }
  8436. if (is("keyword", "function")) {
  8437. next();
  8438. var func = function_(AST_Function);
  8439. func.start = start;
  8440. func.end = prev();
  8441. return subscripts(func, allow_calls);
  8442. }
  8443. if (ATOMIC_START_TOKEN[S.token.type]) {
  8444. return subscripts(as_atom_node(), allow_calls);
  8445. }
  8446. unexpected();
  8447. };
  8448. function expr_list(closing, allow_trailing_comma, allow_empty) {
  8449. var first = true, a = [];
  8450. while (!is("punc", closing)) {
  8451. if (first) first = false; else expect(",");
  8452. if (allow_trailing_comma && is("punc", closing)) break;
  8453. if (is("punc", ",") && allow_empty) {
  8454. a.push(new AST_Hole({ start: S.token, end: S.token }));
  8455. } else {
  8456. a.push(expression(false));
  8457. }
  8458. }
  8459. next();
  8460. return a;
  8461. };
  8462. var array_ = embed_tokens(function() {
  8463. expect("[");
  8464. return new AST_Array({
  8465. elements: expr_list("]", !options.strict, true)
  8466. });
  8467. });
  8468. var object_ = embed_tokens(function() {
  8469. expect("{");
  8470. var first = true, a = [];
  8471. while (!is("punc", "}")) {
  8472. if (first) first = false; else expect(",");
  8473. if (!options.strict && is("punc", "}"))
  8474. // allow trailing comma
  8475. break;
  8476. var start = S.token;
  8477. var type = start.type;
  8478. var name = as_property_name();
  8479. if (type == "name" && !is("punc", ":")) {
  8480. if (name == "get") {
  8481. a.push(new AST_ObjectGetter({
  8482. start : start,
  8483. key : as_atom_node(),
  8484. value : function_(AST_Accessor),
  8485. end : prev()
  8486. }));
  8487. continue;
  8488. }
  8489. if (name == "set") {
  8490. a.push(new AST_ObjectSetter({
  8491. start : start,
  8492. key : as_atom_node(),
  8493. value : function_(AST_Accessor),
  8494. end : prev()
  8495. }));
  8496. continue;
  8497. }
  8498. }
  8499. expect(":");
  8500. a.push(new AST_ObjectKeyVal({
  8501. start : start,
  8502. key : name,
  8503. value : expression(false),
  8504. end : prev()
  8505. }));
  8506. }
  8507. next();
  8508. return new AST_Object({ properties: a });
  8509. });
  8510. function as_property_name() {
  8511. var tmp = S.token;
  8512. next();
  8513. switch (tmp.type) {
  8514. case "num":
  8515. case "string":
  8516. case "name":
  8517. case "operator":
  8518. case "keyword":
  8519. case "atom":
  8520. return tmp.value;
  8521. default:
  8522. unexpected();
  8523. }
  8524. };
  8525. function as_name() {
  8526. var tmp = S.token;
  8527. next();
  8528. switch (tmp.type) {
  8529. case "name":
  8530. case "operator":
  8531. case "keyword":
  8532. case "atom":
  8533. return tmp.value;
  8534. default:
  8535. unexpected();
  8536. }
  8537. };
  8538. function _make_symbol(type) {
  8539. var name = S.token.value;
  8540. return new (name == "this" ? AST_This : type)({
  8541. name : String(name),
  8542. start : S.token,
  8543. end : S.token
  8544. });
  8545. };
  8546. function as_symbol(type, noerror) {
  8547. if (!is("name")) {
  8548. if (!noerror) croak("Name expected");
  8549. return null;
  8550. }
  8551. var sym = _make_symbol(type);
  8552. next();
  8553. return sym;
  8554. };
  8555. var subscripts = function(expr, allow_calls) {
  8556. var start = expr.start;
  8557. if (is("punc", ".")) {
  8558. next();
  8559. return subscripts(new AST_Dot({
  8560. start : start,
  8561. expression : expr,
  8562. property : as_name(),
  8563. end : prev()
  8564. }), allow_calls);
  8565. }
  8566. if (is("punc", "[")) {
  8567. next();
  8568. var prop = expression(true);
  8569. expect("]");
  8570. return subscripts(new AST_Sub({
  8571. start : start,
  8572. expression : expr,
  8573. property : prop,
  8574. end : prev()
  8575. }), allow_calls);
  8576. }
  8577. if (allow_calls && is("punc", "(")) {
  8578. next();
  8579. return subscripts(new AST_Call({
  8580. start : start,
  8581. expression : expr,
  8582. args : expr_list(")"),
  8583. end : prev()
  8584. }), true);
  8585. }
  8586. return expr;
  8587. };
  8588. var maybe_unary = function(allow_calls) {
  8589. var start = S.token;
  8590. if (is("operator") && UNARY_PREFIX(start.value)) {
  8591. next();
  8592. handle_regexp();
  8593. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  8594. ex.start = start;
  8595. ex.end = prev();
  8596. return ex;
  8597. }
  8598. var val = expr_atom(allow_calls);
  8599. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  8600. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  8601. val.start = start;
  8602. val.end = S.token;
  8603. next();
  8604. }
  8605. return val;
  8606. };
  8607. function make_unary(ctor, op, expr) {
  8608. if ((op == "++" || op == "--") && !is_assignable(expr))
  8609. croak("Invalid use of " + op + " operator");
  8610. return new ctor({ operator: op, expression: expr });
  8611. };
  8612. var expr_op = function(left, min_prec, no_in) {
  8613. var op = is("operator") ? S.token.value : null;
  8614. if (op == "in" && no_in) op = null;
  8615. var prec = op != null ? PRECEDENCE[op] : null;
  8616. if (prec != null && prec > min_prec) {
  8617. next();
  8618. var right = expr_op(maybe_unary(true), prec, no_in);
  8619. return expr_op(new AST_Binary({
  8620. start : left.start,
  8621. left : left,
  8622. operator : op,
  8623. right : right,
  8624. end : right.end
  8625. }), min_prec, no_in);
  8626. }
  8627. return left;
  8628. };
  8629. function expr_ops(no_in) {
  8630. return expr_op(maybe_unary(true), 0, no_in);
  8631. };
  8632. var maybe_conditional = function(no_in) {
  8633. var start = S.token;
  8634. var expr = expr_ops(no_in);
  8635. if (is("operator", "?")) {
  8636. next();
  8637. var yes = expression(false);
  8638. expect(":");
  8639. return new AST_Conditional({
  8640. start : start,
  8641. condition : expr,
  8642. consequent : yes,
  8643. alternative : expression(false, no_in),
  8644. end : prev()
  8645. });
  8646. }
  8647. return expr;
  8648. };
  8649. function is_assignable(expr) {
  8650. if (!options.strict) return true;
  8651. if (expr instanceof AST_This) return false;
  8652. return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
  8653. };
  8654. var maybe_assign = function(no_in) {
  8655. var start = S.token;
  8656. var left = maybe_conditional(no_in), val = S.token.value;
  8657. if (is("operator") && ASSIGNMENT(val)) {
  8658. if (is_assignable(left)) {
  8659. next();
  8660. return new AST_Assign({
  8661. start : start,
  8662. left : left,
  8663. operator : val,
  8664. right : maybe_assign(no_in),
  8665. end : prev()
  8666. });
  8667. }
  8668. croak("Invalid assignment");
  8669. }
  8670. return left;
  8671. };
  8672. var expression = function(commas, no_in) {
  8673. var start = S.token;
  8674. var expr = maybe_assign(no_in);
  8675. if (commas && is("punc", ",")) {
  8676. next();
  8677. return new AST_Seq({
  8678. start : start,
  8679. car : expr,
  8680. cdr : expression(true, no_in),
  8681. end : peek()
  8682. });
  8683. }
  8684. return expr;
  8685. };
  8686. function in_loop(cont) {
  8687. ++S.in_loop;
  8688. var ret = cont();
  8689. --S.in_loop;
  8690. return ret;
  8691. };
  8692. if (options.expression) {
  8693. return expression(true);
  8694. }
  8695. return (function(){
  8696. var start = S.token;
  8697. var body = [];
  8698. while (!is("eof"))
  8699. body.push(statement());
  8700. var end = prev();
  8701. var toplevel = options.toplevel;
  8702. if (toplevel) {
  8703. toplevel.body = toplevel.body.concat(body);
  8704. toplevel.end = end;
  8705. } else {
  8706. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  8707. }
  8708. return toplevel;
  8709. })();
  8710. };
  8711. /***********************************************************************
  8712. A JavaScript tokenizer / parser / beautifier / compressor.
  8713. https://github.com/mishoo/UglifyJS2
  8714. -------------------------------- (C) ---------------------------------
  8715. Author: Mihai Bazon
  8716. <mihai.bazon@gmail.com>
  8717. http://mihai.bazon.net/blog
  8718. Distributed under the BSD license:
  8719. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  8720. Redistribution and use in source and binary forms, with or without
  8721. modification, are permitted provided that the following conditions
  8722. are met:
  8723. * Redistributions of source code must retain the above
  8724. copyright notice, this list of conditions and the following
  8725. disclaimer.
  8726. * Redistributions in binary form must reproduce the above
  8727. copyright notice, this list of conditions and the following
  8728. disclaimer in the documentation and/or other materials
  8729. provided with the distribution.
  8730. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  8731. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8732. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  8733. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  8734. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  8735. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  8736. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  8737. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8738. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  8739. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  8740. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  8741. SUCH DAMAGE.
  8742. ***********************************************************************/
  8743. "use strict";
  8744. // Tree transformer helpers.
  8745. function TreeTransformer(before, after) {
  8746. TreeWalker.call(this);
  8747. this.before = before;
  8748. this.after = after;
  8749. }
  8750. TreeTransformer.prototype = new TreeWalker;
  8751. (function(undefined){
  8752. function _(node, descend) {
  8753. node.DEFMETHOD("transform", function(tw, in_list){
  8754. var x, y;
  8755. tw.push(this);
  8756. if (tw.before) x = tw.before(this, descend, in_list);
  8757. if (x === undefined) {
  8758. if (!tw.after) {
  8759. x = this;
  8760. descend(x, tw);
  8761. } else {
  8762. tw.stack[tw.stack.length - 1] = x = this.clone();
  8763. descend(x, tw);
  8764. y = tw.after(x, in_list);
  8765. if (y !== undefined) x = y;
  8766. }
  8767. }
  8768. tw.pop();
  8769. return x;
  8770. });
  8771. };
  8772. function do_list(list, tw) {
  8773. return MAP(list, function(node){
  8774. return node.transform(tw, true);
  8775. });
  8776. };
  8777. _(AST_Node, noop);
  8778. _(AST_LabeledStatement, function(self, tw){
  8779. self.label = self.label.transform(tw);
  8780. self.body = self.body.transform(tw);
  8781. });
  8782. _(AST_SimpleStatement, function(self, tw){
  8783. self.body = self.body.transform(tw);
  8784. });
  8785. _(AST_Block, function(self, tw){
  8786. self.body = do_list(self.body, tw);
  8787. });
  8788. _(AST_DWLoop, function(self, tw){
  8789. self.condition = self.condition.transform(tw);
  8790. self.body = self.body.transform(tw);
  8791. });
  8792. _(AST_For, function(self, tw){
  8793. if (self.init) self.init = self.init.transform(tw);
  8794. if (self.condition) self.condition = self.condition.transform(tw);
  8795. if (self.step) self.step = self.step.transform(tw);
  8796. self.body = self.body.transform(tw);
  8797. });
  8798. _(AST_ForIn, function(self, tw){
  8799. self.init = self.init.transform(tw);
  8800. self.object = self.object.transform(tw);
  8801. self.body = self.body.transform(tw);
  8802. });
  8803. _(AST_With, function(self, tw){
  8804. self.expression = self.expression.transform(tw);
  8805. self.body = self.body.transform(tw);
  8806. });
  8807. _(AST_Exit, function(self, tw){
  8808. if (self.value) self.value = self.value.transform(tw);
  8809. });
  8810. _(AST_LoopControl, function(self, tw){
  8811. if (self.label) self.label = self.label.transform(tw);
  8812. });
  8813. _(AST_If, function(self, tw){
  8814. self.condition = self.condition.transform(tw);
  8815. self.body = self.body.transform(tw);
  8816. if (self.alternative) self.alternative = self.alternative.transform(tw);
  8817. });
  8818. _(AST_Switch, function(self, tw){
  8819. self.expression = self.expression.transform(tw);
  8820. self.body = do_list(self.body, tw);
  8821. });
  8822. _(AST_Case, function(self, tw){
  8823. self.expression = self.expression.transform(tw);
  8824. self.body = do_list(self.body, tw);
  8825. });
  8826. _(AST_Try, function(self, tw){
  8827. self.body = do_list(self.body, tw);
  8828. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  8829. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  8830. });
  8831. _(AST_Catch, function(self, tw){
  8832. self.argname = self.argname.transform(tw);
  8833. self.body = do_list(self.body, tw);
  8834. });
  8835. _(AST_Definitions, function(self, tw){
  8836. self.definitions = do_list(self.definitions, tw);
  8837. });
  8838. _(AST_VarDef, function(self, tw){
  8839. self.name = self.name.transform(tw);
  8840. if (self.value) self.value = self.value.transform(tw);
  8841. });
  8842. _(AST_Lambda, function(self, tw){
  8843. if (self.name) self.name = self.name.transform(tw);
  8844. self.argnames = do_list(self.argnames, tw);
  8845. self.body = do_list(self.body, tw);
  8846. });
  8847. _(AST_Call, function(self, tw){
  8848. self.expression = self.expression.transform(tw);
  8849. self.args = do_list(self.args, tw);
  8850. });
  8851. _(AST_Seq, function(self, tw){
  8852. self.car = self.car.transform(tw);
  8853. self.cdr = self.cdr.transform(tw);
  8854. });
  8855. _(AST_Dot, function(self, tw){
  8856. self.expression = self.expression.transform(tw);
  8857. });
  8858. _(AST_Sub, function(self, tw){
  8859. self.expression = self.expression.transform(tw);
  8860. self.property = self.property.transform(tw);
  8861. });
  8862. _(AST_Unary, function(self, tw){
  8863. self.expression = self.expression.transform(tw);
  8864. });
  8865. _(AST_Binary, function(self, tw){
  8866. self.left = self.left.transform(tw);
  8867. self.right = self.right.transform(tw);
  8868. });
  8869. _(AST_Conditional, function(self, tw){
  8870. self.condition = self.condition.transform(tw);
  8871. self.consequent = self.consequent.transform(tw);
  8872. self.alternative = self.alternative.transform(tw);
  8873. });
  8874. _(AST_Array, function(self, tw){
  8875. self.elements = do_list(self.elements, tw);
  8876. });
  8877. _(AST_Object, function(self, tw){
  8878. self.properties = do_list(self.properties, tw);
  8879. });
  8880. _(AST_ObjectProperty, function(self, tw){
  8881. self.value = self.value.transform(tw);
  8882. });
  8883. })();
  8884. /***********************************************************************
  8885. A JavaScript tokenizer / parser / beautifier / compressor.
  8886. https://github.com/mishoo/UglifyJS2
  8887. -------------------------------- (C) ---------------------------------
  8888. Author: Mihai Bazon
  8889. <mihai.bazon@gmail.com>
  8890. http://mihai.bazon.net/blog
  8891. Distributed under the BSD license:
  8892. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  8893. Redistribution and use in source and binary forms, with or without
  8894. modification, are permitted provided that the following conditions
  8895. are met:
  8896. * Redistributions of source code must retain the above
  8897. copyright notice, this list of conditions and the following
  8898. disclaimer.
  8899. * Redistributions in binary form must reproduce the above
  8900. copyright notice, this list of conditions and the following
  8901. disclaimer in the documentation and/or other materials
  8902. provided with the distribution.
  8903. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  8904. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8905. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  8906. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  8907. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  8908. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  8909. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  8910. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8911. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  8912. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  8913. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  8914. SUCH DAMAGE.
  8915. ***********************************************************************/
  8916. "use strict";
  8917. function SymbolDef(scope, index, orig) {
  8918. this.name = orig.name;
  8919. this.orig = [ orig ];
  8920. this.scope = scope;
  8921. this.references = [];
  8922. this.global = false;
  8923. this.mangled_name = null;
  8924. this.undeclared = false;
  8925. this.constant = false;
  8926. this.index = index;
  8927. };
  8928. SymbolDef.prototype = {
  8929. unmangleable: function(options) {
  8930. return (this.global && !(options && options.toplevel))
  8931. || this.undeclared
  8932. || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));
  8933. },
  8934. mangle: function(options) {
  8935. if (!this.mangled_name && !this.unmangleable(options)) {
  8936. var s = this.scope;
  8937. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  8938. s = s.parent_scope;
  8939. this.mangled_name = s.next_mangled(options, this);
  8940. }
  8941. }
  8942. };
  8943. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  8944. options = defaults(options, {
  8945. screw_ie8: false
  8946. });
  8947. // pass 1: setup scope chaining and handle definitions
  8948. var self = this;
  8949. var scope = self.parent_scope = null;
  8950. var defun = null;
  8951. var nesting = 0;
  8952. var tw = new TreeWalker(function(node, descend){
  8953. if (options.screw_ie8 && node instanceof AST_Catch) {
  8954. var save_scope = scope;
  8955. scope = new AST_Scope(node);
  8956. scope.init_scope_vars(nesting);
  8957. scope.parent_scope = save_scope;
  8958. descend();
  8959. scope = save_scope;
  8960. return true;
  8961. }
  8962. if (node instanceof AST_Scope) {
  8963. node.init_scope_vars(nesting);
  8964. var save_scope = node.parent_scope = scope;
  8965. var save_defun = defun;
  8966. defun = scope = node;
  8967. ++nesting; descend(); --nesting;
  8968. scope = save_scope;
  8969. defun = save_defun;
  8970. return true; // don't descend again in TreeWalker
  8971. }
  8972. if (node instanceof AST_Directive) {
  8973. node.scope = scope;
  8974. push_uniq(scope.directives, node.value);
  8975. return true;
  8976. }
  8977. if (node instanceof AST_With) {
  8978. for (var s = scope; s; s = s.parent_scope)
  8979. s.uses_with = true;
  8980. return;
  8981. }
  8982. if (node instanceof AST_Symbol) {
  8983. node.scope = scope;
  8984. }
  8985. if (node instanceof AST_SymbolLambda) {
  8986. defun.def_function(node);
  8987. }
  8988. else if (node instanceof AST_SymbolDefun) {
  8989. // Careful here, the scope where this should be defined is
  8990. // the parent scope. The reason is that we enter a new
  8991. // scope when we encounter the AST_Defun node (which is
  8992. // instanceof AST_Scope) but we get to the symbol a bit
  8993. // later.
  8994. (node.scope = defun.parent_scope).def_function(node);
  8995. }
  8996. else if (node instanceof AST_SymbolVar
  8997. || node instanceof AST_SymbolConst) {
  8998. var def = defun.def_variable(node);
  8999. def.constant = node instanceof AST_SymbolConst;
  9000. def.init = tw.parent().value;
  9001. }
  9002. else if (node instanceof AST_SymbolCatch) {
  9003. (options.screw_ie8 ? scope : defun)
  9004. .def_variable(node);
  9005. }
  9006. });
  9007. self.walk(tw);
  9008. // pass 2: find back references and eval
  9009. var func = null;
  9010. var globals = self.globals = new Dictionary();
  9011. var tw = new TreeWalker(function(node, descend){
  9012. if (node instanceof AST_Lambda) {
  9013. var prev_func = func;
  9014. func = node;
  9015. descend();
  9016. func = prev_func;
  9017. return true;
  9018. }
  9019. if (node instanceof AST_SymbolRef) {
  9020. var name = node.name;
  9021. var sym = node.scope.find_variable(name);
  9022. if (!sym) {
  9023. var g;
  9024. if (globals.has(name)) {
  9025. g = globals.get(name);
  9026. } else {
  9027. g = new SymbolDef(self, globals.size(), node);
  9028. g.undeclared = true;
  9029. g.global = true;
  9030. globals.set(name, g);
  9031. }
  9032. node.thedef = g;
  9033. if (name == "eval" && tw.parent() instanceof AST_Call) {
  9034. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
  9035. s.uses_eval = true;
  9036. }
  9037. if (func && name == "arguments") {
  9038. func.uses_arguments = true;
  9039. }
  9040. } else {
  9041. node.thedef = sym;
  9042. }
  9043. node.reference();
  9044. return true;
  9045. }
  9046. });
  9047. self.walk(tw);
  9048. });
  9049. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  9050. this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
  9051. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  9052. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  9053. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  9054. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  9055. this.parent_scope = null; // the parent scope
  9056. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  9057. this.cname = -1; // the current index for mangling functions/variables
  9058. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  9059. });
  9060. AST_Scope.DEFMETHOD("strict", function(){
  9061. return this.has_directive("use strict");
  9062. });
  9063. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  9064. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  9065. this.uses_arguments = false;
  9066. });
  9067. AST_SymbolRef.DEFMETHOD("reference", function() {
  9068. var def = this.definition();
  9069. def.references.push(this);
  9070. var s = this.scope;
  9071. while (s) {
  9072. push_uniq(s.enclosed, def);
  9073. if (s === def.scope) break;
  9074. s = s.parent_scope;
  9075. }
  9076. this.frame = this.scope.nesting - def.scope.nesting;
  9077. });
  9078. AST_Scope.DEFMETHOD("find_variable", function(name){
  9079. if (name instanceof AST_Symbol) name = name.name;
  9080. return this.variables.get(name)
  9081. || (this.parent_scope && this.parent_scope.find_variable(name));
  9082. });
  9083. AST_Scope.DEFMETHOD("has_directive", function(value){
  9084. return this.parent_scope && this.parent_scope.has_directive(value)
  9085. || (this.directives.indexOf(value) >= 0 ? this : null);
  9086. });
  9087. AST_Scope.DEFMETHOD("def_function", function(symbol){
  9088. this.functions.set(symbol.name, this.def_variable(symbol));
  9089. });
  9090. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  9091. var def;
  9092. if (!this.variables.has(symbol.name)) {
  9093. def = new SymbolDef(this, this.variables.size(), symbol);
  9094. this.variables.set(symbol.name, def);
  9095. def.global = !this.parent_scope;
  9096. } else {
  9097. def = this.variables.get(symbol.name);
  9098. def.orig.push(symbol);
  9099. }
  9100. return symbol.thedef = def;
  9101. });
  9102. AST_Scope.DEFMETHOD("next_mangled", function(options){
  9103. var ext = this.enclosed;
  9104. out: while (true) {
  9105. var m = base54(++this.cname);
  9106. if (!is_identifier(m)) continue; // skip over "do"
  9107. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  9108. // shadow a name excepted from mangling.
  9109. if (options.except.indexOf(m) >= 0) continue;
  9110. // we must ensure that the mangled name does not shadow a name
  9111. // from some parent scope that is referenced in this or in
  9112. // inner scopes.
  9113. for (var i = ext.length; --i >= 0;) {
  9114. var sym = ext[i];
  9115. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  9116. if (m == name) continue out;
  9117. }
  9118. return m;
  9119. }
  9120. });
  9121. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  9122. // #179, #326
  9123. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  9124. // a function expression's argument cannot shadow the function expression's name
  9125. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  9126. while (true) {
  9127. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  9128. if (!(tricky_def && tricky_def.mangled_name == name))
  9129. return name;
  9130. }
  9131. });
  9132. AST_Scope.DEFMETHOD("references", function(sym){
  9133. if (sym instanceof AST_Symbol) sym = sym.definition();
  9134. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  9135. });
  9136. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  9137. return this.definition().unmangleable(options);
  9138. });
  9139. // property accessors are not mangleable
  9140. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  9141. return true;
  9142. });
  9143. // labels are always mangleable
  9144. AST_Label.DEFMETHOD("unmangleable", function(){
  9145. return false;
  9146. });
  9147. AST_Symbol.DEFMETHOD("unreferenced", function(){
  9148. return this.definition().references.length == 0
  9149. && !(this.scope.uses_eval || this.scope.uses_with);
  9150. });
  9151. AST_Symbol.DEFMETHOD("undeclared", function(){
  9152. return this.definition().undeclared;
  9153. });
  9154. AST_LabelRef.DEFMETHOD("undeclared", function(){
  9155. return false;
  9156. });
  9157. AST_Label.DEFMETHOD("undeclared", function(){
  9158. return false;
  9159. });
  9160. AST_Symbol.DEFMETHOD("definition", function(){
  9161. return this.thedef;
  9162. });
  9163. AST_Symbol.DEFMETHOD("global", function(){
  9164. return this.definition().global;
  9165. });
  9166. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  9167. return defaults(options, {
  9168. except : [],
  9169. eval : false,
  9170. sort : false,
  9171. toplevel : false,
  9172. screw_ie8 : false
  9173. });
  9174. });
  9175. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  9176. options = this._default_mangler_options(options);
  9177. // We only need to mangle declaration nodes. Special logic wired
  9178. // into the code generator will display the mangled name if it's
  9179. // present (and for AST_SymbolRef-s it'll use the mangled name of
  9180. // the AST_SymbolDeclaration that it points to).
  9181. var lname = -1;
  9182. var to_mangle = [];
  9183. var tw = new TreeWalker(function(node, descend){
  9184. if (node instanceof AST_LabeledStatement) {
  9185. // lname is incremented when we get to the AST_Label
  9186. var save_nesting = lname;
  9187. descend();
  9188. lname = save_nesting;
  9189. return true; // don't descend again in TreeWalker
  9190. }
  9191. if (node instanceof AST_Scope) {
  9192. var p = tw.parent(), a = [];
  9193. node.variables.each(function(symbol){
  9194. if (options.except.indexOf(symbol.name) < 0) {
  9195. a.push(symbol);
  9196. }
  9197. });
  9198. if (options.sort) a.sort(function(a, b){
  9199. return b.references.length - a.references.length;
  9200. });
  9201. to_mangle.push.apply(to_mangle, a);
  9202. return;
  9203. }
  9204. if (node instanceof AST_Label) {
  9205. var name;
  9206. do name = base54(++lname); while (!is_identifier(name));
  9207. node.mangled_name = name;
  9208. return true;
  9209. }
  9210. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  9211. to_mangle.push(node.definition());
  9212. return;
  9213. }
  9214. });
  9215. this.walk(tw);
  9216. to_mangle.forEach(function(def){ def.mangle(options) });
  9217. });
  9218. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  9219. options = this._default_mangler_options(options);
  9220. var tw = new TreeWalker(function(node){
  9221. if (node instanceof AST_Constant)
  9222. base54.consider(node.print_to_string());
  9223. else if (node instanceof AST_Return)
  9224. base54.consider("return");
  9225. else if (node instanceof AST_Throw)
  9226. base54.consider("throw");
  9227. else if (node instanceof AST_Continue)
  9228. base54.consider("continue");
  9229. else if (node instanceof AST_Break)
  9230. base54.consider("break");
  9231. else if (node instanceof AST_Debugger)
  9232. base54.consider("debugger");
  9233. else if (node instanceof AST_Directive)
  9234. base54.consider(node.value);
  9235. else if (node instanceof AST_While)
  9236. base54.consider("while");
  9237. else if (node instanceof AST_Do)
  9238. base54.consider("do while");
  9239. else if (node instanceof AST_If) {
  9240. base54.consider("if");
  9241. if (node.alternative) base54.consider("else");
  9242. }
  9243. else if (node instanceof AST_Var)
  9244. base54.consider("var");
  9245. else if (node instanceof AST_Const)
  9246. base54.consider("const");
  9247. else if (node instanceof AST_Lambda)
  9248. base54.consider("function");
  9249. else if (node instanceof AST_For)
  9250. base54.consider("fo" + "r");
  9251. else if (node instanceof AST_ForIn)
  9252. base54.consider("for in");
  9253. else if (node instanceof AST_Switch)
  9254. base54.consider("switch");
  9255. else if (node instanceof AST_Case)
  9256. base54.consider("case");
  9257. else if (node instanceof AST_Default)
  9258. base54.consider("default");
  9259. else if (node instanceof AST_With)
  9260. base54.consider("with");
  9261. else if (node instanceof AST_ObjectSetter)
  9262. base54.consider("set" + node.key);
  9263. else if (node instanceof AST_ObjectGetter)
  9264. base54.consider("get" + node.key);
  9265. else if (node instanceof AST_ObjectKeyVal)
  9266. base54.consider(node.key);
  9267. else if (node instanceof AST_New)
  9268. base54.consider("new");
  9269. else if (node instanceof AST_This)
  9270. base54.consider("this");
  9271. else if (node instanceof AST_Try)
  9272. base54.consider("try");
  9273. else if (node instanceof AST_Catch)
  9274. base54.consider("catch");
  9275. else if (node instanceof AST_Finally)
  9276. base54.consider("finally");
  9277. else if (node instanceof AST_Symbol && node.unmangleable(options))
  9278. base54.consider(node.name);
  9279. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  9280. base54.consider(node.operator);
  9281. else if (node instanceof AST_Dot)
  9282. base54.consider(node.property);
  9283. });
  9284. this.walk(tw);
  9285. base54.sort();
  9286. });
  9287. var base54 = (function() {
  9288. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  9289. var chars, frequency;
  9290. function reset() {
  9291. frequency = Object.create(null);
  9292. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  9293. chars.forEach(function(ch){ frequency[ch] = 0 });
  9294. }
  9295. base54.consider = function(str){
  9296. for (var i = str.length; --i >= 0;) {
  9297. var code = str.charCodeAt(i);
  9298. if (code in frequency) ++frequency[code];
  9299. }
  9300. };
  9301. base54.sort = function() {
  9302. chars = mergeSort(chars, function(a, b){
  9303. if (is_digit(a) && !is_digit(b)) return 1;
  9304. if (is_digit(b) && !is_digit(a)) return -1;
  9305. return frequency[b] - frequency[a];
  9306. });
  9307. };
  9308. base54.reset = reset;
  9309. reset();
  9310. base54.get = function(){ return chars };
  9311. base54.freq = function(){ return frequency };
  9312. function base54(num) {
  9313. var ret = "", base = 54;
  9314. do {
  9315. ret += String.fromCharCode(chars[num % base]);
  9316. num = Math.floor(num / base);
  9317. base = 64;
  9318. } while (num > 0);
  9319. return ret;
  9320. };
  9321. return base54;
  9322. })();
  9323. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  9324. options = defaults(options, {
  9325. undeclared : false, // this makes a lot of noise
  9326. unreferenced : true,
  9327. assign_to_global : true,
  9328. func_arguments : true,
  9329. nested_defuns : true,
  9330. eval : true
  9331. });
  9332. var tw = new TreeWalker(function(node){
  9333. if (options.undeclared
  9334. && node instanceof AST_SymbolRef
  9335. && node.undeclared())
  9336. {
  9337. // XXX: this also warns about JS standard names,
  9338. // i.e. Object, Array, parseInt etc. Should add a list of
  9339. // exceptions.
  9340. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  9341. name: node.name,
  9342. file: node.start.file,
  9343. line: node.start.line,
  9344. col: node.start.col
  9345. });
  9346. }
  9347. if (options.assign_to_global)
  9348. {
  9349. var sym = null;
  9350. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  9351. sym = node.left;
  9352. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  9353. sym = node.init;
  9354. if (sym
  9355. && (sym.undeclared()
  9356. || (sym.global() && sym.scope !== sym.definition().scope))) {
  9357. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  9358. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  9359. name: sym.name,
  9360. file: sym.start.file,
  9361. line: sym.start.line,
  9362. col: sym.start.col
  9363. });
  9364. }
  9365. }
  9366. if (options.eval
  9367. && node instanceof AST_SymbolRef
  9368. && node.undeclared()
  9369. && node.name == "eval") {
  9370. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  9371. }
  9372. if (options.unreferenced
  9373. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  9374. && node.unreferenced()) {
  9375. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  9376. type: node instanceof AST_Label ? "Label" : "Symbol",
  9377. name: node.name,
  9378. file: node.start.file,
  9379. line: node.start.line,
  9380. col: node.start.col
  9381. });
  9382. }
  9383. if (options.func_arguments
  9384. && node instanceof AST_Lambda
  9385. && node.uses_arguments) {
  9386. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  9387. name: node.name ? node.name.name : "anonymous",
  9388. file: node.start.file,
  9389. line: node.start.line,
  9390. col: node.start.col
  9391. });
  9392. }
  9393. if (options.nested_defuns
  9394. && node instanceof AST_Defun
  9395. && !(tw.parent() instanceof AST_Scope)) {
  9396. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  9397. name: node.name.name,
  9398. type: tw.parent().TYPE,
  9399. file: node.start.file,
  9400. line: node.start.line,
  9401. col: node.start.col
  9402. });
  9403. }
  9404. });
  9405. this.walk(tw);
  9406. });
  9407. /***********************************************************************
  9408. A JavaScript tokenizer / parser / beautifier / compressor.
  9409. https://github.com/mishoo/UglifyJS2
  9410. -------------------------------- (C) ---------------------------------
  9411. Author: Mihai Bazon
  9412. <mihai.bazon@gmail.com>
  9413. http://mihai.bazon.net/blog
  9414. Distributed under the BSD license:
  9415. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  9416. Redistribution and use in source and binary forms, with or without
  9417. modification, are permitted provided that the following conditions
  9418. are met:
  9419. * Redistributions of source code must retain the above
  9420. copyright notice, this list of conditions and the following
  9421. disclaimer.
  9422. * Redistributions in binary form must reproduce the above
  9423. copyright notice, this list of conditions and the following
  9424. disclaimer in the documentation and/or other materials
  9425. provided with the distribution.
  9426. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  9427. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  9428. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  9429. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  9430. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  9431. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  9432. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  9433. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9434. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  9435. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  9436. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  9437. SUCH DAMAGE.
  9438. ***********************************************************************/
  9439. "use strict";
  9440. function OutputStream(options) {
  9441. options = defaults(options, {
  9442. indent_start : 0,
  9443. indent_level : 4,
  9444. quote_keys : false,
  9445. space_colon : true,
  9446. ascii_only : false,
  9447. unescape_regexps : false,
  9448. inline_script : false,
  9449. width : 80,
  9450. max_line_len : 32000,
  9451. beautify : false,
  9452. source_map : null,
  9453. bracketize : false,
  9454. semicolons : true,
  9455. comments : false,
  9456. preserve_line : false,
  9457. screw_ie8 : false,
  9458. preamble : null,
  9459. }, true);
  9460. var indentation = 0;
  9461. var current_col = 0;
  9462. var current_line = 1;
  9463. var current_pos = 0;
  9464. var OUTPUT = "";
  9465. function to_ascii(str, identifier) {
  9466. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  9467. var code = ch.charCodeAt(0).toString(16);
  9468. if (code.length <= 2 && !identifier) {
  9469. while (code.length < 2) code = "0" + code;
  9470. return "\\x" + code;
  9471. } else {
  9472. while (code.length < 4) code = "0" + code;
  9473. return "\\u" + code;
  9474. }
  9475. });
  9476. };
  9477. function make_string(str) {
  9478. var dq = 0, sq = 0;
  9479. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  9480. switch (s) {
  9481. case "\\": return "\\\\";
  9482. case "\b": return "\\b";
  9483. case "\f": return "\\f";
  9484. case "\n": return "\\n";
  9485. case "\r": return "\\r";
  9486. case "\u2028": return "\\u2028";
  9487. case "\u2029": return "\\u2029";
  9488. case '"': ++dq; return '"';
  9489. case "'": ++sq; return "'";
  9490. case "\0": return "\\x00";
  9491. }
  9492. return s;
  9493. });
  9494. if (options.ascii_only) str = to_ascii(str);
  9495. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  9496. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  9497. };
  9498. function encode_string(str) {
  9499. var ret = make_string(str);
  9500. if (options.inline_script)
  9501. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  9502. return ret;
  9503. };
  9504. function make_name(name) {
  9505. name = name.toString();
  9506. if (options.ascii_only)
  9507. name = to_ascii(name, true);
  9508. return name;
  9509. };
  9510. function make_indent(back) {
  9511. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  9512. };
  9513. /* -----[ beautification/minification ]----- */
  9514. var might_need_space = false;
  9515. var might_need_semicolon = false;
  9516. var last = null;
  9517. function last_char() {
  9518. return last.charAt(last.length - 1);
  9519. };
  9520. function maybe_newline() {
  9521. if (options.max_line_len && current_col > options.max_line_len)
  9522. print("\n");
  9523. };
  9524. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  9525. function print(str) {
  9526. str = String(str);
  9527. var ch = str.charAt(0);
  9528. if (might_need_semicolon) {
  9529. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  9530. if (options.semicolons || requireSemicolonChars(ch)) {
  9531. OUTPUT += ";";
  9532. current_col++;
  9533. current_pos++;
  9534. } else {
  9535. OUTPUT += "\n";
  9536. current_pos++;
  9537. current_line++;
  9538. current_col = 0;
  9539. }
  9540. if (!options.beautify)
  9541. might_need_space = false;
  9542. }
  9543. might_need_semicolon = false;
  9544. maybe_newline();
  9545. }
  9546. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  9547. var target_line = stack[stack.length - 1].start.line;
  9548. while (current_line < target_line) {
  9549. OUTPUT += "\n";
  9550. current_pos++;
  9551. current_line++;
  9552. current_col = 0;
  9553. might_need_space = false;
  9554. }
  9555. }
  9556. if (might_need_space) {
  9557. var prev = last_char();
  9558. if ((is_identifier_char(prev)
  9559. && (is_identifier_char(ch) || ch == "\\"))
  9560. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  9561. {
  9562. OUTPUT += " ";
  9563. current_col++;
  9564. current_pos++;
  9565. }
  9566. might_need_space = false;
  9567. }
  9568. var a = str.split(/\r?\n/), n = a.length - 1;
  9569. current_line += n;
  9570. if (n == 0) {
  9571. current_col += a[n].length;
  9572. } else {
  9573. current_col = a[n].length;
  9574. }
  9575. current_pos += str.length;
  9576. last = str;
  9577. OUTPUT += str;
  9578. };
  9579. var space = options.beautify ? function() {
  9580. print(" ");
  9581. } : function() {
  9582. might_need_space = true;
  9583. };
  9584. var indent = options.beautify ? function(half) {
  9585. if (options.beautify) {
  9586. print(make_indent(half ? 0.5 : 0));
  9587. }
  9588. } : noop;
  9589. var with_indent = options.beautify ? function(col, cont) {
  9590. if (col === true) col = next_indent();
  9591. var save_indentation = indentation;
  9592. indentation = col;
  9593. var ret = cont();
  9594. indentation = save_indentation;
  9595. return ret;
  9596. } : function(col, cont) { return cont() };
  9597. var newline = options.beautify ? function() {
  9598. print("\n");
  9599. } : noop;
  9600. var semicolon = options.beautify ? function() {
  9601. print(";");
  9602. } : function() {
  9603. might_need_semicolon = true;
  9604. };
  9605. function force_semicolon() {
  9606. might_need_semicolon = false;
  9607. print(";");
  9608. };
  9609. function next_indent() {
  9610. return indentation + options.indent_level;
  9611. };
  9612. function with_block(cont) {
  9613. var ret;
  9614. print("{");
  9615. newline();
  9616. with_indent(next_indent(), function(){
  9617. ret = cont();
  9618. });
  9619. indent();
  9620. print("}");
  9621. return ret;
  9622. };
  9623. function with_parens(cont) {
  9624. print("(");
  9625. //XXX: still nice to have that for argument lists
  9626. //var ret = with_indent(current_col, cont);
  9627. var ret = cont();
  9628. print(")");
  9629. return ret;
  9630. };
  9631. function with_square(cont) {
  9632. print("[");
  9633. //var ret = with_indent(current_col, cont);
  9634. var ret = cont();
  9635. print("]");
  9636. return ret;
  9637. };
  9638. function comma() {
  9639. print(",");
  9640. space();
  9641. };
  9642. function colon() {
  9643. print(":");
  9644. if (options.space_colon) space();
  9645. };
  9646. var add_mapping = options.source_map ? function(token, name) {
  9647. try {
  9648. if (token) options.source_map.add(
  9649. token.file || "?",
  9650. current_line, current_col,
  9651. token.line, token.col,
  9652. (!name && token.type == "name") ? token.value : name
  9653. );
  9654. } catch(ex) {
  9655. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  9656. file: token.file,
  9657. line: token.line,
  9658. col: token.col,
  9659. cline: current_line,
  9660. ccol: current_col,
  9661. name: name || ""
  9662. })
  9663. }
  9664. } : noop;
  9665. function get() {
  9666. return OUTPUT;
  9667. };
  9668. if (options.preamble) {
  9669. print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  9670. }
  9671. var stack = [];
  9672. return {
  9673. get : get,
  9674. toString : get,
  9675. indent : indent,
  9676. indentation : function() { return indentation },
  9677. current_width : function() { return current_col - indentation },
  9678. should_break : function() { return options.width && this.current_width() >= options.width },
  9679. newline : newline,
  9680. print : print,
  9681. space : space,
  9682. comma : comma,
  9683. colon : colon,
  9684. last : function() { return last },
  9685. semicolon : semicolon,
  9686. force_semicolon : force_semicolon,
  9687. to_ascii : to_ascii,
  9688. print_name : function(name) { print(make_name(name)) },
  9689. print_string : function(str) { print(encode_string(str)) },
  9690. next_indent : next_indent,
  9691. with_indent : with_indent,
  9692. with_block : with_block,
  9693. with_parens : with_parens,
  9694. with_square : with_square,
  9695. add_mapping : add_mapping,
  9696. option : function(opt) { return options[opt] },
  9697. line : function() { return current_line },
  9698. col : function() { return current_col },
  9699. pos : function() { return current_pos },
  9700. push_node : function(node) { stack.push(node) },
  9701. pop_node : function() { return stack.pop() },
  9702. stack : function() { return stack },
  9703. parent : function(n) {
  9704. return stack[stack.length - 2 - (n || 0)];
  9705. }
  9706. };
  9707. };
  9708. /* -----[ code generators ]----- */
  9709. (function(){
  9710. /* -----[ utils ]----- */
  9711. function DEFPRINT(nodetype, generator) {
  9712. nodetype.DEFMETHOD("_codegen", generator);
  9713. };
  9714. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  9715. var self = this, generator = self._codegen;
  9716. function doit() {
  9717. self.add_comments(stream);
  9718. self.add_source_map(stream);
  9719. generator(self, stream);
  9720. }
  9721. stream.push_node(self);
  9722. if (force_parens || self.needs_parens(stream)) {
  9723. stream.with_parens(doit);
  9724. } else {
  9725. doit();
  9726. }
  9727. stream.pop_node();
  9728. });
  9729. AST_Node.DEFMETHOD("print_to_string", function(options){
  9730. var s = OutputStream(options);
  9731. this.print(s);
  9732. return s.get();
  9733. });
  9734. /* -----[ comments ]----- */
  9735. AST_Node.DEFMETHOD("add_comments", function(output){
  9736. var c = output.option("comments"), self = this;
  9737. if (c) {
  9738. var start = self.start;
  9739. if (start && !start._comments_dumped) {
  9740. start._comments_dumped = true;
  9741. var comments = start.comments_before || [];
  9742. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  9743. // and https://github.com/mishoo/UglifyJS2/issues/372
  9744. if (self instanceof AST_Exit && self.value) {
  9745. self.value.walk(new TreeWalker(function(node){
  9746. if (node.start && node.start.comments_before) {
  9747. comments = comments.concat(node.start.comments_before);
  9748. node.start.comments_before = [];
  9749. }
  9750. if (node instanceof AST_Function ||
  9751. node instanceof AST_Array ||
  9752. node instanceof AST_Object)
  9753. {
  9754. return true; // don't go inside.
  9755. }
  9756. }));
  9757. }
  9758. if (c.test) {
  9759. comments = comments.filter(function(comment){
  9760. return c.test(comment.value);
  9761. });
  9762. } else if (typeof c == "function") {
  9763. comments = comments.filter(function(comment){
  9764. return c(self, comment);
  9765. });
  9766. }
  9767. comments.forEach(function(c){
  9768. if (/comment[134]/.test(c.type)) {
  9769. output.print("//" + c.value + "\n");
  9770. output.indent();
  9771. }
  9772. else if (c.type == "comment2") {
  9773. output.print("/*" + c.value + "*/");
  9774. if (start.nlb) {
  9775. output.print("\n");
  9776. output.indent();
  9777. } else {
  9778. output.space();
  9779. }
  9780. }
  9781. });
  9782. }
  9783. }
  9784. });
  9785. /* -----[ PARENTHESES ]----- */
  9786. function PARENS(nodetype, func) {
  9787. nodetype.DEFMETHOD("needs_parens", func);
  9788. };
  9789. PARENS(AST_Node, function(){
  9790. return false;
  9791. });
  9792. // a function expression needs parens around it when it's provably
  9793. // the first token to appear in a statement.
  9794. PARENS(AST_Function, function(output){
  9795. return first_in_statement(output);
  9796. });
  9797. // same goes for an object literal, because otherwise it would be
  9798. // interpreted as a block of code.
  9799. PARENS(AST_Object, function(output){
  9800. return first_in_statement(output);
  9801. });
  9802. PARENS(AST_Unary, function(output){
  9803. var p = output.parent();
  9804. return p instanceof AST_PropAccess && p.expression === this;
  9805. });
  9806. PARENS(AST_Seq, function(output){
  9807. var p = output.parent();
  9808. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  9809. || p instanceof AST_Unary // !(foo, bar, baz)
  9810. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  9811. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  9812. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  9813. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  9814. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  9815. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  9816. * ==> 20 (side effect, set a := 10 and b := 20) */
  9817. ;
  9818. });
  9819. PARENS(AST_Binary, function(output){
  9820. var p = output.parent();
  9821. // (foo && bar)()
  9822. if (p instanceof AST_Call && p.expression === this)
  9823. return true;
  9824. // typeof (foo && bar)
  9825. if (p instanceof AST_Unary)
  9826. return true;
  9827. // (foo && bar)["prop"], (foo && bar).prop
  9828. if (p instanceof AST_PropAccess && p.expression === this)
  9829. return true;
  9830. // this deals with precedence: 3 * (2 + 1)
  9831. if (p instanceof AST_Binary) {
  9832. var po = p.operator, pp = PRECEDENCE[po];
  9833. var so = this.operator, sp = PRECEDENCE[so];
  9834. if (pp > sp
  9835. || (pp == sp
  9836. && this === p.right)) {
  9837. return true;
  9838. }
  9839. }
  9840. });
  9841. PARENS(AST_PropAccess, function(output){
  9842. var p = output.parent();
  9843. if (p instanceof AST_New && p.expression === this) {
  9844. // i.e. new (foo.bar().baz)
  9845. //
  9846. // if there's one call into this subtree, then we need
  9847. // parens around it too, otherwise the call will be
  9848. // interpreted as passing the arguments to the upper New
  9849. // expression.
  9850. try {
  9851. this.walk(new TreeWalker(function(node){
  9852. if (node instanceof AST_Call) throw p;
  9853. }));
  9854. } catch(ex) {
  9855. if (ex !== p) throw ex;
  9856. return true;
  9857. }
  9858. }
  9859. });
  9860. PARENS(AST_Call, function(output){
  9861. var p = output.parent(), p1;
  9862. if (p instanceof AST_New && p.expression === this)
  9863. return true;
  9864. // workaround for Safari bug.
  9865. // https://bugs.webkit.org/show_bug.cgi?id=123506
  9866. return this.expression instanceof AST_Function
  9867. && p instanceof AST_PropAccess
  9868. && p.expression === this
  9869. && (p1 = output.parent(1)) instanceof AST_Assign
  9870. && p1.left === p;
  9871. });
  9872. PARENS(AST_New, function(output){
  9873. var p = output.parent();
  9874. if (no_constructor_parens(this, output)
  9875. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  9876. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  9877. return true;
  9878. });
  9879. PARENS(AST_Number, function(output){
  9880. var p = output.parent();
  9881. if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
  9882. return true;
  9883. });
  9884. PARENS(AST_NaN, function(output){
  9885. var p = output.parent();
  9886. if (p instanceof AST_PropAccess && p.expression === this)
  9887. return true;
  9888. });
  9889. function assign_and_conditional_paren_rules(output) {
  9890. var p = output.parent();
  9891. // !(a = false) → true
  9892. if (p instanceof AST_Unary)
  9893. return true;
  9894. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  9895. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  9896. return true;
  9897. // (a = func)() —or— new (a = Object)()
  9898. if (p instanceof AST_Call && p.expression === this)
  9899. return true;
  9900. // (a = foo) ? bar : baz
  9901. if (p instanceof AST_Conditional && p.condition === this)
  9902. return true;
  9903. // (a = foo)["prop"] —or— (a = foo).prop
  9904. if (p instanceof AST_PropAccess && p.expression === this)
  9905. return true;
  9906. };
  9907. PARENS(AST_Assign, assign_and_conditional_paren_rules);
  9908. PARENS(AST_Conditional, assign_and_conditional_paren_rules);
  9909. /* -----[ PRINTERS ]----- */
  9910. DEFPRINT(AST_Directive, function(self, output){
  9911. output.print_string(self.value);
  9912. output.semicolon();
  9913. });
  9914. DEFPRINT(AST_Debugger, function(self, output){
  9915. output.print("debugger");
  9916. output.semicolon();
  9917. });
  9918. /* -----[ statements ]----- */
  9919. function display_body(body, is_toplevel, output) {
  9920. var last = body.length - 1;
  9921. body.forEach(function(stmt, i){
  9922. if (!(stmt instanceof AST_EmptyStatement)) {
  9923. output.indent();
  9924. stmt.print(output);
  9925. if (!(i == last && is_toplevel)) {
  9926. output.newline();
  9927. if (is_toplevel) output.newline();
  9928. }
  9929. }
  9930. });
  9931. };
  9932. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  9933. force_statement(this.body, output);
  9934. });
  9935. DEFPRINT(AST_Statement, function(self, output){
  9936. self.body.print(output);
  9937. output.semicolon();
  9938. });
  9939. DEFPRINT(AST_Toplevel, function(self, output){
  9940. display_body(self.body, true, output);
  9941. output.print("");
  9942. });
  9943. DEFPRINT(AST_LabeledStatement, function(self, output){
  9944. self.label.print(output);
  9945. output.colon();
  9946. self.body.print(output);
  9947. });
  9948. DEFPRINT(AST_SimpleStatement, function(self, output){
  9949. self.body.print(output);
  9950. output.semicolon();
  9951. });
  9952. function print_bracketed(body, output) {
  9953. if (body.length > 0) output.with_block(function(){
  9954. display_body(body, false, output);
  9955. });
  9956. else output.print("{}");
  9957. };
  9958. DEFPRINT(AST_BlockStatement, function(self, output){
  9959. print_bracketed(self.body, output);
  9960. });
  9961. DEFPRINT(AST_EmptyStatement, function(self, output){
  9962. output.semicolon();
  9963. });
  9964. DEFPRINT(AST_Do, function(self, output){
  9965. output.print("do");
  9966. output.space();
  9967. self._do_print_body(output);
  9968. output.space();
  9969. output.print("while");
  9970. output.space();
  9971. output.with_parens(function(){
  9972. self.condition.print(output);
  9973. });
  9974. output.semicolon();
  9975. });
  9976. DEFPRINT(AST_While, function(self, output){
  9977. output.print("while");
  9978. output.space();
  9979. output.with_parens(function(){
  9980. self.condition.print(output);
  9981. });
  9982. output.space();
  9983. self._do_print_body(output);
  9984. });
  9985. DEFPRINT(AST_For, function(self, output){
  9986. output.print("fo" + "r");
  9987. output.space();
  9988. output.with_parens(function(){
  9989. if (self.init && !(self.init instanceof AST_EmptyStatement)) {
  9990. if (self.init instanceof AST_Definitions) {
  9991. self.init.print(output);
  9992. } else {
  9993. parenthesize_for_noin(self.init, output, true);
  9994. }
  9995. output.print(";");
  9996. output.space();
  9997. } else {
  9998. output.print(";");
  9999. }
  10000. if (self.condition) {
  10001. self.condition.print(output);
  10002. output.print(";");
  10003. output.space();
  10004. } else {
  10005. output.print(";");
  10006. }
  10007. if (self.step) {
  10008. self.step.print(output);
  10009. }
  10010. });
  10011. output.space();
  10012. self._do_print_body(output);
  10013. });
  10014. DEFPRINT(AST_ForIn, function(self, output){
  10015. output.print("fo" + "r");
  10016. output.space();
  10017. output.with_parens(function(){
  10018. self.init.print(output);
  10019. output.space();
  10020. output.print("in");
  10021. output.space();
  10022. self.object.print(output);
  10023. });
  10024. output.space();
  10025. self._do_print_body(output);
  10026. });
  10027. DEFPRINT(AST_With, function(self, output){
  10028. output.print("with");
  10029. output.space();
  10030. output.with_parens(function(){
  10031. self.expression.print(output);
  10032. });
  10033. output.space();
  10034. self._do_print_body(output);
  10035. });
  10036. /* -----[ functions ]----- */
  10037. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  10038. var self = this;
  10039. if (!nokeyword) {
  10040. output.print("function");
  10041. }
  10042. if (self.name) {
  10043. output.space();
  10044. self.name.print(output);
  10045. }
  10046. output.with_parens(function(){
  10047. self.argnames.forEach(function(arg, i){
  10048. if (i) output.comma();
  10049. arg.print(output);
  10050. });
  10051. });
  10052. output.space();
  10053. print_bracketed(self.body, output);
  10054. });
  10055. DEFPRINT(AST_Lambda, function(self, output){
  10056. self._do_print(output);
  10057. });
  10058. /* -----[ exits ]----- */
  10059. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  10060. output.print(kind);
  10061. if (this.value) {
  10062. output.space();
  10063. this.value.print(output);
  10064. }
  10065. output.semicolon();
  10066. });
  10067. DEFPRINT(AST_Return, function(self, output){
  10068. self._do_print(output, "return");
  10069. });
  10070. DEFPRINT(AST_Throw, function(self, output){
  10071. self._do_print(output, "throw");
  10072. });
  10073. /* -----[ loop control ]----- */
  10074. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  10075. output.print(kind);
  10076. if (this.label) {
  10077. output.space();
  10078. this.label.print(output);
  10079. }
  10080. output.semicolon();
  10081. });
  10082. DEFPRINT(AST_Break, function(self, output){
  10083. self._do_print(output, "break");
  10084. });
  10085. DEFPRINT(AST_Continue, function(self, output){
  10086. self._do_print(output, "continue");
  10087. });
  10088. /* -----[ if ]----- */
  10089. function make_then(self, output) {
  10090. if (output.option("bracketize")) {
  10091. make_block(self.body, output);
  10092. return;
  10093. }
  10094. // The squeezer replaces "block"-s that contain only a single
  10095. // statement with the statement itself; technically, the AST
  10096. // is correct, but this can create problems when we output an
  10097. // IF having an ELSE clause where the THEN clause ends in an
  10098. // IF *without* an ELSE block (then the outer ELSE would refer
  10099. // to the inner IF). This function checks for this case and
  10100. // adds the block brackets if needed.
  10101. if (!self.body)
  10102. return output.force_semicolon();
  10103. if (self.body instanceof AST_Do
  10104. && !output.option("screw_ie8")) {
  10105. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  10106. // croaks with "syntax error" on code like this: if (foo)
  10107. // do ... while(cond); else ... we need block brackets
  10108. // around do/while
  10109. make_block(self.body, output);
  10110. return;
  10111. }
  10112. var b = self.body;
  10113. while (true) {
  10114. if (b instanceof AST_If) {
  10115. if (!b.alternative) {
  10116. make_block(self.body, output);
  10117. return;
  10118. }
  10119. b = b.alternative;
  10120. }
  10121. else if (b instanceof AST_StatementWithBody) {
  10122. b = b.body;
  10123. }
  10124. else break;
  10125. }
  10126. force_statement(self.body, output);
  10127. };
  10128. DEFPRINT(AST_If, function(self, output){
  10129. output.print("if");
  10130. output.space();
  10131. output.with_parens(function(){
  10132. self.condition.print(output);
  10133. });
  10134. output.space();
  10135. if (self.alternative) {
  10136. make_then(self, output);
  10137. output.space();
  10138. output.print("else");
  10139. output.space();
  10140. force_statement(self.alternative, output);
  10141. } else {
  10142. self._do_print_body(output);
  10143. }
  10144. });
  10145. /* -----[ switch ]----- */
  10146. DEFPRINT(AST_Switch, function(self, output){
  10147. output.print("switch");
  10148. output.space();
  10149. output.with_parens(function(){
  10150. self.expression.print(output);
  10151. });
  10152. output.space();
  10153. if (self.body.length > 0) output.with_block(function(){
  10154. self.body.forEach(function(stmt, i){
  10155. if (i) output.newline();
  10156. output.indent(true);
  10157. stmt.print(output);
  10158. });
  10159. });
  10160. else output.print("{}");
  10161. });
  10162. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  10163. if (this.body.length > 0) {
  10164. output.newline();
  10165. this.body.forEach(function(stmt){
  10166. output.indent();
  10167. stmt.print(output);
  10168. output.newline();
  10169. });
  10170. }
  10171. });
  10172. DEFPRINT(AST_Default, function(self, output){
  10173. output.print("default:");
  10174. self._do_print_body(output);
  10175. });
  10176. DEFPRINT(AST_Case, function(self, output){
  10177. output.print("case");
  10178. output.space();
  10179. self.expression.print(output);
  10180. output.print(":");
  10181. self._do_print_body(output);
  10182. });
  10183. /* -----[ exceptions ]----- */
  10184. DEFPRINT(AST_Try, function(self, output){
  10185. output.print("try");
  10186. output.space();
  10187. print_bracketed(self.body, output);
  10188. if (self.bcatch) {
  10189. output.space();
  10190. self.bcatch.print(output);
  10191. }
  10192. if (self.bfinally) {
  10193. output.space();
  10194. self.bfinally.print(output);
  10195. }
  10196. });
  10197. DEFPRINT(AST_Catch, function(self, output){
  10198. output.print("catch");
  10199. output.space();
  10200. output.with_parens(function(){
  10201. self.argname.print(output);
  10202. });
  10203. output.space();
  10204. print_bracketed(self.body, output);
  10205. });
  10206. DEFPRINT(AST_Finally, function(self, output){
  10207. output.print("finally");
  10208. output.space();
  10209. print_bracketed(self.body, output);
  10210. });
  10211. /* -----[ var/const ]----- */
  10212. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  10213. output.print(kind);
  10214. output.space();
  10215. this.definitions.forEach(function(def, i){
  10216. if (i) output.comma();
  10217. def.print(output);
  10218. });
  10219. var p = output.parent();
  10220. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  10221. var avoid_semicolon = in_for && p.init === this;
  10222. if (!avoid_semicolon)
  10223. output.semicolon();
  10224. });
  10225. DEFPRINT(AST_Var, function(self, output){
  10226. self._do_print(output, "var");
  10227. });
  10228. DEFPRINT(AST_Const, function(self, output){
  10229. self._do_print(output, "const");
  10230. });
  10231. function parenthesize_for_noin(node, output, noin) {
  10232. if (!noin) node.print(output);
  10233. else try {
  10234. // need to take some precautions here:
  10235. // https://github.com/mishoo/UglifyJS2/issues/60
  10236. node.walk(new TreeWalker(function(node){
  10237. if (node instanceof AST_Binary && node.operator == "in")
  10238. throw output;
  10239. }));
  10240. node.print(output);
  10241. } catch(ex) {
  10242. if (ex !== output) throw ex;
  10243. node.print(output, true);
  10244. }
  10245. };
  10246. DEFPRINT(AST_VarDef, function(self, output){
  10247. self.name.print(output);
  10248. if (self.value) {
  10249. output.space();
  10250. output.print("=");
  10251. output.space();
  10252. var p = output.parent(1);
  10253. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  10254. parenthesize_for_noin(self.value, output, noin);
  10255. }
  10256. });
  10257. /* -----[ other expressions ]----- */
  10258. DEFPRINT(AST_Call, function(self, output){
  10259. self.expression.print(output);
  10260. if (self instanceof AST_New && no_constructor_parens(self, output))
  10261. return;
  10262. output.with_parens(function(){
  10263. self.args.forEach(function(expr, i){
  10264. if (i) output.comma();
  10265. expr.print(output);
  10266. });
  10267. });
  10268. });
  10269. DEFPRINT(AST_New, function(self, output){
  10270. output.print("new");
  10271. output.space();
  10272. AST_Call.prototype._codegen(self, output);
  10273. });
  10274. AST_Seq.DEFMETHOD("_do_print", function(output){
  10275. this.car.print(output);
  10276. if (this.cdr) {
  10277. output.comma();
  10278. if (output.should_break()) {
  10279. output.newline();
  10280. output.indent();
  10281. }
  10282. this.cdr.print(output);
  10283. }
  10284. });
  10285. DEFPRINT(AST_Seq, function(self, output){
  10286. self._do_print(output);
  10287. // var p = output.parent();
  10288. // if (p instanceof AST_Statement) {
  10289. // output.with_indent(output.next_indent(), function(){
  10290. // self._do_print(output);
  10291. // });
  10292. // } else {
  10293. // self._do_print(output);
  10294. // }
  10295. });
  10296. DEFPRINT(AST_Dot, function(self, output){
  10297. var expr = self.expression;
  10298. expr.print(output);
  10299. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  10300. if (!/[xa-f.]/i.test(output.last())) {
  10301. output.print(".");
  10302. }
  10303. }
  10304. output.print(".");
  10305. // the name after dot would be mapped about here.
  10306. output.add_mapping(self.end);
  10307. output.print_name(self.property);
  10308. });
  10309. DEFPRINT(AST_Sub, function(self, output){
  10310. self.expression.print(output);
  10311. output.print("[");
  10312. self.property.print(output);
  10313. output.print("]");
  10314. });
  10315. DEFPRINT(AST_UnaryPrefix, function(self, output){
  10316. var op = self.operator;
  10317. output.print(op);
  10318. if (/^[a-z]/i.test(op)
  10319. || (/[+-]$/.test(op)
  10320. && self.expression instanceof AST_UnaryPrefix
  10321. && /^[+-]/.test(self.expression.operator))) {
  10322. output.space();
  10323. }
  10324. self.expression.print(output);
  10325. });
  10326. DEFPRINT(AST_UnaryPostfix, function(self, output){
  10327. self.expression.print(output);
  10328. output.print(self.operator);
  10329. });
  10330. DEFPRINT(AST_Binary, function(self, output){
  10331. self.left.print(output);
  10332. output.space();
  10333. output.print(self.operator);
  10334. if (self.operator == "<"
  10335. && self.right instanceof AST_UnaryPrefix
  10336. && self.right.operator == "!"
  10337. && self.right.expression instanceof AST_UnaryPrefix
  10338. && self.right.expression.operator == "--") {
  10339. // space is mandatory to avoid outputting <!--
  10340. // http://javascript.spec.whatwg.org/#comment-syntax
  10341. output.print(" ");
  10342. } else {
  10343. // the space is optional depending on "beautify"
  10344. output.space();
  10345. }
  10346. self.right.print(output);
  10347. });
  10348. DEFPRINT(AST_Conditional, function(self, output){
  10349. self.condition.print(output);
  10350. output.space();
  10351. output.print("?");
  10352. output.space();
  10353. self.consequent.print(output);
  10354. output.space();
  10355. output.colon();
  10356. self.alternative.print(output);
  10357. });
  10358. /* -----[ literals ]----- */
  10359. DEFPRINT(AST_Array, function(self, output){
  10360. output.with_square(function(){
  10361. var a = self.elements, len = a.length;
  10362. if (len > 0) output.space();
  10363. a.forEach(function(exp, i){
  10364. if (i) output.comma();
  10365. exp.print(output);
  10366. // If the final element is a hole, we need to make sure it
  10367. // doesn't look like a trailing comma, by inserting an actual
  10368. // trailing comma.
  10369. if (i === len - 1 && exp instanceof AST_Hole)
  10370. output.comma();
  10371. });
  10372. if (len > 0) output.space();
  10373. });
  10374. });
  10375. DEFPRINT(AST_Object, function(self, output){
  10376. if (self.properties.length > 0) output.with_block(function(){
  10377. self.properties.forEach(function(prop, i){
  10378. if (i) {
  10379. output.print(",");
  10380. output.newline();
  10381. }
  10382. output.indent();
  10383. prop.print(output);
  10384. });
  10385. output.newline();
  10386. });
  10387. else output.print("{}");
  10388. });
  10389. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  10390. var key = self.key;
  10391. if (output.option("quote_keys")) {
  10392. output.print_string(key + "");
  10393. } else if ((typeof key == "number"
  10394. || !output.option("beautify")
  10395. && +key + "" == key)
  10396. && parseFloat(key) >= 0) {
  10397. output.print(make_num(key));
  10398. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  10399. output.print_name(key);
  10400. } else {
  10401. output.print_string(key);
  10402. }
  10403. output.colon();
  10404. self.value.print(output);
  10405. });
  10406. DEFPRINT(AST_ObjectSetter, function(self, output){
  10407. output.print("set");
  10408. output.space();
  10409. self.key.print(output);
  10410. self.value._do_print(output, true);
  10411. });
  10412. DEFPRINT(AST_ObjectGetter, function(self, output){
  10413. output.print("get");
  10414. output.space();
  10415. self.key.print(output);
  10416. self.value._do_print(output, true);
  10417. });
  10418. DEFPRINT(AST_Symbol, function(self, output){
  10419. var def = self.definition();
  10420. output.print_name(def ? def.mangled_name || def.name : self.name);
  10421. });
  10422. DEFPRINT(AST_Undefined, function(self, output){
  10423. output.print("void 0");
  10424. });
  10425. DEFPRINT(AST_Hole, noop);
  10426. DEFPRINT(AST_Infinity, function(self, output){
  10427. output.print("1/0");
  10428. });
  10429. DEFPRINT(AST_NaN, function(self, output){
  10430. output.print("0/0");
  10431. });
  10432. DEFPRINT(AST_This, function(self, output){
  10433. output.print("this");
  10434. });
  10435. DEFPRINT(AST_Constant, function(self, output){
  10436. output.print(self.getValue());
  10437. });
  10438. DEFPRINT(AST_String, function(self, output){
  10439. output.print_string(self.getValue());
  10440. });
  10441. DEFPRINT(AST_Number, function(self, output){
  10442. output.print(make_num(self.getValue()));
  10443. });
  10444. function regexp_safe_literal(code) {
  10445. return [
  10446. 0x5c , // \
  10447. 0x2f , // /
  10448. 0x2e , // .
  10449. 0x2b , // +
  10450. 0x2a , // *
  10451. 0x3f , // ?
  10452. 0x28 , // (
  10453. 0x29 , // )
  10454. 0x5b , // [
  10455. 0x5d , // ]
  10456. 0x7b , // {
  10457. 0x7d , // }
  10458. 0x24 , // $
  10459. 0x5e , // ^
  10460. 0x3a , // :
  10461. 0x7c , // |
  10462. 0x21 , // !
  10463. 0x0a , // \n
  10464. 0x0d , // \r
  10465. 0x00 , // \0
  10466. 0xfeff , // Unicode BOM
  10467. 0x2028 , // unicode "line separator"
  10468. 0x2029 , // unicode "paragraph separator"
  10469. ].indexOf(code) < 0;
  10470. };
  10471. DEFPRINT(AST_RegExp, function(self, output){
  10472. var str = self.getValue().toString();
  10473. if (output.option("ascii_only")) {
  10474. str = output.to_ascii(str);
  10475. } else if (output.option("unescape_regexps")) {
  10476. str = str.split("\\\\").map(function(str){
  10477. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  10478. var code = parseInt(s.substr(2), 16);
  10479. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  10480. });
  10481. }).join("\\\\");
  10482. }
  10483. output.print(str);
  10484. var p = output.parent();
  10485. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  10486. output.print(" ");
  10487. });
  10488. function force_statement(stat, output) {
  10489. if (output.option("bracketize")) {
  10490. if (!stat || stat instanceof AST_EmptyStatement)
  10491. output.print("{}");
  10492. else if (stat instanceof AST_BlockStatement)
  10493. stat.print(output);
  10494. else output.with_block(function(){
  10495. output.indent();
  10496. stat.print(output);
  10497. output.newline();
  10498. });
  10499. } else {
  10500. if (!stat || stat instanceof AST_EmptyStatement)
  10501. output.force_semicolon();
  10502. else
  10503. stat.print(output);
  10504. }
  10505. };
  10506. // return true if the node at the top of the stack (that means the
  10507. // innermost node in the current output) is lexically the first in
  10508. // a statement.
  10509. function first_in_statement(output) {
  10510. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  10511. while (i > 0) {
  10512. if (p instanceof AST_Statement && p.body === node)
  10513. return true;
  10514. if ((p instanceof AST_Seq && p.car === node ) ||
  10515. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  10516. (p instanceof AST_Dot && p.expression === node ) ||
  10517. (p instanceof AST_Sub && p.expression === node ) ||
  10518. (p instanceof AST_Conditional && p.condition === node ) ||
  10519. (p instanceof AST_Binary && p.left === node ) ||
  10520. (p instanceof AST_UnaryPostfix && p.expression === node ))
  10521. {
  10522. node = p;
  10523. p = a[--i];
  10524. } else {
  10525. return false;
  10526. }
  10527. }
  10528. };
  10529. // self should be AST_New. decide if we want to show parens or not.
  10530. function no_constructor_parens(self, output) {
  10531. return self.args.length == 0 && !output.option("beautify");
  10532. };
  10533. function best_of(a) {
  10534. var best = a[0], len = best.length;
  10535. for (var i = 1; i < a.length; ++i) {
  10536. if (a[i].length < len) {
  10537. best = a[i];
  10538. len = best.length;
  10539. }
  10540. }
  10541. return best;
  10542. };
  10543. function make_num(num) {
  10544. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  10545. if (Math.floor(num) === num) {
  10546. if (num >= 0) {
  10547. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  10548. "0" + num.toString(8)); // same.
  10549. } else {
  10550. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  10551. "-0" + (-num).toString(8)); // same.
  10552. }
  10553. if ((m = /^(.*?)(0+)$/.exec(num))) {
  10554. a.push(m[1] + "e" + m[2].length);
  10555. }
  10556. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  10557. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  10558. str.substr(str.indexOf(".")));
  10559. }
  10560. return best_of(a);
  10561. };
  10562. function make_block(stmt, output) {
  10563. if (stmt instanceof AST_BlockStatement) {
  10564. stmt.print(output);
  10565. return;
  10566. }
  10567. output.with_block(function(){
  10568. output.indent();
  10569. stmt.print(output);
  10570. output.newline();
  10571. });
  10572. };
  10573. /* -----[ source map generators ]----- */
  10574. function DEFMAP(nodetype, generator) {
  10575. nodetype.DEFMETHOD("add_source_map", function(stream){
  10576. generator(this, stream);
  10577. });
  10578. };
  10579. // We could easily add info for ALL nodes, but it seems to me that
  10580. // would be quite wasteful, hence this noop in the base class.
  10581. DEFMAP(AST_Node, noop);
  10582. function basic_sourcemap_gen(self, output) {
  10583. output.add_mapping(self.start);
  10584. };
  10585. // XXX: I'm not exactly sure if we need it for all of these nodes,
  10586. // or if we should add even more.
  10587. DEFMAP(AST_Directive, basic_sourcemap_gen);
  10588. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  10589. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  10590. DEFMAP(AST_Jump, basic_sourcemap_gen);
  10591. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  10592. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  10593. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  10594. DEFMAP(AST_Switch, basic_sourcemap_gen);
  10595. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  10596. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  10597. DEFMAP(AST_Toplevel, noop);
  10598. DEFMAP(AST_New, basic_sourcemap_gen);
  10599. DEFMAP(AST_Try, basic_sourcemap_gen);
  10600. DEFMAP(AST_Catch, basic_sourcemap_gen);
  10601. DEFMAP(AST_Finally, basic_sourcemap_gen);
  10602. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  10603. DEFMAP(AST_Constant, basic_sourcemap_gen);
  10604. DEFMAP(AST_ObjectProperty, function(self, output){
  10605. output.add_mapping(self.start, self.key);
  10606. });
  10607. })();
  10608. /***********************************************************************
  10609. A JavaScript tokenizer / parser / beautifier / compressor.
  10610. https://github.com/mishoo/UglifyJS2
  10611. -------------------------------- (C) ---------------------------------
  10612. Author: Mihai Bazon
  10613. <mihai.bazon@gmail.com>
  10614. http://mihai.bazon.net/blog
  10615. Distributed under the BSD license:
  10616. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10617. Redistribution and use in source and binary forms, with or without
  10618. modification, are permitted provided that the following conditions
  10619. are met:
  10620. * Redistributions of source code must retain the above
  10621. copyright notice, this list of conditions and the following
  10622. disclaimer.
  10623. * Redistributions in binary form must reproduce the above
  10624. copyright notice, this list of conditions and the following
  10625. disclaimer in the documentation and/or other materials
  10626. provided with the distribution.
  10627. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  10628. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  10629. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  10630. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  10631. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  10632. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  10633. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  10634. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10635. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  10636. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  10637. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  10638. SUCH DAMAGE.
  10639. ***********************************************************************/
  10640. "use strict";
  10641. function Compressor(options, false_by_default) {
  10642. if (!(this instanceof Compressor))
  10643. return new Compressor(options, false_by_default);
  10644. TreeTransformer.call(this, this.before, this.after);
  10645. this.options = defaults(options, {
  10646. sequences : !false_by_default,
  10647. properties : !false_by_default,
  10648. dead_code : !false_by_default,
  10649. drop_debugger : !false_by_default,
  10650. unsafe : false,
  10651. unsafe_comps : false,
  10652. conditionals : !false_by_default,
  10653. comparisons : !false_by_default,
  10654. evaluate : !false_by_default,
  10655. booleans : !false_by_default,
  10656. loops : !false_by_default,
  10657. unused : !false_by_default,
  10658. hoist_funs : !false_by_default,
  10659. keep_fargs : false,
  10660. hoist_vars : false,
  10661. if_return : !false_by_default,
  10662. join_vars : !false_by_default,
  10663. cascade : !false_by_default,
  10664. side_effects : !false_by_default,
  10665. pure_getters : false,
  10666. pure_funcs : null,
  10667. negate_iife : !false_by_default,
  10668. screw_ie8 : false,
  10669. drop_console : false,
  10670. angular : false,
  10671. warnings : true,
  10672. global_defs : {}
  10673. }, true);
  10674. };
  10675. Compressor.prototype = new TreeTransformer;
  10676. merge(Compressor.prototype, {
  10677. option: function(key) { return this.options[key] },
  10678. warn: function() {
  10679. if (this.options.warnings)
  10680. AST_Node.warn.apply(AST_Node, arguments);
  10681. },
  10682. before: function(node, descend, in_list) {
  10683. if (node._squeezed) return node;
  10684. var was_scope = false;
  10685. if (node instanceof AST_Scope) {
  10686. node = node.hoist_declarations(this);
  10687. was_scope = true;
  10688. }
  10689. descend(node, this);
  10690. node = node.optimize(this);
  10691. if (was_scope && node instanceof AST_Scope) {
  10692. node.drop_unused(this);
  10693. descend(node, this);
  10694. }
  10695. node._squeezed = true;
  10696. return node;
  10697. }
  10698. });
  10699. (function(){
  10700. function OPT(node, optimizer) {
  10701. node.DEFMETHOD("optimize", function(compressor){
  10702. var self = this;
  10703. if (self._optimized) return self;
  10704. var opt = optimizer(self, compressor);
  10705. opt._optimized = true;
  10706. if (opt === self) return opt;
  10707. return opt.transform(compressor);
  10708. });
  10709. };
  10710. OPT(AST_Node, function(self, compressor){
  10711. return self;
  10712. });
  10713. AST_Node.DEFMETHOD("equivalent_to", function(node){
  10714. // XXX: this is a rather expensive way to test two node's equivalence:
  10715. return this.print_to_string() == node.print_to_string();
  10716. });
  10717. function make_node(ctor, orig, props) {
  10718. if (!props) props = {};
  10719. if (orig) {
  10720. if (!props.start) props.start = orig.start;
  10721. if (!props.end) props.end = orig.end;
  10722. }
  10723. return new ctor(props);
  10724. };
  10725. function make_node_from_constant(compressor, val, orig) {
  10726. // XXX: WIP.
  10727. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  10728. // if (node instanceof AST_SymbolRef) {
  10729. // var scope = compressor.find_parent(AST_Scope);
  10730. // var def = scope.find_variable(node);
  10731. // node.thedef = def;
  10732. // return node;
  10733. // }
  10734. // })).transform(compressor);
  10735. if (val instanceof AST_Node) return val.transform(compressor);
  10736. switch (typeof val) {
  10737. case "string":
  10738. return make_node(AST_String, orig, {
  10739. value: val
  10740. }).optimize(compressor);
  10741. case "number":
  10742. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  10743. value: val
  10744. }).optimize(compressor);
  10745. case "boolean":
  10746. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  10747. case "undefined":
  10748. return make_node(AST_Undefined, orig).optimize(compressor);
  10749. default:
  10750. if (val === null) {
  10751. return make_node(AST_Null, orig).optimize(compressor);
  10752. }
  10753. if (val instanceof RegExp) {
  10754. return make_node(AST_RegExp, orig).optimize(compressor);
  10755. }
  10756. throw new Error(string_template("Can't handle constant of type: {type}", {
  10757. type: typeof val
  10758. }));
  10759. }
  10760. };
  10761. function as_statement_array(thing) {
  10762. if (thing === null) return [];
  10763. if (thing instanceof AST_BlockStatement) return thing.body;
  10764. if (thing instanceof AST_EmptyStatement) return [];
  10765. if (thing instanceof AST_Statement) return [ thing ];
  10766. throw new Error("Can't convert thing to statement array");
  10767. };
  10768. function is_empty(thing) {
  10769. if (thing === null) return true;
  10770. if (thing instanceof AST_EmptyStatement) return true;
  10771. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  10772. return false;
  10773. };
  10774. function loop_body(x) {
  10775. if (x instanceof AST_Switch) return x;
  10776. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  10777. return (x.body instanceof AST_BlockStatement ? x.body : x);
  10778. }
  10779. return x;
  10780. };
  10781. function tighten_body(statements, compressor) {
  10782. var CHANGED;
  10783. do {
  10784. CHANGED = false;
  10785. if (compressor.option("angular")) {
  10786. statements = process_for_angular(statements);
  10787. }
  10788. statements = eliminate_spurious_blocks(statements);
  10789. if (compressor.option("dead_code")) {
  10790. statements = eliminate_dead_code(statements, compressor);
  10791. }
  10792. if (compressor.option("if_return")) {
  10793. statements = handle_if_return(statements, compressor);
  10794. }
  10795. if (compressor.option("sequences")) {
  10796. statements = sequencesize(statements, compressor);
  10797. }
  10798. if (compressor.option("join_vars")) {
  10799. statements = join_consecutive_vars(statements, compressor);
  10800. }
  10801. } while (CHANGED);
  10802. if (compressor.option("negate_iife")) {
  10803. negate_iifes(statements, compressor);
  10804. }
  10805. return statements;
  10806. function process_for_angular(statements) {
  10807. function make_injector(func, name) {
  10808. return make_node(AST_SimpleStatement, func, {
  10809. body: make_node(AST_Assign, func, {
  10810. operator: "=",
  10811. left: make_node(AST_Dot, name, {
  10812. expression: make_node(AST_SymbolRef, name, name),
  10813. property: "$inject"
  10814. }),
  10815. right: make_node(AST_Array, func, {
  10816. elements: func.argnames.map(function(sym){
  10817. return make_node(AST_String, sym, { value: sym.name });
  10818. })
  10819. })
  10820. })
  10821. });
  10822. }
  10823. return statements.reduce(function(a, stat){
  10824. a.push(stat);
  10825. var token = stat.start;
  10826. var comments = token.comments_before;
  10827. if (comments && comments.length > 0) {
  10828. var last = comments.pop();
  10829. if (/@ngInject/.test(last.value)) {
  10830. // case 1: defun
  10831. if (stat instanceof AST_Defun) {
  10832. a.push(make_injector(stat, stat.name));
  10833. }
  10834. else if (stat instanceof AST_Definitions) {
  10835. stat.definitions.forEach(function(def){
  10836. if (def.value && def.value instanceof AST_Lambda) {
  10837. a.push(make_injector(def.value, def.name));
  10838. }
  10839. });
  10840. }
  10841. else {
  10842. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  10843. }
  10844. }
  10845. }
  10846. return a;
  10847. }, []);
  10848. }
  10849. function eliminate_spurious_blocks(statements) {
  10850. var seen_dirs = [];
  10851. return statements.reduce(function(a, stat){
  10852. if (stat instanceof AST_BlockStatement) {
  10853. CHANGED = true;
  10854. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  10855. } else if (stat instanceof AST_EmptyStatement) {
  10856. CHANGED = true;
  10857. } else if (stat instanceof AST_Directive) {
  10858. if (seen_dirs.indexOf(stat.value) < 0) {
  10859. a.push(stat);
  10860. seen_dirs.push(stat.value);
  10861. } else {
  10862. CHANGED = true;
  10863. }
  10864. } else {
  10865. a.push(stat);
  10866. }
  10867. return a;
  10868. }, []);
  10869. };
  10870. function handle_if_return(statements, compressor) {
  10871. var self = compressor.self();
  10872. var in_lambda = self instanceof AST_Lambda;
  10873. var ret = [];
  10874. loop: for (var i = statements.length; --i >= 0;) {
  10875. var stat = statements[i];
  10876. switch (true) {
  10877. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  10878. CHANGED = true;
  10879. // note, ret.length is probably always zero
  10880. // because we drop unreachable code before this
  10881. // step. nevertheless, it's good to check.
  10882. continue loop;
  10883. case stat instanceof AST_If:
  10884. if (stat.body instanceof AST_Return) {
  10885. //---
  10886. // pretty silly case, but:
  10887. // if (foo()) return; return; ==> foo(); return;
  10888. if (((in_lambda && ret.length == 0)
  10889. || (ret[0] instanceof AST_Return && !ret[0].value))
  10890. && !stat.body.value && !stat.alternative) {
  10891. CHANGED = true;
  10892. var cond = make_node(AST_SimpleStatement, stat.condition, {
  10893. body: stat.condition
  10894. });
  10895. ret.unshift(cond);
  10896. continue loop;
  10897. }
  10898. //---
  10899. // if (foo()) return x; return y; ==> return foo() ? x : y;
  10900. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  10901. CHANGED = true;
  10902. stat = stat.clone();
  10903. stat.alternative = ret[0];
  10904. ret[0] = stat.transform(compressor);
  10905. continue loop;
  10906. }
  10907. //---
  10908. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  10909. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  10910. CHANGED = true;
  10911. stat = stat.clone();
  10912. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  10913. value: make_node(AST_Undefined, stat)
  10914. });
  10915. ret[0] = stat.transform(compressor);
  10916. continue loop;
  10917. }
  10918. //---
  10919. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  10920. if (!stat.body.value && in_lambda) {
  10921. CHANGED = true;
  10922. stat = stat.clone();
  10923. stat.condition = stat.condition.negate(compressor);
  10924. stat.body = make_node(AST_BlockStatement, stat, {
  10925. body: as_statement_array(stat.alternative).concat(ret)
  10926. });
  10927. stat.alternative = null;
  10928. ret = [ stat.transform(compressor) ];
  10929. continue loop;
  10930. }
  10931. //---
  10932. if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  10933. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  10934. CHANGED = true;
  10935. ret.push(make_node(AST_Return, ret[0], {
  10936. value: make_node(AST_Undefined, ret[0])
  10937. }).transform(compressor));
  10938. ret = as_statement_array(stat.alternative).concat(ret);
  10939. ret.unshift(stat);
  10940. continue loop;
  10941. }
  10942. }
  10943. var ab = aborts(stat.body);
  10944. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  10945. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  10946. || (ab instanceof AST_Continue && self === loop_body(lct))
  10947. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  10948. if (ab.label) {
  10949. remove(ab.label.thedef.references, ab);
  10950. }
  10951. CHANGED = true;
  10952. var body = as_statement_array(stat.body).slice(0, -1);
  10953. stat = stat.clone();
  10954. stat.condition = stat.condition.negate(compressor);
  10955. stat.body = make_node(AST_BlockStatement, stat, {
  10956. body: as_statement_array(stat.alternative).concat(ret)
  10957. });
  10958. stat.alternative = make_node(AST_BlockStatement, stat, {
  10959. body: body
  10960. });
  10961. ret = [ stat.transform(compressor) ];
  10962. continue loop;
  10963. }
  10964. var ab = aborts(stat.alternative);
  10965. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  10966. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  10967. || (ab instanceof AST_Continue && self === loop_body(lct))
  10968. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  10969. if (ab.label) {
  10970. remove(ab.label.thedef.references, ab);
  10971. }
  10972. CHANGED = true;
  10973. stat = stat.clone();
  10974. stat.body = make_node(AST_BlockStatement, stat.body, {
  10975. body: as_statement_array(stat.body).concat(ret)
  10976. });
  10977. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  10978. body: as_statement_array(stat.alternative).slice(0, -1)
  10979. });
  10980. ret = [ stat.transform(compressor) ];
  10981. continue loop;
  10982. }
  10983. ret.unshift(stat);
  10984. break;
  10985. default:
  10986. ret.unshift(stat);
  10987. break;
  10988. }
  10989. }
  10990. return ret;
  10991. };
  10992. function eliminate_dead_code(statements, compressor) {
  10993. var has_quit = false;
  10994. var orig = statements.length;
  10995. var self = compressor.self();
  10996. statements = statements.reduce(function(a, stat){
  10997. if (has_quit) {
  10998. extract_declarations_from_unreachable_code(compressor, stat, a);
  10999. } else {
  11000. if (stat instanceof AST_LoopControl) {
  11001. var lct = compressor.loopcontrol_target(stat.label);
  11002. if ((stat instanceof AST_Break
  11003. && lct instanceof AST_BlockStatement
  11004. && loop_body(lct) === self) || (stat instanceof AST_Continue
  11005. && loop_body(lct) === self)) {
  11006. if (stat.label) {
  11007. remove(stat.label.thedef.references, stat);
  11008. }
  11009. } else {
  11010. a.push(stat);
  11011. }
  11012. } else {
  11013. a.push(stat);
  11014. }
  11015. if (aborts(stat)) has_quit = true;
  11016. }
  11017. return a;
  11018. }, []);
  11019. CHANGED = statements.length != orig;
  11020. return statements;
  11021. };
  11022. function sequencesize(statements, compressor) {
  11023. if (statements.length < 2) return statements;
  11024. var seq = [], ret = [];
  11025. function push_seq() {
  11026. seq = AST_Seq.from_array(seq);
  11027. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  11028. body: seq
  11029. }));
  11030. seq = [];
  11031. };
  11032. statements.forEach(function(stat){
  11033. if (stat instanceof AST_SimpleStatement) seq.push(stat.body);
  11034. else push_seq(), ret.push(stat);
  11035. });
  11036. push_seq();
  11037. ret = sequencesize_2(ret, compressor);
  11038. CHANGED = ret.length != statements.length;
  11039. return ret;
  11040. };
  11041. function sequencesize_2(statements, compressor) {
  11042. function cons_seq(right) {
  11043. ret.pop();
  11044. var left = prev.body;
  11045. if (left instanceof AST_Seq) {
  11046. left.add(right);
  11047. } else {
  11048. left = AST_Seq.cons(left, right);
  11049. }
  11050. return left.transform(compressor);
  11051. };
  11052. var ret = [], prev = null;
  11053. statements.forEach(function(stat){
  11054. if (prev) {
  11055. if (stat instanceof AST_For) {
  11056. var opera = {};
  11057. try {
  11058. prev.body.walk(new TreeWalker(function(node){
  11059. if (node instanceof AST_Binary && node.operator == "in")
  11060. throw opera;
  11061. }));
  11062. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  11063. stat.init = cons_seq(stat.init);
  11064. }
  11065. else if (!stat.init) {
  11066. stat.init = prev.body;
  11067. ret.pop();
  11068. }
  11069. } catch(ex) {
  11070. if (ex !== opera) throw ex;
  11071. }
  11072. }
  11073. else if (stat instanceof AST_If) {
  11074. stat.condition = cons_seq(stat.condition);
  11075. }
  11076. else if (stat instanceof AST_With) {
  11077. stat.expression = cons_seq(stat.expression);
  11078. }
  11079. else if (stat instanceof AST_Exit && stat.value) {
  11080. stat.value = cons_seq(stat.value);
  11081. }
  11082. else if (stat instanceof AST_Exit) {
  11083. stat.value = cons_seq(make_node(AST_Undefined, stat));
  11084. }
  11085. else if (stat instanceof AST_Switch) {
  11086. stat.expression = cons_seq(stat.expression);
  11087. }
  11088. }
  11089. ret.push(stat);
  11090. prev = stat instanceof AST_SimpleStatement ? stat : null;
  11091. });
  11092. return ret;
  11093. };
  11094. function join_consecutive_vars(statements, compressor) {
  11095. var prev = null;
  11096. return statements.reduce(function(a, stat){
  11097. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  11098. prev.definitions = prev.definitions.concat(stat.definitions);
  11099. CHANGED = true;
  11100. }
  11101. else if (stat instanceof AST_For
  11102. && prev instanceof AST_Definitions
  11103. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  11104. CHANGED = true;
  11105. a.pop();
  11106. if (stat.init) {
  11107. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  11108. } else {
  11109. stat.init = prev;
  11110. }
  11111. a.push(stat);
  11112. prev = stat;
  11113. }
  11114. else {
  11115. prev = stat;
  11116. a.push(stat);
  11117. }
  11118. return a;
  11119. }, []);
  11120. };
  11121. function negate_iifes(statements, compressor) {
  11122. statements.forEach(function(stat){
  11123. if (stat instanceof AST_SimpleStatement) {
  11124. stat.body = (function transform(thing) {
  11125. return thing.transform(new TreeTransformer(function(node){
  11126. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  11127. return make_node(AST_UnaryPrefix, node, {
  11128. operator: "!",
  11129. expression: node
  11130. });
  11131. }
  11132. else if (node instanceof AST_Call) {
  11133. node.expression = transform(node.expression);
  11134. }
  11135. else if (node instanceof AST_Seq) {
  11136. node.car = transform(node.car);
  11137. }
  11138. else if (node instanceof AST_Conditional) {
  11139. var expr = transform(node.condition);
  11140. if (expr !== node.condition) {
  11141. // it has been negated, reverse
  11142. node.condition = expr;
  11143. var tmp = node.consequent;
  11144. node.consequent = node.alternative;
  11145. node.alternative = tmp;
  11146. }
  11147. }
  11148. return node;
  11149. }));
  11150. })(stat.body);
  11151. }
  11152. });
  11153. };
  11154. };
  11155. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  11156. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  11157. stat.walk(new TreeWalker(function(node){
  11158. if (node instanceof AST_Definitions) {
  11159. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  11160. node.remove_initializers();
  11161. target.push(node);
  11162. return true;
  11163. }
  11164. if (node instanceof AST_Defun) {
  11165. target.push(node);
  11166. return true;
  11167. }
  11168. if (node instanceof AST_Scope) {
  11169. return true;
  11170. }
  11171. }));
  11172. };
  11173. /* -----[ boolean/negation helpers ]----- */
  11174. // methods to determine whether an expression has a boolean result type
  11175. (function (def){
  11176. var unary_bool = [ "!", "delete" ];
  11177. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  11178. def(AST_Node, function(){ return false });
  11179. def(AST_UnaryPrefix, function(){
  11180. return member(this.operator, unary_bool);
  11181. });
  11182. def(AST_Binary, function(){
  11183. return member(this.operator, binary_bool) ||
  11184. ( (this.operator == "&&" || this.operator == "||") &&
  11185. this.left.is_boolean() && this.right.is_boolean() );
  11186. });
  11187. def(AST_Conditional, function(){
  11188. return this.consequent.is_boolean() && this.alternative.is_boolean();
  11189. });
  11190. def(AST_Assign, function(){
  11191. return this.operator == "=" && this.right.is_boolean();
  11192. });
  11193. def(AST_Seq, function(){
  11194. return this.cdr.is_boolean();
  11195. });
  11196. def(AST_True, function(){ return true });
  11197. def(AST_False, function(){ return true });
  11198. })(function(node, func){
  11199. node.DEFMETHOD("is_boolean", func);
  11200. });
  11201. // methods to determine if an expression has a string result type
  11202. (function (def){
  11203. def(AST_Node, function(){ return false });
  11204. def(AST_String, function(){ return true });
  11205. def(AST_UnaryPrefix, function(){
  11206. return this.operator == "typeof";
  11207. });
  11208. def(AST_Binary, function(compressor){
  11209. return this.operator == "+" &&
  11210. (this.left.is_string(compressor) || this.right.is_string(compressor));
  11211. });
  11212. def(AST_Assign, function(compressor){
  11213. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  11214. });
  11215. def(AST_Seq, function(compressor){
  11216. return this.cdr.is_string(compressor);
  11217. });
  11218. def(AST_Conditional, function(compressor){
  11219. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  11220. });
  11221. def(AST_Call, function(compressor){
  11222. return compressor.option("unsafe")
  11223. && this.expression instanceof AST_SymbolRef
  11224. && this.expression.name == "String"
  11225. && this.expression.undeclared();
  11226. });
  11227. })(function(node, func){
  11228. node.DEFMETHOD("is_string", func);
  11229. });
  11230. function best_of(ast1, ast2) {
  11231. return ast1.print_to_string().length >
  11232. ast2.print_to_string().length
  11233. ? ast2 : ast1;
  11234. };
  11235. // methods to evaluate a constant expression
  11236. (function (def){
  11237. // The evaluate method returns an array with one or two
  11238. // elements. If the node has been successfully reduced to a
  11239. // constant, then the second element tells us the value;
  11240. // otherwise the second element is missing. The first element
  11241. // of the array is always an AST_Node descendant; if
  11242. // evaluation was successful it's a node that represents the
  11243. // constant; otherwise it's the original or a replacement node.
  11244. AST_Node.DEFMETHOD("evaluate", function(compressor){
  11245. if (!compressor.option("evaluate")) return [ this ];
  11246. try {
  11247. var val = this._eval(compressor);
  11248. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  11249. } catch(ex) {
  11250. if (ex !== def) throw ex;
  11251. return [ this ];
  11252. }
  11253. });
  11254. def(AST_Statement, function(){
  11255. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  11256. });
  11257. def(AST_Function, function(){
  11258. // XXX: AST_Function inherits from AST_Scope, which itself
  11259. // inherits from AST_Statement; however, an AST_Function
  11260. // isn't really a statement. This could byte in other
  11261. // places too. :-( Wish JS had multiple inheritance.
  11262. throw def;
  11263. });
  11264. function ev(node, compressor) {
  11265. if (!compressor) throw new Error("Compressor must be passed");
  11266. return node._eval(compressor);
  11267. };
  11268. def(AST_Node, function(){
  11269. throw def; // not constant
  11270. });
  11271. def(AST_Constant, function(){
  11272. return this.getValue();
  11273. });
  11274. def(AST_UnaryPrefix, function(compressor){
  11275. var e = this.expression;
  11276. switch (this.operator) {
  11277. case "!": return !ev(e, compressor);
  11278. case "typeof":
  11279. // Function would be evaluated to an array and so typeof would
  11280. // incorrectly return 'object'. Hence making is a special case.
  11281. if (e instanceof AST_Function) return typeof function(){};
  11282. e = ev(e, compressor);
  11283. // typeof <RegExp> returns "object" or "function" on different platforms
  11284. // so cannot evaluate reliably
  11285. if (e instanceof RegExp) throw def;
  11286. return typeof e;
  11287. case "void": return void ev(e, compressor);
  11288. case "~": return ~ev(e, compressor);
  11289. case "-":
  11290. e = ev(e, compressor);
  11291. if (e === 0) throw def;
  11292. return -e;
  11293. case "+": return +ev(e, compressor);
  11294. }
  11295. throw def;
  11296. });
  11297. def(AST_Binary, function(c){
  11298. var left = this.left, right = this.right;
  11299. switch (this.operator) {
  11300. case "&&" : return ev(left, c) && ev(right, c);
  11301. case "||" : return ev(left, c) || ev(right, c);
  11302. case "|" : return ev(left, c) | ev(right, c);
  11303. case "&" : return ev(left, c) & ev(right, c);
  11304. case "^" : return ev(left, c) ^ ev(right, c);
  11305. case "+" : return ev(left, c) + ev(right, c);
  11306. case "*" : return ev(left, c) * ev(right, c);
  11307. case "/" : return ev(left, c) / ev(right, c);
  11308. case "%" : return ev(left, c) % ev(right, c);
  11309. case "-" : return ev(left, c) - ev(right, c);
  11310. case "<<" : return ev(left, c) << ev(right, c);
  11311. case ">>" : return ev(left, c) >> ev(right, c);
  11312. case ">>>" : return ev(left, c) >>> ev(right, c);
  11313. case "==" : return ev(left, c) == ev(right, c);
  11314. case "===" : return ev(left, c) === ev(right, c);
  11315. case "!=" : return ev(left, c) != ev(right, c);
  11316. case "!==" : return ev(left, c) !== ev(right, c);
  11317. case "<" : return ev(left, c) < ev(right, c);
  11318. case "<=" : return ev(left, c) <= ev(right, c);
  11319. case ">" : return ev(left, c) > ev(right, c);
  11320. case ">=" : return ev(left, c) >= ev(right, c);
  11321. case "in" : return ev(left, c) in ev(right, c);
  11322. case "instanceof" : return ev(left, c) instanceof ev(right, c);
  11323. }
  11324. throw def;
  11325. });
  11326. def(AST_Conditional, function(compressor){
  11327. return ev(this.condition, compressor)
  11328. ? ev(this.consequent, compressor)
  11329. : ev(this.alternative, compressor);
  11330. });
  11331. def(AST_SymbolRef, function(compressor){
  11332. var d = this.definition();
  11333. if (d && d.constant && d.init) return ev(d.init, compressor);
  11334. throw def;
  11335. });
  11336. def(AST_Dot, function(compressor){
  11337. if (compressor.option("unsafe") && this.property == "length") {
  11338. var str = ev(this.expression, compressor);
  11339. if (typeof str == "string")
  11340. return str.length;
  11341. }
  11342. throw def;
  11343. });
  11344. })(function(node, func){
  11345. node.DEFMETHOD("_eval", func);
  11346. });
  11347. // method to negate an expression
  11348. (function(def){
  11349. function basic_negation(exp) {
  11350. return make_node(AST_UnaryPrefix, exp, {
  11351. operator: "!",
  11352. expression: exp
  11353. });
  11354. };
  11355. def(AST_Node, function(){
  11356. return basic_negation(this);
  11357. });
  11358. def(AST_Statement, function(){
  11359. throw new Error("Cannot negate a statement");
  11360. });
  11361. def(AST_Function, function(){
  11362. return basic_negation(this);
  11363. });
  11364. def(AST_UnaryPrefix, function(){
  11365. if (this.operator == "!")
  11366. return this.expression;
  11367. return basic_negation(this);
  11368. });
  11369. def(AST_Seq, function(compressor){
  11370. var self = this.clone();
  11371. self.cdr = self.cdr.negate(compressor);
  11372. return self;
  11373. });
  11374. def(AST_Conditional, function(compressor){
  11375. var self = this.clone();
  11376. self.consequent = self.consequent.negate(compressor);
  11377. self.alternative = self.alternative.negate(compressor);
  11378. return best_of(basic_negation(this), self);
  11379. });
  11380. def(AST_Binary, function(compressor){
  11381. var self = this.clone(), op = this.operator;
  11382. if (compressor.option("unsafe_comps")) {
  11383. switch (op) {
  11384. case "<=" : self.operator = ">" ; return self;
  11385. case "<" : self.operator = ">=" ; return self;
  11386. case ">=" : self.operator = "<" ; return self;
  11387. case ">" : self.operator = "<=" ; return self;
  11388. }
  11389. }
  11390. switch (op) {
  11391. case "==" : self.operator = "!="; return self;
  11392. case "!=" : self.operator = "=="; return self;
  11393. case "===": self.operator = "!=="; return self;
  11394. case "!==": self.operator = "==="; return self;
  11395. case "&&":
  11396. self.operator = "||";
  11397. self.left = self.left.negate(compressor);
  11398. self.right = self.right.negate(compressor);
  11399. return best_of(basic_negation(this), self);
  11400. case "||":
  11401. self.operator = "&&";
  11402. self.left = self.left.negate(compressor);
  11403. self.right = self.right.negate(compressor);
  11404. return best_of(basic_negation(this), self);
  11405. }
  11406. return basic_negation(this);
  11407. });
  11408. })(function(node, func){
  11409. node.DEFMETHOD("negate", function(compressor){
  11410. return func.call(this, compressor);
  11411. });
  11412. });
  11413. // determine if expression has side effects
  11414. (function(def){
  11415. def(AST_Node, function(compressor){ return true });
  11416. def(AST_EmptyStatement, function(compressor){ return false });
  11417. def(AST_Constant, function(compressor){ return false });
  11418. def(AST_This, function(compressor){ return false });
  11419. def(AST_Call, function(compressor){
  11420. var pure = compressor.option("pure_funcs");
  11421. if (!pure) return true;
  11422. return pure.indexOf(this.expression.print_to_string()) < 0;
  11423. });
  11424. def(AST_Block, function(compressor){
  11425. for (var i = this.body.length; --i >= 0;) {
  11426. if (this.body[i].has_side_effects(compressor))
  11427. return true;
  11428. }
  11429. return false;
  11430. });
  11431. def(AST_SimpleStatement, function(compressor){
  11432. return this.body.has_side_effects(compressor);
  11433. });
  11434. def(AST_Defun, function(compressor){ return true });
  11435. def(AST_Function, function(compressor){ return false });
  11436. def(AST_Binary, function(compressor){
  11437. return this.left.has_side_effects(compressor)
  11438. || this.right.has_side_effects(compressor);
  11439. });
  11440. def(AST_Assign, function(compressor){ return true });
  11441. def(AST_Conditional, function(compressor){
  11442. return this.condition.has_side_effects(compressor)
  11443. || this.consequent.has_side_effects(compressor)
  11444. || this.alternative.has_side_effects(compressor);
  11445. });
  11446. def(AST_Unary, function(compressor){
  11447. return this.operator == "delete"
  11448. || this.operator == "++"
  11449. || this.operator == "--"
  11450. || this.expression.has_side_effects(compressor);
  11451. });
  11452. def(AST_SymbolRef, function(compressor){ return false });
  11453. def(AST_Object, function(compressor){
  11454. for (var i = this.properties.length; --i >= 0;)
  11455. if (this.properties[i].has_side_effects(compressor))
  11456. return true;
  11457. return false;
  11458. });
  11459. def(AST_ObjectProperty, function(compressor){
  11460. return this.value.has_side_effects(compressor);
  11461. });
  11462. def(AST_Array, function(compressor){
  11463. for (var i = this.elements.length; --i >= 0;)
  11464. if (this.elements[i].has_side_effects(compressor))
  11465. return true;
  11466. return false;
  11467. });
  11468. def(AST_Dot, function(compressor){
  11469. if (!compressor.option("pure_getters")) return true;
  11470. return this.expression.has_side_effects(compressor);
  11471. });
  11472. def(AST_Sub, function(compressor){
  11473. if (!compressor.option("pure_getters")) return true;
  11474. return this.expression.has_side_effects(compressor)
  11475. || this.property.has_side_effects(compressor);
  11476. });
  11477. def(AST_PropAccess, function(compressor){
  11478. return !compressor.option("pure_getters");
  11479. });
  11480. def(AST_Seq, function(compressor){
  11481. return this.car.has_side_effects(compressor)
  11482. || this.cdr.has_side_effects(compressor);
  11483. });
  11484. })(function(node, func){
  11485. node.DEFMETHOD("has_side_effects", func);
  11486. });
  11487. // tell me if a statement aborts
  11488. function aborts(thing) {
  11489. return thing && thing.aborts();
  11490. };
  11491. (function(def){
  11492. def(AST_Statement, function(){ return null });
  11493. def(AST_Jump, function(){ return this });
  11494. function block_aborts(){
  11495. var n = this.body.length;
  11496. return n > 0 && aborts(this.body[n - 1]);
  11497. };
  11498. def(AST_BlockStatement, block_aborts);
  11499. def(AST_SwitchBranch, block_aborts);
  11500. def(AST_If, function(){
  11501. return this.alternative && aborts(this.body) && aborts(this.alternative);
  11502. });
  11503. })(function(node, func){
  11504. node.DEFMETHOD("aborts", func);
  11505. });
  11506. /* -----[ optimizers ]----- */
  11507. OPT(AST_Directive, function(self, compressor){
  11508. if (self.scope.has_directive(self.value) !== self.scope) {
  11509. return make_node(AST_EmptyStatement, self);
  11510. }
  11511. return self;
  11512. });
  11513. OPT(AST_Debugger, function(self, compressor){
  11514. if (compressor.option("drop_debugger"))
  11515. return make_node(AST_EmptyStatement, self);
  11516. return self;
  11517. });
  11518. OPT(AST_LabeledStatement, function(self, compressor){
  11519. if (self.body instanceof AST_Break
  11520. && compressor.loopcontrol_target(self.body.label) === self.body) {
  11521. return make_node(AST_EmptyStatement, self);
  11522. }
  11523. return self.label.references.length == 0 ? self.body : self;
  11524. });
  11525. OPT(AST_Block, function(self, compressor){
  11526. self.body = tighten_body(self.body, compressor);
  11527. return self;
  11528. });
  11529. OPT(AST_BlockStatement, function(self, compressor){
  11530. self.body = tighten_body(self.body, compressor);
  11531. switch (self.body.length) {
  11532. case 1: return self.body[0];
  11533. case 0: return make_node(AST_EmptyStatement, self);
  11534. }
  11535. return self;
  11536. });
  11537. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  11538. var self = this;
  11539. if (compressor.option("unused")
  11540. && !(self instanceof AST_Toplevel)
  11541. && !self.uses_eval
  11542. ) {
  11543. var in_use = [];
  11544. var initializations = new Dictionary();
  11545. // pass 1: find out which symbols are directly used in
  11546. // this scope (not in nested scopes).
  11547. var scope = this;
  11548. var tw = new TreeWalker(function(node, descend){
  11549. if (node !== self) {
  11550. if (node instanceof AST_Defun) {
  11551. initializations.add(node.name.name, node);
  11552. return true; // don't go in nested scopes
  11553. }
  11554. if (node instanceof AST_Definitions && scope === self) {
  11555. node.definitions.forEach(function(def){
  11556. if (def.value) {
  11557. initializations.add(def.name.name, def.value);
  11558. if (def.value.has_side_effects(compressor)) {
  11559. def.value.walk(tw);
  11560. }
  11561. }
  11562. });
  11563. return true;
  11564. }
  11565. if (node instanceof AST_SymbolRef) {
  11566. push_uniq(in_use, node.definition());
  11567. return true;
  11568. }
  11569. if (node instanceof AST_Scope) {
  11570. var save_scope = scope;
  11571. scope = node;
  11572. descend();
  11573. scope = save_scope;
  11574. return true;
  11575. }
  11576. }
  11577. });
  11578. self.walk(tw);
  11579. // pass 2: for every used symbol we need to walk its
  11580. // initialization code to figure out if it uses other
  11581. // symbols (that may not be in_use).
  11582. for (var i = 0; i < in_use.length; ++i) {
  11583. in_use[i].orig.forEach(function(decl){
  11584. // undeclared globals will be instanceof AST_SymbolRef
  11585. var init = initializations.get(decl.name);
  11586. if (init) init.forEach(function(init){
  11587. var tw = new TreeWalker(function(node){
  11588. if (node instanceof AST_SymbolRef) {
  11589. push_uniq(in_use, node.definition());
  11590. }
  11591. });
  11592. init.walk(tw);
  11593. });
  11594. });
  11595. }
  11596. // pass 3: we should drop declarations not in_use
  11597. var tt = new TreeTransformer(
  11598. function before(node, descend, in_list) {
  11599. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  11600. if (!compressor.option("keep_fargs")) {
  11601. for (var a = node.argnames, i = a.length; --i >= 0;) {
  11602. var sym = a[i];
  11603. if (sym.unreferenced()) {
  11604. a.pop();
  11605. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  11606. name : sym.name,
  11607. file : sym.start.file,
  11608. line : sym.start.line,
  11609. col : sym.start.col
  11610. });
  11611. }
  11612. else break;
  11613. }
  11614. }
  11615. }
  11616. if (node instanceof AST_Defun && node !== self) {
  11617. if (!member(node.name.definition(), in_use)) {
  11618. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  11619. name : node.name.name,
  11620. file : node.name.start.file,
  11621. line : node.name.start.line,
  11622. col : node.name.start.col
  11623. });
  11624. return make_node(AST_EmptyStatement, node);
  11625. }
  11626. return node;
  11627. }
  11628. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  11629. var def = node.definitions.filter(function(def){
  11630. if (member(def.name.definition(), in_use)) return true;
  11631. var w = {
  11632. name : def.name.name,
  11633. file : def.name.start.file,
  11634. line : def.name.start.line,
  11635. col : def.name.start.col
  11636. };
  11637. if (def.value && def.value.has_side_effects(compressor)) {
  11638. def._unused_side_effects = true;
  11639. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  11640. return true;
  11641. }
  11642. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  11643. return false;
  11644. });
  11645. // place uninitialized names at the start
  11646. def = mergeSort(def, function(a, b){
  11647. if (!a.value && b.value) return -1;
  11648. if (!b.value && a.value) return 1;
  11649. return 0;
  11650. });
  11651. // for unused names whose initialization has
  11652. // side effects, we can cascade the init. code
  11653. // into the next one, or next statement.
  11654. var side_effects = [];
  11655. for (var i = 0; i < def.length;) {
  11656. var x = def[i];
  11657. if (x._unused_side_effects) {
  11658. side_effects.push(x.value);
  11659. def.splice(i, 1);
  11660. } else {
  11661. if (side_effects.length > 0) {
  11662. side_effects.push(x.value);
  11663. x.value = AST_Seq.from_array(side_effects);
  11664. side_effects = [];
  11665. }
  11666. ++i;
  11667. }
  11668. }
  11669. if (side_effects.length > 0) {
  11670. side_effects = make_node(AST_BlockStatement, node, {
  11671. body: [ make_node(AST_SimpleStatement, node, {
  11672. body: AST_Seq.from_array(side_effects)
  11673. }) ]
  11674. });
  11675. } else {
  11676. side_effects = null;
  11677. }
  11678. if (def.length == 0 && !side_effects) {
  11679. return make_node(AST_EmptyStatement, node);
  11680. }
  11681. if (def.length == 0) {
  11682. return side_effects;
  11683. }
  11684. node.definitions = def;
  11685. if (side_effects) {
  11686. side_effects.body.unshift(node);
  11687. node = side_effects;
  11688. }
  11689. return node;
  11690. }
  11691. if (node instanceof AST_For) {
  11692. descend(node, this);
  11693. if (node.init instanceof AST_BlockStatement) {
  11694. // certain combination of unused name + side effect leads to:
  11695. // https://github.com/mishoo/UglifyJS2/issues/44
  11696. // that's an invalid AST.
  11697. // We fix it at this stage by moving the `var` outside the `for`.
  11698. var body = node.init.body.slice(0, -1);
  11699. node.init = node.init.body.slice(-1)[0].body;
  11700. body.push(node);
  11701. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  11702. body: body
  11703. });
  11704. }
  11705. }
  11706. if (node instanceof AST_Scope && node !== self)
  11707. return node;
  11708. }
  11709. );
  11710. self.transform(tt);
  11711. }
  11712. });
  11713. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  11714. var hoist_funs = compressor.option("hoist_funs");
  11715. var hoist_vars = compressor.option("hoist_vars");
  11716. var self = this;
  11717. if (hoist_funs || hoist_vars) {
  11718. var dirs = [];
  11719. var hoisted = [];
  11720. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  11721. // let's count var_decl first, we seem to waste a lot of
  11722. // space if we hoist `var` when there's only one.
  11723. self.walk(new TreeWalker(function(node){
  11724. if (node instanceof AST_Scope && node !== self)
  11725. return true;
  11726. if (node instanceof AST_Var) {
  11727. ++var_decl;
  11728. return true;
  11729. }
  11730. }));
  11731. hoist_vars = hoist_vars && var_decl > 1;
  11732. var tt = new TreeTransformer(
  11733. function before(node) {
  11734. if (node !== self) {
  11735. if (node instanceof AST_Directive) {
  11736. dirs.push(node);
  11737. return make_node(AST_EmptyStatement, node);
  11738. }
  11739. if (node instanceof AST_Defun && hoist_funs) {
  11740. hoisted.push(node);
  11741. return make_node(AST_EmptyStatement, node);
  11742. }
  11743. if (node instanceof AST_Var && hoist_vars) {
  11744. node.definitions.forEach(function(def){
  11745. vars.set(def.name.name, def);
  11746. ++vars_found;
  11747. });
  11748. var seq = node.to_assignments();
  11749. var p = tt.parent();
  11750. if (p instanceof AST_ForIn && p.init === node) {
  11751. if (seq == null) return node.definitions[0].name;
  11752. return seq;
  11753. }
  11754. if (p instanceof AST_For && p.init === node) {
  11755. return seq;
  11756. }
  11757. if (!seq) return make_node(AST_EmptyStatement, node);
  11758. return make_node(AST_SimpleStatement, node, {
  11759. body: seq
  11760. });
  11761. }
  11762. if (node instanceof AST_Scope)
  11763. return node; // to avoid descending in nested scopes
  11764. }
  11765. }
  11766. );
  11767. self = self.transform(tt);
  11768. if (vars_found > 0) {
  11769. // collect only vars which don't show up in self's arguments list
  11770. var defs = [];
  11771. vars.each(function(def, name){
  11772. if (self instanceof AST_Lambda
  11773. && find_if(function(x){ return x.name == def.name.name },
  11774. self.argnames)) {
  11775. vars.del(name);
  11776. } else {
  11777. def = def.clone();
  11778. def.value = null;
  11779. defs.push(def);
  11780. vars.set(name, def);
  11781. }
  11782. });
  11783. if (defs.length > 0) {
  11784. // try to merge in assignments
  11785. for (var i = 0; i < self.body.length;) {
  11786. if (self.body[i] instanceof AST_SimpleStatement) {
  11787. var expr = self.body[i].body, sym, assign;
  11788. if (expr instanceof AST_Assign
  11789. && expr.operator == "="
  11790. && (sym = expr.left) instanceof AST_Symbol
  11791. && vars.has(sym.name))
  11792. {
  11793. var def = vars.get(sym.name);
  11794. if (def.value) break;
  11795. def.value = expr.right;
  11796. remove(defs, def);
  11797. defs.push(def);
  11798. self.body.splice(i, 1);
  11799. continue;
  11800. }
  11801. if (expr instanceof AST_Seq
  11802. && (assign = expr.car) instanceof AST_Assign
  11803. && assign.operator == "="
  11804. && (sym = assign.left) instanceof AST_Symbol
  11805. && vars.has(sym.name))
  11806. {
  11807. var def = vars.get(sym.name);
  11808. if (def.value) break;
  11809. def.value = assign.right;
  11810. remove(defs, def);
  11811. defs.push(def);
  11812. self.body[i].body = expr.cdr;
  11813. continue;
  11814. }
  11815. }
  11816. if (self.body[i] instanceof AST_EmptyStatement) {
  11817. self.body.splice(i, 1);
  11818. continue;
  11819. }
  11820. if (self.body[i] instanceof AST_BlockStatement) {
  11821. var tmp = [ i, 1 ].concat(self.body[i].body);
  11822. self.body.splice.apply(self.body, tmp);
  11823. continue;
  11824. }
  11825. break;
  11826. }
  11827. defs = make_node(AST_Var, self, {
  11828. definitions: defs
  11829. });
  11830. hoisted.push(defs);
  11831. };
  11832. }
  11833. self.body = dirs.concat(hoisted, self.body);
  11834. }
  11835. return self;
  11836. });
  11837. OPT(AST_SimpleStatement, function(self, compressor){
  11838. if (compressor.option("side_effects")) {
  11839. if (!self.body.has_side_effects(compressor)) {
  11840. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  11841. return make_node(AST_EmptyStatement, self);
  11842. }
  11843. }
  11844. return self;
  11845. });
  11846. OPT(AST_DWLoop, function(self, compressor){
  11847. var cond = self.condition.evaluate(compressor);
  11848. self.condition = cond[0];
  11849. if (!compressor.option("loops")) return self;
  11850. if (cond.length > 1) {
  11851. if (cond[1]) {
  11852. return make_node(AST_For, self, {
  11853. body: self.body
  11854. });
  11855. } else if (self instanceof AST_While) {
  11856. if (compressor.option("dead_code")) {
  11857. var a = [];
  11858. extract_declarations_from_unreachable_code(compressor, self.body, a);
  11859. return make_node(AST_BlockStatement, self, { body: a });
  11860. }
  11861. }
  11862. }
  11863. return self;
  11864. });
  11865. function if_break_in_loop(self, compressor) {
  11866. function drop_it(rest) {
  11867. rest = as_statement_array(rest);
  11868. if (self.body instanceof AST_BlockStatement) {
  11869. self.body = self.body.clone();
  11870. self.body.body = rest.concat(self.body.body.slice(1));
  11871. self.body = self.body.transform(compressor);
  11872. } else {
  11873. self.body = make_node(AST_BlockStatement, self.body, {
  11874. body: rest
  11875. }).transform(compressor);
  11876. }
  11877. if_break_in_loop(self, compressor);
  11878. }
  11879. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  11880. if (first instanceof AST_If) {
  11881. if (first.body instanceof AST_Break
  11882. && compressor.loopcontrol_target(first.body.label) === self) {
  11883. if (self.condition) {
  11884. self.condition = make_node(AST_Binary, self.condition, {
  11885. left: self.condition,
  11886. operator: "&&",
  11887. right: first.condition.negate(compressor),
  11888. });
  11889. } else {
  11890. self.condition = first.condition.negate(compressor);
  11891. }
  11892. drop_it(first.alternative);
  11893. }
  11894. else if (first.alternative instanceof AST_Break
  11895. && compressor.loopcontrol_target(first.alternative.label) === self) {
  11896. if (self.condition) {
  11897. self.condition = make_node(AST_Binary, self.condition, {
  11898. left: self.condition,
  11899. operator: "&&",
  11900. right: first.condition,
  11901. });
  11902. } else {
  11903. self.condition = first.condition;
  11904. }
  11905. drop_it(first.body);
  11906. }
  11907. }
  11908. };
  11909. OPT(AST_While, function(self, compressor) {
  11910. if (!compressor.option("loops")) return self;
  11911. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  11912. if (self instanceof AST_While) {
  11913. if_break_in_loop(self, compressor);
  11914. self = make_node(AST_For, self, self).transform(compressor);
  11915. }
  11916. return self;
  11917. });
  11918. OPT(AST_For, function(self, compressor){
  11919. var cond = self.condition;
  11920. if (cond) {
  11921. cond = cond.evaluate(compressor);
  11922. self.condition = cond[0];
  11923. }
  11924. if (!compressor.option("loops")) return self;
  11925. if (cond) {
  11926. if (cond.length > 1 && !cond[1]) {
  11927. if (compressor.option("dead_code")) {
  11928. var a = [];
  11929. if (self.init instanceof AST_Statement) {
  11930. a.push(self.init);
  11931. }
  11932. else if (self.init) {
  11933. a.push(make_node(AST_SimpleStatement, self.init, {
  11934. body: self.init
  11935. }));
  11936. }
  11937. extract_declarations_from_unreachable_code(compressor, self.body, a);
  11938. return make_node(AST_BlockStatement, self, { body: a });
  11939. }
  11940. }
  11941. }
  11942. if_break_in_loop(self, compressor);
  11943. return self;
  11944. });
  11945. OPT(AST_If, function(self, compressor){
  11946. if (!compressor.option("conditionals")) return self;
  11947. // if condition can be statically determined, warn and drop
  11948. // one of the blocks. note, statically determined implies
  11949. // “has no side effects”; also it doesn't work for cases like
  11950. // `x && true`, though it probably should.
  11951. var cond = self.condition.evaluate(compressor);
  11952. self.condition = cond[0];
  11953. if (cond.length > 1) {
  11954. if (cond[1]) {
  11955. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  11956. if (compressor.option("dead_code")) {
  11957. var a = [];
  11958. if (self.alternative) {
  11959. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  11960. }
  11961. a.push(self.body);
  11962. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  11963. }
  11964. } else {
  11965. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  11966. if (compressor.option("dead_code")) {
  11967. var a = [];
  11968. extract_declarations_from_unreachable_code(compressor, self.body, a);
  11969. if (self.alternative) a.push(self.alternative);
  11970. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  11971. }
  11972. }
  11973. }
  11974. if (is_empty(self.alternative)) self.alternative = null;
  11975. var negated = self.condition.negate(compressor);
  11976. var negated_is_best = best_of(self.condition, negated) === negated;
  11977. if (self.alternative && negated_is_best) {
  11978. negated_is_best = false; // because we already do the switch here.
  11979. self.condition = negated;
  11980. var tmp = self.body;
  11981. self.body = self.alternative || make_node(AST_EmptyStatement);
  11982. self.alternative = tmp;
  11983. }
  11984. if (is_empty(self.body) && is_empty(self.alternative)) {
  11985. return make_node(AST_SimpleStatement, self.condition, {
  11986. body: self.condition
  11987. }).transform(compressor);
  11988. }
  11989. if (self.body instanceof AST_SimpleStatement
  11990. && self.alternative instanceof AST_SimpleStatement) {
  11991. return make_node(AST_SimpleStatement, self, {
  11992. body: make_node(AST_Conditional, self, {
  11993. condition : self.condition,
  11994. consequent : self.body.body,
  11995. alternative : self.alternative.body
  11996. })
  11997. }).transform(compressor);
  11998. }
  11999. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  12000. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  12001. body: make_node(AST_Binary, self, {
  12002. operator : "||",
  12003. left : negated,
  12004. right : self.body.body
  12005. })
  12006. }).transform(compressor);
  12007. return make_node(AST_SimpleStatement, self, {
  12008. body: make_node(AST_Binary, self, {
  12009. operator : "&&",
  12010. left : self.condition,
  12011. right : self.body.body
  12012. })
  12013. }).transform(compressor);
  12014. }
  12015. if (self.body instanceof AST_EmptyStatement
  12016. && self.alternative
  12017. && self.alternative instanceof AST_SimpleStatement) {
  12018. return make_node(AST_SimpleStatement, self, {
  12019. body: make_node(AST_Binary, self, {
  12020. operator : "||",
  12021. left : self.condition,
  12022. right : self.alternative.body
  12023. })
  12024. }).transform(compressor);
  12025. }
  12026. if (self.body instanceof AST_Exit
  12027. && self.alternative instanceof AST_Exit
  12028. && self.body.TYPE == self.alternative.TYPE) {
  12029. return make_node(self.body.CTOR, self, {
  12030. value: make_node(AST_Conditional, self, {
  12031. condition : self.condition,
  12032. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  12033. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  12034. })
  12035. }).transform(compressor);
  12036. }
  12037. if (self.body instanceof AST_If
  12038. && !self.body.alternative
  12039. && !self.alternative) {
  12040. self.condition = make_node(AST_Binary, self.condition, {
  12041. operator: "&&",
  12042. left: self.condition,
  12043. right: self.body.condition
  12044. }).transform(compressor);
  12045. self.body = self.body.body;
  12046. }
  12047. if (aborts(self.body)) {
  12048. if (self.alternative) {
  12049. var alt = self.alternative;
  12050. self.alternative = null;
  12051. return make_node(AST_BlockStatement, self, {
  12052. body: [ self, alt ]
  12053. }).transform(compressor);
  12054. }
  12055. }
  12056. if (aborts(self.alternative)) {
  12057. var body = self.body;
  12058. self.body = self.alternative;
  12059. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  12060. self.alternative = null;
  12061. return make_node(AST_BlockStatement, self, {
  12062. body: [ self, body ]
  12063. }).transform(compressor);
  12064. }
  12065. return self;
  12066. });
  12067. OPT(AST_Switch, function(self, compressor){
  12068. if (self.body.length == 0 && compressor.option("conditionals")) {
  12069. return make_node(AST_SimpleStatement, self, {
  12070. body: self.expression
  12071. }).transform(compressor);
  12072. }
  12073. for(;;) {
  12074. var last_branch = self.body[self.body.length - 1];
  12075. if (last_branch) {
  12076. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  12077. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  12078. last_branch.body.pop();
  12079. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  12080. self.body.pop();
  12081. continue;
  12082. }
  12083. }
  12084. break;
  12085. }
  12086. var exp = self.expression.evaluate(compressor);
  12087. out: if (exp.length == 2) try {
  12088. // constant expression
  12089. self.expression = exp[0];
  12090. if (!compressor.option("dead_code")) break out;
  12091. var value = exp[1];
  12092. var in_if = false;
  12093. var in_block = false;
  12094. var started = false;
  12095. var stopped = false;
  12096. var ruined = false;
  12097. var tt = new TreeTransformer(function(node, descend, in_list){
  12098. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  12099. // no need to descend these node types
  12100. return node;
  12101. }
  12102. else if (node instanceof AST_Switch && node === self) {
  12103. node = node.clone();
  12104. descend(node, this);
  12105. return ruined ? node : make_node(AST_BlockStatement, node, {
  12106. body: node.body.reduce(function(a, branch){
  12107. return a.concat(branch.body);
  12108. }, [])
  12109. }).transform(compressor);
  12110. }
  12111. else if (node instanceof AST_If || node instanceof AST_Try) {
  12112. var save = in_if;
  12113. in_if = !in_block;
  12114. descend(node, this);
  12115. in_if = save;
  12116. return node;
  12117. }
  12118. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  12119. var save = in_block;
  12120. in_block = true;
  12121. descend(node, this);
  12122. in_block = save;
  12123. return node;
  12124. }
  12125. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  12126. if (in_if) {
  12127. ruined = true;
  12128. return node;
  12129. }
  12130. if (in_block) return node;
  12131. stopped = true;
  12132. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  12133. }
  12134. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  12135. if (stopped) return MAP.skip;
  12136. if (node instanceof AST_Case) {
  12137. var exp = node.expression.evaluate(compressor);
  12138. if (exp.length < 2) {
  12139. // got a case with non-constant expression, baling out
  12140. throw self;
  12141. }
  12142. if (exp[1] === value || started) {
  12143. started = true;
  12144. if (aborts(node)) stopped = true;
  12145. descend(node, this);
  12146. return node;
  12147. }
  12148. return MAP.skip;
  12149. }
  12150. descend(node, this);
  12151. return node;
  12152. }
  12153. });
  12154. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  12155. self = self.transform(tt);
  12156. } catch(ex) {
  12157. if (ex !== self) throw ex;
  12158. }
  12159. return self;
  12160. });
  12161. OPT(AST_Case, function(self, compressor){
  12162. self.body = tighten_body(self.body, compressor);
  12163. return self;
  12164. });
  12165. OPT(AST_Try, function(self, compressor){
  12166. self.body = tighten_body(self.body, compressor);
  12167. return self;
  12168. });
  12169. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  12170. this.definitions.forEach(function(def){ def.value = null });
  12171. });
  12172. AST_Definitions.DEFMETHOD("to_assignments", function(){
  12173. var assignments = this.definitions.reduce(function(a, def){
  12174. if (def.value) {
  12175. var name = make_node(AST_SymbolRef, def.name, def.name);
  12176. a.push(make_node(AST_Assign, def, {
  12177. operator : "=",
  12178. left : name,
  12179. right : def.value
  12180. }));
  12181. }
  12182. return a;
  12183. }, []);
  12184. if (assignments.length == 0) return null;
  12185. return AST_Seq.from_array(assignments);
  12186. });
  12187. OPT(AST_Definitions, function(self, compressor){
  12188. if (self.definitions.length == 0)
  12189. return make_node(AST_EmptyStatement, self);
  12190. return self;
  12191. });
  12192. OPT(AST_Function, function(self, compressor){
  12193. self = AST_Lambda.prototype.optimize.call(self, compressor);
  12194. if (compressor.option("unused")) {
  12195. if (self.name && self.name.unreferenced()) {
  12196. self.name = null;
  12197. }
  12198. }
  12199. return self;
  12200. });
  12201. OPT(AST_Call, function(self, compressor){
  12202. if (compressor.option("unsafe")) {
  12203. var exp = self.expression;
  12204. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  12205. switch (exp.name) {
  12206. case "Array":
  12207. if (self.args.length != 1) {
  12208. return make_node(AST_Array, self, {
  12209. elements: self.args
  12210. }).transform(compressor);
  12211. }
  12212. break;
  12213. case "Object":
  12214. if (self.args.length == 0) {
  12215. return make_node(AST_Object, self, {
  12216. properties: []
  12217. });
  12218. }
  12219. break;
  12220. case "String":
  12221. if (self.args.length == 0) return make_node(AST_String, self, {
  12222. value: ""
  12223. });
  12224. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  12225. left: self.args[0],
  12226. operator: "+",
  12227. right: make_node(AST_String, self, { value: "" })
  12228. }).transform(compressor);
  12229. break;
  12230. case "Number":
  12231. if (self.args.length == 0) return make_node(AST_Number, self, {
  12232. value: 0
  12233. });
  12234. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  12235. expression: self.args[0],
  12236. operator: "+"
  12237. }).transform(compressor);
  12238. case "Boolean":
  12239. if (self.args.length == 0) return make_node(AST_False, self);
  12240. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  12241. expression: make_node(AST_UnaryPrefix, null, {
  12242. expression: self.args[0],
  12243. operator: "!"
  12244. }),
  12245. operator: "!"
  12246. }).transform(compressor);
  12247. break;
  12248. case "Function":
  12249. if (all(self.args, function(x){ return x instanceof AST_String })) {
  12250. // quite a corner-case, but we can handle it:
  12251. // https://github.com/mishoo/UglifyJS2/issues/203
  12252. // if the code argument is a constant, then we can minify it.
  12253. try {
  12254. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  12255. return arg.value;
  12256. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  12257. var ast = parse(code);
  12258. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  12259. var comp = new Compressor(compressor.options);
  12260. ast = ast.transform(comp);
  12261. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  12262. ast.mangle_names();
  12263. var fun;
  12264. try {
  12265. ast.walk(new TreeWalker(function(node){
  12266. if (node instanceof AST_Lambda) {
  12267. fun = node;
  12268. throw ast;
  12269. }
  12270. }));
  12271. } catch(ex) {
  12272. if (ex !== ast) throw ex;
  12273. };
  12274. var args = fun.argnames.map(function(arg, i){
  12275. return make_node(AST_String, self.args[i], {
  12276. value: arg.print_to_string()
  12277. });
  12278. });
  12279. var code = OutputStream();
  12280. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  12281. code = code.toString().replace(/^\{|\}$/g, "");
  12282. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  12283. value: code
  12284. }));
  12285. self.args = args;
  12286. return self;
  12287. } catch(ex) {
  12288. if (ex instanceof JS_Parse_Error) {
  12289. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  12290. compressor.warn(ex.toString());
  12291. } else {
  12292. console.log(ex);
  12293. throw ex;
  12294. }
  12295. }
  12296. }
  12297. break;
  12298. }
  12299. }
  12300. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  12301. return make_node(AST_Binary, self, {
  12302. left: make_node(AST_String, self, { value: "" }),
  12303. operator: "+",
  12304. right: exp.expression
  12305. }).transform(compressor);
  12306. }
  12307. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  12308. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  12309. if (separator == null) break EXIT; // not a constant
  12310. var elements = exp.expression.elements.reduce(function(a, el){
  12311. el = el.evaluate(compressor);
  12312. if (a.length == 0 || el.length == 1) {
  12313. a.push(el);
  12314. } else {
  12315. var last = a[a.length - 1];
  12316. if (last.length == 2) {
  12317. // it's a constant
  12318. var val = "" + last[1] + separator + el[1];
  12319. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  12320. } else {
  12321. a.push(el);
  12322. }
  12323. }
  12324. return a;
  12325. }, []);
  12326. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  12327. if (elements.length == 1) return elements[0][0];
  12328. if (separator == "") {
  12329. var first;
  12330. if (elements[0][0] instanceof AST_String
  12331. || elements[1][0] instanceof AST_String) {
  12332. first = elements.shift()[0];
  12333. } else {
  12334. first = make_node(AST_String, self, { value: "" });
  12335. }
  12336. return elements.reduce(function(prev, el){
  12337. return make_node(AST_Binary, el[0], {
  12338. operator : "+",
  12339. left : prev,
  12340. right : el[0],
  12341. });
  12342. }, first).transform(compressor);
  12343. }
  12344. // need this awkward cloning to not affect original element
  12345. // best_of will decide which one to get through.
  12346. var node = self.clone();
  12347. node.expression = node.expression.clone();
  12348. node.expression.expression = node.expression.expression.clone();
  12349. node.expression.expression.elements = elements.map(function(el){
  12350. return el[0];
  12351. });
  12352. return best_of(self, node);
  12353. }
  12354. }
  12355. if (compressor.option("side_effects")) {
  12356. if (self.expression instanceof AST_Function
  12357. && self.args.length == 0
  12358. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  12359. return make_node(AST_Undefined, self).transform(compressor);
  12360. }
  12361. }
  12362. if (compressor.option("drop_console")) {
  12363. if (self.expression instanceof AST_PropAccess &&
  12364. self.expression.expression instanceof AST_SymbolRef &&
  12365. self.expression.expression.name == "console" &&
  12366. self.expression.expression.undeclared()) {
  12367. return make_node(AST_Undefined, self).transform(compressor);
  12368. }
  12369. }
  12370. return self.evaluate(compressor)[0];
  12371. });
  12372. OPT(AST_New, function(self, compressor){
  12373. if (compressor.option("unsafe")) {
  12374. var exp = self.expression;
  12375. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  12376. switch (exp.name) {
  12377. case "Object":
  12378. case "RegExp":
  12379. case "Function":
  12380. case "Error":
  12381. case "Array":
  12382. return make_node(AST_Call, self, self).transform(compressor);
  12383. }
  12384. }
  12385. }
  12386. return self;
  12387. });
  12388. OPT(AST_Seq, function(self, compressor){
  12389. if (!compressor.option("side_effects"))
  12390. return self;
  12391. if (!self.car.has_side_effects(compressor)) {
  12392. // we shouldn't compress (1,eval)(something) to
  12393. // eval(something) because that changes the meaning of
  12394. // eval (becomes lexical instead of global).
  12395. var p;
  12396. if (!(self.cdr instanceof AST_SymbolRef
  12397. && self.cdr.name == "eval"
  12398. && self.cdr.undeclared()
  12399. && (p = compressor.parent()) instanceof AST_Call
  12400. && p.expression === self)) {
  12401. return self.cdr;
  12402. }
  12403. }
  12404. if (compressor.option("cascade")) {
  12405. if (self.car instanceof AST_Assign
  12406. && !self.car.left.has_side_effects(compressor)) {
  12407. if (self.car.left.equivalent_to(self.cdr)) {
  12408. return self.car;
  12409. }
  12410. if (self.cdr instanceof AST_Call
  12411. && self.cdr.expression.equivalent_to(self.car.left)) {
  12412. self.cdr.expression = self.car;
  12413. return self.cdr;
  12414. }
  12415. }
  12416. if (!self.car.has_side_effects(compressor)
  12417. && !self.cdr.has_side_effects(compressor)
  12418. && self.car.equivalent_to(self.cdr)) {
  12419. return self.car;
  12420. }
  12421. }
  12422. if (self.cdr instanceof AST_UnaryPrefix
  12423. && self.cdr.operator == "void"
  12424. && !self.cdr.expression.has_side_effects(compressor)) {
  12425. self.cdr.operator = self.car;
  12426. return self.cdr;
  12427. }
  12428. if (self.cdr instanceof AST_Undefined) {
  12429. return make_node(AST_UnaryPrefix, self, {
  12430. operator : "void",
  12431. expression : self.car
  12432. });
  12433. }
  12434. return self;
  12435. });
  12436. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  12437. if (compressor.option("sequences")) {
  12438. if (this.expression instanceof AST_Seq) {
  12439. var seq = this.expression;
  12440. var x = seq.to_array();
  12441. this.expression = x.pop();
  12442. x.push(this);
  12443. seq = AST_Seq.from_array(x).transform(compressor);
  12444. return seq;
  12445. }
  12446. }
  12447. return this;
  12448. });
  12449. OPT(AST_UnaryPostfix, function(self, compressor){
  12450. return self.lift_sequences(compressor);
  12451. });
  12452. OPT(AST_UnaryPrefix, function(self, compressor){
  12453. self = self.lift_sequences(compressor);
  12454. var e = self.expression;
  12455. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  12456. switch (self.operator) {
  12457. case "!":
  12458. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  12459. // !!foo ==> foo, if we're in boolean context
  12460. return e.expression;
  12461. }
  12462. break;
  12463. case "typeof":
  12464. // typeof always returns a non-empty string, thus it's
  12465. // always true in booleans
  12466. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  12467. return make_node(AST_True, self);
  12468. }
  12469. if (e instanceof AST_Binary && self.operator == "!") {
  12470. self = best_of(self, e.negate(compressor));
  12471. }
  12472. }
  12473. return self.evaluate(compressor)[0];
  12474. });
  12475. function has_side_effects_or_prop_access(node, compressor) {
  12476. var save_pure_getters = compressor.option("pure_getters");
  12477. compressor.options.pure_getters = false;
  12478. var ret = node.has_side_effects(compressor);
  12479. compressor.options.pure_getters = save_pure_getters;
  12480. return ret;
  12481. }
  12482. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  12483. if (compressor.option("sequences")) {
  12484. if (this.left instanceof AST_Seq) {
  12485. var seq = this.left;
  12486. var x = seq.to_array();
  12487. this.left = x.pop();
  12488. x.push(this);
  12489. seq = AST_Seq.from_array(x).transform(compressor);
  12490. return seq;
  12491. }
  12492. if (this.right instanceof AST_Seq
  12493. && this instanceof AST_Assign
  12494. && !has_side_effects_or_prop_access(this.left, compressor)) {
  12495. var seq = this.right;
  12496. var x = seq.to_array();
  12497. this.right = x.pop();
  12498. x.push(this);
  12499. seq = AST_Seq.from_array(x).transform(compressor);
  12500. return seq;
  12501. }
  12502. }
  12503. return this;
  12504. });
  12505. var commutativeOperators = makePredicate("== === != !== * & | ^");
  12506. OPT(AST_Binary, function(self, compressor){
  12507. var reverse = compressor.has_directive("use asm") ? noop
  12508. : function(op, force) {
  12509. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  12510. if (op) self.operator = op;
  12511. var tmp = self.left;
  12512. self.left = self.right;
  12513. self.right = tmp;
  12514. }
  12515. };
  12516. if (commutativeOperators(self.operator)) {
  12517. if (self.right instanceof AST_Constant
  12518. && !(self.left instanceof AST_Constant)) {
  12519. // if right is a constant, whatever side effects the
  12520. // left side might have could not influence the
  12521. // result. hence, force switch.
  12522. if (!(self.left instanceof AST_Binary
  12523. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  12524. reverse(null, true);
  12525. }
  12526. }
  12527. if (/^[!=]==?$/.test(self.operator)) {
  12528. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  12529. if (self.right.consequent instanceof AST_SymbolRef
  12530. && self.right.consequent.definition() === self.left.definition()) {
  12531. if (/^==/.test(self.operator)) return self.right.condition;
  12532. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  12533. }
  12534. if (self.right.alternative instanceof AST_SymbolRef
  12535. && self.right.alternative.definition() === self.left.definition()) {
  12536. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  12537. if (/^!=/.test(self.operator)) return self.right.condition;
  12538. }
  12539. }
  12540. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  12541. if (self.left.consequent instanceof AST_SymbolRef
  12542. && self.left.consequent.definition() === self.right.definition()) {
  12543. if (/^==/.test(self.operator)) return self.left.condition;
  12544. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  12545. }
  12546. if (self.left.alternative instanceof AST_SymbolRef
  12547. && self.left.alternative.definition() === self.right.definition()) {
  12548. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  12549. if (/^!=/.test(self.operator)) return self.left.condition;
  12550. }
  12551. }
  12552. }
  12553. }
  12554. self = self.lift_sequences(compressor);
  12555. if (compressor.option("comparisons")) switch (self.operator) {
  12556. case "===":
  12557. case "!==":
  12558. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  12559. (self.left.is_boolean() && self.right.is_boolean())) {
  12560. self.operator = self.operator.substr(0, 2);
  12561. }
  12562. // XXX: intentionally falling down to the next case
  12563. case "==":
  12564. case "!=":
  12565. if (self.left instanceof AST_String
  12566. && self.left.value == "undefined"
  12567. && self.right instanceof AST_UnaryPrefix
  12568. && self.right.operator == "typeof"
  12569. && compressor.option("unsafe")) {
  12570. if (!(self.right.expression instanceof AST_SymbolRef)
  12571. || !self.right.expression.undeclared()) {
  12572. self.right = self.right.expression;
  12573. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  12574. if (self.operator.length == 2) self.operator += "=";
  12575. }
  12576. }
  12577. break;
  12578. }
  12579. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  12580. case "&&":
  12581. var ll = self.left.evaluate(compressor);
  12582. var rr = self.right.evaluate(compressor);
  12583. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  12584. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  12585. return make_node(AST_False, self);
  12586. }
  12587. if (ll.length > 1 && ll[1]) {
  12588. return rr[0];
  12589. }
  12590. if (rr.length > 1 && rr[1]) {
  12591. return ll[0];
  12592. }
  12593. break;
  12594. case "||":
  12595. var ll = self.left.evaluate(compressor);
  12596. var rr = self.right.evaluate(compressor);
  12597. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  12598. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  12599. return make_node(AST_True, self);
  12600. }
  12601. if (ll.length > 1 && !ll[1]) {
  12602. return rr[0];
  12603. }
  12604. if (rr.length > 1 && !rr[1]) {
  12605. return ll[0];
  12606. }
  12607. break;
  12608. case "+":
  12609. var ll = self.left.evaluate(compressor);
  12610. var rr = self.right.evaluate(compressor);
  12611. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  12612. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  12613. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  12614. return make_node(AST_True, self);
  12615. }
  12616. break;
  12617. }
  12618. if (compressor.option("comparisons")) {
  12619. if (!(compressor.parent() instanceof AST_Binary)
  12620. || compressor.parent() instanceof AST_Assign) {
  12621. var negated = make_node(AST_UnaryPrefix, self, {
  12622. operator: "!",
  12623. expression: self.negate(compressor)
  12624. });
  12625. self = best_of(self, negated);
  12626. }
  12627. switch (self.operator) {
  12628. case "<": reverse(">"); break;
  12629. case "<=": reverse(">="); break;
  12630. }
  12631. }
  12632. if (self.operator == "+" && self.right instanceof AST_String
  12633. && self.right.getValue() === "" && self.left instanceof AST_Binary
  12634. && self.left.operator == "+" && self.left.is_string(compressor)) {
  12635. return self.left;
  12636. }
  12637. if (compressor.option("evaluate")) {
  12638. if (self.operator == "+") {
  12639. if (self.left instanceof AST_Constant
  12640. && self.right instanceof AST_Binary
  12641. && self.right.operator == "+"
  12642. && self.right.left instanceof AST_Constant
  12643. && self.right.is_string(compressor)) {
  12644. self = make_node(AST_Binary, self, {
  12645. operator: "+",
  12646. left: make_node(AST_String, null, {
  12647. value: "" + self.left.getValue() + self.right.left.getValue(),
  12648. start: self.left.start,
  12649. end: self.right.left.end
  12650. }),
  12651. right: self.right.right
  12652. });
  12653. }
  12654. if (self.right instanceof AST_Constant
  12655. && self.left instanceof AST_Binary
  12656. && self.left.operator == "+"
  12657. && self.left.right instanceof AST_Constant
  12658. && self.left.is_string(compressor)) {
  12659. self = make_node(AST_Binary, self, {
  12660. operator: "+",
  12661. left: self.left.left,
  12662. right: make_node(AST_String, null, {
  12663. value: "" + self.left.right.getValue() + self.right.getValue(),
  12664. start: self.left.right.start,
  12665. end: self.right.end
  12666. })
  12667. });
  12668. }
  12669. if (self.left instanceof AST_Binary
  12670. && self.left.operator == "+"
  12671. && self.left.is_string(compressor)
  12672. && self.left.right instanceof AST_Constant
  12673. && self.right instanceof AST_Binary
  12674. && self.right.operator == "+"
  12675. && self.right.left instanceof AST_Constant
  12676. && self.right.is_string(compressor)) {
  12677. self = make_node(AST_Binary, self, {
  12678. operator: "+",
  12679. left: make_node(AST_Binary, self.left, {
  12680. operator: "+",
  12681. left: self.left.left,
  12682. right: make_node(AST_String, null, {
  12683. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  12684. start: self.left.right.start,
  12685. end: self.right.left.end
  12686. })
  12687. }),
  12688. right: self.right.right
  12689. });
  12690. }
  12691. }
  12692. }
  12693. // x * (y * z) ==> x * y * z
  12694. if (self.right instanceof AST_Binary
  12695. && self.right.operator == self.operator
  12696. && (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
  12697. {
  12698. self.left = make_node(AST_Binary, self.left, {
  12699. operator : self.operator,
  12700. left : self.left,
  12701. right : self.right.left
  12702. });
  12703. self.right = self.right.right;
  12704. return self.transform(compressor);
  12705. }
  12706. return self.evaluate(compressor)[0];
  12707. });
  12708. OPT(AST_SymbolRef, function(self, compressor){
  12709. if (self.undeclared()) {
  12710. var defines = compressor.option("global_defs");
  12711. if (defines && defines.hasOwnProperty(self.name)) {
  12712. return make_node_from_constant(compressor, defines[self.name], self);
  12713. }
  12714. switch (self.name) {
  12715. case "undefined":
  12716. return make_node(AST_Undefined, self);
  12717. case "NaN":
  12718. return make_node(AST_NaN, self);
  12719. case "Infinity":
  12720. return make_node(AST_Infinity, self);
  12721. }
  12722. }
  12723. return self;
  12724. });
  12725. OPT(AST_Undefined, function(self, compressor){
  12726. if (compressor.option("unsafe")) {
  12727. var scope = compressor.find_parent(AST_Scope);
  12728. var undef = scope.find_variable("undefined");
  12729. if (undef) {
  12730. var ref = make_node(AST_SymbolRef, self, {
  12731. name : "undefined",
  12732. scope : scope,
  12733. thedef : undef
  12734. });
  12735. ref.reference();
  12736. return ref;
  12737. }
  12738. }
  12739. return self;
  12740. });
  12741. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  12742. OPT(AST_Assign, function(self, compressor){
  12743. self = self.lift_sequences(compressor);
  12744. if (self.operator == "="
  12745. && self.left instanceof AST_SymbolRef
  12746. && self.right instanceof AST_Binary
  12747. && self.right.left instanceof AST_SymbolRef
  12748. && self.right.left.name == self.left.name
  12749. && member(self.right.operator, ASSIGN_OPS)) {
  12750. self.operator = self.right.operator + "=";
  12751. self.right = self.right.right;
  12752. }
  12753. return self;
  12754. });
  12755. OPT(AST_Conditional, function(self, compressor){
  12756. if (!compressor.option("conditionals")) return self;
  12757. if (self.condition instanceof AST_Seq) {
  12758. var car = self.condition.car;
  12759. self.condition = self.condition.cdr;
  12760. return AST_Seq.cons(car, self);
  12761. }
  12762. var cond = self.condition.evaluate(compressor);
  12763. if (cond.length > 1) {
  12764. if (cond[1]) {
  12765. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  12766. return self.consequent;
  12767. } else {
  12768. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  12769. return self.alternative;
  12770. }
  12771. }
  12772. var negated = cond[0].negate(compressor);
  12773. if (best_of(cond[0], negated) === negated) {
  12774. self = make_node(AST_Conditional, self, {
  12775. condition: negated,
  12776. consequent: self.alternative,
  12777. alternative: self.consequent
  12778. });
  12779. }
  12780. var consequent = self.consequent;
  12781. var alternative = self.alternative;
  12782. if (consequent instanceof AST_Assign
  12783. && alternative instanceof AST_Assign
  12784. && consequent.operator == alternative.operator
  12785. && consequent.left.equivalent_to(alternative.left)
  12786. ) {
  12787. /*
  12788. * Stuff like this:
  12789. * if (foo) exp = something; else exp = something_else;
  12790. * ==>
  12791. * exp = foo ? something : something_else;
  12792. */
  12793. return make_node(AST_Assign, self, {
  12794. operator: consequent.operator,
  12795. left: consequent.left,
  12796. right: make_node(AST_Conditional, self, {
  12797. condition: self.condition,
  12798. consequent: consequent.right,
  12799. alternative: alternative.right
  12800. })
  12801. });
  12802. }
  12803. if (consequent instanceof AST_Call
  12804. && alternative.TYPE === consequent.TYPE
  12805. && consequent.args.length == alternative.args.length
  12806. && consequent.expression.equivalent_to(alternative.expression)) {
  12807. if (consequent.args.length == 0) {
  12808. return make_node(AST_Seq, self, {
  12809. car: self.condition,
  12810. cdr: consequent
  12811. });
  12812. }
  12813. if (consequent.args.length == 1) {
  12814. consequent.args[0] = make_node(AST_Conditional, self, {
  12815. condition: self.condition,
  12816. consequent: consequent.args[0],
  12817. alternative: alternative.args[0]
  12818. });
  12819. return consequent;
  12820. }
  12821. }
  12822. // x?y?z:a:a --> x&&y?z:a
  12823. if (consequent instanceof AST_Conditional
  12824. && consequent.alternative.equivalent_to(alternative)) {
  12825. return make_node(AST_Conditional, self, {
  12826. condition: make_node(AST_Binary, self, {
  12827. left: self.condition,
  12828. operator: "&&",
  12829. right: consequent.condition
  12830. }),
  12831. consequent: consequent.consequent,
  12832. alternative: alternative
  12833. });
  12834. }
  12835. return self;
  12836. });
  12837. OPT(AST_Boolean, function(self, compressor){
  12838. if (compressor.option("booleans")) {
  12839. var p = compressor.parent();
  12840. if (p instanceof AST_Binary && (p.operator == "=="
  12841. || p.operator == "!=")) {
  12842. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  12843. operator : p.operator,
  12844. value : self.value,
  12845. file : p.start.file,
  12846. line : p.start.line,
  12847. col : p.start.col,
  12848. });
  12849. return make_node(AST_Number, self, {
  12850. value: +self.value
  12851. });
  12852. }
  12853. return make_node(AST_UnaryPrefix, self, {
  12854. operator: "!",
  12855. expression: make_node(AST_Number, self, {
  12856. value: 1 - self.value
  12857. })
  12858. });
  12859. }
  12860. return self;
  12861. });
  12862. OPT(AST_Sub, function(self, compressor){
  12863. var prop = self.property;
  12864. if (prop instanceof AST_String && compressor.option("properties")) {
  12865. prop = prop.getValue();
  12866. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  12867. return make_node(AST_Dot, self, {
  12868. expression : self.expression,
  12869. property : prop
  12870. }).optimize(compressor);
  12871. }
  12872. var v = parseFloat(prop);
  12873. if (!isNaN(v) && v.toString() == prop) {
  12874. self.property = make_node(AST_Number, self.property, {
  12875. value: v
  12876. });
  12877. }
  12878. }
  12879. return self;
  12880. });
  12881. OPT(AST_Dot, function(self, compressor){
  12882. return self.evaluate(compressor)[0];
  12883. });
  12884. function literals_in_boolean_context(self, compressor) {
  12885. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  12886. return make_node(AST_True, self);
  12887. }
  12888. return self;
  12889. };
  12890. OPT(AST_Array, literals_in_boolean_context);
  12891. OPT(AST_Object, literals_in_boolean_context);
  12892. OPT(AST_RegExp, literals_in_boolean_context);
  12893. })();
  12894. /***********************************************************************
  12895. A JavaScript tokenizer / parser / beautifier / compressor.
  12896. https://github.com/mishoo/UglifyJS2
  12897. -------------------------------- (C) ---------------------------------
  12898. Author: Mihai Bazon
  12899. <mihai.bazon@gmail.com>
  12900. http://mihai.bazon.net/blog
  12901. Distributed under the BSD license:
  12902. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  12903. Redistribution and use in source and binary forms, with or without
  12904. modification, are permitted provided that the following conditions
  12905. are met:
  12906. * Redistributions of source code must retain the above
  12907. copyright notice, this list of conditions and the following
  12908. disclaimer.
  12909. * Redistributions in binary form must reproduce the above
  12910. copyright notice, this list of conditions and the following
  12911. disclaimer in the documentation and/or other materials
  12912. provided with the distribution.
  12913. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  12914. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12915. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  12916. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  12917. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  12918. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  12919. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  12920. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12921. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  12922. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  12923. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12924. SUCH DAMAGE.
  12925. ***********************************************************************/
  12926. "use strict";
  12927. // a small wrapper around fitzgen's source-map library
  12928. function SourceMap(options) {
  12929. options = defaults(options, {
  12930. file : null,
  12931. root : null,
  12932. orig : null,
  12933. orig_line_diff : 0,
  12934. dest_line_diff : 0,
  12935. });
  12936. var generator = new MOZ_SourceMap.SourceMapGenerator({
  12937. file : options.file,
  12938. sourceRoot : options.root
  12939. });
  12940. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  12941. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  12942. if (orig_map) {
  12943. var info = orig_map.originalPositionFor({
  12944. line: orig_line,
  12945. column: orig_col
  12946. });
  12947. if (info.source === null) {
  12948. return;
  12949. }
  12950. source = info.source;
  12951. orig_line = info.line;
  12952. orig_col = info.column;
  12953. name = info.name;
  12954. }
  12955. generator.addMapping({
  12956. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  12957. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  12958. source : source,
  12959. name : name
  12960. });
  12961. };
  12962. return {
  12963. add : add,
  12964. get : function() { return generator },
  12965. toString : function() { return generator.toString() }
  12966. };
  12967. };
  12968. /***********************************************************************
  12969. A JavaScript tokenizer / parser / beautifier / compressor.
  12970. https://github.com/mishoo/UglifyJS2
  12971. -------------------------------- (C) ---------------------------------
  12972. Author: Mihai Bazon
  12973. <mihai.bazon@gmail.com>
  12974. http://mihai.bazon.net/blog
  12975. Distributed under the BSD license:
  12976. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  12977. Redistribution and use in source and binary forms, with or without
  12978. modification, are permitted provided that the following conditions
  12979. are met:
  12980. * Redistributions of source code must retain the above
  12981. copyright notice, this list of conditions and the following
  12982. disclaimer.
  12983. * Redistributions in binary form must reproduce the above
  12984. copyright notice, this list of conditions and the following
  12985. disclaimer in the documentation and/or other materials
  12986. provided with the distribution.
  12987. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  12988. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12989. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  12990. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  12991. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  12992. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  12993. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  12994. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12995. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  12996. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  12997. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12998. SUCH DAMAGE.
  12999. ***********************************************************************/
  13000. "use strict";
  13001. (function(){
  13002. var MOZ_TO_ME = {
  13003. TryStatement : function(M) {
  13004. return new AST_Try({
  13005. start : my_start_token(M),
  13006. end : my_end_token(M),
  13007. body : from_moz(M.block).body,
  13008. bcatch : from_moz(M.handlers ? M.handlers[0] : M.handler),
  13009. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  13010. });
  13011. },
  13012. CatchClause : function(M) {
  13013. return new AST_Catch({
  13014. start : my_start_token(M),
  13015. end : my_end_token(M),
  13016. argname : from_moz(M.param),
  13017. body : from_moz(M.body).body
  13018. });
  13019. },
  13020. ObjectExpression : function(M) {
  13021. return new AST_Object({
  13022. start : my_start_token(M),
  13023. end : my_end_token(M),
  13024. properties : M.properties.map(function(prop){
  13025. var key = prop.key;
  13026. var name = key.type == "Identifier" ? key.name : key.value;
  13027. var args = {
  13028. start : my_start_token(key),
  13029. end : my_end_token(prop.value),
  13030. key : name,
  13031. value : from_moz(prop.value)
  13032. };
  13033. switch (prop.kind) {
  13034. case "init":
  13035. return new AST_ObjectKeyVal(args);
  13036. case "set":
  13037. args.value.name = from_moz(key);
  13038. return new AST_ObjectSetter(args);
  13039. case "get":
  13040. args.value.name = from_moz(key);
  13041. return new AST_ObjectGetter(args);
  13042. }
  13043. })
  13044. });
  13045. },
  13046. SequenceExpression : function(M) {
  13047. return AST_Seq.from_array(M.expressions.map(from_moz));
  13048. },
  13049. MemberExpression : function(M) {
  13050. return new (M.computed ? AST_Sub : AST_Dot)({
  13051. start : my_start_token(M),
  13052. end : my_end_token(M),
  13053. property : M.computed ? from_moz(M.property) : M.property.name,
  13054. expression : from_moz(M.object)
  13055. });
  13056. },
  13057. SwitchCase : function(M) {
  13058. return new (M.test ? AST_Case : AST_Default)({
  13059. start : my_start_token(M),
  13060. end : my_end_token(M),
  13061. expression : from_moz(M.test),
  13062. body : M.consequent.map(from_moz)
  13063. });
  13064. },
  13065. Literal : function(M) {
  13066. var val = M.value, args = {
  13067. start : my_start_token(M),
  13068. end : my_end_token(M)
  13069. };
  13070. if (val === null) return new AST_Null(args);
  13071. switch (typeof val) {
  13072. case "string":
  13073. args.value = val;
  13074. return new AST_String(args);
  13075. case "number":
  13076. args.value = val;
  13077. return new AST_Number(args);
  13078. case "boolean":
  13079. return new (val ? AST_True : AST_False)(args);
  13080. default:
  13081. args.value = val;
  13082. return new AST_RegExp(args);
  13083. }
  13084. },
  13085. UnaryExpression: From_Moz_Unary,
  13086. UpdateExpression: From_Moz_Unary,
  13087. Identifier: function(M) {
  13088. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  13089. return new (M.name == "this" ? AST_This
  13090. : p.type == "LabeledStatement" ? AST_Label
  13091. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  13092. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  13093. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  13094. : p.type == "CatchClause" ? AST_SymbolCatch
  13095. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  13096. : AST_SymbolRef)({
  13097. start : my_start_token(M),
  13098. end : my_end_token(M),
  13099. name : M.name
  13100. });
  13101. }
  13102. };
  13103. function From_Moz_Unary(M) {
  13104. var prefix = "prefix" in M ? M.prefix
  13105. : M.type == "UnaryExpression" ? true : false;
  13106. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  13107. start : my_start_token(M),
  13108. end : my_end_token(M),
  13109. operator : M.operator,
  13110. expression : from_moz(M.argument)
  13111. });
  13112. };
  13113. var ME_TO_MOZ = {};
  13114. map("Node", AST_Node);
  13115. map("Program", AST_Toplevel, "body@body");
  13116. map("Function", AST_Function, "id>name, params@argnames, body%body");
  13117. map("EmptyStatement", AST_EmptyStatement);
  13118. map("BlockStatement", AST_BlockStatement, "body@body");
  13119. map("ExpressionStatement", AST_SimpleStatement, "expression>body");
  13120. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  13121. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  13122. map("BreakStatement", AST_Break, "label>label");
  13123. map("ContinueStatement", AST_Continue, "label>label");
  13124. map("WithStatement", AST_With, "object>expression, body>body");
  13125. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  13126. map("ReturnStatement", AST_Return, "argument>value");
  13127. map("ThrowStatement", AST_Throw, "argument>value");
  13128. map("WhileStatement", AST_While, "test>condition, body>body");
  13129. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  13130. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  13131. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  13132. map("DebuggerStatement", AST_Debugger);
  13133. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  13134. map("VariableDeclaration", AST_Var, "declarations@definitions");
  13135. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  13136. map("ThisExpression", AST_This);
  13137. map("ArrayExpression", AST_Array, "elements@elements");
  13138. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  13139. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  13140. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  13141. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  13142. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  13143. map("NewExpression", AST_New, "callee>expression, arguments@args");
  13144. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  13145. /* -----[ tools ]----- */
  13146. function my_start_token(moznode) {
  13147. return new AST_Token({
  13148. file : moznode.loc && moznode.loc.source,
  13149. line : moznode.loc && moznode.loc.start.line,
  13150. col : moznode.loc && moznode.loc.start.column,
  13151. pos : moznode.start,
  13152. endpos : moznode.start
  13153. });
  13154. };
  13155. function my_end_token(moznode) {
  13156. return new AST_Token({
  13157. file : moznode.loc && moznode.loc.source,
  13158. line : moznode.loc && moznode.loc.end.line,
  13159. col : moznode.loc && moznode.loc.end.column,
  13160. pos : moznode.end,
  13161. endpos : moznode.end
  13162. });
  13163. };
  13164. function map(moztype, mytype, propmap) {
  13165. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  13166. moz_to_me += "return new mytype({\n" +
  13167. "start: my_start_token(M),\n" +
  13168. "end: my_end_token(M)";
  13169. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  13170. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  13171. if (!m) throw new Error("Can't understand property map: " + prop);
  13172. var moz = "M." + m[1], how = m[2], my = m[3];
  13173. moz_to_me += ",\n" + my + ": ";
  13174. if (how == "@") {
  13175. moz_to_me += moz + ".map(from_moz)";
  13176. } else if (how == ">") {
  13177. moz_to_me += "from_moz(" + moz + ")";
  13178. } else if (how == "=") {
  13179. moz_to_me += moz;
  13180. } else if (how == "%") {
  13181. moz_to_me += "from_moz(" + moz + ").body";
  13182. } else throw new Error("Can't understand operator in propmap: " + prop);
  13183. });
  13184. moz_to_me += "\n})}";
  13185. // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  13186. // console.log(moz_to_me);
  13187. moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  13188. mytype, my_start_token, my_end_token, from_moz
  13189. );
  13190. return MOZ_TO_ME[moztype] = moz_to_me;
  13191. };
  13192. var FROM_MOZ_STACK = null;
  13193. function from_moz(node) {
  13194. FROM_MOZ_STACK.push(node);
  13195. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  13196. FROM_MOZ_STACK.pop();
  13197. return ret;
  13198. };
  13199. AST_Node.from_mozilla_ast = function(node){
  13200. var save_stack = FROM_MOZ_STACK;
  13201. FROM_MOZ_STACK = [];
  13202. var ast = from_moz(node);
  13203. FROM_MOZ_STACK = save_stack;
  13204. return ast;
  13205. };
  13206. })();
  13207. exports.sys = sys;
  13208. exports.MOZ_SourceMap = MOZ_SourceMap;
  13209. exports.UglifyJS = UglifyJS;
  13210. exports.array_to_hash = array_to_hash;
  13211. exports.slice = slice;
  13212. exports.characters = characters;
  13213. exports.member = member;
  13214. exports.find_if = find_if;
  13215. exports.repeat_string = repeat_string;
  13216. exports.DefaultsError = DefaultsError;
  13217. exports.defaults = defaults;
  13218. exports.merge = merge;
  13219. exports.noop = noop;
  13220. exports.MAP = MAP;
  13221. exports.push_uniq = push_uniq;
  13222. exports.string_template = string_template;
  13223. exports.remove = remove;
  13224. exports.mergeSort = mergeSort;
  13225. exports.set_difference = set_difference;
  13226. exports.set_intersection = set_intersection;
  13227. exports.makePredicate = makePredicate;
  13228. exports.all = all;
  13229. exports.Dictionary = Dictionary;
  13230. exports.DEFNODE = DEFNODE;
  13231. exports.AST_Token = AST_Token;
  13232. exports.AST_Node = AST_Node;
  13233. exports.AST_Statement = AST_Statement;
  13234. exports.AST_Debugger = AST_Debugger;
  13235. exports.AST_Directive = AST_Directive;
  13236. exports.AST_SimpleStatement = AST_SimpleStatement;
  13237. exports.walk_body = walk_body;
  13238. exports.AST_Block = AST_Block;
  13239. exports.AST_BlockStatement = AST_BlockStatement;
  13240. exports.AST_EmptyStatement = AST_EmptyStatement;
  13241. exports.AST_StatementWithBody = AST_StatementWithBody;
  13242. exports.AST_LabeledStatement = AST_LabeledStatement;
  13243. exports.AST_IterationStatement = AST_IterationStatement;
  13244. exports.AST_DWLoop = AST_DWLoop;
  13245. exports.AST_Do = AST_Do;
  13246. exports.AST_While = AST_While;
  13247. exports.AST_For = AST_For;
  13248. exports.AST_ForIn = AST_ForIn;
  13249. exports.AST_With = AST_With;
  13250. exports.AST_Scope = AST_Scope;
  13251. exports.AST_Toplevel = AST_Toplevel;
  13252. exports.AST_Lambda = AST_Lambda;
  13253. exports.AST_Accessor = AST_Accessor;
  13254. exports.AST_Function = AST_Function;
  13255. exports.AST_Defun = AST_Defun;
  13256. exports.AST_Jump = AST_Jump;
  13257. exports.AST_Exit = AST_Exit;
  13258. exports.AST_Return = AST_Return;
  13259. exports.AST_Throw = AST_Throw;
  13260. exports.AST_LoopControl = AST_LoopControl;
  13261. exports.AST_Break = AST_Break;
  13262. exports.AST_Continue = AST_Continue;
  13263. exports.AST_If = AST_If;
  13264. exports.AST_Switch = AST_Switch;
  13265. exports.AST_SwitchBranch = AST_SwitchBranch;
  13266. exports.AST_Default = AST_Default;
  13267. exports.AST_Case = AST_Case;
  13268. exports.AST_Try = AST_Try;
  13269. exports.AST_Catch = AST_Catch;
  13270. exports.AST_Finally = AST_Finally;
  13271. exports.AST_Definitions = AST_Definitions;
  13272. exports.AST_Var = AST_Var;
  13273. exports.AST_Const = AST_Const;
  13274. exports.AST_VarDef = AST_VarDef;
  13275. exports.AST_Call = AST_Call;
  13276. exports.AST_New = AST_New;
  13277. exports.AST_Seq = AST_Seq;
  13278. exports.AST_PropAccess = AST_PropAccess;
  13279. exports.AST_Dot = AST_Dot;
  13280. exports.AST_Sub = AST_Sub;
  13281. exports.AST_Unary = AST_Unary;
  13282. exports.AST_UnaryPrefix = AST_UnaryPrefix;
  13283. exports.AST_UnaryPostfix = AST_UnaryPostfix;
  13284. exports.AST_Binary = AST_Binary;
  13285. exports.AST_Conditional = AST_Conditional;
  13286. exports.AST_Assign = AST_Assign;
  13287. exports.AST_Array = AST_Array;
  13288. exports.AST_Object = AST_Object;
  13289. exports.AST_ObjectProperty = AST_ObjectProperty;
  13290. exports.AST_ObjectKeyVal = AST_ObjectKeyVal;
  13291. exports.AST_ObjectSetter = AST_ObjectSetter;
  13292. exports.AST_ObjectGetter = AST_ObjectGetter;
  13293. exports.AST_Symbol = AST_Symbol;
  13294. exports.AST_SymbolAccessor = AST_SymbolAccessor;
  13295. exports.AST_SymbolDeclaration = AST_SymbolDeclaration;
  13296. exports.AST_SymbolVar = AST_SymbolVar;
  13297. exports.AST_SymbolConst = AST_SymbolConst;
  13298. exports.AST_SymbolFunarg = AST_SymbolFunarg;
  13299. exports.AST_SymbolDefun = AST_SymbolDefun;
  13300. exports.AST_SymbolLambda = AST_SymbolLambda;
  13301. exports.AST_SymbolCatch = AST_SymbolCatch;
  13302. exports.AST_Label = AST_Label;
  13303. exports.AST_SymbolRef = AST_SymbolRef;
  13304. exports.AST_LabelRef = AST_LabelRef;
  13305. exports.AST_This = AST_This;
  13306. exports.AST_Constant = AST_Constant;
  13307. exports.AST_String = AST_String;
  13308. exports.AST_Number = AST_Number;
  13309. exports.AST_RegExp = AST_RegExp;
  13310. exports.AST_Atom = AST_Atom;
  13311. exports.AST_Null = AST_Null;
  13312. exports.AST_NaN = AST_NaN;
  13313. exports.AST_Undefined = AST_Undefined;
  13314. exports.AST_Hole = AST_Hole;
  13315. exports.AST_Infinity = AST_Infinity;
  13316. exports.AST_Boolean = AST_Boolean;
  13317. exports.AST_False = AST_False;
  13318. exports.AST_True = AST_True;
  13319. exports.TreeWalker = TreeWalker;
  13320. exports.KEYWORDS = KEYWORDS;
  13321. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  13322. exports.RESERVED_WORDS = RESERVED_WORDS;
  13323. exports.KEYWORDS_BEFORE_EXPRESSION = KEYWORDS_BEFORE_EXPRESSION;
  13324. exports.OPERATOR_CHARS = OPERATOR_CHARS;
  13325. exports.RE_HEX_NUMBER = RE_HEX_NUMBER;
  13326. exports.RE_OCT_NUMBER = RE_OCT_NUMBER;
  13327. exports.RE_DEC_NUMBER = RE_DEC_NUMBER;
  13328. exports.OPERATORS = OPERATORS;
  13329. exports.WHITESPACE_CHARS = WHITESPACE_CHARS;
  13330. exports.PUNC_BEFORE_EXPRESSION = PUNC_BEFORE_EXPRESSION;
  13331. exports.PUNC_CHARS = PUNC_CHARS;
  13332. exports.REGEXP_MODIFIERS = REGEXP_MODIFIERS;
  13333. exports.UNICODE = UNICODE;
  13334. exports.is_letter = is_letter;
  13335. exports.is_digit = is_digit;
  13336. exports.is_alphanumeric_char = is_alphanumeric_char;
  13337. exports.is_unicode_combining_mark = is_unicode_combining_mark;
  13338. exports.is_unicode_connector_punctuation = is_unicode_connector_punctuation;
  13339. exports.is_identifier = is_identifier;
  13340. exports.is_identifier_start = is_identifier_start;
  13341. exports.is_identifier_char = is_identifier_char;
  13342. exports.is_identifier_string = is_identifier_string;
  13343. exports.parse_js_number = parse_js_number;
  13344. exports.JS_Parse_Error = JS_Parse_Error;
  13345. exports.js_error = js_error;
  13346. exports.is_token = is_token;
  13347. exports.EX_EOF = EX_EOF;
  13348. exports.tokenizer = tokenizer;
  13349. exports.UNARY_PREFIX = UNARY_PREFIX;
  13350. exports.UNARY_POSTFIX = UNARY_POSTFIX;
  13351. exports.ASSIGNMENT = ASSIGNMENT;
  13352. exports.PRECEDENCE = PRECEDENCE;
  13353. exports.STATEMENTS_WITH_LABELS = STATEMENTS_WITH_LABELS;
  13354. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  13355. exports.parse = parse;
  13356. exports.TreeTransformer = TreeTransformer;
  13357. exports.SymbolDef = SymbolDef;
  13358. exports.base54 = base54;
  13359. exports.OutputStream = OutputStream;
  13360. exports.Compressor = Compressor;
  13361. exports.SourceMap = SourceMap;
  13362. exports.AST_Node.warn_function = function (txt) { if (typeof console != "undefined" && typeof console.warn === "function") console.warn(txt) }
  13363. exports.minify = function (files, options) {
  13364. options = UglifyJS.defaults(options, {
  13365. spidermonkey : false,
  13366. outSourceMap : null,
  13367. sourceRoot : null,
  13368. inSourceMap : null,
  13369. fromString : false,
  13370. warnings : false,
  13371. mangle : {},
  13372. output : null,
  13373. compress : {}
  13374. });
  13375. UglifyJS.base54.reset();
  13376. // 1. parse
  13377. var toplevel = null,
  13378. sourcesContent = {};
  13379. if (options.spidermonkey) {
  13380. toplevel = UglifyJS.AST_Node.from_mozilla_ast(files);
  13381. } else {
  13382. if (typeof files == "string")
  13383. files = [ files ];
  13384. files.forEach(function(file){
  13385. var code = options.fromString
  13386. ? file
  13387. : fs.readFileSync(file, "utf8");
  13388. sourcesContent[file] = code;
  13389. toplevel = UglifyJS.parse(code, {
  13390. filename: options.fromString ? "?" : file,
  13391. toplevel: toplevel
  13392. });
  13393. });
  13394. }
  13395. // 2. compress
  13396. if (options.compress) {
  13397. var compress = { warnings: options.warnings };
  13398. UglifyJS.merge(compress, options.compress);
  13399. toplevel.figure_out_scope();
  13400. var sq = UglifyJS.Compressor(compress);
  13401. toplevel = toplevel.transform(sq);
  13402. }
  13403. // 3. mangle
  13404. if (options.mangle) {
  13405. toplevel.figure_out_scope();
  13406. toplevel.compute_char_frequency();
  13407. toplevel.mangle_names(options.mangle);
  13408. }
  13409. // 4. output
  13410. var inMap = options.inSourceMap;
  13411. var output = {};
  13412. if (typeof options.inSourceMap == "string") {
  13413. inMap = fs.readFileSync(options.inSourceMap, "utf8");
  13414. }
  13415. if (options.outSourceMap) {
  13416. output.source_map = UglifyJS.SourceMap({
  13417. file: options.outSourceMap,
  13418. orig: inMap,
  13419. root: options.sourceRoot
  13420. });
  13421. if (options.sourceMapIncludeSources) {
  13422. for (var file in sourcesContent) {
  13423. if (sourcesContent.hasOwnProperty(file)) {
  13424. output.source_map.get().setSourceContent(file, sourcesContent[file]);
  13425. }
  13426. }
  13427. }
  13428. }
  13429. if (options.output) {
  13430. UglifyJS.merge(output, options.output);
  13431. }
  13432. var stream = UglifyJS.OutputStream(output);
  13433. toplevel.print(stream);
  13434. if(options.outSourceMap){
  13435. stream += "\n//# sourceMappingURL=" + options.outSourceMap;
  13436. }
  13437. return {
  13438. code : stream + "",
  13439. map : output.source_map + ""
  13440. };
  13441. };
  13442. exports.describe_ast = function () {
  13443. var out = UglifyJS.OutputStream({ beautify: true });
  13444. function doitem(ctor) {
  13445. out.print("AST_" + ctor.TYPE);
  13446. var props = ctor.SELF_PROPS.filter(function(prop){
  13447. return !/^\$/.test(prop);
  13448. });
  13449. if (props.length > 0) {
  13450. out.space();
  13451. out.with_parens(function(){
  13452. props.forEach(function(prop, i){
  13453. if (i) out.space();
  13454. out.print(prop);
  13455. });
  13456. });
  13457. }
  13458. if (ctor.documentation) {
  13459. out.space();
  13460. out.print_string(ctor.documentation);
  13461. }
  13462. if (ctor.SUBCLASSES.length > 0) {
  13463. out.space();
  13464. out.with_block(function(){
  13465. ctor.SUBCLASSES.forEach(function(ctor, i){
  13466. out.indent();
  13467. doitem(ctor);
  13468. out.newline();
  13469. });
  13470. });
  13471. }
  13472. };
  13473. doitem(UglifyJS.AST_Node);
  13474. return out + "";
  13475. };
  13476. },{"source-map":34,"util":31}],45:[function(require,module,exports){
  13477. /**
  13478. * This file automatically generated from `build.js`.
  13479. * Do not manually edit.
  13480. */
  13481. module.exports = [
  13482. "area",
  13483. "base",
  13484. "br",
  13485. "col",
  13486. "embed",
  13487. "hr",
  13488. "img",
  13489. "input",
  13490. "keygen",
  13491. "link",
  13492. "menuitem",
  13493. "meta",
  13494. "param",
  13495. "source",
  13496. "track",
  13497. "wbr"
  13498. ];
  13499. },{}],46:[function(require,module,exports){
  13500. 'use strict';
  13501. var uglify = require('uglify-js')
  13502. module.exports = addWith
  13503. /**
  13504. * Mimic `with` as far as possible but at compile time
  13505. *
  13506. * @param {String} obj The object part of a with expression
  13507. * @param {String} src The body of the with expression
  13508. * @param {Array.<String>} exclude A list of variable names to explicitly exclude
  13509. */
  13510. function addWith(obj, src, exclude) {
  13511. obj = obj + ''
  13512. src = src + ''
  13513. exclude = exclude || []
  13514. exclude = exclude.concat(detect(obj))
  13515. var vars = detect(src)
  13516. .filter(function (v) {
  13517. return exclude.indexOf(v) === -1
  13518. })
  13519. if (vars.length === 0) return src
  13520. var declareLocal = ''
  13521. var local = 'locals_for_with'
  13522. var result = 'result_of_with'
  13523. if (/^[a-zA-Z0-9$_]+$/.test(obj)) {
  13524. local = obj
  13525. } else {
  13526. while (vars.indexOf(local) != -1 || exclude.indexOf(local) != -1) {
  13527. local += '_'
  13528. }
  13529. declareLocal = 'var ' + local + ' = (' + obj + ')'
  13530. }
  13531. while (vars.indexOf(result) != -1 || exclude.indexOf(result) != -1) {
  13532. result += '_'
  13533. }
  13534. var inputVars = vars.map(function (v) {
  13535. return JSON.stringify(v) + ' in ' + local + '?' +
  13536. local + '.' + v + ':' +
  13537. 'typeof ' + v + '!=="undefined"?' + v + ':undefined'
  13538. })
  13539. src = '(function (' + vars.join(', ') + ') {' +
  13540. src +
  13541. '}.call(this' + inputVars.map(function (v) { return ',' + v; }).join('') + '))'
  13542. return ';' + declareLocal + ';' + unwrapReturns(src, result) + ';'
  13543. }
  13544. /**
  13545. * Detect, and return a list of, any global variables in a function
  13546. *
  13547. * @param {String} src Some JavaScript code
  13548. */
  13549. function detect(src) {
  13550. var ast = uglify.parse('(function () {' + src + '}())') // allow return keyword
  13551. ast.figure_out_scope()
  13552. var globals = ast.globals
  13553. .map(function (node, name) {
  13554. return name
  13555. })
  13556. return globals
  13557. }
  13558. /**
  13559. * Take a self calling function, and unwrap it such that return inside the function
  13560. * results in return outside the function
  13561. *
  13562. * @param {String} src Some JavaScript code representing a self-calling function
  13563. * @param {String} result A temporary variable to store the result in
  13564. */
  13565. function unwrapReturns(src, result) {
  13566. var originalSource = src
  13567. var hasReturn = false
  13568. var ast = uglify.parse(src)
  13569. var ref
  13570. src = src.split('')
  13571. // get a reference to the function that was inserted to add an inner context
  13572. if ((ref = ast.body).length !== 1
  13573. || (ref = ref[0]).TYPE !== 'SimpleStatement'
  13574. || (ref = ref.body).TYPE !== 'Call'
  13575. || (ref = ref.expression).TYPE !== 'Dot' || ref.property !== 'call'
  13576. || (ref = ref.expression).TYPE !== 'Function')
  13577. throw new Error('AST does not seem to represent a self-calling function')
  13578. var fn = ref
  13579. var walker = new uglify.TreeWalker(visitor)
  13580. function visitor(node, descend) {
  13581. if (node !== fn && (node.TYPE === 'Defun' || node.TYPE === 'Function')) {
  13582. return true //don't descend into functions
  13583. }
  13584. if (node.TYPE === 'Return') {
  13585. descend()
  13586. hasReturn = true
  13587. replace(node, 'return {value: ' + source(node.value) + '};')
  13588. return true //don't descend again
  13589. }
  13590. }
  13591. function source(node) {
  13592. return src.slice(node.start.pos, node.end.endpos).join('')
  13593. }
  13594. function replace(node, str) {
  13595. for (var i = node.start.pos; i < node.end.endpos; i++) {
  13596. src[i] = ''
  13597. }
  13598. src[node.start.pos] = str
  13599. }
  13600. ast.walk(walker)
  13601. if (!hasReturn) return originalSource
  13602. else return 'var ' + result + '=' + src.join('') + ';if (' + result + ') return ' + result + '.value'
  13603. }
  13604. },{"uglify-js":44}]},{},[5])(5)
  13605. });