r.js 1016 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994
  1. #!/usr/bin/env node
  2. /**
  3. * @license r.js 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  4. * Available via the MIT or new BSD license.
  5. * see: http://github.com/jrburke/requirejs for details
  6. */
  7. /*
  8. * This is a bootstrap script to allow running RequireJS in the command line
  9. * in either a Java/Rhino or Node environment. It is modified by the top-level
  10. * dist.js file to inject other files to completely enable this file. It is
  11. * the shell of the r.js file.
  12. */
  13. /*jslint evil: true, nomen: true, sloppy: true */
  14. /*global readFile: true, process: false, Packages: false, print: false,
  15. console: false, java: false, module: false, requirejsVars, navigator,
  16. document, importScripts, self, location, Components, FileUtils */
  17. var requirejs, require, define, xpcUtil;
  18. (function (console, args, readFileFunc) {
  19. var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
  20. nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci,
  21. version = '2.1.15',
  22. jsSuffixRegExp = /\.js$/,
  23. commandOption = '',
  24. useLibLoaded = {},
  25. //Used by jslib/rhino/args.js
  26. rhinoArgs = args,
  27. //Used by jslib/xpconnect/args.js
  28. xpconnectArgs = args,
  29. readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
  30. function showHelp() {
  31. console.log('See https://github.com/jrburke/r.js for usage.');
  32. }
  33. if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  34. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  35. env = 'browser';
  36. readFile = function (path) {
  37. return fs.readFileSync(path, 'utf8');
  38. };
  39. exec = function (string) {
  40. return eval(string);
  41. };
  42. exists = function () {
  43. console.log('x.js exists not applicable in browser env');
  44. return false;
  45. };
  46. } else if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  47. env = 'node';
  48. //Get the fs module via Node's require before it
  49. //gets replaced. Used in require/node.js
  50. fs = require('fs');
  51. vm = require('vm');
  52. path = require('path');
  53. //In Node 0.7+ existsSync is on fs.
  54. existsForNode = fs.existsSync || path.existsSync;
  55. nodeRequire = require;
  56. nodeDefine = define;
  57. reqMain = require.main;
  58. //Temporarily hide require and define to allow require.js to define
  59. //them.
  60. require = undefined;
  61. define = undefined;
  62. readFile = function (path) {
  63. return fs.readFileSync(path, 'utf8');
  64. };
  65. exec = function (string, name) {
  66. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  67. name ? fs.realpathSync(name) : '');
  68. };
  69. exists = function (fileName) {
  70. return existsForNode(fileName);
  71. };
  72. fileName = process.argv[2];
  73. if (fileName && fileName.indexOf('-') === 0) {
  74. commandOption = fileName.substring(1);
  75. fileName = process.argv[3];
  76. }
  77. } else if (typeof Packages !== 'undefined') {
  78. env = 'rhino';
  79. fileName = args[0];
  80. if (fileName && fileName.indexOf('-') === 0) {
  81. commandOption = fileName.substring(1);
  82. fileName = args[1];
  83. }
  84. //Set up execution context.
  85. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  86. exec = function (string, name) {
  87. return rhinoContext.evaluateString(this, string, name, 0, null);
  88. };
  89. exists = function (fileName) {
  90. return (new java.io.File(fileName)).exists();
  91. };
  92. //Define a console.log for easier logging. Don't
  93. //get fancy though.
  94. if (typeof console === 'undefined') {
  95. console = {
  96. log: function () {
  97. print.apply(undefined, arguments);
  98. }
  99. };
  100. }
  101. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  102. env = 'xpconnect';
  103. Components.utils['import']('resource://gre/modules/FileUtils.jsm');
  104. Cc = Components.classes;
  105. Ci = Components.interfaces;
  106. fileName = args[0];
  107. if (fileName && fileName.indexOf('-') === 0) {
  108. commandOption = fileName.substring(1);
  109. fileName = args[1];
  110. }
  111. xpcUtil = {
  112. isWindows: ('@mozilla.org/windows-registry-key;1' in Cc),
  113. cwd: function () {
  114. return FileUtils.getFile("CurWorkD", []).path;
  115. },
  116. //Remove . and .. from paths, normalize on front slashes
  117. normalize: function (path) {
  118. //There has to be an easier way to do this.
  119. var i, part, ary,
  120. firstChar = path.charAt(0);
  121. if (firstChar !== '/' &&
  122. firstChar !== '\\' &&
  123. path.indexOf(':') === -1) {
  124. //A relative path. Use the current working directory.
  125. path = xpcUtil.cwd() + '/' + path;
  126. }
  127. ary = path.replace(/\\/g, '/').split('/');
  128. for (i = 0; i < ary.length; i += 1) {
  129. part = ary[i];
  130. if (part === '.') {
  131. ary.splice(i, 1);
  132. i -= 1;
  133. } else if (part === '..') {
  134. ary.splice(i - 1, 2);
  135. i -= 2;
  136. }
  137. }
  138. return ary.join('/');
  139. },
  140. xpfile: function (path) {
  141. var fullPath;
  142. try {
  143. fullPath = xpcUtil.normalize(path);
  144. if (xpcUtil.isWindows) {
  145. fullPath = fullPath.replace(/\//g, '\\');
  146. }
  147. return new FileUtils.File(fullPath);
  148. } catch (e) {
  149. throw new Error((fullPath || path) + ' failed: ' + e);
  150. }
  151. },
  152. readFile: function (/*String*/path, /*String?*/encoding) {
  153. //A file read function that can deal with BOMs
  154. encoding = encoding || "utf-8";
  155. var inStream, convertStream,
  156. readData = {},
  157. fileObj = xpcUtil.xpfile(path);
  158. //XPCOM, you so crazy
  159. try {
  160. inStream = Cc['@mozilla.org/network/file-input-stream;1']
  161. .createInstance(Ci.nsIFileInputStream);
  162. inStream.init(fileObj, 1, 0, false);
  163. convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
  164. .createInstance(Ci.nsIConverterInputStream);
  165. convertStream.init(inStream, encoding, inStream.available(),
  166. Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  167. convertStream.readString(inStream.available(), readData);
  168. return readData.value;
  169. } catch (e) {
  170. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  171. } finally {
  172. if (convertStream) {
  173. convertStream.close();
  174. }
  175. if (inStream) {
  176. inStream.close();
  177. }
  178. }
  179. }
  180. };
  181. readFile = xpcUtil.readFile;
  182. exec = function (string) {
  183. return eval(string);
  184. };
  185. exists = function (fileName) {
  186. return xpcUtil.xpfile(fileName).exists();
  187. };
  188. //Define a console.log for easier logging. Don't
  189. //get fancy though.
  190. if (typeof console === 'undefined') {
  191. console = {
  192. log: function () {
  193. print.apply(undefined, arguments);
  194. }
  195. };
  196. }
  197. }
  198. /** vim: et:ts=4:sw=4:sts=4
  199. * @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  200. * Available via the MIT or new BSD license.
  201. * see: http://github.com/jrburke/requirejs for details
  202. */
  203. //Not using strict: uneven strict support in browsers, #392, and causes
  204. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  205. /*jslint regexp: true, nomen: true, sloppy: true */
  206. /*global window, navigator, document, importScripts, setTimeout, opera */
  207. (function (global) {
  208. var req, s, head, baseElement, dataMain, src,
  209. interactiveScript, currentlyAddingScript, mainScript, subPath,
  210. version = '2.1.15',
  211. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  212. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  213. jsSuffixRegExp = /\.js$/,
  214. currDirRegExp = /^\.\//,
  215. op = Object.prototype,
  216. ostring = op.toString,
  217. hasOwn = op.hasOwnProperty,
  218. ap = Array.prototype,
  219. apsp = ap.splice,
  220. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  221. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  222. //PS3 indicates loaded and complete, but need to wait for complete
  223. //specifically. Sequence is 'loading', 'loaded', execution,
  224. // then 'complete'. The UA check is unfortunate, but not sure how
  225. //to feature test w/o causing perf issues.
  226. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  227. /^complete$/ : /^(complete|loaded)$/,
  228. defContextName = '_',
  229. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  230. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  231. contexts = {},
  232. cfg = {},
  233. globalDefQueue = [],
  234. useInteractive = false;
  235. function isFunction(it) {
  236. return ostring.call(it) === '[object Function]';
  237. }
  238. function isArray(it) {
  239. return ostring.call(it) === '[object Array]';
  240. }
  241. /**
  242. * Helper function for iterating over an array. If the func returns
  243. * a true value, it will break out of the loop.
  244. */
  245. function each(ary, func) {
  246. if (ary) {
  247. var i;
  248. for (i = 0; i < ary.length; i += 1) {
  249. if (ary[i] && func(ary[i], i, ary)) {
  250. break;
  251. }
  252. }
  253. }
  254. }
  255. /**
  256. * Helper function for iterating over an array backwards. If the func
  257. * returns a true value, it will break out of the loop.
  258. */
  259. function eachReverse(ary, func) {
  260. if (ary) {
  261. var i;
  262. for (i = ary.length - 1; i > -1; i -= 1) {
  263. if (ary[i] && func(ary[i], i, ary)) {
  264. break;
  265. }
  266. }
  267. }
  268. }
  269. function hasProp(obj, prop) {
  270. return hasOwn.call(obj, prop);
  271. }
  272. function getOwn(obj, prop) {
  273. return hasProp(obj, prop) && obj[prop];
  274. }
  275. /**
  276. * Cycles over properties in an object and calls a function for each
  277. * property value. If the function returns a truthy value, then the
  278. * iteration is stopped.
  279. */
  280. function eachProp(obj, func) {
  281. var prop;
  282. for (prop in obj) {
  283. if (hasProp(obj, prop)) {
  284. if (func(obj[prop], prop)) {
  285. break;
  286. }
  287. }
  288. }
  289. }
  290. /**
  291. * Simple function to mix in properties from source into target,
  292. * but only if target does not already have a property of the same name.
  293. */
  294. function mixin(target, source, force, deepStringMixin) {
  295. if (source) {
  296. eachProp(source, function (value, prop) {
  297. if (force || !hasProp(target, prop)) {
  298. if (deepStringMixin && typeof value === 'object' && value &&
  299. !isArray(value) && !isFunction(value) &&
  300. !(value instanceof RegExp)) {
  301. if (!target[prop]) {
  302. target[prop] = {};
  303. }
  304. mixin(target[prop], value, force, deepStringMixin);
  305. } else {
  306. target[prop] = value;
  307. }
  308. }
  309. });
  310. }
  311. return target;
  312. }
  313. //Similar to Function.prototype.bind, but the 'this' object is specified
  314. //first, since it is easier to read/figure out what 'this' will be.
  315. function bind(obj, fn) {
  316. return function () {
  317. return fn.apply(obj, arguments);
  318. };
  319. }
  320. function scripts() {
  321. return document.getElementsByTagName('script');
  322. }
  323. function defaultOnError(err) {
  324. throw err;
  325. }
  326. //Allow getting a global that is expressed in
  327. //dot notation, like 'a.b.c'.
  328. function getGlobal(value) {
  329. if (!value) {
  330. return value;
  331. }
  332. var g = global;
  333. each(value.split('.'), function (part) {
  334. g = g[part];
  335. });
  336. return g;
  337. }
  338. /**
  339. * Constructs an error with a pointer to an URL with more information.
  340. * @param {String} id the error ID that maps to an ID on a web page.
  341. * @param {String} message human readable error.
  342. * @param {Error} [err] the original error, if there is one.
  343. *
  344. * @returns {Error}
  345. */
  346. function makeError(id, msg, err, requireModules) {
  347. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  348. e.requireType = id;
  349. e.requireModules = requireModules;
  350. if (err) {
  351. e.originalError = err;
  352. }
  353. return e;
  354. }
  355. if (typeof define !== 'undefined') {
  356. //If a define is already in play via another AMD loader,
  357. //do not overwrite.
  358. return;
  359. }
  360. if (typeof requirejs !== 'undefined') {
  361. if (isFunction(requirejs)) {
  362. //Do not overwrite an existing requirejs instance.
  363. return;
  364. }
  365. cfg = requirejs;
  366. requirejs = undefined;
  367. }
  368. //Allow for a require config object
  369. if (typeof require !== 'undefined' && !isFunction(require)) {
  370. //assume it is a config object.
  371. cfg = require;
  372. require = undefined;
  373. }
  374. function newContext(contextName) {
  375. var inCheckLoaded, Module, context, handlers,
  376. checkLoadedTimeoutId,
  377. config = {
  378. //Defaults. Do not set a default for map
  379. //config to speed up normalize(), which
  380. //will run faster if there is no default.
  381. waitSeconds: 7,
  382. baseUrl: './',
  383. paths: {},
  384. bundles: {},
  385. pkgs: {},
  386. shim: {},
  387. config: {}
  388. },
  389. registry = {},
  390. //registry of just enabled modules, to speed
  391. //cycle breaking code when lots of modules
  392. //are registered, but not activated.
  393. enabledRegistry = {},
  394. undefEvents = {},
  395. defQueue = [],
  396. defined = {},
  397. urlFetched = {},
  398. bundlesMap = {},
  399. requireCounter = 1,
  400. unnormalizedCounter = 1;
  401. /**
  402. * Trims the . and .. from an array of path segments.
  403. * It will keep a leading path segment if a .. will become
  404. * the first path segment, to help with module name lookups,
  405. * which act like paths, but can be remapped. But the end result,
  406. * all paths that use this function should look normalized.
  407. * NOTE: this method MODIFIES the input array.
  408. * @param {Array} ary the array of path segments.
  409. */
  410. function trimDots(ary) {
  411. var i, part;
  412. for (i = 0; i < ary.length; i++) {
  413. part = ary[i];
  414. if (part === '.') {
  415. ary.splice(i, 1);
  416. i -= 1;
  417. } else if (part === '..') {
  418. // If at the start, or previous value is still ..,
  419. // keep them so that when converted to a path it may
  420. // still work when converted to a path, even though
  421. // as an ID it is less than ideal. In larger point
  422. // releases, may be better to just kick out an error.
  423. if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
  424. continue;
  425. } else if (i > 0) {
  426. ary.splice(i - 1, 2);
  427. i -= 2;
  428. }
  429. }
  430. }
  431. }
  432. /**
  433. * Given a relative module name, like ./something, normalize it to
  434. * a real name that can be mapped to a path.
  435. * @param {String} name the relative name
  436. * @param {String} baseName a real name that the name arg is relative
  437. * to.
  438. * @param {Boolean} applyMap apply the map config to the value. Should
  439. * only be done if this normalization is for a dependency ID.
  440. * @returns {String} normalized name
  441. */
  442. function normalize(name, baseName, applyMap) {
  443. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  444. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  445. baseParts = (baseName && baseName.split('/')),
  446. map = config.map,
  447. starMap = map && map['*'];
  448. //Adjust any relative paths.
  449. if (name) {
  450. name = name.split('/');
  451. lastIndex = name.length - 1;
  452. // If wanting node ID compatibility, strip .js from end
  453. // of IDs. Have to do this here, and not in nameToUrl
  454. // because node allows either .js or non .js to map
  455. // to same file.
  456. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  457. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  458. }
  459. // Starts with a '.' so need the baseName
  460. if (name[0].charAt(0) === '.' && baseParts) {
  461. //Convert baseName to array, and lop off the last part,
  462. //so that . matches that 'directory' and not name of the baseName's
  463. //module. For instance, baseName of 'one/two/three', maps to
  464. //'one/two/three.js', but we want the directory, 'one/two' for
  465. //this normalization.
  466. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  467. name = normalizedBaseParts.concat(name);
  468. }
  469. trimDots(name);
  470. name = name.join('/');
  471. }
  472. //Apply map config if available.
  473. if (applyMap && map && (baseParts || starMap)) {
  474. nameParts = name.split('/');
  475. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  476. nameSegment = nameParts.slice(0, i).join('/');
  477. if (baseParts) {
  478. //Find the longest baseName segment match in the config.
  479. //So, do joins on the biggest to smallest lengths of baseParts.
  480. for (j = baseParts.length; j > 0; j -= 1) {
  481. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  482. //baseName segment has config, find if it has one for
  483. //this name.
  484. if (mapValue) {
  485. mapValue = getOwn(mapValue, nameSegment);
  486. if (mapValue) {
  487. //Match, update name to the new value.
  488. foundMap = mapValue;
  489. foundI = i;
  490. break outerLoop;
  491. }
  492. }
  493. }
  494. }
  495. //Check for a star map match, but just hold on to it,
  496. //if there is a shorter segment match later in a matching
  497. //config, then favor over this star map.
  498. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  499. foundStarMap = getOwn(starMap, nameSegment);
  500. starI = i;
  501. }
  502. }
  503. if (!foundMap && foundStarMap) {
  504. foundMap = foundStarMap;
  505. foundI = starI;
  506. }
  507. if (foundMap) {
  508. nameParts.splice(0, foundI, foundMap);
  509. name = nameParts.join('/');
  510. }
  511. }
  512. // If the name points to a package's name, use
  513. // the package main instead.
  514. pkgMain = getOwn(config.pkgs, name);
  515. return pkgMain ? pkgMain : name;
  516. }
  517. function removeScript(name) {
  518. if (isBrowser) {
  519. each(scripts(), function (scriptNode) {
  520. if (scriptNode.getAttribute('data-requiremodule') === name &&
  521. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  522. scriptNode.parentNode.removeChild(scriptNode);
  523. return true;
  524. }
  525. });
  526. }
  527. }
  528. function hasPathFallback(id) {
  529. var pathConfig = getOwn(config.paths, id);
  530. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  531. //Pop off the first array value, since it failed, and
  532. //retry
  533. pathConfig.shift();
  534. context.require.undef(id);
  535. //Custom require that does not do map translation, since
  536. //ID is "absolute", already mapped/resolved.
  537. context.makeRequire(null, {
  538. skipMap: true
  539. })([id]);
  540. return true;
  541. }
  542. }
  543. //Turns a plugin!resource to [plugin, resource]
  544. //with the plugin being undefined if the name
  545. //did not have a plugin prefix.
  546. function splitPrefix(name) {
  547. var prefix,
  548. index = name ? name.indexOf('!') : -1;
  549. if (index > -1) {
  550. prefix = name.substring(0, index);
  551. name = name.substring(index + 1, name.length);
  552. }
  553. return [prefix, name];
  554. }
  555. /**
  556. * Creates a module mapping that includes plugin prefix, module
  557. * name, and path. If parentModuleMap is provided it will
  558. * also normalize the name via require.normalize()
  559. *
  560. * @param {String} name the module name
  561. * @param {String} [parentModuleMap] parent module map
  562. * for the module name, used to resolve relative names.
  563. * @param {Boolean} isNormalized: is the ID already normalized.
  564. * This is true if this call is done for a define() module ID.
  565. * @param {Boolean} applyMap: apply the map config to the ID.
  566. * Should only be true if this map is for a dependency.
  567. *
  568. * @returns {Object}
  569. */
  570. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  571. var url, pluginModule, suffix, nameParts,
  572. prefix = null,
  573. parentName = parentModuleMap ? parentModuleMap.name : null,
  574. originalName = name,
  575. isDefine = true,
  576. normalizedName = '';
  577. //If no name, then it means it is a require call, generate an
  578. //internal name.
  579. if (!name) {
  580. isDefine = false;
  581. name = '_@r' + (requireCounter += 1);
  582. }
  583. nameParts = splitPrefix(name);
  584. prefix = nameParts[0];
  585. name = nameParts[1];
  586. if (prefix) {
  587. prefix = normalize(prefix, parentName, applyMap);
  588. pluginModule = getOwn(defined, prefix);
  589. }
  590. //Account for relative paths if there is a base name.
  591. if (name) {
  592. if (prefix) {
  593. if (pluginModule && pluginModule.normalize) {
  594. //Plugin is loaded, use its normalize method.
  595. normalizedName = pluginModule.normalize(name, function (name) {
  596. return normalize(name, parentName, applyMap);
  597. });
  598. } else {
  599. // If nested plugin references, then do not try to
  600. // normalize, as it will not normalize correctly. This
  601. // places a restriction on resourceIds, and the longer
  602. // term solution is not to normalize until plugins are
  603. // loaded and all normalizations to allow for async
  604. // loading of a loader plugin. But for now, fixes the
  605. // common uses. Details in #1131
  606. normalizedName = name.indexOf('!') === -1 ?
  607. normalize(name, parentName, applyMap) :
  608. name;
  609. }
  610. } else {
  611. //A regular module.
  612. normalizedName = normalize(name, parentName, applyMap);
  613. //Normalized name may be a plugin ID due to map config
  614. //application in normalize. The map config values must
  615. //already be normalized, so do not need to redo that part.
  616. nameParts = splitPrefix(normalizedName);
  617. prefix = nameParts[0];
  618. normalizedName = nameParts[1];
  619. isNormalized = true;
  620. url = context.nameToUrl(normalizedName);
  621. }
  622. }
  623. //If the id is a plugin id that cannot be determined if it needs
  624. //normalization, stamp it with a unique ID so two matching relative
  625. //ids that may conflict can be separate.
  626. suffix = prefix && !pluginModule && !isNormalized ?
  627. '_unnormalized' + (unnormalizedCounter += 1) :
  628. '';
  629. return {
  630. prefix: prefix,
  631. name: normalizedName,
  632. parentMap: parentModuleMap,
  633. unnormalized: !!suffix,
  634. url: url,
  635. originalName: originalName,
  636. isDefine: isDefine,
  637. id: (prefix ?
  638. prefix + '!' + normalizedName :
  639. normalizedName) + suffix
  640. };
  641. }
  642. function getModule(depMap) {
  643. var id = depMap.id,
  644. mod = getOwn(registry, id);
  645. if (!mod) {
  646. mod = registry[id] = new context.Module(depMap);
  647. }
  648. return mod;
  649. }
  650. function on(depMap, name, fn) {
  651. var id = depMap.id,
  652. mod = getOwn(registry, id);
  653. if (hasProp(defined, id) &&
  654. (!mod || mod.defineEmitComplete)) {
  655. if (name === 'defined') {
  656. fn(defined[id]);
  657. }
  658. } else {
  659. mod = getModule(depMap);
  660. if (mod.error && name === 'error') {
  661. fn(mod.error);
  662. } else {
  663. mod.on(name, fn);
  664. }
  665. }
  666. }
  667. function onError(err, errback) {
  668. var ids = err.requireModules,
  669. notified = false;
  670. if (errback) {
  671. errback(err);
  672. } else {
  673. each(ids, function (id) {
  674. var mod = getOwn(registry, id);
  675. if (mod) {
  676. //Set error on module, so it skips timeout checks.
  677. mod.error = err;
  678. if (mod.events.error) {
  679. notified = true;
  680. mod.emit('error', err);
  681. }
  682. }
  683. });
  684. if (!notified) {
  685. req.onError(err);
  686. }
  687. }
  688. }
  689. /**
  690. * Internal method to transfer globalQueue items to this context's
  691. * defQueue.
  692. */
  693. function takeGlobalQueue() {
  694. //Push all the globalDefQueue items into the context's defQueue
  695. if (globalDefQueue.length) {
  696. //Array splice in the values since the context code has a
  697. //local var ref to defQueue, so cannot just reassign the one
  698. //on context.
  699. apsp.apply(defQueue,
  700. [defQueue.length, 0].concat(globalDefQueue));
  701. globalDefQueue = [];
  702. }
  703. }
  704. handlers = {
  705. 'require': function (mod) {
  706. if (mod.require) {
  707. return mod.require;
  708. } else {
  709. return (mod.require = context.makeRequire(mod.map));
  710. }
  711. },
  712. 'exports': function (mod) {
  713. mod.usingExports = true;
  714. if (mod.map.isDefine) {
  715. if (mod.exports) {
  716. return (defined[mod.map.id] = mod.exports);
  717. } else {
  718. return (mod.exports = defined[mod.map.id] = {});
  719. }
  720. }
  721. },
  722. 'module': function (mod) {
  723. if (mod.module) {
  724. return mod.module;
  725. } else {
  726. return (mod.module = {
  727. id: mod.map.id,
  728. uri: mod.map.url,
  729. config: function () {
  730. return getOwn(config.config, mod.map.id) || {};
  731. },
  732. exports: mod.exports || (mod.exports = {})
  733. });
  734. }
  735. }
  736. };
  737. function cleanRegistry(id) {
  738. //Clean up machinery used for waiting modules.
  739. delete registry[id];
  740. delete enabledRegistry[id];
  741. }
  742. function breakCycle(mod, traced, processed) {
  743. var id = mod.map.id;
  744. if (mod.error) {
  745. mod.emit('error', mod.error);
  746. } else {
  747. traced[id] = true;
  748. each(mod.depMaps, function (depMap, i) {
  749. var depId = depMap.id,
  750. dep = getOwn(registry, depId);
  751. //Only force things that have not completed
  752. //being defined, so still in the registry,
  753. //and only if it has not been matched up
  754. //in the module already.
  755. if (dep && !mod.depMatched[i] && !processed[depId]) {
  756. if (getOwn(traced, depId)) {
  757. mod.defineDep(i, defined[depId]);
  758. mod.check(); //pass false?
  759. } else {
  760. breakCycle(dep, traced, processed);
  761. }
  762. }
  763. });
  764. processed[id] = true;
  765. }
  766. }
  767. function checkLoaded() {
  768. var err, usingPathFallback,
  769. waitInterval = config.waitSeconds * 1000,
  770. //It is possible to disable the wait interval by using waitSeconds of 0.
  771. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  772. noLoads = [],
  773. reqCalls = [],
  774. stillLoading = false,
  775. needCycleCheck = true;
  776. //Do not bother if this call was a result of a cycle break.
  777. if (inCheckLoaded) {
  778. return;
  779. }
  780. inCheckLoaded = true;
  781. //Figure out the state of all the modules.
  782. eachProp(enabledRegistry, function (mod) {
  783. var map = mod.map,
  784. modId = map.id;
  785. //Skip things that are not enabled or in error state.
  786. if (!mod.enabled) {
  787. return;
  788. }
  789. if (!map.isDefine) {
  790. reqCalls.push(mod);
  791. }
  792. if (!mod.error) {
  793. //If the module should be executed, and it has not
  794. //been inited and time is up, remember it.
  795. if (!mod.inited && expired) {
  796. if (hasPathFallback(modId)) {
  797. usingPathFallback = true;
  798. stillLoading = true;
  799. } else {
  800. noLoads.push(modId);
  801. removeScript(modId);
  802. }
  803. } else if (!mod.inited && mod.fetched && map.isDefine) {
  804. stillLoading = true;
  805. if (!map.prefix) {
  806. //No reason to keep looking for unfinished
  807. //loading. If the only stillLoading is a
  808. //plugin resource though, keep going,
  809. //because it may be that a plugin resource
  810. //is waiting on a non-plugin cycle.
  811. return (needCycleCheck = false);
  812. }
  813. }
  814. }
  815. });
  816. if (expired && noLoads.length) {
  817. //If wait time expired, throw error of unloaded modules.
  818. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  819. err.contextName = context.contextName;
  820. return onError(err);
  821. }
  822. //Not expired, check for a cycle.
  823. if (needCycleCheck) {
  824. each(reqCalls, function (mod) {
  825. breakCycle(mod, {}, {});
  826. });
  827. }
  828. //If still waiting on loads, and the waiting load is something
  829. //other than a plugin resource, or there are still outstanding
  830. //scripts, then just try back later.
  831. if ((!expired || usingPathFallback) && stillLoading) {
  832. //Something is still waiting to load. Wait for it, but only
  833. //if a timeout is not already in effect.
  834. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  835. checkLoadedTimeoutId = setTimeout(function () {
  836. checkLoadedTimeoutId = 0;
  837. checkLoaded();
  838. }, 50);
  839. }
  840. }
  841. inCheckLoaded = false;
  842. }
  843. Module = function (map) {
  844. this.events = getOwn(undefEvents, map.id) || {};
  845. this.map = map;
  846. this.shim = getOwn(config.shim, map.id);
  847. this.depExports = [];
  848. this.depMaps = [];
  849. this.depMatched = [];
  850. this.pluginMaps = {};
  851. this.depCount = 0;
  852. /* this.exports this.factory
  853. this.depMaps = [],
  854. this.enabled, this.fetched
  855. */
  856. };
  857. Module.prototype = {
  858. init: function (depMaps, factory, errback, options) {
  859. options = options || {};
  860. //Do not do more inits if already done. Can happen if there
  861. //are multiple define calls for the same module. That is not
  862. //a normal, common case, but it is also not unexpected.
  863. if (this.inited) {
  864. return;
  865. }
  866. this.factory = factory;
  867. if (errback) {
  868. //Register for errors on this module.
  869. this.on('error', errback);
  870. } else if (this.events.error) {
  871. //If no errback already, but there are error listeners
  872. //on this module, set up an errback to pass to the deps.
  873. errback = bind(this, function (err) {
  874. this.emit('error', err);
  875. });
  876. }
  877. //Do a copy of the dependency array, so that
  878. //source inputs are not modified. For example
  879. //"shim" deps are passed in here directly, and
  880. //doing a direct modification of the depMaps array
  881. //would affect that config.
  882. this.depMaps = depMaps && depMaps.slice(0);
  883. this.errback = errback;
  884. //Indicate this module has be initialized
  885. this.inited = true;
  886. this.ignore = options.ignore;
  887. //Could have option to init this module in enabled mode,
  888. //or could have been previously marked as enabled. However,
  889. //the dependencies are not known until init is called. So
  890. //if enabled previously, now trigger dependencies as enabled.
  891. if (options.enabled || this.enabled) {
  892. //Enable this module and dependencies.
  893. //Will call this.check()
  894. this.enable();
  895. } else {
  896. this.check();
  897. }
  898. },
  899. defineDep: function (i, depExports) {
  900. //Because of cycles, defined callback for a given
  901. //export can be called more than once.
  902. if (!this.depMatched[i]) {
  903. this.depMatched[i] = true;
  904. this.depCount -= 1;
  905. this.depExports[i] = depExports;
  906. }
  907. },
  908. fetch: function () {
  909. if (this.fetched) {
  910. return;
  911. }
  912. this.fetched = true;
  913. context.startTime = (new Date()).getTime();
  914. var map = this.map;
  915. //If the manager is for a plugin managed resource,
  916. //ask the plugin to load it now.
  917. if (this.shim) {
  918. context.makeRequire(this.map, {
  919. enableBuildCallback: true
  920. })(this.shim.deps || [], bind(this, function () {
  921. return map.prefix ? this.callPlugin() : this.load();
  922. }));
  923. } else {
  924. //Regular dependency.
  925. return map.prefix ? this.callPlugin() : this.load();
  926. }
  927. },
  928. load: function () {
  929. var url = this.map.url;
  930. //Regular dependency.
  931. if (!urlFetched[url]) {
  932. urlFetched[url] = true;
  933. context.load(this.map.id, url);
  934. }
  935. },
  936. /**
  937. * Checks if the module is ready to define itself, and if so,
  938. * define it.
  939. */
  940. check: function () {
  941. if (!this.enabled || this.enabling) {
  942. return;
  943. }
  944. var err, cjsModule,
  945. id = this.map.id,
  946. depExports = this.depExports,
  947. exports = this.exports,
  948. factory = this.factory;
  949. if (!this.inited) {
  950. this.fetch();
  951. } else if (this.error) {
  952. this.emit('error', this.error);
  953. } else if (!this.defining) {
  954. //The factory could trigger another require call
  955. //that would result in checking this module to
  956. //define itself again. If already in the process
  957. //of doing that, skip this work.
  958. this.defining = true;
  959. if (this.depCount < 1 && !this.defined) {
  960. if (isFunction(factory)) {
  961. //If there is an error listener, favor passing
  962. //to that instead of throwing an error. However,
  963. //only do it for define()'d modules. require
  964. //errbacks should not be called for failures in
  965. //their callbacks (#699). However if a global
  966. //onError is set, use that.
  967. if ((this.events.error && this.map.isDefine) ||
  968. req.onError !== defaultOnError) {
  969. try {
  970. exports = context.execCb(id, factory, depExports, exports);
  971. } catch (e) {
  972. err = e;
  973. }
  974. } else {
  975. exports = context.execCb(id, factory, depExports, exports);
  976. }
  977. // Favor return value over exports. If node/cjs in play,
  978. // then will not have a return value anyway. Favor
  979. // module.exports assignment over exports object.
  980. if (this.map.isDefine && exports === undefined) {
  981. cjsModule = this.module;
  982. if (cjsModule) {
  983. exports = cjsModule.exports;
  984. } else if (this.usingExports) {
  985. //exports already set the defined value.
  986. exports = this.exports;
  987. }
  988. }
  989. if (err) {
  990. err.requireMap = this.map;
  991. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  992. err.requireType = this.map.isDefine ? 'define' : 'require';
  993. return onError((this.error = err));
  994. }
  995. } else {
  996. //Just a literal value
  997. exports = factory;
  998. }
  999. this.exports = exports;
  1000. if (this.map.isDefine && !this.ignore) {
  1001. defined[id] = exports;
  1002. if (req.onResourceLoad) {
  1003. req.onResourceLoad(context, this.map, this.depMaps);
  1004. }
  1005. }
  1006. //Clean up
  1007. cleanRegistry(id);
  1008. this.defined = true;
  1009. }
  1010. //Finished the define stage. Allow calling check again
  1011. //to allow define notifications below in the case of a
  1012. //cycle.
  1013. this.defining = false;
  1014. if (this.defined && !this.defineEmitted) {
  1015. this.defineEmitted = true;
  1016. this.emit('defined', this.exports);
  1017. this.defineEmitComplete = true;
  1018. }
  1019. }
  1020. },
  1021. callPlugin: function () {
  1022. var map = this.map,
  1023. id = map.id,
  1024. //Map already normalized the prefix.
  1025. pluginMap = makeModuleMap(map.prefix);
  1026. //Mark this as a dependency for this plugin, so it
  1027. //can be traced for cycles.
  1028. this.depMaps.push(pluginMap);
  1029. on(pluginMap, 'defined', bind(this, function (plugin) {
  1030. var load, normalizedMap, normalizedMod,
  1031. bundleId = getOwn(bundlesMap, this.map.id),
  1032. name = this.map.name,
  1033. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1034. localRequire = context.makeRequire(map.parentMap, {
  1035. enableBuildCallback: true
  1036. });
  1037. //If current map is not normalized, wait for that
  1038. //normalized name to load instead of continuing.
  1039. if (this.map.unnormalized) {
  1040. //Normalize the ID if the plugin allows it.
  1041. if (plugin.normalize) {
  1042. name = plugin.normalize(name, function (name) {
  1043. return normalize(name, parentName, true);
  1044. }) || '';
  1045. }
  1046. //prefix and name should already be normalized, no need
  1047. //for applying map config again either.
  1048. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1049. this.map.parentMap);
  1050. on(normalizedMap,
  1051. 'defined', bind(this, function (value) {
  1052. this.init([], function () { return value; }, null, {
  1053. enabled: true,
  1054. ignore: true
  1055. });
  1056. }));
  1057. normalizedMod = getOwn(registry, normalizedMap.id);
  1058. if (normalizedMod) {
  1059. //Mark this as a dependency for this plugin, so it
  1060. //can be traced for cycles.
  1061. this.depMaps.push(normalizedMap);
  1062. if (this.events.error) {
  1063. normalizedMod.on('error', bind(this, function (err) {
  1064. this.emit('error', err);
  1065. }));
  1066. }
  1067. normalizedMod.enable();
  1068. }
  1069. return;
  1070. }
  1071. //If a paths config, then just load that file instead to
  1072. //resolve the plugin, as it is built into that paths layer.
  1073. if (bundleId) {
  1074. this.map.url = context.nameToUrl(bundleId);
  1075. this.load();
  1076. return;
  1077. }
  1078. load = bind(this, function (value) {
  1079. this.init([], function () { return value; }, null, {
  1080. enabled: true
  1081. });
  1082. });
  1083. load.error = bind(this, function (err) {
  1084. this.inited = true;
  1085. this.error = err;
  1086. err.requireModules = [id];
  1087. //Remove temp unnormalized modules for this module,
  1088. //since they will never be resolved otherwise now.
  1089. eachProp(registry, function (mod) {
  1090. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1091. cleanRegistry(mod.map.id);
  1092. }
  1093. });
  1094. onError(err);
  1095. });
  1096. //Allow plugins to load other code without having to know the
  1097. //context or how to 'complete' the load.
  1098. load.fromText = bind(this, function (text, textAlt) {
  1099. /*jslint evil: true */
  1100. var moduleName = map.name,
  1101. moduleMap = makeModuleMap(moduleName),
  1102. hasInteractive = useInteractive;
  1103. //As of 2.1.0, support just passing the text, to reinforce
  1104. //fromText only being called once per resource. Still
  1105. //support old style of passing moduleName but discard
  1106. //that moduleName in favor of the internal ref.
  1107. if (textAlt) {
  1108. text = textAlt;
  1109. }
  1110. //Turn off interactive script matching for IE for any define
  1111. //calls in the text, then turn it back on at the end.
  1112. if (hasInteractive) {
  1113. useInteractive = false;
  1114. }
  1115. //Prime the system by creating a module instance for
  1116. //it.
  1117. getModule(moduleMap);
  1118. //Transfer any config to this other module.
  1119. if (hasProp(config.config, id)) {
  1120. config.config[moduleName] = config.config[id];
  1121. }
  1122. try {
  1123. req.exec(text);
  1124. } catch (e) {
  1125. return onError(makeError('fromtexteval',
  1126. 'fromText eval for ' + id +
  1127. ' failed: ' + e,
  1128. e,
  1129. [id]));
  1130. }
  1131. if (hasInteractive) {
  1132. useInteractive = true;
  1133. }
  1134. //Mark this as a dependency for the plugin
  1135. //resource
  1136. this.depMaps.push(moduleMap);
  1137. //Support anonymous modules.
  1138. context.completeLoad(moduleName);
  1139. //Bind the value of that module to the value for this
  1140. //resource ID.
  1141. localRequire([moduleName], load);
  1142. });
  1143. //Use parentName here since the plugin's name is not reliable,
  1144. //could be some weird string with no path that actually wants to
  1145. //reference the parentName's path.
  1146. plugin.load(map.name, localRequire, load, config);
  1147. }));
  1148. context.enable(pluginMap, this);
  1149. this.pluginMaps[pluginMap.id] = pluginMap;
  1150. },
  1151. enable: function () {
  1152. enabledRegistry[this.map.id] = this;
  1153. this.enabled = true;
  1154. //Set flag mentioning that the module is enabling,
  1155. //so that immediate calls to the defined callbacks
  1156. //for dependencies do not trigger inadvertent load
  1157. //with the depCount still being zero.
  1158. this.enabling = true;
  1159. //Enable each dependency
  1160. each(this.depMaps, bind(this, function (depMap, i) {
  1161. var id, mod, handler;
  1162. if (typeof depMap === 'string') {
  1163. //Dependency needs to be converted to a depMap
  1164. //and wired up to this module.
  1165. depMap = makeModuleMap(depMap,
  1166. (this.map.isDefine ? this.map : this.map.parentMap),
  1167. false,
  1168. !this.skipMap);
  1169. this.depMaps[i] = depMap;
  1170. handler = getOwn(handlers, depMap.id);
  1171. if (handler) {
  1172. this.depExports[i] = handler(this);
  1173. return;
  1174. }
  1175. this.depCount += 1;
  1176. on(depMap, 'defined', bind(this, function (depExports) {
  1177. this.defineDep(i, depExports);
  1178. this.check();
  1179. }));
  1180. if (this.errback) {
  1181. on(depMap, 'error', bind(this, this.errback));
  1182. }
  1183. }
  1184. id = depMap.id;
  1185. mod = registry[id];
  1186. //Skip special modules like 'require', 'exports', 'module'
  1187. //Also, don't call enable if it is already enabled,
  1188. //important in circular dependency cases.
  1189. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1190. context.enable(depMap, this);
  1191. }
  1192. }));
  1193. //Enable each plugin that is used in
  1194. //a dependency
  1195. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1196. var mod = getOwn(registry, pluginMap.id);
  1197. if (mod && !mod.enabled) {
  1198. context.enable(pluginMap, this);
  1199. }
  1200. }));
  1201. this.enabling = false;
  1202. this.check();
  1203. },
  1204. on: function (name, cb) {
  1205. var cbs = this.events[name];
  1206. if (!cbs) {
  1207. cbs = this.events[name] = [];
  1208. }
  1209. cbs.push(cb);
  1210. },
  1211. emit: function (name, evt) {
  1212. each(this.events[name], function (cb) {
  1213. cb(evt);
  1214. });
  1215. if (name === 'error') {
  1216. //Now that the error handler was triggered, remove
  1217. //the listeners, since this broken Module instance
  1218. //can stay around for a while in the registry.
  1219. delete this.events[name];
  1220. }
  1221. }
  1222. };
  1223. function callGetModule(args) {
  1224. //Skip modules already defined.
  1225. if (!hasProp(defined, args[0])) {
  1226. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1227. }
  1228. }
  1229. function removeListener(node, func, name, ieName) {
  1230. //Favor detachEvent because of IE9
  1231. //issue, see attachEvent/addEventListener comment elsewhere
  1232. //in this file.
  1233. if (node.detachEvent && !isOpera) {
  1234. //Probably IE. If not it will throw an error, which will be
  1235. //useful to know.
  1236. if (ieName) {
  1237. node.detachEvent(ieName, func);
  1238. }
  1239. } else {
  1240. node.removeEventListener(name, func, false);
  1241. }
  1242. }
  1243. /**
  1244. * Given an event from a script node, get the requirejs info from it,
  1245. * and then removes the event listeners on the node.
  1246. * @param {Event} evt
  1247. * @returns {Object}
  1248. */
  1249. function getScriptData(evt) {
  1250. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1251. //all old browsers will be supported, but this one was easy enough
  1252. //to support and still makes sense.
  1253. var node = evt.currentTarget || evt.srcElement;
  1254. //Remove the listeners once here.
  1255. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1256. removeListener(node, context.onScriptError, 'error');
  1257. return {
  1258. node: node,
  1259. id: node && node.getAttribute('data-requiremodule')
  1260. };
  1261. }
  1262. function intakeDefines() {
  1263. var args;
  1264. //Any defined modules in the global queue, intake them now.
  1265. takeGlobalQueue();
  1266. //Make sure any remaining defQueue items get properly processed.
  1267. while (defQueue.length) {
  1268. args = defQueue.shift();
  1269. if (args[0] === null) {
  1270. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  1271. } else {
  1272. //args are id, deps, factory. Should be normalized by the
  1273. //define() function.
  1274. callGetModule(args);
  1275. }
  1276. }
  1277. }
  1278. context = {
  1279. config: config,
  1280. contextName: contextName,
  1281. registry: registry,
  1282. defined: defined,
  1283. urlFetched: urlFetched,
  1284. defQueue: defQueue,
  1285. Module: Module,
  1286. makeModuleMap: makeModuleMap,
  1287. nextTick: req.nextTick,
  1288. onError: onError,
  1289. /**
  1290. * Set a configuration for the context.
  1291. * @param {Object} cfg config object to integrate.
  1292. */
  1293. configure: function (cfg) {
  1294. //Make sure the baseUrl ends in a slash.
  1295. if (cfg.baseUrl) {
  1296. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1297. cfg.baseUrl += '/';
  1298. }
  1299. }
  1300. //Save off the paths since they require special processing,
  1301. //they are additive.
  1302. var shim = config.shim,
  1303. objs = {
  1304. paths: true,
  1305. bundles: true,
  1306. config: true,
  1307. map: true
  1308. };
  1309. eachProp(cfg, function (value, prop) {
  1310. if (objs[prop]) {
  1311. if (!config[prop]) {
  1312. config[prop] = {};
  1313. }
  1314. mixin(config[prop], value, true, true);
  1315. } else {
  1316. config[prop] = value;
  1317. }
  1318. });
  1319. //Reverse map the bundles
  1320. if (cfg.bundles) {
  1321. eachProp(cfg.bundles, function (value, prop) {
  1322. each(value, function (v) {
  1323. if (v !== prop) {
  1324. bundlesMap[v] = prop;
  1325. }
  1326. });
  1327. });
  1328. }
  1329. //Merge shim
  1330. if (cfg.shim) {
  1331. eachProp(cfg.shim, function (value, id) {
  1332. //Normalize the structure
  1333. if (isArray(value)) {
  1334. value = {
  1335. deps: value
  1336. };
  1337. }
  1338. if ((value.exports || value.init) && !value.exportsFn) {
  1339. value.exportsFn = context.makeShimExports(value);
  1340. }
  1341. shim[id] = value;
  1342. });
  1343. config.shim = shim;
  1344. }
  1345. //Adjust packages if necessary.
  1346. if (cfg.packages) {
  1347. each(cfg.packages, function (pkgObj) {
  1348. var location, name;
  1349. pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  1350. name = pkgObj.name;
  1351. location = pkgObj.location;
  1352. if (location) {
  1353. config.paths[name] = pkgObj.location;
  1354. }
  1355. //Save pointer to main module ID for pkg name.
  1356. //Remove leading dot in main, so main paths are normalized,
  1357. //and remove any trailing .js, since different package
  1358. //envs have different conventions: some use a module name,
  1359. //some use a file name.
  1360. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1361. .replace(currDirRegExp, '')
  1362. .replace(jsSuffixRegExp, '');
  1363. });
  1364. }
  1365. //If there are any "waiting to execute" modules in the registry,
  1366. //update the maps for them, since their info, like URLs to load,
  1367. //may have changed.
  1368. eachProp(registry, function (mod, id) {
  1369. //If module already has init called, since it is too
  1370. //late to modify them, and ignore unnormalized ones
  1371. //since they are transient.
  1372. if (!mod.inited && !mod.map.unnormalized) {
  1373. mod.map = makeModuleMap(id);
  1374. }
  1375. });
  1376. //If a deps array or a config callback is specified, then call
  1377. //require with those args. This is useful when require is defined as a
  1378. //config object before require.js is loaded.
  1379. if (cfg.deps || cfg.callback) {
  1380. context.require(cfg.deps || [], cfg.callback);
  1381. }
  1382. },
  1383. makeShimExports: function (value) {
  1384. function fn() {
  1385. var ret;
  1386. if (value.init) {
  1387. ret = value.init.apply(global, arguments);
  1388. }
  1389. return ret || (value.exports && getGlobal(value.exports));
  1390. }
  1391. return fn;
  1392. },
  1393. makeRequire: function (relMap, options) {
  1394. options = options || {};
  1395. function localRequire(deps, callback, errback) {
  1396. var id, map, requireMod;
  1397. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1398. callback.__requireJsBuild = true;
  1399. }
  1400. if (typeof deps === 'string') {
  1401. if (isFunction(callback)) {
  1402. //Invalid call
  1403. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1404. }
  1405. //If require|exports|module are requested, get the
  1406. //value for them from the special handlers. Caveat:
  1407. //this only works while module is being defined.
  1408. if (relMap && hasProp(handlers, deps)) {
  1409. return handlers[deps](registry[relMap.id]);
  1410. }
  1411. //Synchronous access to one module. If require.get is
  1412. //available (as in the Node adapter), prefer that.
  1413. if (req.get) {
  1414. return req.get(context, deps, relMap, localRequire);
  1415. }
  1416. //Normalize module name, if it contains . or ..
  1417. map = makeModuleMap(deps, relMap, false, true);
  1418. id = map.id;
  1419. if (!hasProp(defined, id)) {
  1420. return onError(makeError('notloaded', 'Module name "' +
  1421. id +
  1422. '" has not been loaded yet for context: ' +
  1423. contextName +
  1424. (relMap ? '' : '. Use require([])')));
  1425. }
  1426. return defined[id];
  1427. }
  1428. //Grab defines waiting in the global queue.
  1429. intakeDefines();
  1430. //Mark all the dependencies as needing to be loaded.
  1431. context.nextTick(function () {
  1432. //Some defines could have been added since the
  1433. //require call, collect them.
  1434. intakeDefines();
  1435. requireMod = getModule(makeModuleMap(null, relMap));
  1436. //Store if map config should be applied to this require
  1437. //call for dependencies.
  1438. requireMod.skipMap = options.skipMap;
  1439. requireMod.init(deps, callback, errback, {
  1440. enabled: true
  1441. });
  1442. checkLoaded();
  1443. });
  1444. return localRequire;
  1445. }
  1446. mixin(localRequire, {
  1447. isBrowser: isBrowser,
  1448. /**
  1449. * Converts a module name + .extension into an URL path.
  1450. * *Requires* the use of a module name. It does not support using
  1451. * plain URLs like nameToUrl.
  1452. */
  1453. toUrl: function (moduleNamePlusExt) {
  1454. var ext,
  1455. index = moduleNamePlusExt.lastIndexOf('.'),
  1456. segment = moduleNamePlusExt.split('/')[0],
  1457. isRelative = segment === '.' || segment === '..';
  1458. //Have a file extension alias, and it is not the
  1459. //dots from a relative path.
  1460. if (index !== -1 && (!isRelative || index > 1)) {
  1461. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1462. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1463. }
  1464. return context.nameToUrl(normalize(moduleNamePlusExt,
  1465. relMap && relMap.id, true), ext, true);
  1466. },
  1467. defined: function (id) {
  1468. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1469. },
  1470. specified: function (id) {
  1471. id = makeModuleMap(id, relMap, false, true).id;
  1472. return hasProp(defined, id) || hasProp(registry, id);
  1473. }
  1474. });
  1475. //Only allow undef on top level require calls
  1476. if (!relMap) {
  1477. localRequire.undef = function (id) {
  1478. //Bind any waiting define() calls to this context,
  1479. //fix for #408
  1480. takeGlobalQueue();
  1481. var map = makeModuleMap(id, relMap, true),
  1482. mod = getOwn(registry, id);
  1483. removeScript(id);
  1484. delete defined[id];
  1485. delete urlFetched[map.url];
  1486. delete undefEvents[id];
  1487. //Clean queued defines too. Go backwards
  1488. //in array so that the splices do not
  1489. //mess up the iteration.
  1490. eachReverse(defQueue, function(args, i) {
  1491. if(args[0] === id) {
  1492. defQueue.splice(i, 1);
  1493. }
  1494. });
  1495. if (mod) {
  1496. //Hold on to listeners in case the
  1497. //module will be attempted to be reloaded
  1498. //using a different config.
  1499. if (mod.events.defined) {
  1500. undefEvents[id] = mod.events;
  1501. }
  1502. cleanRegistry(id);
  1503. }
  1504. };
  1505. }
  1506. return localRequire;
  1507. },
  1508. /**
  1509. * Called to enable a module if it is still in the registry
  1510. * awaiting enablement. A second arg, parent, the parent module,
  1511. * is passed in for context, when this method is overridden by
  1512. * the optimizer. Not shown here to keep code compact.
  1513. */
  1514. enable: function (depMap) {
  1515. var mod = getOwn(registry, depMap.id);
  1516. if (mod) {
  1517. getModule(depMap).enable();
  1518. }
  1519. },
  1520. /**
  1521. * Internal method used by environment adapters to complete a load event.
  1522. * A load event could be a script load or just a load pass from a synchronous
  1523. * load call.
  1524. * @param {String} moduleName the name of the module to potentially complete.
  1525. */
  1526. completeLoad: function (moduleName) {
  1527. var found, args, mod,
  1528. shim = getOwn(config.shim, moduleName) || {},
  1529. shExports = shim.exports;
  1530. takeGlobalQueue();
  1531. while (defQueue.length) {
  1532. args = defQueue.shift();
  1533. if (args[0] === null) {
  1534. args[0] = moduleName;
  1535. //If already found an anonymous module and bound it
  1536. //to this name, then this is some other anon module
  1537. //waiting for its completeLoad to fire.
  1538. if (found) {
  1539. break;
  1540. }
  1541. found = true;
  1542. } else if (args[0] === moduleName) {
  1543. //Found matching define call for this script!
  1544. found = true;
  1545. }
  1546. callGetModule(args);
  1547. }
  1548. //Do this after the cycle of callGetModule in case the result
  1549. //of those calls/init calls changes the registry.
  1550. mod = getOwn(registry, moduleName);
  1551. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1552. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1553. if (hasPathFallback(moduleName)) {
  1554. return;
  1555. } else {
  1556. return onError(makeError('nodefine',
  1557. 'No define call for ' + moduleName,
  1558. null,
  1559. [moduleName]));
  1560. }
  1561. } else {
  1562. //A script that does not call define(), so just simulate
  1563. //the call for it.
  1564. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1565. }
  1566. }
  1567. checkLoaded();
  1568. },
  1569. /**
  1570. * Converts a module name to a file path. Supports cases where
  1571. * moduleName may actually be just an URL.
  1572. * Note that it **does not** call normalize on the moduleName,
  1573. * it is assumed to have already been normalized. This is an
  1574. * internal API, not a public one. Use toUrl for the public API.
  1575. */
  1576. nameToUrl: function (moduleName, ext, skipExt) {
  1577. var paths, syms, i, parentModule, url,
  1578. parentPath, bundleId,
  1579. pkgMain = getOwn(config.pkgs, moduleName);
  1580. if (pkgMain) {
  1581. moduleName = pkgMain;
  1582. }
  1583. bundleId = getOwn(bundlesMap, moduleName);
  1584. if (bundleId) {
  1585. return context.nameToUrl(bundleId, ext, skipExt);
  1586. }
  1587. //If a colon is in the URL, it indicates a protocol is used and it is just
  1588. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1589. //or ends with .js, then assume the user meant to use an url and not a module id.
  1590. //The slash is important for protocol-less URLs as well as full paths.
  1591. if (req.jsExtRegExp.test(moduleName)) {
  1592. //Just a plain path, not module name lookup, so just return it.
  1593. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1594. //an extension, this method probably needs to be reworked.
  1595. url = moduleName + (ext || '');
  1596. } else {
  1597. //A module that needs to be converted to a path.
  1598. paths = config.paths;
  1599. syms = moduleName.split('/');
  1600. //For each module name segment, see if there is a path
  1601. //registered for it. Start with most specific name
  1602. //and work up from it.
  1603. for (i = syms.length; i > 0; i -= 1) {
  1604. parentModule = syms.slice(0, i).join('/');
  1605. parentPath = getOwn(paths, parentModule);
  1606. if (parentPath) {
  1607. //If an array, it means there are a few choices,
  1608. //Choose the one that is desired
  1609. if (isArray(parentPath)) {
  1610. parentPath = parentPath[0];
  1611. }
  1612. syms.splice(0, i, parentPath);
  1613. break;
  1614. }
  1615. }
  1616. //Join the path parts together, then figure out if baseUrl is needed.
  1617. url = syms.join('/');
  1618. url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
  1619. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1620. }
  1621. return config.urlArgs ? url +
  1622. ((url.indexOf('?') === -1 ? '?' : '&') +
  1623. config.urlArgs) : url;
  1624. },
  1625. //Delegates to req.load. Broken out as a separate function to
  1626. //allow overriding in the optimizer.
  1627. load: function (id, url) {
  1628. req.load(context, id, url);
  1629. },
  1630. /**
  1631. * Executes a module callback function. Broken out as a separate function
  1632. * solely to allow the build system to sequence the files in the built
  1633. * layer in the right sequence.
  1634. *
  1635. * @private
  1636. */
  1637. execCb: function (name, callback, args, exports) {
  1638. return callback.apply(exports, args);
  1639. },
  1640. /**
  1641. * callback for script loads, used to check status of loading.
  1642. *
  1643. * @param {Event} evt the event from the browser for the script
  1644. * that was loaded.
  1645. */
  1646. onScriptLoad: function (evt) {
  1647. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1648. //all old browsers will be supported, but this one was easy enough
  1649. //to support and still makes sense.
  1650. if (evt.type === 'load' ||
  1651. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1652. //Reset interactive script so a script node is not held onto for
  1653. //to long.
  1654. interactiveScript = null;
  1655. //Pull out the name of the module and the context.
  1656. var data = getScriptData(evt);
  1657. context.completeLoad(data.id);
  1658. }
  1659. },
  1660. /**
  1661. * Callback for script errors.
  1662. */
  1663. onScriptError: function (evt) {
  1664. var data = getScriptData(evt);
  1665. if (!hasPathFallback(data.id)) {
  1666. return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
  1667. }
  1668. }
  1669. };
  1670. context.require = context.makeRequire();
  1671. return context;
  1672. }
  1673. /**
  1674. * Main entry point.
  1675. *
  1676. * If the only argument to require is a string, then the module that
  1677. * is represented by that string is fetched for the appropriate context.
  1678. *
  1679. * If the first argument is an array, then it will be treated as an array
  1680. * of dependency string names to fetch. An optional function callback can
  1681. * be specified to execute when all of those dependencies are available.
  1682. *
  1683. * Make a local req variable to help Caja compliance (it assumes things
  1684. * on a require that are not standardized), and to give a short
  1685. * name for minification/local scope use.
  1686. */
  1687. req = requirejs = function (deps, callback, errback, optional) {
  1688. //Find the right context, use default
  1689. var context, config,
  1690. contextName = defContextName;
  1691. // Determine if have config object in the call.
  1692. if (!isArray(deps) && typeof deps !== 'string') {
  1693. // deps is a config object
  1694. config = deps;
  1695. if (isArray(callback)) {
  1696. // Adjust args if there are dependencies
  1697. deps = callback;
  1698. callback = errback;
  1699. errback = optional;
  1700. } else {
  1701. deps = [];
  1702. }
  1703. }
  1704. if (config && config.context) {
  1705. contextName = config.context;
  1706. }
  1707. context = getOwn(contexts, contextName);
  1708. if (!context) {
  1709. context = contexts[contextName] = req.s.newContext(contextName);
  1710. }
  1711. if (config) {
  1712. context.configure(config);
  1713. }
  1714. return context.require(deps, callback, errback);
  1715. };
  1716. /**
  1717. * Support require.config() to make it easier to cooperate with other
  1718. * AMD loaders on globally agreed names.
  1719. */
  1720. req.config = function (config) {
  1721. return req(config);
  1722. };
  1723. /**
  1724. * Execute something after the current tick
  1725. * of the event loop. Override for other envs
  1726. * that have a better solution than setTimeout.
  1727. * @param {Function} fn function to execute later.
  1728. */
  1729. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1730. setTimeout(fn, 4);
  1731. } : function (fn) { fn(); };
  1732. /**
  1733. * Export require as a global, but only if it does not already exist.
  1734. */
  1735. if (!require) {
  1736. require = req;
  1737. }
  1738. req.version = version;
  1739. //Used to filter out dependencies that are already paths.
  1740. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1741. req.isBrowser = isBrowser;
  1742. s = req.s = {
  1743. contexts: contexts,
  1744. newContext: newContext
  1745. };
  1746. //Create default context.
  1747. req({});
  1748. //Exports some context-sensitive methods on global require.
  1749. each([
  1750. 'toUrl',
  1751. 'undef',
  1752. 'defined',
  1753. 'specified'
  1754. ], function (prop) {
  1755. //Reference from contexts instead of early binding to default context,
  1756. //so that during builds, the latest instance of the default context
  1757. //with its config gets used.
  1758. req[prop] = function () {
  1759. var ctx = contexts[defContextName];
  1760. return ctx.require[prop].apply(ctx, arguments);
  1761. };
  1762. });
  1763. if (isBrowser) {
  1764. head = s.head = document.getElementsByTagName('head')[0];
  1765. //If BASE tag is in play, using appendChild is a problem for IE6.
  1766. //When that browser dies, this can be removed. Details in this jQuery bug:
  1767. //http://dev.jquery.com/ticket/2709
  1768. baseElement = document.getElementsByTagName('base')[0];
  1769. if (baseElement) {
  1770. head = s.head = baseElement.parentNode;
  1771. }
  1772. }
  1773. /**
  1774. * Any errors that require explicitly generates will be passed to this
  1775. * function. Intercept/override it if you want custom error handling.
  1776. * @param {Error} err the error object.
  1777. */
  1778. req.onError = defaultOnError;
  1779. /**
  1780. * Creates the node for the load command. Only used in browser envs.
  1781. */
  1782. req.createNode = function (config, moduleName, url) {
  1783. var node = config.xhtml ?
  1784. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1785. document.createElement('script');
  1786. node.type = config.scriptType || 'text/javascript';
  1787. node.charset = 'utf-8';
  1788. node.async = true;
  1789. return node;
  1790. };
  1791. /**
  1792. * Does the request to load a module for the browser case.
  1793. * Make this a separate function to allow other environments
  1794. * to override it.
  1795. *
  1796. * @param {Object} context the require context to find state.
  1797. * @param {String} moduleName the name of the module.
  1798. * @param {Object} url the URL to the module.
  1799. */
  1800. req.load = function (context, moduleName, url) {
  1801. var config = (context && context.config) || {},
  1802. node;
  1803. if (isBrowser) {
  1804. //In the browser so use a script tag
  1805. node = req.createNode(config, moduleName, url);
  1806. node.setAttribute('data-requirecontext', context.contextName);
  1807. node.setAttribute('data-requiremodule', moduleName);
  1808. //Set up load listener. Test attachEvent first because IE9 has
  1809. //a subtle issue in its addEventListener and script onload firings
  1810. //that do not match the behavior of all other browsers with
  1811. //addEventListener support, which fire the onload event for a
  1812. //script right after the script execution. See:
  1813. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1814. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1815. //script execution mode.
  1816. if (node.attachEvent &&
  1817. //Check if node.attachEvent is artificially added by custom script or
  1818. //natively supported by browser
  1819. //read https://github.com/jrburke/requirejs/issues/187
  1820. //if we can NOT find [native code] then it must NOT natively supported.
  1821. //in IE8, node.attachEvent does not have toString()
  1822. //Note the test for "[native code" with no closing brace, see:
  1823. //https://github.com/jrburke/requirejs/issues/273
  1824. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1825. !isOpera) {
  1826. //Probably IE. IE (at least 6-8) do not fire
  1827. //script onload right after executing the script, so
  1828. //we cannot tie the anonymous define call to a name.
  1829. //However, IE reports the script as being in 'interactive'
  1830. //readyState at the time of the define call.
  1831. useInteractive = true;
  1832. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1833. //It would be great to add an error handler here to catch
  1834. //404s in IE9+. However, onreadystatechange will fire before
  1835. //the error handler, so that does not help. If addEventListener
  1836. //is used, then IE will fire error before load, but we cannot
  1837. //use that pathway given the connect.microsoft.com issue
  1838. //mentioned above about not doing the 'script execute,
  1839. //then fire the script load event listener before execute
  1840. //next script' that other browsers do.
  1841. //Best hope: IE10 fixes the issues,
  1842. //and then destroys all installs of IE 6-9.
  1843. //node.attachEvent('onerror', context.onScriptError);
  1844. } else {
  1845. node.addEventListener('load', context.onScriptLoad, false);
  1846. node.addEventListener('error', context.onScriptError, false);
  1847. }
  1848. node.src = url;
  1849. //For some cache cases in IE 6-8, the script executes before the end
  1850. //of the appendChild execution, so to tie an anonymous define
  1851. //call to the module name (which is stored on the node), hold on
  1852. //to a reference to this node, but clear after the DOM insertion.
  1853. currentlyAddingScript = node;
  1854. if (baseElement) {
  1855. head.insertBefore(node, baseElement);
  1856. } else {
  1857. head.appendChild(node);
  1858. }
  1859. currentlyAddingScript = null;
  1860. return node;
  1861. } else if (isWebWorker) {
  1862. try {
  1863. //In a web worker, use importScripts. This is not a very
  1864. //efficient use of importScripts, importScripts will block until
  1865. //its script is downloaded and evaluated. However, if web workers
  1866. //are in play, the expectation that a build has been done so that
  1867. //only one script needs to be loaded anyway. This may need to be
  1868. //reevaluated if other use cases become common.
  1869. importScripts(url);
  1870. //Account for anonymous modules
  1871. context.completeLoad(moduleName);
  1872. } catch (e) {
  1873. context.onError(makeError('importscripts',
  1874. 'importScripts failed for ' +
  1875. moduleName + ' at ' + url,
  1876. e,
  1877. [moduleName]));
  1878. }
  1879. }
  1880. };
  1881. function getInteractiveScript() {
  1882. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1883. return interactiveScript;
  1884. }
  1885. eachReverse(scripts(), function (script) {
  1886. if (script.readyState === 'interactive') {
  1887. return (interactiveScript = script);
  1888. }
  1889. });
  1890. return interactiveScript;
  1891. }
  1892. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1893. if (isBrowser && !cfg.skipDataMain) {
  1894. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1895. eachReverse(scripts(), function (script) {
  1896. //Set the 'head' where we can append children by
  1897. //using the script's parent.
  1898. if (!head) {
  1899. head = script.parentNode;
  1900. }
  1901. //Look for a data-main attribute to set main script for the page
  1902. //to load. If it is there, the path to data main becomes the
  1903. //baseUrl, if it is not already set.
  1904. dataMain = script.getAttribute('data-main');
  1905. if (dataMain) {
  1906. //Preserve dataMain in case it is a path (i.e. contains '?')
  1907. mainScript = dataMain;
  1908. //Set final baseUrl if there is not already an explicit one.
  1909. if (!cfg.baseUrl) {
  1910. //Pull off the directory of data-main for use as the
  1911. //baseUrl.
  1912. src = mainScript.split('/');
  1913. mainScript = src.pop();
  1914. subPath = src.length ? src.join('/') + '/' : './';
  1915. cfg.baseUrl = subPath;
  1916. }
  1917. //Strip off any trailing .js since mainScript is now
  1918. //like a module name.
  1919. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1920. //If mainScript is still a path, fall back to dataMain
  1921. if (req.jsExtRegExp.test(mainScript)) {
  1922. mainScript = dataMain;
  1923. }
  1924. //Put the data-main script in the files to load.
  1925. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1926. return true;
  1927. }
  1928. });
  1929. }
  1930. /**
  1931. * The function that handles definitions of modules. Differs from
  1932. * require() in that a string for the module should be the first argument,
  1933. * and the function to execute after dependencies are loaded should
  1934. * return a value to define the module corresponding to the first argument's
  1935. * name.
  1936. */
  1937. define = function (name, deps, callback) {
  1938. var node, context;
  1939. //Allow for anonymous modules
  1940. if (typeof name !== 'string') {
  1941. //Adjust args appropriately
  1942. callback = deps;
  1943. deps = name;
  1944. name = null;
  1945. }
  1946. //This module may not have dependencies
  1947. if (!isArray(deps)) {
  1948. callback = deps;
  1949. deps = null;
  1950. }
  1951. //If no name, and callback is a function, then figure out if it a
  1952. //CommonJS thing with dependencies.
  1953. if (!deps && isFunction(callback)) {
  1954. deps = [];
  1955. //Remove comments from the callback string,
  1956. //look for require calls, and pull them into the dependencies,
  1957. //but only if there are function args.
  1958. if (callback.length) {
  1959. callback
  1960. .toString()
  1961. .replace(commentRegExp, '')
  1962. .replace(cjsRequireRegExp, function (match, dep) {
  1963. deps.push(dep);
  1964. });
  1965. //May be a CommonJS thing even without require calls, but still
  1966. //could use exports, and module. Avoid doing exports and module
  1967. //work though if it just needs require.
  1968. //REQUIRES the function to expect the CommonJS variables in the
  1969. //order listed below.
  1970. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  1971. }
  1972. }
  1973. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  1974. //work.
  1975. if (useInteractive) {
  1976. node = currentlyAddingScript || getInteractiveScript();
  1977. if (node) {
  1978. if (!name) {
  1979. name = node.getAttribute('data-requiremodule');
  1980. }
  1981. context = contexts[node.getAttribute('data-requirecontext')];
  1982. }
  1983. }
  1984. //Always save off evaluating the def call until the script onload handler.
  1985. //This allows multiple modules to be in a file without prematurely
  1986. //tracing dependencies, and allows for anonymous module support,
  1987. //where the module name is not known until the script onload event
  1988. //occurs. If no context, use the global queue, and get it processed
  1989. //in the onscript load callback.
  1990. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
  1991. };
  1992. define.amd = {
  1993. jQuery: true
  1994. };
  1995. /**
  1996. * Executes the text. Normally just uses eval, but can be modified
  1997. * to use a better, environment-specific call. Only used for transpiling
  1998. * loader plugins, not for plain JS modules.
  1999. * @param {String} text the text to execute/evaluate.
  2000. */
  2001. req.exec = function (text) {
  2002. /*jslint evil: true */
  2003. return eval(text);
  2004. };
  2005. //Set up with config info.
  2006. req(cfg);
  2007. }(this));
  2008. this.requirejsVars = {
  2009. require: require,
  2010. requirejs: require,
  2011. define: define
  2012. };
  2013. if (env === 'browser') {
  2014. /**
  2015. * @license RequireJS rhino Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2016. * Available via the MIT or new BSD license.
  2017. * see: http://github.com/jrburke/requirejs for details
  2018. */
  2019. //sloppy since eval enclosed with use strict causes problems if the source
  2020. //text is not strict-compliant.
  2021. /*jslint sloppy: true, evil: true */
  2022. /*global require, XMLHttpRequest */
  2023. (function () {
  2024. require.load = function (context, moduleName, url) {
  2025. var xhr = new XMLHttpRequest();
  2026. xhr.open('GET', url, true);
  2027. xhr.send();
  2028. xhr.onreadystatechange = function () {
  2029. if (xhr.readyState === 4) {
  2030. eval(xhr.responseText);
  2031. //Support anonymous modules.
  2032. context.completeLoad(moduleName);
  2033. }
  2034. };
  2035. };
  2036. }());
  2037. } else if (env === 'rhino') {
  2038. /**
  2039. * @license RequireJS rhino Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2040. * Available via the MIT or new BSD license.
  2041. * see: http://github.com/jrburke/requirejs for details
  2042. */
  2043. /*jslint */
  2044. /*global require: false, java: false, load: false */
  2045. (function () {
  2046. 'use strict';
  2047. require.load = function (context, moduleName, url) {
  2048. load(url);
  2049. //Support anonymous modules.
  2050. context.completeLoad(moduleName);
  2051. };
  2052. }());
  2053. } else if (env === 'node') {
  2054. this.requirejsVars.nodeRequire = nodeRequire;
  2055. require.nodeRequire = nodeRequire;
  2056. /**
  2057. * @license RequireJS node Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2058. * Available via the MIT or new BSD license.
  2059. * see: http://github.com/jrburke/requirejs for details
  2060. */
  2061. /*jslint regexp: false */
  2062. /*global require: false, define: false, requirejsVars: false, process: false */
  2063. /**
  2064. * This adapter assumes that x.js has loaded it and set up
  2065. * some variables. This adapter just allows limited RequireJS
  2066. * usage from within the requirejs directory. The general
  2067. * node adapater is r.js.
  2068. */
  2069. (function () {
  2070. 'use strict';
  2071. var nodeReq = requirejsVars.nodeRequire,
  2072. req = requirejsVars.require,
  2073. def = requirejsVars.define,
  2074. fs = nodeReq('fs'),
  2075. path = nodeReq('path'),
  2076. vm = nodeReq('vm'),
  2077. //In Node 0.7+ existsSync is on fs.
  2078. exists = fs.existsSync || path.existsSync,
  2079. hasOwn = Object.prototype.hasOwnProperty;
  2080. function hasProp(obj, prop) {
  2081. return hasOwn.call(obj, prop);
  2082. }
  2083. function syncTick(fn) {
  2084. fn();
  2085. }
  2086. function makeError(message, moduleName) {
  2087. var err = new Error(message);
  2088. err.requireModules = [moduleName];
  2089. return err;
  2090. }
  2091. //Supply an implementation that allows synchronous get of a module.
  2092. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2093. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2094. context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
  2095. }
  2096. var ret, oldTick,
  2097. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2098. //Normalize module name, if it contains . or ..
  2099. moduleName = moduleMap.id;
  2100. if (hasProp(context.defined, moduleName)) {
  2101. ret = context.defined[moduleName];
  2102. } else {
  2103. if (ret === undefined) {
  2104. //Make sure nextTick for this type of call is sync-based.
  2105. oldTick = context.nextTick;
  2106. context.nextTick = syncTick;
  2107. try {
  2108. if (moduleMap.prefix) {
  2109. //A plugin, call requirejs to handle it. Now that
  2110. //nextTick is syncTick, the require will complete
  2111. //synchronously.
  2112. localRequire([moduleMap.originalName]);
  2113. //Now that plugin is loaded, can regenerate the moduleMap
  2114. //to get the final, normalized ID.
  2115. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2116. moduleName = moduleMap.id;
  2117. } else {
  2118. //Try to dynamically fetch it.
  2119. req.load(context, moduleName, moduleMap.url);
  2120. //Enable the module
  2121. context.enable(moduleMap, relModuleMap);
  2122. }
  2123. //Break any cycles by requiring it normally, but this will
  2124. //finish synchronously
  2125. context.require([moduleName]);
  2126. //The above calls are sync, so can do the next thing safely.
  2127. ret = context.defined[moduleName];
  2128. } finally {
  2129. context.nextTick = oldTick;
  2130. }
  2131. }
  2132. }
  2133. return ret;
  2134. };
  2135. req.nextTick = function (fn) {
  2136. process.nextTick(fn);
  2137. };
  2138. //Add wrapper around the code so that it gets the requirejs
  2139. //API instead of the Node API, and it is done lexically so
  2140. //that it survives later execution.
  2141. req.makeNodeWrapper = function (contents) {
  2142. return '(function (require, requirejs, define) { ' +
  2143. contents +
  2144. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2145. };
  2146. req.load = function (context, moduleName, url) {
  2147. var contents, err,
  2148. config = context.config;
  2149. if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
  2150. console.warn('Shim config not supported in Node, may or may not work. Detected ' +
  2151. 'for module: ' + moduleName);
  2152. }
  2153. if (exists(url)) {
  2154. contents = fs.readFileSync(url, 'utf8');
  2155. contents = req.makeNodeWrapper(contents);
  2156. try {
  2157. vm.runInThisContext(contents, fs.realpathSync(url));
  2158. } catch (e) {
  2159. err = new Error('Evaluating ' + url + ' as module "' +
  2160. moduleName + '" failed with error: ' + e);
  2161. err.originalError = e;
  2162. err.moduleName = moduleName;
  2163. err.requireModules = [moduleName];
  2164. err.fileName = url;
  2165. return context.onError(err);
  2166. }
  2167. } else {
  2168. def(moduleName, function () {
  2169. //Get the original name, since relative requires may be
  2170. //resolved differently in node (issue #202). Also, if relative,
  2171. //make it relative to the URL of the item requesting it
  2172. //(issue #393)
  2173. var dirName,
  2174. map = hasProp(context.registry, moduleName) &&
  2175. context.registry[moduleName].map,
  2176. parentMap = map && map.parentMap,
  2177. originalName = map && map.originalName;
  2178. if (originalName.charAt(0) === '.' && parentMap) {
  2179. dirName = parentMap.url.split('/');
  2180. dirName.pop();
  2181. originalName = dirName.join('/') + '/' + originalName;
  2182. }
  2183. try {
  2184. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2185. } catch (e) {
  2186. err = new Error('Tried loading "' + moduleName + '" at ' +
  2187. url + ' then tried node\'s require("' +
  2188. originalName + '") and it failed ' +
  2189. 'with error: ' + e);
  2190. err.originalError = e;
  2191. err.moduleName = originalName;
  2192. err.requireModules = [moduleName];
  2193. throw err;
  2194. }
  2195. });
  2196. }
  2197. //Support anonymous modules.
  2198. context.completeLoad(moduleName);
  2199. };
  2200. //Override to provide the function wrapper for define/require.
  2201. req.exec = function (text) {
  2202. /*jslint evil: true */
  2203. text = req.makeNodeWrapper(text);
  2204. return eval(text);
  2205. };
  2206. }());
  2207. } else if (env === 'xpconnect') {
  2208. /**
  2209. * @license RequireJS xpconnect Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2210. * Available via the MIT or new BSD license.
  2211. * see: http://github.com/jrburke/requirejs for details
  2212. */
  2213. /*jslint */
  2214. /*global require, load */
  2215. (function () {
  2216. 'use strict';
  2217. require.load = function (context, moduleName, url) {
  2218. load(url);
  2219. //Support anonymous modules.
  2220. context.completeLoad(moduleName);
  2221. };
  2222. }());
  2223. }
  2224. //Support a default file name to execute. Useful for hosted envs
  2225. //like Joyent where it defaults to a server.js as the only executed
  2226. //script. But only do it if this is not an optimization run.
  2227. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2228. fileName = 'main.js';
  2229. }
  2230. /**
  2231. * Loads the library files that can be used for the optimizer, or for other
  2232. * tasks.
  2233. */
  2234. function loadLib() {
  2235. /**
  2236. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2237. * Available via the MIT or new BSD license.
  2238. * see: http://github.com/jrburke/requirejs for details
  2239. */
  2240. /*jslint strict: false */
  2241. /*global Packages: false, process: false, window: false, navigator: false,
  2242. document: false, define: false */
  2243. /**
  2244. * A plugin that modifies any /env/ path to be the right path based on
  2245. * the host environment. Right now only works for Node, Rhino and browser.
  2246. */
  2247. (function () {
  2248. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2249. env = 'unknown';
  2250. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  2251. env = 'node';
  2252. } else if (typeof Packages !== 'undefined') {
  2253. env = 'rhino';
  2254. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2255. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2256. env = 'browser';
  2257. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2258. env = 'xpconnect';
  2259. }
  2260. define('env', {
  2261. get: function () {
  2262. return env;
  2263. },
  2264. load: function (name, req, load, config) {
  2265. //Allow override in the config.
  2266. if (config.env) {
  2267. env = config.env;
  2268. }
  2269. name = name.replace(pathRegExp, function (match, prefix) {
  2270. if (match.indexOf('{') === -1) {
  2271. return prefix + env + '/';
  2272. } else {
  2273. return env;
  2274. }
  2275. });
  2276. req([name], function (mod) {
  2277. load(mod);
  2278. });
  2279. }
  2280. });
  2281. }());
  2282. /**
  2283. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2284. * Available via the MIT or new BSD license.
  2285. * see: http://github.com/jrburke/requirejs for details
  2286. */
  2287. /*jslint plusplus: true */
  2288. /*global define, java */
  2289. define('lang', function () {
  2290. 'use strict';
  2291. var lang, isJavaObj,
  2292. hasOwn = Object.prototype.hasOwnProperty;
  2293. function hasProp(obj, prop) {
  2294. return hasOwn.call(obj, prop);
  2295. }
  2296. isJavaObj = function () {
  2297. return false;
  2298. };
  2299. if (typeof java !== 'undefined' && java.lang && java.lang.Object) {
  2300. isJavaObj = function (obj) {
  2301. return obj instanceof java.lang.Object;
  2302. };
  2303. }
  2304. lang = {
  2305. backSlashRegExp: /\\/g,
  2306. ostring: Object.prototype.toString,
  2307. isArray: Array.isArray || function (it) {
  2308. return lang.ostring.call(it) === "[object Array]";
  2309. },
  2310. isFunction: function(it) {
  2311. return lang.ostring.call(it) === "[object Function]";
  2312. },
  2313. isRegExp: function(it) {
  2314. return it && it instanceof RegExp;
  2315. },
  2316. hasProp: hasProp,
  2317. //returns true if the object does not have an own property prop,
  2318. //or if it does, it is a falsy value.
  2319. falseProp: function (obj, prop) {
  2320. return !hasProp(obj, prop) || !obj[prop];
  2321. },
  2322. //gets own property value for given prop on object
  2323. getOwn: function (obj, prop) {
  2324. return hasProp(obj, prop) && obj[prop];
  2325. },
  2326. _mixin: function(dest, source, override){
  2327. var name;
  2328. for (name in source) {
  2329. if(source.hasOwnProperty(name) &&
  2330. (override || !dest.hasOwnProperty(name))) {
  2331. dest[name] = source[name];
  2332. }
  2333. }
  2334. return dest; // Object
  2335. },
  2336. /**
  2337. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2338. * then the source objects properties are force copied over to dest.
  2339. */
  2340. mixin: function(dest){
  2341. var parameters = Array.prototype.slice.call(arguments),
  2342. override, i, l;
  2343. if (!dest) { dest = {}; }
  2344. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2345. override = parameters.pop();
  2346. }
  2347. for (i = 1, l = parameters.length; i < l; i++) {
  2348. lang._mixin(dest, parameters[i], override);
  2349. }
  2350. return dest; // Object
  2351. },
  2352. /**
  2353. * Does a deep mix of source into dest, where source values override
  2354. * dest values if a winner is needed.
  2355. * @param {Object} dest destination object that receives the mixed
  2356. * values.
  2357. * @param {Object} source source object contributing properties to mix
  2358. * in.
  2359. * @return {[Object]} returns dest object with the modification.
  2360. */
  2361. deepMix: function(dest, source) {
  2362. lang.eachProp(source, function (value, prop) {
  2363. if (typeof value === 'object' && value &&
  2364. !lang.isArray(value) && !lang.isFunction(value) &&
  2365. !(value instanceof RegExp)) {
  2366. if (!dest[prop]) {
  2367. dest[prop] = {};
  2368. }
  2369. lang.deepMix(dest[prop], value);
  2370. } else {
  2371. dest[prop] = value;
  2372. }
  2373. });
  2374. return dest;
  2375. },
  2376. /**
  2377. * Does a type of deep copy. Do not give it anything fancy, best
  2378. * for basic object copies of objects that also work well as
  2379. * JSON-serialized things, or has properties pointing to functions.
  2380. * For non-array/object values, just returns the same object.
  2381. * @param {Object} obj copy properties from this object
  2382. * @param {Object} [result] optional result object to use
  2383. * @return {Object}
  2384. */
  2385. deeplikeCopy: function (obj) {
  2386. var type, result;
  2387. if (lang.isArray(obj)) {
  2388. result = [];
  2389. obj.forEach(function(value) {
  2390. result.push(lang.deeplikeCopy(value));
  2391. });
  2392. return result;
  2393. }
  2394. type = typeof obj;
  2395. if (obj === null || obj === undefined || type === 'boolean' ||
  2396. type === 'string' || type === 'number' || lang.isFunction(obj) ||
  2397. lang.isRegExp(obj)|| isJavaObj(obj)) {
  2398. return obj;
  2399. }
  2400. //Anything else is an object, hopefully.
  2401. result = {};
  2402. lang.eachProp(obj, function(value, key) {
  2403. result[key] = lang.deeplikeCopy(value);
  2404. });
  2405. return result;
  2406. },
  2407. delegate: (function () {
  2408. // boodman/crockford delegation w/ cornford optimization
  2409. function TMP() {}
  2410. return function (obj, props) {
  2411. TMP.prototype = obj;
  2412. var tmp = new TMP();
  2413. TMP.prototype = null;
  2414. if (props) {
  2415. lang.mixin(tmp, props);
  2416. }
  2417. return tmp; // Object
  2418. };
  2419. }()),
  2420. /**
  2421. * Helper function for iterating over an array. If the func returns
  2422. * a true value, it will break out of the loop.
  2423. */
  2424. each: function each(ary, func) {
  2425. if (ary) {
  2426. var i;
  2427. for (i = 0; i < ary.length; i += 1) {
  2428. if (func(ary[i], i, ary)) {
  2429. break;
  2430. }
  2431. }
  2432. }
  2433. },
  2434. /**
  2435. * Cycles over properties in an object and calls a function for each
  2436. * property value. If the function returns a truthy value, then the
  2437. * iteration is stopped.
  2438. */
  2439. eachProp: function eachProp(obj, func) {
  2440. var prop;
  2441. for (prop in obj) {
  2442. if (hasProp(obj, prop)) {
  2443. if (func(obj[prop], prop)) {
  2444. break;
  2445. }
  2446. }
  2447. }
  2448. },
  2449. //Similar to Function.prototype.bind, but the "this" object is specified
  2450. //first, since it is easier to read/figure out what "this" will be.
  2451. bind: function bind(obj, fn) {
  2452. return function () {
  2453. return fn.apply(obj, arguments);
  2454. };
  2455. },
  2456. //Escapes a content string to be be a string that has characters escaped
  2457. //for inclusion as part of a JS string.
  2458. jsEscape: function (content) {
  2459. return content.replace(/(["'\\])/g, '\\$1')
  2460. .replace(/[\f]/g, "\\f")
  2461. .replace(/[\b]/g, "\\b")
  2462. .replace(/[\n]/g, "\\n")
  2463. .replace(/[\t]/g, "\\t")
  2464. .replace(/[\r]/g, "\\r");
  2465. }
  2466. };
  2467. return lang;
  2468. });
  2469. /**
  2470. * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2471. * Available via the MIT or new BSD license.
  2472. * see: http://github.com/requirejs/prim for details
  2473. */
  2474. /*global setImmediate, process, setTimeout, define, module */
  2475. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2476. //in promise-tests to pass.
  2477. //Since the goal of prim is to be a small impl for trusted code, it is
  2478. //more important to normally throw in this case so that we can find
  2479. //logic errors quicker.
  2480. var prim;
  2481. (function () {
  2482. 'use strict';
  2483. var op = Object.prototype,
  2484. hasOwn = op.hasOwnProperty;
  2485. function hasProp(obj, prop) {
  2486. return hasOwn.call(obj, prop);
  2487. }
  2488. /**
  2489. * Helper function for iterating over an array. If the func returns
  2490. * a true value, it will break out of the loop.
  2491. */
  2492. function each(ary, func) {
  2493. if (ary) {
  2494. var i;
  2495. for (i = 0; i < ary.length; i += 1) {
  2496. if (ary[i]) {
  2497. func(ary[i], i, ary);
  2498. }
  2499. }
  2500. }
  2501. }
  2502. function check(p) {
  2503. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2504. if (!prim.hideResolutionConflict) {
  2505. throw new Error('nope');
  2506. }
  2507. return false;
  2508. }
  2509. return true;
  2510. }
  2511. function notify(ary, value) {
  2512. prim.nextTick(function () {
  2513. each(ary, function (item) {
  2514. item(value);
  2515. });
  2516. });
  2517. }
  2518. prim = function prim() {
  2519. var p,
  2520. ok = [],
  2521. fail = [];
  2522. return (p = {
  2523. callback: function (yes, no) {
  2524. if (no) {
  2525. p.errback(no);
  2526. }
  2527. if (hasProp(p, 'v')) {
  2528. prim.nextTick(function () {
  2529. yes(p.v);
  2530. });
  2531. } else {
  2532. ok.push(yes);
  2533. }
  2534. },
  2535. errback: function (no) {
  2536. if (hasProp(p, 'e')) {
  2537. prim.nextTick(function () {
  2538. no(p.e);
  2539. });
  2540. } else {
  2541. fail.push(no);
  2542. }
  2543. },
  2544. finished: function () {
  2545. return hasProp(p, 'e') || hasProp(p, 'v');
  2546. },
  2547. rejected: function () {
  2548. return hasProp(p, 'e');
  2549. },
  2550. resolve: function (v) {
  2551. if (check(p)) {
  2552. p.v = v;
  2553. notify(ok, v);
  2554. }
  2555. return p;
  2556. },
  2557. reject: function (e) {
  2558. if (check(p)) {
  2559. p.e = e;
  2560. notify(fail, e);
  2561. }
  2562. return p;
  2563. },
  2564. start: function (fn) {
  2565. p.resolve();
  2566. return p.promise.then(fn);
  2567. },
  2568. promise: {
  2569. then: function (yes, no) {
  2570. var next = prim();
  2571. p.callback(function (v) {
  2572. try {
  2573. if (yes && typeof yes === 'function') {
  2574. v = yes(v);
  2575. }
  2576. if (v && v.then) {
  2577. v.then(next.resolve, next.reject);
  2578. } else {
  2579. next.resolve(v);
  2580. }
  2581. } catch (e) {
  2582. next.reject(e);
  2583. }
  2584. }, function (e) {
  2585. var err;
  2586. try {
  2587. if (!no || typeof no !== 'function') {
  2588. next.reject(e);
  2589. } else {
  2590. err = no(e);
  2591. if (err && err.then) {
  2592. err.then(next.resolve, next.reject);
  2593. } else {
  2594. next.resolve(err);
  2595. }
  2596. }
  2597. } catch (e2) {
  2598. next.reject(e2);
  2599. }
  2600. });
  2601. return next.promise;
  2602. },
  2603. fail: function (no) {
  2604. return p.promise.then(null, no);
  2605. },
  2606. end: function () {
  2607. p.errback(function (e) {
  2608. throw e;
  2609. });
  2610. }
  2611. }
  2612. });
  2613. };
  2614. prim.serial = function (ary) {
  2615. var result = prim().resolve().promise;
  2616. each(ary, function (item) {
  2617. result = result.then(function () {
  2618. return item();
  2619. });
  2620. });
  2621. return result;
  2622. };
  2623. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2624. (typeof process !== 'undefined' && process.nextTick ?
  2625. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2626. function (fn) {
  2627. setTimeout(fn, 0);
  2628. } : function (fn) {
  2629. fn();
  2630. }));
  2631. if (typeof define === 'function' && define.amd) {
  2632. define('prim', function () { return prim; });
  2633. } else if (typeof module !== 'undefined' && module.exports) {
  2634. module.exports = prim;
  2635. }
  2636. }());
  2637. if(env === 'browser') {
  2638. /**
  2639. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2640. * Available via the MIT or new BSD license.
  2641. * see: http://github.com/jrburke/requirejs for details
  2642. */
  2643. /*jslint strict: false */
  2644. /*global define: false, load: false */
  2645. //Just a stub for use with uglify's consolidator.js
  2646. define('browser/assert', function () {
  2647. return {};
  2648. });
  2649. }
  2650. if(env === 'node') {
  2651. /**
  2652. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2653. * Available via the MIT or new BSD license.
  2654. * see: http://github.com/jrburke/requirejs for details
  2655. */
  2656. /*jslint strict: false */
  2657. /*global define: false, load: false */
  2658. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2659. define('node/assert', ['assert'], function (assert) {
  2660. return assert;
  2661. });
  2662. }
  2663. if(env === 'rhino') {
  2664. /**
  2665. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2666. * Available via the MIT or new BSD license.
  2667. * see: http://github.com/jrburke/requirejs for details
  2668. */
  2669. /*jslint strict: false */
  2670. /*global define: false, load: false */
  2671. //Just a stub for use with uglify's consolidator.js
  2672. define('rhino/assert', function () {
  2673. return {};
  2674. });
  2675. }
  2676. if(env === 'xpconnect') {
  2677. /**
  2678. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2679. * Available via the MIT or new BSD license.
  2680. * see: http://github.com/jrburke/requirejs for details
  2681. */
  2682. /*jslint strict: false */
  2683. /*global define: false, load: false */
  2684. //Just a stub for use with uglify's consolidator.js
  2685. define('xpconnect/assert', function () {
  2686. return {};
  2687. });
  2688. }
  2689. if(env === 'browser') {
  2690. /**
  2691. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2692. * Available via the MIT or new BSD license.
  2693. * see: http://github.com/jrburke/requirejs for details
  2694. */
  2695. /*jslint strict: false */
  2696. /*global define: false, process: false */
  2697. define('browser/args', function () {
  2698. //Always expect config via an API call
  2699. return [];
  2700. });
  2701. }
  2702. if(env === 'node') {
  2703. /**
  2704. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2705. * Available via the MIT or new BSD license.
  2706. * see: http://github.com/jrburke/requirejs for details
  2707. */
  2708. /*jslint strict: false */
  2709. /*global define: false, process: false */
  2710. define('node/args', function () {
  2711. //Do not return the "node" or "r.js" arguments
  2712. var args = process.argv.slice(2);
  2713. //Ignore any command option used for main x.js branching
  2714. if (args[0] && args[0].indexOf('-') === 0) {
  2715. args = args.slice(1);
  2716. }
  2717. return args;
  2718. });
  2719. }
  2720. if(env === 'rhino') {
  2721. /**
  2722. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2723. * Available via the MIT or new BSD license.
  2724. * see: http://github.com/jrburke/requirejs for details
  2725. */
  2726. /*jslint strict: false */
  2727. /*global define: false, process: false */
  2728. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2729. define('rhino/args', function () {
  2730. var args = jsLibRhinoArgs;
  2731. //Ignore any command option used for main x.js branching
  2732. if (args[0] && args[0].indexOf('-') === 0) {
  2733. args = args.slice(1);
  2734. }
  2735. return args;
  2736. });
  2737. }
  2738. if(env === 'xpconnect') {
  2739. /**
  2740. * @license Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2741. * Available via the MIT or new BSD license.
  2742. * see: http://github.com/jrburke/requirejs for details
  2743. */
  2744. /*jslint strict: false */
  2745. /*global define, xpconnectArgs */
  2746. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2747. define('xpconnect/args', function () {
  2748. var args = jsLibXpConnectArgs;
  2749. //Ignore any command option used for main x.js branching
  2750. if (args[0] && args[0].indexOf('-') === 0) {
  2751. args = args.slice(1);
  2752. }
  2753. return args;
  2754. });
  2755. }
  2756. if(env === 'browser') {
  2757. /**
  2758. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2759. * Available via the MIT or new BSD license.
  2760. * see: http://github.com/jrburke/requirejs for details
  2761. */
  2762. /*jslint strict: false */
  2763. /*global define: false, console: false */
  2764. define('browser/load', ['./file'], function (file) {
  2765. function load(fileName) {
  2766. eval(file.readFile(fileName));
  2767. }
  2768. return load;
  2769. });
  2770. }
  2771. if(env === 'node') {
  2772. /**
  2773. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2774. * Available via the MIT or new BSD license.
  2775. * see: http://github.com/jrburke/requirejs for details
  2776. */
  2777. /*jslint strict: false */
  2778. /*global define: false, console: false */
  2779. define('node/load', ['fs'], function (fs) {
  2780. function load(fileName) {
  2781. var contents = fs.readFileSync(fileName, 'utf8');
  2782. process.compile(contents, fileName);
  2783. }
  2784. return load;
  2785. });
  2786. }
  2787. if(env === 'rhino') {
  2788. /**
  2789. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2790. * Available via the MIT or new BSD license.
  2791. * see: http://github.com/jrburke/requirejs for details
  2792. */
  2793. /*jslint strict: false */
  2794. /*global define: false, load: false */
  2795. define('rhino/load', function () {
  2796. return load;
  2797. });
  2798. }
  2799. if(env === 'xpconnect') {
  2800. /**
  2801. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2802. * Available via the MIT or new BSD license.
  2803. * see: http://github.com/jrburke/requirejs for details
  2804. */
  2805. /*jslint strict: false */
  2806. /*global define: false, load: false */
  2807. define('xpconnect/load', function () {
  2808. return load;
  2809. });
  2810. }
  2811. if(env === 'browser') {
  2812. /**
  2813. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2814. * Available via the MIT or new BSD license.
  2815. * see: http://github.com/jrburke/requirejs for details
  2816. */
  2817. /*jslint sloppy: true, nomen: true */
  2818. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2819. define('browser/file', ['prim'], function (prim) {
  2820. var file,
  2821. currDirRegExp = /^\.(\/|$)/;
  2822. function frontSlash(path) {
  2823. return path.replace(/\\/g, '/');
  2824. }
  2825. function exists(path) {
  2826. var status, xhr = new XMLHttpRequest();
  2827. //Oh yeah, that is right SYNC IO. Behold its glory
  2828. //and horrible blocking behavior.
  2829. xhr.open('HEAD', path, false);
  2830. xhr.send();
  2831. status = xhr.status;
  2832. return status === 200 || status === 304;
  2833. }
  2834. function mkDir(dir) {
  2835. console.log('mkDir is no-op in browser');
  2836. }
  2837. function mkFullDir(dir) {
  2838. console.log('mkFullDir is no-op in browser');
  2839. }
  2840. file = {
  2841. backSlashRegExp: /\\/g,
  2842. exclusionRegExp: /^\./,
  2843. getLineSeparator: function () {
  2844. return '/';
  2845. },
  2846. exists: function (fileName) {
  2847. return exists(fileName);
  2848. },
  2849. parent: function (fileName) {
  2850. var parts = fileName.split('/');
  2851. parts.pop();
  2852. return parts.join('/');
  2853. },
  2854. /**
  2855. * Gets the absolute file path as a string, normalized
  2856. * to using front slashes for path separators.
  2857. * @param {String} fileName
  2858. */
  2859. absPath: function (fileName) {
  2860. var dir;
  2861. if (currDirRegExp.test(fileName)) {
  2862. dir = frontSlash(location.href);
  2863. if (dir.indexOf('/') !== -1) {
  2864. dir = dir.split('/');
  2865. //Pull off protocol and host, just want
  2866. //to allow paths (other build parts, like
  2867. //require._isSupportedBuildUrl do not support
  2868. //full URLs), but a full path from
  2869. //the root.
  2870. dir.splice(0, 3);
  2871. dir.pop();
  2872. dir = '/' + dir.join('/');
  2873. }
  2874. fileName = dir + fileName.substring(1);
  2875. }
  2876. return fileName;
  2877. },
  2878. normalize: function (fileName) {
  2879. return fileName;
  2880. },
  2881. isFile: function (path) {
  2882. return true;
  2883. },
  2884. isDirectory: function (path) {
  2885. return false;
  2886. },
  2887. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2888. console.log('file.getFilteredFileList is no-op in browser');
  2889. },
  2890. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2891. console.log('file.copyDir is no-op in browser');
  2892. },
  2893. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2894. console.log('file.copyFile is no-op in browser');
  2895. },
  2896. /**
  2897. * Renames a file. May fail if "to" already exists or is on another drive.
  2898. */
  2899. renameFile: function (from, to) {
  2900. console.log('file.renameFile is no-op in browser');
  2901. },
  2902. /**
  2903. * Reads a *text* file.
  2904. */
  2905. readFile: function (path, encoding) {
  2906. var xhr = new XMLHttpRequest();
  2907. //Oh yeah, that is right SYNC IO. Behold its glory
  2908. //and horrible blocking behavior.
  2909. xhr.open('GET', path, false);
  2910. xhr.send();
  2911. return xhr.responseText;
  2912. },
  2913. readFileAsync: function (path, encoding) {
  2914. var xhr = new XMLHttpRequest(),
  2915. d = prim();
  2916. xhr.open('GET', path, true);
  2917. xhr.send();
  2918. xhr.onreadystatechange = function () {
  2919. if (xhr.readyState === 4) {
  2920. if (xhr.status > 400) {
  2921. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2922. } else {
  2923. d.resolve(xhr.responseText);
  2924. }
  2925. }
  2926. };
  2927. return d.promise;
  2928. },
  2929. saveUtf8File: function (fileName, fileContents) {
  2930. //summary: saves a *text* file using UTF-8 encoding.
  2931. file.saveFile(fileName, fileContents, "utf8");
  2932. },
  2933. saveFile: function (fileName, fileContents, encoding) {
  2934. requirejs.browser.saveFile(fileName, fileContents, encoding);
  2935. },
  2936. deleteFile: function (fileName) {
  2937. console.log('file.deleteFile is no-op in browser');
  2938. },
  2939. /**
  2940. * Deletes any empty directories under the given directory.
  2941. */
  2942. deleteEmptyDirs: function (startDir) {
  2943. console.log('file.deleteEmptyDirs is no-op in browser');
  2944. }
  2945. };
  2946. return file;
  2947. });
  2948. }
  2949. if(env === 'node') {
  2950. /**
  2951. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2952. * Available via the MIT or new BSD license.
  2953. * see: http://github.com/jrburke/requirejs for details
  2954. */
  2955. /*jslint plusplus: false, octal:false, strict: false */
  2956. /*global define: false, process: false */
  2957. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  2958. var isWindows = process.platform === 'win32',
  2959. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  2960. file;
  2961. function frontSlash(path) {
  2962. return path.replace(/\\/g, '/');
  2963. }
  2964. function exists(path) {
  2965. if (isWindows && path.charAt(path.length - 1) === '/' &&
  2966. path.charAt(path.length - 2) !== ':') {
  2967. path = path.substring(0, path.length - 1);
  2968. }
  2969. try {
  2970. fs.statSync(path);
  2971. return true;
  2972. } catch (e) {
  2973. return false;
  2974. }
  2975. }
  2976. function mkDir(dir) {
  2977. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  2978. fs.mkdirSync(dir, 511);
  2979. }
  2980. }
  2981. function mkFullDir(dir) {
  2982. var parts = dir.split('/'),
  2983. currDir = '',
  2984. first = true;
  2985. parts.forEach(function (part) {
  2986. //First part may be empty string if path starts with a slash.
  2987. currDir += part + '/';
  2988. first = false;
  2989. if (part) {
  2990. mkDir(currDir);
  2991. }
  2992. });
  2993. }
  2994. file = {
  2995. backSlashRegExp: /\\/g,
  2996. exclusionRegExp: /^\./,
  2997. getLineSeparator: function () {
  2998. return '/';
  2999. },
  3000. exists: function (fileName) {
  3001. return exists(fileName);
  3002. },
  3003. parent: function (fileName) {
  3004. var parts = fileName.split('/');
  3005. parts.pop();
  3006. return parts.join('/');
  3007. },
  3008. /**
  3009. * Gets the absolute file path as a string, normalized
  3010. * to using front slashes for path separators.
  3011. * @param {String} fileName
  3012. */
  3013. absPath: function (fileName) {
  3014. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  3015. },
  3016. normalize: function (fileName) {
  3017. return frontSlash(path.normalize(fileName));
  3018. },
  3019. isFile: function (path) {
  3020. return fs.statSync(path).isFile();
  3021. },
  3022. isDirectory: function (path) {
  3023. return fs.statSync(path).isDirectory();
  3024. },
  3025. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  3026. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3027. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3028. //and it will be treated as the "include" case.
  3029. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3030. //is set to another value.
  3031. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3032. i, stat, filePath, ok, dirFiles, fileName;
  3033. topDir = startDir;
  3034. regExpInclude = regExpFilters.include || regExpFilters;
  3035. regExpExclude = regExpFilters.exclude || null;
  3036. if (file.exists(topDir)) {
  3037. dirFileArray = fs.readdirSync(topDir);
  3038. for (i = 0; i < dirFileArray.length; i++) {
  3039. fileName = dirFileArray[i];
  3040. filePath = path.join(topDir, fileName);
  3041. stat = fs.statSync(filePath);
  3042. if (stat.isFile()) {
  3043. if (makeUnixPaths) {
  3044. //Make sure we have a JS string.
  3045. if (filePath.indexOf("/") === -1) {
  3046. filePath = frontSlash(filePath);
  3047. }
  3048. }
  3049. ok = true;
  3050. if (regExpInclude) {
  3051. ok = filePath.match(regExpInclude);
  3052. }
  3053. if (ok && regExpExclude) {
  3054. ok = !filePath.match(regExpExclude);
  3055. }
  3056. if (ok && (!file.exclusionRegExp ||
  3057. !file.exclusionRegExp.test(fileName))) {
  3058. files.push(filePath);
  3059. }
  3060. } else if (stat.isDirectory() &&
  3061. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  3062. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  3063. files.push.apply(files, dirFiles);
  3064. }
  3065. }
  3066. }
  3067. return files; //Array
  3068. },
  3069. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3070. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3071. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3072. regExpFilter = regExpFilter || /\w/;
  3073. //Normalize th directory names, but keep front slashes.
  3074. //path module on windows now returns backslashed paths.
  3075. srcDir = frontSlash(path.normalize(srcDir));
  3076. destDir = frontSlash(path.normalize(destDir));
  3077. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3078. copiedFiles = [], i, srcFileName, destFileName;
  3079. for (i = 0; i < fileNames.length; i++) {
  3080. srcFileName = fileNames[i];
  3081. destFileName = srcFileName.replace(srcDir, destDir);
  3082. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3083. copiedFiles.push(destFileName);
  3084. }
  3085. }
  3086. return copiedFiles.length ? copiedFiles : null; //Array or null
  3087. },
  3088. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3089. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3090. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3091. var parentDir;
  3092. //logger.trace("Src filename: " + srcFileName);
  3093. //logger.trace("Dest filename: " + destFileName);
  3094. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3095. //than dest.
  3096. if (onlyCopyNew) {
  3097. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  3098. return false; //Boolean
  3099. }
  3100. }
  3101. //Make sure destination dir exists.
  3102. parentDir = path.dirname(destFileName);
  3103. if (!file.exists(parentDir)) {
  3104. mkFullDir(parentDir);
  3105. }
  3106. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  3107. return true; //Boolean
  3108. },
  3109. /**
  3110. * Renames a file. May fail if "to" already exists or is on another drive.
  3111. */
  3112. renameFile: function (from, to) {
  3113. return fs.renameSync(from, to);
  3114. },
  3115. /**
  3116. * Reads a *text* file.
  3117. */
  3118. readFile: function (/*String*/path, /*String?*/encoding) {
  3119. if (encoding === 'utf-8') {
  3120. encoding = 'utf8';
  3121. }
  3122. if (!encoding) {
  3123. encoding = 'utf8';
  3124. }
  3125. var text = fs.readFileSync(path, encoding);
  3126. //Hmm, would not expect to get A BOM, but it seems to happen,
  3127. //remove it just in case.
  3128. if (text.indexOf('\uFEFF') === 0) {
  3129. text = text.substring(1, text.length);
  3130. }
  3131. return text;
  3132. },
  3133. readFileAsync: function (path, encoding) {
  3134. var d = prim();
  3135. try {
  3136. d.resolve(file.readFile(path, encoding));
  3137. } catch (e) {
  3138. d.reject(e);
  3139. }
  3140. return d.promise;
  3141. },
  3142. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3143. //summary: saves a *text* file using UTF-8 encoding.
  3144. file.saveFile(fileName, fileContents, "utf8");
  3145. },
  3146. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3147. //summary: saves a *text* file.
  3148. var parentDir;
  3149. if (encoding === 'utf-8') {
  3150. encoding = 'utf8';
  3151. }
  3152. if (!encoding) {
  3153. encoding = 'utf8';
  3154. }
  3155. //Make sure destination directories exist.
  3156. parentDir = path.dirname(fileName);
  3157. if (!file.exists(parentDir)) {
  3158. mkFullDir(parentDir);
  3159. }
  3160. fs.writeFileSync(fileName, fileContents, encoding);
  3161. },
  3162. deleteFile: function (/*String*/fileName) {
  3163. //summary: deletes a file or directory if it exists.
  3164. var files, i, stat;
  3165. if (file.exists(fileName)) {
  3166. stat = fs.lstatSync(fileName);
  3167. if (stat.isDirectory()) {
  3168. files = fs.readdirSync(fileName);
  3169. for (i = 0; i < files.length; i++) {
  3170. this.deleteFile(path.join(fileName, files[i]));
  3171. }
  3172. fs.rmdirSync(fileName);
  3173. } else {
  3174. fs.unlinkSync(fileName);
  3175. }
  3176. }
  3177. },
  3178. /**
  3179. * Deletes any empty directories under the given directory.
  3180. */
  3181. deleteEmptyDirs: function (startDir) {
  3182. var dirFileArray, i, fileName, filePath, stat;
  3183. if (file.exists(startDir)) {
  3184. dirFileArray = fs.readdirSync(startDir);
  3185. for (i = 0; i < dirFileArray.length; i++) {
  3186. fileName = dirFileArray[i];
  3187. filePath = path.join(startDir, fileName);
  3188. stat = fs.lstatSync(filePath);
  3189. if (stat.isDirectory()) {
  3190. file.deleteEmptyDirs(filePath);
  3191. }
  3192. }
  3193. //If directory is now empty, remove it.
  3194. if (fs.readdirSync(startDir).length === 0) {
  3195. file.deleteFile(startDir);
  3196. }
  3197. }
  3198. }
  3199. };
  3200. return file;
  3201. });
  3202. }
  3203. if(env === 'rhino') {
  3204. /**
  3205. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3206. * Available via the MIT or new BSD license.
  3207. * see: http://github.com/jrburke/requirejs for details
  3208. */
  3209. //Helper functions to deal with file I/O.
  3210. /*jslint plusplus: false */
  3211. /*global java: false, define: false */
  3212. define('rhino/file', ['prim'], function (prim) {
  3213. var file = {
  3214. backSlashRegExp: /\\/g,
  3215. exclusionRegExp: /^\./,
  3216. getLineSeparator: function () {
  3217. return file.lineSeparator;
  3218. },
  3219. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3220. exists: function (fileName) {
  3221. return (new java.io.File(fileName)).exists();
  3222. },
  3223. parent: function (fileName) {
  3224. return file.absPath((new java.io.File(fileName)).getParentFile());
  3225. },
  3226. normalize: function (fileName) {
  3227. return file.absPath(fileName);
  3228. },
  3229. isFile: function (path) {
  3230. return (new java.io.File(path)).isFile();
  3231. },
  3232. isDirectory: function (path) {
  3233. return (new java.io.File(path)).isDirectory();
  3234. },
  3235. /**
  3236. * Gets the absolute file path as a string, normalized
  3237. * to using front slashes for path separators.
  3238. * @param {java.io.File||String} file
  3239. */
  3240. absPath: function (fileObj) {
  3241. if (typeof fileObj === "string") {
  3242. fileObj = new java.io.File(fileObj);
  3243. }
  3244. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3245. },
  3246. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3247. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3248. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3249. //and it will be treated as the "include" case.
  3250. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3251. //is set to another value.
  3252. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3253. i, fileObj, filePath, ok, dirFiles;
  3254. topDir = startDir;
  3255. if (!startDirIsJavaObject) {
  3256. topDir = new java.io.File(startDir);
  3257. }
  3258. regExpInclude = regExpFilters.include || regExpFilters;
  3259. regExpExclude = regExpFilters.exclude || null;
  3260. if (topDir.exists()) {
  3261. dirFileArray = topDir.listFiles();
  3262. for (i = 0; i < dirFileArray.length; i++) {
  3263. fileObj = dirFileArray[i];
  3264. if (fileObj.isFile()) {
  3265. filePath = fileObj.getPath();
  3266. if (makeUnixPaths) {
  3267. //Make sure we have a JS string.
  3268. filePath = String(filePath);
  3269. if (filePath.indexOf("/") === -1) {
  3270. filePath = filePath.replace(/\\/g, "/");
  3271. }
  3272. }
  3273. ok = true;
  3274. if (regExpInclude) {
  3275. ok = filePath.match(regExpInclude);
  3276. }
  3277. if (ok && regExpExclude) {
  3278. ok = !filePath.match(regExpExclude);
  3279. }
  3280. if (ok && (!file.exclusionRegExp ||
  3281. !file.exclusionRegExp.test(fileObj.getName()))) {
  3282. files.push(filePath);
  3283. }
  3284. } else if (fileObj.isDirectory() &&
  3285. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3286. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3287. files.push.apply(files, dirFiles);
  3288. }
  3289. }
  3290. }
  3291. return files; //Array
  3292. },
  3293. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3294. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3295. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3296. regExpFilter = regExpFilter || /\w/;
  3297. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3298. copiedFiles = [], i, srcFileName, destFileName;
  3299. for (i = 0; i < fileNames.length; i++) {
  3300. srcFileName = fileNames[i];
  3301. destFileName = srcFileName.replace(srcDir, destDir);
  3302. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3303. copiedFiles.push(destFileName);
  3304. }
  3305. }
  3306. return copiedFiles.length ? copiedFiles : null; //Array or null
  3307. },
  3308. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3309. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3310. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3311. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3312. srcChannel, destChannel;
  3313. //logger.trace("Src filename: " + srcFileName);
  3314. //logger.trace("Dest filename: " + destFileName);
  3315. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3316. //than dest.
  3317. if (onlyCopyNew) {
  3318. srcFile = new java.io.File(srcFileName);
  3319. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3320. return false; //Boolean
  3321. }
  3322. }
  3323. //Make sure destination dir exists.
  3324. parentDir = destFile.getParentFile();
  3325. if (!parentDir.exists()) {
  3326. if (!parentDir.mkdirs()) {
  3327. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3328. }
  3329. }
  3330. //Java's version of copy file.
  3331. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3332. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3333. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3334. srcChannel.close();
  3335. destChannel.close();
  3336. return true; //Boolean
  3337. },
  3338. /**
  3339. * Renames a file. May fail if "to" already exists or is on another drive.
  3340. */
  3341. renameFile: function (from, to) {
  3342. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3343. },
  3344. readFile: function (/*String*/path, /*String?*/encoding) {
  3345. //A file read function that can deal with BOMs
  3346. encoding = encoding || "utf-8";
  3347. var fileObj = new java.io.File(path),
  3348. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3349. stringBuffer, line;
  3350. try {
  3351. stringBuffer = new java.lang.StringBuffer();
  3352. line = input.readLine();
  3353. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3354. // http://www.unicode.org/faq/utf_bom.html
  3355. // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
  3356. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3357. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3358. // Eat the BOM, since we've already found the encoding on this file,
  3359. // and we plan to concatenating this buffer with others; the BOM should
  3360. // only appear at the top of a file.
  3361. line = line.substring(1);
  3362. }
  3363. while (line !== null) {
  3364. stringBuffer.append(line);
  3365. stringBuffer.append(file.lineSeparator);
  3366. line = input.readLine();
  3367. }
  3368. //Make sure we return a JavaScript string and not a Java string.
  3369. return String(stringBuffer.toString()); //String
  3370. } finally {
  3371. input.close();
  3372. }
  3373. },
  3374. readFileAsync: function (path, encoding) {
  3375. var d = prim();
  3376. try {
  3377. d.resolve(file.readFile(path, encoding));
  3378. } catch (e) {
  3379. d.reject(e);
  3380. }
  3381. return d.promise;
  3382. },
  3383. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3384. //summary: saves a file using UTF-8 encoding.
  3385. file.saveFile(fileName, fileContents, "utf-8");
  3386. },
  3387. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3388. //summary: saves a file.
  3389. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3390. parentDir = outFile.getAbsoluteFile().getParentFile();
  3391. if (!parentDir.exists()) {
  3392. if (!parentDir.mkdirs()) {
  3393. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3394. }
  3395. }
  3396. if (encoding) {
  3397. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3398. } else {
  3399. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3400. }
  3401. os = new java.io.BufferedWriter(outWriter);
  3402. try {
  3403. os.write(fileContents);
  3404. } finally {
  3405. os.close();
  3406. }
  3407. },
  3408. deleteFile: function (/*String*/fileName) {
  3409. //summary: deletes a file or directory if it exists.
  3410. var fileObj = new java.io.File(fileName), files, i;
  3411. if (fileObj.exists()) {
  3412. if (fileObj.isDirectory()) {
  3413. files = fileObj.listFiles();
  3414. for (i = 0; i < files.length; i++) {
  3415. this.deleteFile(files[i]);
  3416. }
  3417. }
  3418. fileObj["delete"]();
  3419. }
  3420. },
  3421. /**
  3422. * Deletes any empty directories under the given directory.
  3423. * The startDirIsJavaObject is private to this implementation's
  3424. * recursion needs.
  3425. */
  3426. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3427. var topDir = startDir,
  3428. dirFileArray, i, fileObj;
  3429. if (!startDirIsJavaObject) {
  3430. topDir = new java.io.File(startDir);
  3431. }
  3432. if (topDir.exists()) {
  3433. dirFileArray = topDir.listFiles();
  3434. for (i = 0; i < dirFileArray.length; i++) {
  3435. fileObj = dirFileArray[i];
  3436. if (fileObj.isDirectory()) {
  3437. file.deleteEmptyDirs(fileObj, true);
  3438. }
  3439. }
  3440. //If the directory is empty now, delete it.
  3441. if (topDir.listFiles().length === 0) {
  3442. file.deleteFile(String(topDir.getPath()));
  3443. }
  3444. }
  3445. }
  3446. };
  3447. return file;
  3448. });
  3449. }
  3450. if(env === 'xpconnect') {
  3451. /**
  3452. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3453. * Available via the MIT or new BSD license.
  3454. * see: http://github.com/jrburke/requirejs for details
  3455. */
  3456. //Helper functions to deal with file I/O.
  3457. /*jslint plusplus: false */
  3458. /*global define, Components, xpcUtil */
  3459. define('xpconnect/file', ['prim'], function (prim) {
  3460. var file,
  3461. Cc = Components.classes,
  3462. Ci = Components.interfaces,
  3463. //Depends on xpcUtil which is set up in x.js
  3464. xpfile = xpcUtil.xpfile;
  3465. function mkFullDir(dirObj) {
  3466. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3467. if (!dirObj.exists()) {
  3468. dirObj.create(1, 511);
  3469. }
  3470. }
  3471. file = {
  3472. backSlashRegExp: /\\/g,
  3473. exclusionRegExp: /^\./,
  3474. getLineSeparator: function () {
  3475. return file.lineSeparator;
  3476. },
  3477. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3478. '\r\n' : '\n',
  3479. exists: function (fileName) {
  3480. return xpfile(fileName).exists();
  3481. },
  3482. parent: function (fileName) {
  3483. return xpfile(fileName).parent;
  3484. },
  3485. normalize: function (fileName) {
  3486. return file.absPath(fileName);
  3487. },
  3488. isFile: function (path) {
  3489. return xpfile(path).isFile();
  3490. },
  3491. isDirectory: function (path) {
  3492. return xpfile(path).isDirectory();
  3493. },
  3494. /**
  3495. * Gets the absolute file path as a string, normalized
  3496. * to using front slashes for path separators.
  3497. * @param {java.io.File||String} file
  3498. */
  3499. absPath: function (fileObj) {
  3500. if (typeof fileObj === "string") {
  3501. fileObj = xpfile(fileObj);
  3502. }
  3503. return fileObj.path;
  3504. },
  3505. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3506. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3507. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3508. //and it will be treated as the "include" case.
  3509. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3510. //is set to another value.
  3511. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3512. fileObj, filePath, ok, dirFiles;
  3513. topDir = startDir;
  3514. if (!startDirIsObject) {
  3515. topDir = xpfile(startDir);
  3516. }
  3517. regExpInclude = regExpFilters.include || regExpFilters;
  3518. regExpExclude = regExpFilters.exclude || null;
  3519. if (topDir.exists()) {
  3520. dirFileArray = topDir.directoryEntries;
  3521. while (dirFileArray.hasMoreElements()) {
  3522. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3523. if (fileObj.isFile()) {
  3524. filePath = fileObj.path;
  3525. if (makeUnixPaths) {
  3526. if (filePath.indexOf("/") === -1) {
  3527. filePath = filePath.replace(/\\/g, "/");
  3528. }
  3529. }
  3530. ok = true;
  3531. if (regExpInclude) {
  3532. ok = filePath.match(regExpInclude);
  3533. }
  3534. if (ok && regExpExclude) {
  3535. ok = !filePath.match(regExpExclude);
  3536. }
  3537. if (ok && (!file.exclusionRegExp ||
  3538. !file.exclusionRegExp.test(fileObj.leafName))) {
  3539. files.push(filePath);
  3540. }
  3541. } else if (fileObj.isDirectory() &&
  3542. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3543. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3544. files.push.apply(files, dirFiles);
  3545. }
  3546. }
  3547. }
  3548. return files; //Array
  3549. },
  3550. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3551. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3552. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3553. regExpFilter = regExpFilter || /\w/;
  3554. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3555. copiedFiles = [], i, srcFileName, destFileName;
  3556. for (i = 0; i < fileNames.length; i += 1) {
  3557. srcFileName = fileNames[i];
  3558. destFileName = srcFileName.replace(srcDir, destDir);
  3559. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3560. copiedFiles.push(destFileName);
  3561. }
  3562. }
  3563. return copiedFiles.length ? copiedFiles : null; //Array or null
  3564. },
  3565. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3566. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3567. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3568. var destFile = xpfile(destFileName),
  3569. srcFile = xpfile(srcFileName);
  3570. //logger.trace("Src filename: " + srcFileName);
  3571. //logger.trace("Dest filename: " + destFileName);
  3572. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3573. //than dest.
  3574. if (onlyCopyNew) {
  3575. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3576. return false; //Boolean
  3577. }
  3578. }
  3579. srcFile.copyTo(destFile.parent, destFile.leafName);
  3580. return true; //Boolean
  3581. },
  3582. /**
  3583. * Renames a file. May fail if "to" already exists or is on another drive.
  3584. */
  3585. renameFile: function (from, to) {
  3586. var toFile = xpfile(to);
  3587. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3588. },
  3589. readFile: xpcUtil.readFile,
  3590. readFileAsync: function (path, encoding) {
  3591. var d = prim();
  3592. try {
  3593. d.resolve(file.readFile(path, encoding));
  3594. } catch (e) {
  3595. d.reject(e);
  3596. }
  3597. return d.promise;
  3598. },
  3599. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3600. //summary: saves a file using UTF-8 encoding.
  3601. file.saveFile(fileName, fileContents, "utf-8");
  3602. },
  3603. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3604. var outStream, convertStream,
  3605. fileObj = xpfile(fileName);
  3606. mkFullDir(fileObj.parent);
  3607. try {
  3608. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3609. .createInstance(Ci.nsIFileOutputStream);
  3610. //438 is decimal for 0777
  3611. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3612. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3613. .createInstance(Ci.nsIConverterOutputStream);
  3614. convertStream.init(outStream, encoding, 0, 0);
  3615. convertStream.writeString(fileContents);
  3616. } catch (e) {
  3617. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3618. } finally {
  3619. if (convertStream) {
  3620. convertStream.close();
  3621. }
  3622. if (outStream) {
  3623. outStream.close();
  3624. }
  3625. }
  3626. },
  3627. deleteFile: function (/*String*/fileName) {
  3628. //summary: deletes a file or directory if it exists.
  3629. var fileObj = xpfile(fileName);
  3630. if (fileObj.exists()) {
  3631. fileObj.remove(true);
  3632. }
  3633. },
  3634. /**
  3635. * Deletes any empty directories under the given directory.
  3636. * The startDirIsJavaObject is private to this implementation's
  3637. * recursion needs.
  3638. */
  3639. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3640. var topDir = startDir,
  3641. dirFileArray, fileObj;
  3642. if (!startDirIsObject) {
  3643. topDir = xpfile(startDir);
  3644. }
  3645. if (topDir.exists()) {
  3646. dirFileArray = topDir.directoryEntries;
  3647. while (dirFileArray.hasMoreElements()) {
  3648. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3649. if (fileObj.isDirectory()) {
  3650. file.deleteEmptyDirs(fileObj, true);
  3651. }
  3652. }
  3653. //If the directory is empty now, delete it.
  3654. dirFileArray = topDir.directoryEntries;
  3655. if (!dirFileArray.hasMoreElements()) {
  3656. file.deleteFile(topDir.path);
  3657. }
  3658. }
  3659. }
  3660. };
  3661. return file;
  3662. });
  3663. }
  3664. if(env === 'browser') {
  3665. /*global process */
  3666. define('browser/quit', function () {
  3667. 'use strict';
  3668. return function (code) {
  3669. };
  3670. });
  3671. }
  3672. if(env === 'node') {
  3673. /*global process */
  3674. define('node/quit', function () {
  3675. 'use strict';
  3676. return function (code) {
  3677. var draining = 0;
  3678. var exit = function () {
  3679. if (draining === 0) {
  3680. process.exit(code);
  3681. } else {
  3682. draining -= 1;
  3683. }
  3684. };
  3685. if (process.stdout.bufferSize) {
  3686. draining += 1;
  3687. process.stdout.once('drain', exit);
  3688. }
  3689. if (process.stderr.bufferSize) {
  3690. draining += 1;
  3691. process.stderr.once('drain', exit);
  3692. }
  3693. exit();
  3694. };
  3695. });
  3696. }
  3697. if(env === 'rhino') {
  3698. /*global quit */
  3699. define('rhino/quit', function () {
  3700. 'use strict';
  3701. return function (code) {
  3702. return quit(code);
  3703. };
  3704. });
  3705. }
  3706. if(env === 'xpconnect') {
  3707. /*global quit */
  3708. define('xpconnect/quit', function () {
  3709. 'use strict';
  3710. return function (code) {
  3711. return quit(code);
  3712. };
  3713. });
  3714. }
  3715. if(env === 'browser') {
  3716. /**
  3717. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3718. * Available via the MIT or new BSD license.
  3719. * see: http://github.com/jrburke/requirejs for details
  3720. */
  3721. /*jslint strict: false */
  3722. /*global define: false, console: false */
  3723. define('browser/print', function () {
  3724. function print(msg) {
  3725. console.log(msg);
  3726. }
  3727. return print;
  3728. });
  3729. }
  3730. if(env === 'node') {
  3731. /**
  3732. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3733. * Available via the MIT or new BSD license.
  3734. * see: http://github.com/jrburke/requirejs for details
  3735. */
  3736. /*jslint strict: false */
  3737. /*global define: false, console: false */
  3738. define('node/print', function () {
  3739. function print(msg) {
  3740. console.log(msg);
  3741. }
  3742. return print;
  3743. });
  3744. }
  3745. if(env === 'rhino') {
  3746. /**
  3747. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3748. * Available via the MIT or new BSD license.
  3749. * see: http://github.com/jrburke/requirejs for details
  3750. */
  3751. /*jslint strict: false */
  3752. /*global define: false, print: false */
  3753. define('rhino/print', function () {
  3754. return print;
  3755. });
  3756. }
  3757. if(env === 'xpconnect') {
  3758. /**
  3759. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3760. * Available via the MIT or new BSD license.
  3761. * see: http://github.com/jrburke/requirejs for details
  3762. */
  3763. /*jslint strict: false */
  3764. /*global define: false, print: false */
  3765. define('xpconnect/print', function () {
  3766. return print;
  3767. });
  3768. }
  3769. /**
  3770. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3771. * Available via the MIT or new BSD license.
  3772. * see: http://github.com/jrburke/requirejs for details
  3773. */
  3774. /*jslint nomen: false, strict: false */
  3775. /*global define: false */
  3776. define('logger', ['env!env/print'], function (print) {
  3777. var logger = {
  3778. TRACE: 0,
  3779. INFO: 1,
  3780. WARN: 2,
  3781. ERROR: 3,
  3782. SILENT: 4,
  3783. level: 0,
  3784. logPrefix: "",
  3785. logLevel: function( level ) {
  3786. this.level = level;
  3787. },
  3788. trace: function (message) {
  3789. if (this.level <= this.TRACE) {
  3790. this._print(message);
  3791. }
  3792. },
  3793. info: function (message) {
  3794. if (this.level <= this.INFO) {
  3795. this._print(message);
  3796. }
  3797. },
  3798. warn: function (message) {
  3799. if (this.level <= this.WARN) {
  3800. this._print(message);
  3801. }
  3802. },
  3803. error: function (message) {
  3804. if (this.level <= this.ERROR) {
  3805. this._print(message);
  3806. }
  3807. },
  3808. _print: function (message) {
  3809. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3810. },
  3811. _sysPrint: function (message) {
  3812. print(message);
  3813. }
  3814. };
  3815. return logger;
  3816. });
  3817. //Just a blank file to use when building the optimizer with the optimizer,
  3818. //so that the build does not attempt to inline some env modules,
  3819. //like Node's fs and path.
  3820. /*
  3821. Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  3822. Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  3823. Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  3824. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  3825. Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  3826. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  3827. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  3828. Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  3829. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  3830. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  3831. Redistribution and use in source and binary forms, with or without
  3832. modification, are permitted provided that the following conditions are met:
  3833. * Redistributions of source code must retain the above copyright
  3834. notice, this list of conditions and the following disclaimer.
  3835. * Redistributions in binary form must reproduce the above copyright
  3836. notice, this list of conditions and the following disclaimer in the
  3837. documentation and/or other materials provided with the distribution.
  3838. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3839. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3840. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3841. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3842. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3843. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3844. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3845. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3846. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3847. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3848. */
  3849. /*jslint bitwise:true plusplus:true */
  3850. /*global esprima:true, define:true, exports:true, window: true,
  3851. throwErrorTolerant: true,
  3852. throwError: true, generateStatement: true, peek: true,
  3853. parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
  3854. parseFunctionDeclaration: true, parseFunctionExpression: true,
  3855. parseFunctionSourceElements: true, parseVariableIdentifier: true,
  3856. parseLeftHandSideExpression: true,
  3857. parseUnaryExpression: true,
  3858. parseStatement: true, parseSourceElement: true */
  3859. (function (root, factory) {
  3860. 'use strict';
  3861. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  3862. // Rhino, and plain browser loading.
  3863. /* istanbul ignore next */
  3864. if (typeof define === 'function' && define.amd) {
  3865. define('esprima', ['exports'], factory);
  3866. } else if (typeof exports !== 'undefined') {
  3867. factory(exports);
  3868. } else {
  3869. factory((root.esprima = {}));
  3870. }
  3871. }(this, function (exports) {
  3872. 'use strict';
  3873. var Token,
  3874. TokenName,
  3875. FnExprTokens,
  3876. Syntax,
  3877. PropertyKind,
  3878. Messages,
  3879. Regex,
  3880. SyntaxTreeDelegate,
  3881. source,
  3882. strict,
  3883. index,
  3884. lineNumber,
  3885. lineStart,
  3886. length,
  3887. delegate,
  3888. lookahead,
  3889. state,
  3890. extra;
  3891. Token = {
  3892. BooleanLiteral: 1,
  3893. EOF: 2,
  3894. Identifier: 3,
  3895. Keyword: 4,
  3896. NullLiteral: 5,
  3897. NumericLiteral: 6,
  3898. Punctuator: 7,
  3899. StringLiteral: 8,
  3900. RegularExpression: 9
  3901. };
  3902. TokenName = {};
  3903. TokenName[Token.BooleanLiteral] = 'Boolean';
  3904. TokenName[Token.EOF] = '<end>';
  3905. TokenName[Token.Identifier] = 'Identifier';
  3906. TokenName[Token.Keyword] = 'Keyword';
  3907. TokenName[Token.NullLiteral] = 'Null';
  3908. TokenName[Token.NumericLiteral] = 'Numeric';
  3909. TokenName[Token.Punctuator] = 'Punctuator';
  3910. TokenName[Token.StringLiteral] = 'String';
  3911. TokenName[Token.RegularExpression] = 'RegularExpression';
  3912. // A function following one of those tokens is an expression.
  3913. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  3914. 'return', 'case', 'delete', 'throw', 'void',
  3915. // assignment operators
  3916. '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
  3917. '&=', '|=', '^=', ',',
  3918. // binary/unary operators
  3919. '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  3920. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  3921. '<=', '<', '>', '!=', '!=='];
  3922. Syntax = {
  3923. AssignmentExpression: 'AssignmentExpression',
  3924. ArrayExpression: 'ArrayExpression',
  3925. BlockStatement: 'BlockStatement',
  3926. BinaryExpression: 'BinaryExpression',
  3927. BreakStatement: 'BreakStatement',
  3928. CallExpression: 'CallExpression',
  3929. CatchClause: 'CatchClause',
  3930. ConditionalExpression: 'ConditionalExpression',
  3931. ContinueStatement: 'ContinueStatement',
  3932. DoWhileStatement: 'DoWhileStatement',
  3933. DebuggerStatement: 'DebuggerStatement',
  3934. EmptyStatement: 'EmptyStatement',
  3935. ExpressionStatement: 'ExpressionStatement',
  3936. ForStatement: 'ForStatement',
  3937. ForInStatement: 'ForInStatement',
  3938. FunctionDeclaration: 'FunctionDeclaration',
  3939. FunctionExpression: 'FunctionExpression',
  3940. Identifier: 'Identifier',
  3941. IfStatement: 'IfStatement',
  3942. Literal: 'Literal',
  3943. LabeledStatement: 'LabeledStatement',
  3944. LogicalExpression: 'LogicalExpression',
  3945. MemberExpression: 'MemberExpression',
  3946. NewExpression: 'NewExpression',
  3947. ObjectExpression: 'ObjectExpression',
  3948. Program: 'Program',
  3949. Property: 'Property',
  3950. ReturnStatement: 'ReturnStatement',
  3951. SequenceExpression: 'SequenceExpression',
  3952. SwitchStatement: 'SwitchStatement',
  3953. SwitchCase: 'SwitchCase',
  3954. ThisExpression: 'ThisExpression',
  3955. ThrowStatement: 'ThrowStatement',
  3956. TryStatement: 'TryStatement',
  3957. UnaryExpression: 'UnaryExpression',
  3958. UpdateExpression: 'UpdateExpression',
  3959. VariableDeclaration: 'VariableDeclaration',
  3960. VariableDeclarator: 'VariableDeclarator',
  3961. WhileStatement: 'WhileStatement',
  3962. WithStatement: 'WithStatement'
  3963. };
  3964. PropertyKind = {
  3965. Data: 1,
  3966. Get: 2,
  3967. Set: 4
  3968. };
  3969. // Error messages should be identical to V8.
  3970. Messages = {
  3971. UnexpectedToken: 'Unexpected token %0',
  3972. UnexpectedNumber: 'Unexpected number',
  3973. UnexpectedString: 'Unexpected string',
  3974. UnexpectedIdentifier: 'Unexpected identifier',
  3975. UnexpectedReserved: 'Unexpected reserved word',
  3976. UnexpectedEOS: 'Unexpected end of input',
  3977. NewlineAfterThrow: 'Illegal newline after throw',
  3978. InvalidRegExp: 'Invalid regular expression',
  3979. UnterminatedRegExp: 'Invalid regular expression: missing /',
  3980. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  3981. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  3982. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  3983. NoCatchOrFinally: 'Missing catch or finally after try',
  3984. UnknownLabel: 'Undefined label \'%0\'',
  3985. Redeclaration: '%0 \'%1\' has already been declared',
  3986. IllegalContinue: 'Illegal continue statement',
  3987. IllegalBreak: 'Illegal break statement',
  3988. IllegalReturn: 'Illegal return statement',
  3989. StrictModeWith: 'Strict mode code may not include a with statement',
  3990. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  3991. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  3992. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  3993. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  3994. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  3995. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  3996. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  3997. StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  3998. AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  3999. AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  4000. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  4001. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  4002. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  4003. StrictReservedWord: 'Use of future reserved word in strict mode'
  4004. };
  4005. // See also tools/generate-unicode-regex.py.
  4006. Regex = {
  4007. NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\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\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\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-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\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]'),
  4008. NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]')
  4009. };
  4010. // Ensure the condition is true, otherwise throw an error.
  4011. // This is only to have a better contract semantic, i.e. another safety net
  4012. // to catch a logic error. The condition shall be fulfilled in normal case.
  4013. // Do NOT use this to enforce a certain condition on any user input.
  4014. function assert(condition, message) {
  4015. /* istanbul ignore if */
  4016. if (!condition) {
  4017. throw new Error('ASSERT: ' + message);
  4018. }
  4019. }
  4020. function isDecimalDigit(ch) {
  4021. return (ch >= 48 && ch <= 57); // 0..9
  4022. }
  4023. function isHexDigit(ch) {
  4024. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  4025. }
  4026. function isOctalDigit(ch) {
  4027. return '01234567'.indexOf(ch) >= 0;
  4028. }
  4029. // 7.2 White Space
  4030. function isWhiteSpace(ch) {
  4031. return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
  4032. (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
  4033. }
  4034. // 7.3 Line Terminators
  4035. function isLineTerminator(ch) {
  4036. return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
  4037. }
  4038. // 7.6 Identifier Names and Identifiers
  4039. function isIdentifierStart(ch) {
  4040. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4041. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4042. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4043. (ch === 0x5C) || // \ (backslash)
  4044. ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
  4045. }
  4046. function isIdentifierPart(ch) {
  4047. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4048. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4049. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4050. (ch >= 0x30 && ch <= 0x39) || // 0..9
  4051. (ch === 0x5C) || // \ (backslash)
  4052. ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
  4053. }
  4054. // 7.6.1.2 Future Reserved Words
  4055. function isFutureReservedWord(id) {
  4056. switch (id) {
  4057. case 'class':
  4058. case 'enum':
  4059. case 'export':
  4060. case 'extends':
  4061. case 'import':
  4062. case 'super':
  4063. return true;
  4064. default:
  4065. return false;
  4066. }
  4067. }
  4068. function isStrictModeReservedWord(id) {
  4069. switch (id) {
  4070. case 'implements':
  4071. case 'interface':
  4072. case 'package':
  4073. case 'private':
  4074. case 'protected':
  4075. case 'public':
  4076. case 'static':
  4077. case 'yield':
  4078. case 'let':
  4079. return true;
  4080. default:
  4081. return false;
  4082. }
  4083. }
  4084. function isRestrictedWord(id) {
  4085. return id === 'eval' || id === 'arguments';
  4086. }
  4087. // 7.6.1.1 Keywords
  4088. function isKeyword(id) {
  4089. if (strict && isStrictModeReservedWord(id)) {
  4090. return true;
  4091. }
  4092. // 'const' is specialized as Keyword in V8.
  4093. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
  4094. // Some others are from future reserved words.
  4095. switch (id.length) {
  4096. case 2:
  4097. return (id === 'if') || (id === 'in') || (id === 'do');
  4098. case 3:
  4099. return (id === 'var') || (id === 'for') || (id === 'new') ||
  4100. (id === 'try') || (id === 'let');
  4101. case 4:
  4102. return (id === 'this') || (id === 'else') || (id === 'case') ||
  4103. (id === 'void') || (id === 'with') || (id === 'enum');
  4104. case 5:
  4105. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  4106. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  4107. (id === 'class') || (id === 'super');
  4108. case 6:
  4109. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  4110. (id === 'switch') || (id === 'export') || (id === 'import');
  4111. case 7:
  4112. return (id === 'default') || (id === 'finally') || (id === 'extends');
  4113. case 8:
  4114. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  4115. case 10:
  4116. return (id === 'instanceof');
  4117. default:
  4118. return false;
  4119. }
  4120. }
  4121. // 7.4 Comments
  4122. function addComment(type, value, start, end, loc) {
  4123. var comment, attacher;
  4124. assert(typeof start === 'number', 'Comment must have valid position');
  4125. // Because the way the actual token is scanned, often the comments
  4126. // (if any) are skipped twice during the lexical analysis.
  4127. // Thus, we need to skip adding a comment if the comment array already
  4128. // handled it.
  4129. if (state.lastCommentStart >= start) {
  4130. return;
  4131. }
  4132. state.lastCommentStart = start;
  4133. comment = {
  4134. type: type,
  4135. value: value
  4136. };
  4137. if (extra.range) {
  4138. comment.range = [start, end];
  4139. }
  4140. if (extra.loc) {
  4141. comment.loc = loc;
  4142. }
  4143. extra.comments.push(comment);
  4144. if (extra.attachComment) {
  4145. extra.leadingComments.push(comment);
  4146. extra.trailingComments.push(comment);
  4147. }
  4148. }
  4149. function skipSingleLineComment(offset) {
  4150. var start, loc, ch, comment;
  4151. start = index - offset;
  4152. loc = {
  4153. start: {
  4154. line: lineNumber,
  4155. column: index - lineStart - offset
  4156. }
  4157. };
  4158. while (index < length) {
  4159. ch = source.charCodeAt(index);
  4160. ++index;
  4161. if (isLineTerminator(ch)) {
  4162. if (extra.comments) {
  4163. comment = source.slice(start + offset, index - 1);
  4164. loc.end = {
  4165. line: lineNumber,
  4166. column: index - lineStart - 1
  4167. };
  4168. addComment('Line', comment, start, index - 1, loc);
  4169. }
  4170. if (ch === 13 && source.charCodeAt(index) === 10) {
  4171. ++index;
  4172. }
  4173. ++lineNumber;
  4174. lineStart = index;
  4175. return;
  4176. }
  4177. }
  4178. if (extra.comments) {
  4179. comment = source.slice(start + offset, index);
  4180. loc.end = {
  4181. line: lineNumber,
  4182. column: index - lineStart
  4183. };
  4184. addComment('Line', comment, start, index, loc);
  4185. }
  4186. }
  4187. function skipMultiLineComment() {
  4188. var start, loc, ch, comment;
  4189. if (extra.comments) {
  4190. start = index - 2;
  4191. loc = {
  4192. start: {
  4193. line: lineNumber,
  4194. column: index - lineStart - 2
  4195. }
  4196. };
  4197. }
  4198. while (index < length) {
  4199. ch = source.charCodeAt(index);
  4200. if (isLineTerminator(ch)) {
  4201. if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
  4202. ++index;
  4203. }
  4204. ++lineNumber;
  4205. ++index;
  4206. lineStart = index;
  4207. if (index >= length) {
  4208. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4209. }
  4210. } else if (ch === 0x2A) {
  4211. // Block comment ends with '*/'.
  4212. if (source.charCodeAt(index + 1) === 0x2F) {
  4213. ++index;
  4214. ++index;
  4215. if (extra.comments) {
  4216. comment = source.slice(start + 2, index - 2);
  4217. loc.end = {
  4218. line: lineNumber,
  4219. column: index - lineStart
  4220. };
  4221. addComment('Block', comment, start, index, loc);
  4222. }
  4223. return;
  4224. }
  4225. ++index;
  4226. } else {
  4227. ++index;
  4228. }
  4229. }
  4230. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4231. }
  4232. function skipComment() {
  4233. var ch, start;
  4234. start = (index === 0);
  4235. while (index < length) {
  4236. ch = source.charCodeAt(index);
  4237. if (isWhiteSpace(ch)) {
  4238. ++index;
  4239. } else if (isLineTerminator(ch)) {
  4240. ++index;
  4241. if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
  4242. ++index;
  4243. }
  4244. ++lineNumber;
  4245. lineStart = index;
  4246. start = true;
  4247. } else if (ch === 0x2F) { // U+002F is '/'
  4248. ch = source.charCodeAt(index + 1);
  4249. if (ch === 0x2F) {
  4250. ++index;
  4251. ++index;
  4252. skipSingleLineComment(2);
  4253. start = true;
  4254. } else if (ch === 0x2A) { // U+002A is '*'
  4255. ++index;
  4256. ++index;
  4257. skipMultiLineComment();
  4258. } else {
  4259. break;
  4260. }
  4261. } else if (start && ch === 0x2D) { // U+002D is '-'
  4262. // U+003E is '>'
  4263. if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
  4264. // '-->' is a single-line comment
  4265. index += 3;
  4266. skipSingleLineComment(3);
  4267. } else {
  4268. break;
  4269. }
  4270. } else if (ch === 0x3C) { // U+003C is '<'
  4271. if (source.slice(index + 1, index + 4) === '!--') {
  4272. ++index; // `<`
  4273. ++index; // `!`
  4274. ++index; // `-`
  4275. ++index; // `-`
  4276. skipSingleLineComment(4);
  4277. } else {
  4278. break;
  4279. }
  4280. } else {
  4281. break;
  4282. }
  4283. }
  4284. }
  4285. function scanHexEscape(prefix) {
  4286. var i, len, ch, code = 0;
  4287. len = (prefix === 'u') ? 4 : 2;
  4288. for (i = 0; i < len; ++i) {
  4289. if (index < length && isHexDigit(source[index])) {
  4290. ch = source[index++];
  4291. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4292. } else {
  4293. return '';
  4294. }
  4295. }
  4296. return String.fromCharCode(code);
  4297. }
  4298. function getEscapedIdentifier() {
  4299. var ch, id;
  4300. ch = source.charCodeAt(index++);
  4301. id = String.fromCharCode(ch);
  4302. // '\u' (U+005C, U+0075) denotes an escaped character.
  4303. if (ch === 0x5C) {
  4304. if (source.charCodeAt(index) !== 0x75) {
  4305. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4306. }
  4307. ++index;
  4308. ch = scanHexEscape('u');
  4309. if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
  4310. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4311. }
  4312. id = ch;
  4313. }
  4314. while (index < length) {
  4315. ch = source.charCodeAt(index);
  4316. if (!isIdentifierPart(ch)) {
  4317. break;
  4318. }
  4319. ++index;
  4320. id += String.fromCharCode(ch);
  4321. // '\u' (U+005C, U+0075) denotes an escaped character.
  4322. if (ch === 0x5C) {
  4323. id = id.substr(0, id.length - 1);
  4324. if (source.charCodeAt(index) !== 0x75) {
  4325. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4326. }
  4327. ++index;
  4328. ch = scanHexEscape('u');
  4329. if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
  4330. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4331. }
  4332. id += ch;
  4333. }
  4334. }
  4335. return id;
  4336. }
  4337. function getIdentifier() {
  4338. var start, ch;
  4339. start = index++;
  4340. while (index < length) {
  4341. ch = source.charCodeAt(index);
  4342. if (ch === 0x5C) {
  4343. // Blackslash (U+005C) marks Unicode escape sequence.
  4344. index = start;
  4345. return getEscapedIdentifier();
  4346. }
  4347. if (isIdentifierPart(ch)) {
  4348. ++index;
  4349. } else {
  4350. break;
  4351. }
  4352. }
  4353. return source.slice(start, index);
  4354. }
  4355. function scanIdentifier() {
  4356. var start, id, type;
  4357. start = index;
  4358. // Backslash (U+005C) starts an escaped character.
  4359. id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();
  4360. // There is no keyword or literal with only one character.
  4361. // Thus, it must be an identifier.
  4362. if (id.length === 1) {
  4363. type = Token.Identifier;
  4364. } else if (isKeyword(id)) {
  4365. type = Token.Keyword;
  4366. } else if (id === 'null') {
  4367. type = Token.NullLiteral;
  4368. } else if (id === 'true' || id === 'false') {
  4369. type = Token.BooleanLiteral;
  4370. } else {
  4371. type = Token.Identifier;
  4372. }
  4373. return {
  4374. type: type,
  4375. value: id,
  4376. lineNumber: lineNumber,
  4377. lineStart: lineStart,
  4378. start: start,
  4379. end: index
  4380. };
  4381. }
  4382. // 7.7 Punctuators
  4383. function scanPunctuator() {
  4384. var start = index,
  4385. code = source.charCodeAt(index),
  4386. code2,
  4387. ch1 = source[index],
  4388. ch2,
  4389. ch3,
  4390. ch4;
  4391. switch (code) {
  4392. // Check for most common single-character punctuators.
  4393. case 0x2E: // . dot
  4394. case 0x28: // ( open bracket
  4395. case 0x29: // ) close bracket
  4396. case 0x3B: // ; semicolon
  4397. case 0x2C: // , comma
  4398. case 0x7B: // { open curly brace
  4399. case 0x7D: // } close curly brace
  4400. case 0x5B: // [
  4401. case 0x5D: // ]
  4402. case 0x3A: // :
  4403. case 0x3F: // ?
  4404. case 0x7E: // ~
  4405. ++index;
  4406. if (extra.tokenize) {
  4407. if (code === 0x28) {
  4408. extra.openParenToken = extra.tokens.length;
  4409. } else if (code === 0x7B) {
  4410. extra.openCurlyToken = extra.tokens.length;
  4411. }
  4412. }
  4413. return {
  4414. type: Token.Punctuator,
  4415. value: String.fromCharCode(code),
  4416. lineNumber: lineNumber,
  4417. lineStart: lineStart,
  4418. start: start,
  4419. end: index
  4420. };
  4421. default:
  4422. code2 = source.charCodeAt(index + 1);
  4423. // '=' (U+003D) marks an assignment or comparison operator.
  4424. if (code2 === 0x3D) {
  4425. switch (code) {
  4426. case 0x2B: // +
  4427. case 0x2D: // -
  4428. case 0x2F: // /
  4429. case 0x3C: // <
  4430. case 0x3E: // >
  4431. case 0x5E: // ^
  4432. case 0x7C: // |
  4433. case 0x25: // %
  4434. case 0x26: // &
  4435. case 0x2A: // *
  4436. index += 2;
  4437. return {
  4438. type: Token.Punctuator,
  4439. value: String.fromCharCode(code) + String.fromCharCode(code2),
  4440. lineNumber: lineNumber,
  4441. lineStart: lineStart,
  4442. start: start,
  4443. end: index
  4444. };
  4445. case 0x21: // !
  4446. case 0x3D: // =
  4447. index += 2;
  4448. // !== and ===
  4449. if (source.charCodeAt(index) === 0x3D) {
  4450. ++index;
  4451. }
  4452. return {
  4453. type: Token.Punctuator,
  4454. value: source.slice(start, index),
  4455. lineNumber: lineNumber,
  4456. lineStart: lineStart,
  4457. start: start,
  4458. end: index
  4459. };
  4460. }
  4461. }
  4462. }
  4463. // 4-character punctuator: >>>=
  4464. ch4 = source.substr(index, 4);
  4465. if (ch4 === '>>>=') {
  4466. index += 4;
  4467. return {
  4468. type: Token.Punctuator,
  4469. value: ch4,
  4470. lineNumber: lineNumber,
  4471. lineStart: lineStart,
  4472. start: start,
  4473. end: index
  4474. };
  4475. }
  4476. // 3-character punctuators: === !== >>> <<= >>=
  4477. ch3 = ch4.substr(0, 3);
  4478. if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
  4479. index += 3;
  4480. return {
  4481. type: Token.Punctuator,
  4482. value: ch3,
  4483. lineNumber: lineNumber,
  4484. lineStart: lineStart,
  4485. start: start,
  4486. end: index
  4487. };
  4488. }
  4489. // Other 2-character punctuators: ++ -- << >> && ||
  4490. ch2 = ch3.substr(0, 2);
  4491. if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {
  4492. index += 2;
  4493. return {
  4494. type: Token.Punctuator,
  4495. value: ch2,
  4496. lineNumber: lineNumber,
  4497. lineStart: lineStart,
  4498. start: start,
  4499. end: index
  4500. };
  4501. }
  4502. // 1-character punctuators: < > = ! + - * % & | ^ /
  4503. if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
  4504. ++index;
  4505. return {
  4506. type: Token.Punctuator,
  4507. value: ch1,
  4508. lineNumber: lineNumber,
  4509. lineStart: lineStart,
  4510. start: start,
  4511. end: index
  4512. };
  4513. }
  4514. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4515. }
  4516. // 7.8.3 Numeric Literals
  4517. function scanHexLiteral(start) {
  4518. var number = '';
  4519. while (index < length) {
  4520. if (!isHexDigit(source[index])) {
  4521. break;
  4522. }
  4523. number += source[index++];
  4524. }
  4525. if (number.length === 0) {
  4526. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4527. }
  4528. if (isIdentifierStart(source.charCodeAt(index))) {
  4529. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4530. }
  4531. return {
  4532. type: Token.NumericLiteral,
  4533. value: parseInt('0x' + number, 16),
  4534. lineNumber: lineNumber,
  4535. lineStart: lineStart,
  4536. start: start,
  4537. end: index
  4538. };
  4539. }
  4540. function scanOctalLiteral(start) {
  4541. var number = '0' + source[index++];
  4542. while (index < length) {
  4543. if (!isOctalDigit(source[index])) {
  4544. break;
  4545. }
  4546. number += source[index++];
  4547. }
  4548. if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
  4549. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4550. }
  4551. return {
  4552. type: Token.NumericLiteral,
  4553. value: parseInt(number, 8),
  4554. octal: true,
  4555. lineNumber: lineNumber,
  4556. lineStart: lineStart,
  4557. start: start,
  4558. end: index
  4559. };
  4560. }
  4561. function scanNumericLiteral() {
  4562. var number, start, ch;
  4563. ch = source[index];
  4564. assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
  4565. 'Numeric literal must start with a decimal digit or a decimal point');
  4566. start = index;
  4567. number = '';
  4568. if (ch !== '.') {
  4569. number = source[index++];
  4570. ch = source[index];
  4571. // Hex number starts with '0x'.
  4572. // Octal number starts with '0'.
  4573. if (number === '0') {
  4574. if (ch === 'x' || ch === 'X') {
  4575. ++index;
  4576. return scanHexLiteral(start);
  4577. }
  4578. if (isOctalDigit(ch)) {
  4579. return scanOctalLiteral(start);
  4580. }
  4581. // decimal number starts with '0' such as '09' is illegal.
  4582. if (ch && isDecimalDigit(ch.charCodeAt(0))) {
  4583. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4584. }
  4585. }
  4586. while (isDecimalDigit(source.charCodeAt(index))) {
  4587. number += source[index++];
  4588. }
  4589. ch = source[index];
  4590. }
  4591. if (ch === '.') {
  4592. number += source[index++];
  4593. while (isDecimalDigit(source.charCodeAt(index))) {
  4594. number += source[index++];
  4595. }
  4596. ch = source[index];
  4597. }
  4598. if (ch === 'e' || ch === 'E') {
  4599. number += source[index++];
  4600. ch = source[index];
  4601. if (ch === '+' || ch === '-') {
  4602. number += source[index++];
  4603. }
  4604. if (isDecimalDigit(source.charCodeAt(index))) {
  4605. while (isDecimalDigit(source.charCodeAt(index))) {
  4606. number += source[index++];
  4607. }
  4608. } else {
  4609. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4610. }
  4611. }
  4612. if (isIdentifierStart(source.charCodeAt(index))) {
  4613. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4614. }
  4615. return {
  4616. type: Token.NumericLiteral,
  4617. value: parseFloat(number),
  4618. lineNumber: lineNumber,
  4619. lineStart: lineStart,
  4620. start: start,
  4621. end: index
  4622. };
  4623. }
  4624. // 7.8.4 String Literals
  4625. function scanStringLiteral() {
  4626. var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;
  4627. startLineNumber = lineNumber;
  4628. startLineStart = lineStart;
  4629. quote = source[index];
  4630. assert((quote === '\'' || quote === '"'),
  4631. 'String literal must starts with a quote');
  4632. start = index;
  4633. ++index;
  4634. while (index < length) {
  4635. ch = source[index++];
  4636. if (ch === quote) {
  4637. quote = '';
  4638. break;
  4639. } else if (ch === '\\') {
  4640. ch = source[index++];
  4641. if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
  4642. switch (ch) {
  4643. case 'u':
  4644. case 'x':
  4645. restore = index;
  4646. unescaped = scanHexEscape(ch);
  4647. if (unescaped) {
  4648. str += unescaped;
  4649. } else {
  4650. index = restore;
  4651. str += ch;
  4652. }
  4653. break;
  4654. case 'n':
  4655. str += '\n';
  4656. break;
  4657. case 'r':
  4658. str += '\r';
  4659. break;
  4660. case 't':
  4661. str += '\t';
  4662. break;
  4663. case 'b':
  4664. str += '\b';
  4665. break;
  4666. case 'f':
  4667. str += '\f';
  4668. break;
  4669. case 'v':
  4670. str += '\x0B';
  4671. break;
  4672. default:
  4673. if (isOctalDigit(ch)) {
  4674. code = '01234567'.indexOf(ch);
  4675. // \0 is not octal escape sequence
  4676. if (code !== 0) {
  4677. octal = true;
  4678. }
  4679. if (index < length && isOctalDigit(source[index])) {
  4680. octal = true;
  4681. code = code * 8 + '01234567'.indexOf(source[index++]);
  4682. // 3 digits are only allowed when string starts
  4683. // with 0, 1, 2, 3
  4684. if ('0123'.indexOf(ch) >= 0 &&
  4685. index < length &&
  4686. isOctalDigit(source[index])) {
  4687. code = code * 8 + '01234567'.indexOf(source[index++]);
  4688. }
  4689. }
  4690. str += String.fromCharCode(code);
  4691. } else {
  4692. str += ch;
  4693. }
  4694. break;
  4695. }
  4696. } else {
  4697. ++lineNumber;
  4698. if (ch === '\r' && source[index] === '\n') {
  4699. ++index;
  4700. }
  4701. lineStart = index;
  4702. }
  4703. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4704. break;
  4705. } else {
  4706. str += ch;
  4707. }
  4708. }
  4709. if (quote !== '') {
  4710. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4711. }
  4712. return {
  4713. type: Token.StringLiteral,
  4714. value: str,
  4715. octal: octal,
  4716. startLineNumber: startLineNumber,
  4717. startLineStart: startLineStart,
  4718. lineNumber: lineNumber,
  4719. lineStart: lineStart,
  4720. start: start,
  4721. end: index
  4722. };
  4723. }
  4724. function testRegExp(pattern, flags) {
  4725. var value;
  4726. try {
  4727. value = new RegExp(pattern, flags);
  4728. } catch (e) {
  4729. throwError({}, Messages.InvalidRegExp);
  4730. }
  4731. return value;
  4732. }
  4733. function scanRegExpBody() {
  4734. var ch, str, classMarker, terminated, body;
  4735. ch = source[index];
  4736. assert(ch === '/', 'Regular expression literal must start with a slash');
  4737. str = source[index++];
  4738. classMarker = false;
  4739. terminated = false;
  4740. while (index < length) {
  4741. ch = source[index++];
  4742. str += ch;
  4743. if (ch === '\\') {
  4744. ch = source[index++];
  4745. // ECMA-262 7.8.5
  4746. if (isLineTerminator(ch.charCodeAt(0))) {
  4747. throwError({}, Messages.UnterminatedRegExp);
  4748. }
  4749. str += ch;
  4750. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4751. throwError({}, Messages.UnterminatedRegExp);
  4752. } else if (classMarker) {
  4753. if (ch === ']') {
  4754. classMarker = false;
  4755. }
  4756. } else {
  4757. if (ch === '/') {
  4758. terminated = true;
  4759. break;
  4760. } else if (ch === '[') {
  4761. classMarker = true;
  4762. }
  4763. }
  4764. }
  4765. if (!terminated) {
  4766. throwError({}, Messages.UnterminatedRegExp);
  4767. }
  4768. // Exclude leading and trailing slash.
  4769. body = str.substr(1, str.length - 2);
  4770. return {
  4771. value: body,
  4772. literal: str
  4773. };
  4774. }
  4775. function scanRegExpFlags() {
  4776. var ch, str, flags, restore;
  4777. str = '';
  4778. flags = '';
  4779. while (index < length) {
  4780. ch = source[index];
  4781. if (!isIdentifierPart(ch.charCodeAt(0))) {
  4782. break;
  4783. }
  4784. ++index;
  4785. if (ch === '\\' && index < length) {
  4786. ch = source[index];
  4787. if (ch === 'u') {
  4788. ++index;
  4789. restore = index;
  4790. ch = scanHexEscape('u');
  4791. if (ch) {
  4792. flags += ch;
  4793. for (str += '\\u'; restore < index; ++restore) {
  4794. str += source[restore];
  4795. }
  4796. } else {
  4797. index = restore;
  4798. flags += 'u';
  4799. str += '\\u';
  4800. }
  4801. throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
  4802. } else {
  4803. str += '\\';
  4804. throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
  4805. }
  4806. } else {
  4807. flags += ch;
  4808. str += ch;
  4809. }
  4810. }
  4811. return {
  4812. value: flags,
  4813. literal: str
  4814. };
  4815. }
  4816. function scanRegExp() {
  4817. var start, body, flags, pattern, value;
  4818. lookahead = null;
  4819. skipComment();
  4820. start = index;
  4821. body = scanRegExpBody();
  4822. flags = scanRegExpFlags();
  4823. value = testRegExp(body.value, flags.value);
  4824. if (extra.tokenize) {
  4825. return {
  4826. type: Token.RegularExpression,
  4827. value: value,
  4828. lineNumber: lineNumber,
  4829. lineStart: lineStart,
  4830. start: start,
  4831. end: index
  4832. };
  4833. }
  4834. return {
  4835. literal: body.literal + flags.literal,
  4836. value: value,
  4837. start: start,
  4838. end: index
  4839. };
  4840. }
  4841. function collectRegex() {
  4842. var pos, loc, regex, token;
  4843. skipComment();
  4844. pos = index;
  4845. loc = {
  4846. start: {
  4847. line: lineNumber,
  4848. column: index - lineStart
  4849. }
  4850. };
  4851. regex = scanRegExp();
  4852. loc.end = {
  4853. line: lineNumber,
  4854. column: index - lineStart
  4855. };
  4856. /* istanbul ignore next */
  4857. if (!extra.tokenize) {
  4858. // Pop the previous token, which is likely '/' or '/='
  4859. if (extra.tokens.length > 0) {
  4860. token = extra.tokens[extra.tokens.length - 1];
  4861. if (token.range[0] === pos && token.type === 'Punctuator') {
  4862. if (token.value === '/' || token.value === '/=') {
  4863. extra.tokens.pop();
  4864. }
  4865. }
  4866. }
  4867. extra.tokens.push({
  4868. type: 'RegularExpression',
  4869. value: regex.literal,
  4870. range: [pos, index],
  4871. loc: loc
  4872. });
  4873. }
  4874. return regex;
  4875. }
  4876. function isIdentifierName(token) {
  4877. return token.type === Token.Identifier ||
  4878. token.type === Token.Keyword ||
  4879. token.type === Token.BooleanLiteral ||
  4880. token.type === Token.NullLiteral;
  4881. }
  4882. function advanceSlash() {
  4883. var prevToken,
  4884. checkToken;
  4885. // Using the following algorithm:
  4886. // https://github.com/mozilla/sweet.js/wiki/design
  4887. prevToken = extra.tokens[extra.tokens.length - 1];
  4888. if (!prevToken) {
  4889. // Nothing before that: it cannot be a division.
  4890. return collectRegex();
  4891. }
  4892. if (prevToken.type === 'Punctuator') {
  4893. if (prevToken.value === ']') {
  4894. return scanPunctuator();
  4895. }
  4896. if (prevToken.value === ')') {
  4897. checkToken = extra.tokens[extra.openParenToken - 1];
  4898. if (checkToken &&
  4899. checkToken.type === 'Keyword' &&
  4900. (checkToken.value === 'if' ||
  4901. checkToken.value === 'while' ||
  4902. checkToken.value === 'for' ||
  4903. checkToken.value === 'with')) {
  4904. return collectRegex();
  4905. }
  4906. return scanPunctuator();
  4907. }
  4908. if (prevToken.value === '}') {
  4909. // Dividing a function by anything makes little sense,
  4910. // but we have to check for that.
  4911. if (extra.tokens[extra.openCurlyToken - 3] &&
  4912. extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
  4913. // Anonymous function.
  4914. checkToken = extra.tokens[extra.openCurlyToken - 4];
  4915. if (!checkToken) {
  4916. return scanPunctuator();
  4917. }
  4918. } else if (extra.tokens[extra.openCurlyToken - 4] &&
  4919. extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
  4920. // Named function.
  4921. checkToken = extra.tokens[extra.openCurlyToken - 5];
  4922. if (!checkToken) {
  4923. return collectRegex();
  4924. }
  4925. } else {
  4926. return scanPunctuator();
  4927. }
  4928. // checkToken determines whether the function is
  4929. // a declaration or an expression.
  4930. if (FnExprTokens.indexOf(checkToken.value) >= 0) {
  4931. // It is an expression.
  4932. return scanPunctuator();
  4933. }
  4934. // It is a declaration.
  4935. return collectRegex();
  4936. }
  4937. return collectRegex();
  4938. }
  4939. if (prevToken.type === 'Keyword') {
  4940. return collectRegex();
  4941. }
  4942. return scanPunctuator();
  4943. }
  4944. function advance() {
  4945. var ch;
  4946. skipComment();
  4947. if (index >= length) {
  4948. return {
  4949. type: Token.EOF,
  4950. lineNumber: lineNumber,
  4951. lineStart: lineStart,
  4952. start: index,
  4953. end: index
  4954. };
  4955. }
  4956. ch = source.charCodeAt(index);
  4957. if (isIdentifierStart(ch)) {
  4958. return scanIdentifier();
  4959. }
  4960. // Very common: ( and ) and ;
  4961. if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
  4962. return scanPunctuator();
  4963. }
  4964. // String literal starts with single quote (U+0027) or double quote (U+0022).
  4965. if (ch === 0x27 || ch === 0x22) {
  4966. return scanStringLiteral();
  4967. }
  4968. // Dot (.) U+002E can also start a floating-point number, hence the need
  4969. // to check the next character.
  4970. if (ch === 0x2E) {
  4971. if (isDecimalDigit(source.charCodeAt(index + 1))) {
  4972. return scanNumericLiteral();
  4973. }
  4974. return scanPunctuator();
  4975. }
  4976. if (isDecimalDigit(ch)) {
  4977. return scanNumericLiteral();
  4978. }
  4979. // Slash (/) U+002F can also start a regex.
  4980. if (extra.tokenize && ch === 0x2F) {
  4981. return advanceSlash();
  4982. }
  4983. return scanPunctuator();
  4984. }
  4985. function collectToken() {
  4986. var loc, token, range, value;
  4987. skipComment();
  4988. loc = {
  4989. start: {
  4990. line: lineNumber,
  4991. column: index - lineStart
  4992. }
  4993. };
  4994. token = advance();
  4995. loc.end = {
  4996. line: lineNumber,
  4997. column: index - lineStart
  4998. };
  4999. if (token.type !== Token.EOF) {
  5000. value = source.slice(token.start, token.end);
  5001. extra.tokens.push({
  5002. type: TokenName[token.type],
  5003. value: value,
  5004. range: [token.start, token.end],
  5005. loc: loc
  5006. });
  5007. }
  5008. return token;
  5009. }
  5010. function lex() {
  5011. var token;
  5012. token = lookahead;
  5013. index = token.end;
  5014. lineNumber = token.lineNumber;
  5015. lineStart = token.lineStart;
  5016. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5017. index = token.end;
  5018. lineNumber = token.lineNumber;
  5019. lineStart = token.lineStart;
  5020. return token;
  5021. }
  5022. function peek() {
  5023. var pos, line, start;
  5024. pos = index;
  5025. line = lineNumber;
  5026. start = lineStart;
  5027. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5028. index = pos;
  5029. lineNumber = line;
  5030. lineStart = start;
  5031. }
  5032. function Position(line, column) {
  5033. this.line = line;
  5034. this.column = column;
  5035. }
  5036. function SourceLocation(startLine, startColumn, line, column) {
  5037. this.start = new Position(startLine, startColumn);
  5038. this.end = new Position(line, column);
  5039. }
  5040. SyntaxTreeDelegate = {
  5041. name: 'SyntaxTree',
  5042. processComment: function (node) {
  5043. var lastChild, trailingComments;
  5044. if (node.type === Syntax.Program) {
  5045. if (node.body.length > 0) {
  5046. return;
  5047. }
  5048. }
  5049. if (extra.trailingComments.length > 0) {
  5050. if (extra.trailingComments[0].range[0] >= node.range[1]) {
  5051. trailingComments = extra.trailingComments;
  5052. extra.trailingComments = [];
  5053. } else {
  5054. extra.trailingComments.length = 0;
  5055. }
  5056. } else {
  5057. if (extra.bottomRightStack.length > 0 &&
  5058. extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
  5059. extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
  5060. trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
  5061. delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
  5062. }
  5063. }
  5064. // Eating the stack.
  5065. while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
  5066. lastChild = extra.bottomRightStack.pop();
  5067. }
  5068. if (lastChild) {
  5069. if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
  5070. node.leadingComments = lastChild.leadingComments;
  5071. delete lastChild.leadingComments;
  5072. }
  5073. } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
  5074. node.leadingComments = extra.leadingComments;
  5075. extra.leadingComments = [];
  5076. }
  5077. if (trailingComments) {
  5078. node.trailingComments = trailingComments;
  5079. }
  5080. extra.bottomRightStack.push(node);
  5081. },
  5082. markEnd: function (node, startToken) {
  5083. if (extra.range) {
  5084. node.range = [startToken.start, index];
  5085. }
  5086. if (extra.loc) {
  5087. node.loc = new SourceLocation(
  5088. startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber,
  5089. startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart),
  5090. lineNumber,
  5091. index - lineStart
  5092. );
  5093. this.postProcess(node);
  5094. }
  5095. if (extra.attachComment) {
  5096. this.processComment(node);
  5097. }
  5098. return node;
  5099. },
  5100. postProcess: function (node) {
  5101. if (extra.source) {
  5102. node.loc.source = extra.source;
  5103. }
  5104. return node;
  5105. },
  5106. createArrayExpression: function (elements) {
  5107. return {
  5108. type: Syntax.ArrayExpression,
  5109. elements: elements
  5110. };
  5111. },
  5112. createAssignmentExpression: function (operator, left, right) {
  5113. return {
  5114. type: Syntax.AssignmentExpression,
  5115. operator: operator,
  5116. left: left,
  5117. right: right
  5118. };
  5119. },
  5120. createBinaryExpression: function (operator, left, right) {
  5121. var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
  5122. Syntax.BinaryExpression;
  5123. return {
  5124. type: type,
  5125. operator: operator,
  5126. left: left,
  5127. right: right
  5128. };
  5129. },
  5130. createBlockStatement: function (body) {
  5131. return {
  5132. type: Syntax.BlockStatement,
  5133. body: body
  5134. };
  5135. },
  5136. createBreakStatement: function (label) {
  5137. return {
  5138. type: Syntax.BreakStatement,
  5139. label: label
  5140. };
  5141. },
  5142. createCallExpression: function (callee, args) {
  5143. return {
  5144. type: Syntax.CallExpression,
  5145. callee: callee,
  5146. 'arguments': args
  5147. };
  5148. },
  5149. createCatchClause: function (param, body) {
  5150. return {
  5151. type: Syntax.CatchClause,
  5152. param: param,
  5153. body: body
  5154. };
  5155. },
  5156. createConditionalExpression: function (test, consequent, alternate) {
  5157. return {
  5158. type: Syntax.ConditionalExpression,
  5159. test: test,
  5160. consequent: consequent,
  5161. alternate: alternate
  5162. };
  5163. },
  5164. createContinueStatement: function (label) {
  5165. return {
  5166. type: Syntax.ContinueStatement,
  5167. label: label
  5168. };
  5169. },
  5170. createDebuggerStatement: function () {
  5171. return {
  5172. type: Syntax.DebuggerStatement
  5173. };
  5174. },
  5175. createDoWhileStatement: function (body, test) {
  5176. return {
  5177. type: Syntax.DoWhileStatement,
  5178. body: body,
  5179. test: test
  5180. };
  5181. },
  5182. createEmptyStatement: function () {
  5183. return {
  5184. type: Syntax.EmptyStatement
  5185. };
  5186. },
  5187. createExpressionStatement: function (expression) {
  5188. return {
  5189. type: Syntax.ExpressionStatement,
  5190. expression: expression
  5191. };
  5192. },
  5193. createForStatement: function (init, test, update, body) {
  5194. return {
  5195. type: Syntax.ForStatement,
  5196. init: init,
  5197. test: test,
  5198. update: update,
  5199. body: body
  5200. };
  5201. },
  5202. createForInStatement: function (left, right, body) {
  5203. return {
  5204. type: Syntax.ForInStatement,
  5205. left: left,
  5206. right: right,
  5207. body: body,
  5208. each: false
  5209. };
  5210. },
  5211. createFunctionDeclaration: function (id, params, defaults, body) {
  5212. return {
  5213. type: Syntax.FunctionDeclaration,
  5214. id: id,
  5215. params: params,
  5216. defaults: defaults,
  5217. body: body,
  5218. rest: null,
  5219. generator: false,
  5220. expression: false
  5221. };
  5222. },
  5223. createFunctionExpression: function (id, params, defaults, body) {
  5224. return {
  5225. type: Syntax.FunctionExpression,
  5226. id: id,
  5227. params: params,
  5228. defaults: defaults,
  5229. body: body,
  5230. rest: null,
  5231. generator: false,
  5232. expression: false
  5233. };
  5234. },
  5235. createIdentifier: function (name) {
  5236. return {
  5237. type: Syntax.Identifier,
  5238. name: name
  5239. };
  5240. },
  5241. createIfStatement: function (test, consequent, alternate) {
  5242. return {
  5243. type: Syntax.IfStatement,
  5244. test: test,
  5245. consequent: consequent,
  5246. alternate: alternate
  5247. };
  5248. },
  5249. createLabeledStatement: function (label, body) {
  5250. return {
  5251. type: Syntax.LabeledStatement,
  5252. label: label,
  5253. body: body
  5254. };
  5255. },
  5256. createLiteral: function (token) {
  5257. return {
  5258. type: Syntax.Literal,
  5259. value: token.value,
  5260. raw: source.slice(token.start, token.end)
  5261. };
  5262. },
  5263. createMemberExpression: function (accessor, object, property) {
  5264. return {
  5265. type: Syntax.MemberExpression,
  5266. computed: accessor === '[',
  5267. object: object,
  5268. property: property
  5269. };
  5270. },
  5271. createNewExpression: function (callee, args) {
  5272. return {
  5273. type: Syntax.NewExpression,
  5274. callee: callee,
  5275. 'arguments': args
  5276. };
  5277. },
  5278. createObjectExpression: function (properties) {
  5279. return {
  5280. type: Syntax.ObjectExpression,
  5281. properties: properties
  5282. };
  5283. },
  5284. createPostfixExpression: function (operator, argument) {
  5285. return {
  5286. type: Syntax.UpdateExpression,
  5287. operator: operator,
  5288. argument: argument,
  5289. prefix: false
  5290. };
  5291. },
  5292. createProgram: function (body) {
  5293. return {
  5294. type: Syntax.Program,
  5295. body: body
  5296. };
  5297. },
  5298. createProperty: function (kind, key, value) {
  5299. return {
  5300. type: Syntax.Property,
  5301. key: key,
  5302. value: value,
  5303. kind: kind
  5304. };
  5305. },
  5306. createReturnStatement: function (argument) {
  5307. return {
  5308. type: Syntax.ReturnStatement,
  5309. argument: argument
  5310. };
  5311. },
  5312. createSequenceExpression: function (expressions) {
  5313. return {
  5314. type: Syntax.SequenceExpression,
  5315. expressions: expressions
  5316. };
  5317. },
  5318. createSwitchCase: function (test, consequent) {
  5319. return {
  5320. type: Syntax.SwitchCase,
  5321. test: test,
  5322. consequent: consequent
  5323. };
  5324. },
  5325. createSwitchStatement: function (discriminant, cases) {
  5326. return {
  5327. type: Syntax.SwitchStatement,
  5328. discriminant: discriminant,
  5329. cases: cases
  5330. };
  5331. },
  5332. createThisExpression: function () {
  5333. return {
  5334. type: Syntax.ThisExpression
  5335. };
  5336. },
  5337. createThrowStatement: function (argument) {
  5338. return {
  5339. type: Syntax.ThrowStatement,
  5340. argument: argument
  5341. };
  5342. },
  5343. createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
  5344. return {
  5345. type: Syntax.TryStatement,
  5346. block: block,
  5347. guardedHandlers: guardedHandlers,
  5348. handlers: handlers,
  5349. finalizer: finalizer
  5350. };
  5351. },
  5352. createUnaryExpression: function (operator, argument) {
  5353. if (operator === '++' || operator === '--') {
  5354. return {
  5355. type: Syntax.UpdateExpression,
  5356. operator: operator,
  5357. argument: argument,
  5358. prefix: true
  5359. };
  5360. }
  5361. return {
  5362. type: Syntax.UnaryExpression,
  5363. operator: operator,
  5364. argument: argument,
  5365. prefix: true
  5366. };
  5367. },
  5368. createVariableDeclaration: function (declarations, kind) {
  5369. return {
  5370. type: Syntax.VariableDeclaration,
  5371. declarations: declarations,
  5372. kind: kind
  5373. };
  5374. },
  5375. createVariableDeclarator: function (id, init) {
  5376. return {
  5377. type: Syntax.VariableDeclarator,
  5378. id: id,
  5379. init: init
  5380. };
  5381. },
  5382. createWhileStatement: function (test, body) {
  5383. return {
  5384. type: Syntax.WhileStatement,
  5385. test: test,
  5386. body: body
  5387. };
  5388. },
  5389. createWithStatement: function (object, body) {
  5390. return {
  5391. type: Syntax.WithStatement,
  5392. object: object,
  5393. body: body
  5394. };
  5395. }
  5396. };
  5397. // Return true if there is a line terminator before the next token.
  5398. function peekLineTerminator() {
  5399. var pos, line, start, found;
  5400. pos = index;
  5401. line = lineNumber;
  5402. start = lineStart;
  5403. skipComment();
  5404. found = lineNumber !== line;
  5405. index = pos;
  5406. lineNumber = line;
  5407. lineStart = start;
  5408. return found;
  5409. }
  5410. // Throw an exception
  5411. function throwError(token, messageFormat) {
  5412. var error,
  5413. args = Array.prototype.slice.call(arguments, 2),
  5414. msg = messageFormat.replace(
  5415. /%(\d)/g,
  5416. function (whole, index) {
  5417. assert(index < args.length, 'Message reference must be in range');
  5418. return args[index];
  5419. }
  5420. );
  5421. if (typeof token.lineNumber === 'number') {
  5422. error = new Error('Line ' + token.lineNumber + ': ' + msg);
  5423. error.index = token.start;
  5424. error.lineNumber = token.lineNumber;
  5425. error.column = token.start - lineStart + 1;
  5426. } else {
  5427. error = new Error('Line ' + lineNumber + ': ' + msg);
  5428. error.index = index;
  5429. error.lineNumber = lineNumber;
  5430. error.column = index - lineStart + 1;
  5431. }
  5432. error.description = msg;
  5433. throw error;
  5434. }
  5435. function throwErrorTolerant() {
  5436. try {
  5437. throwError.apply(null, arguments);
  5438. } catch (e) {
  5439. if (extra.errors) {
  5440. extra.errors.push(e);
  5441. } else {
  5442. throw e;
  5443. }
  5444. }
  5445. }
  5446. // Throw an exception because of the token.
  5447. function throwUnexpected(token) {
  5448. if (token.type === Token.EOF) {
  5449. throwError(token, Messages.UnexpectedEOS);
  5450. }
  5451. if (token.type === Token.NumericLiteral) {
  5452. throwError(token, Messages.UnexpectedNumber);
  5453. }
  5454. if (token.type === Token.StringLiteral) {
  5455. throwError(token, Messages.UnexpectedString);
  5456. }
  5457. if (token.type === Token.Identifier) {
  5458. throwError(token, Messages.UnexpectedIdentifier);
  5459. }
  5460. if (token.type === Token.Keyword) {
  5461. if (isFutureReservedWord(token.value)) {
  5462. throwError(token, Messages.UnexpectedReserved);
  5463. } else if (strict && isStrictModeReservedWord(token.value)) {
  5464. throwErrorTolerant(token, Messages.StrictReservedWord);
  5465. return;
  5466. }
  5467. throwError(token, Messages.UnexpectedToken, token.value);
  5468. }
  5469. // BooleanLiteral, NullLiteral, or Punctuator.
  5470. throwError(token, Messages.UnexpectedToken, token.value);
  5471. }
  5472. // Expect the next token to match the specified punctuator.
  5473. // If not, an exception will be thrown.
  5474. function expect(value) {
  5475. var token = lex();
  5476. if (token.type !== Token.Punctuator || token.value !== value) {
  5477. throwUnexpected(token);
  5478. }
  5479. }
  5480. // Expect the next token to match the specified keyword.
  5481. // If not, an exception will be thrown.
  5482. function expectKeyword(keyword) {
  5483. var token = lex();
  5484. if (token.type !== Token.Keyword || token.value !== keyword) {
  5485. throwUnexpected(token);
  5486. }
  5487. }
  5488. // Return true if the next token matches the specified punctuator.
  5489. function match(value) {
  5490. return lookahead.type === Token.Punctuator && lookahead.value === value;
  5491. }
  5492. // Return true if the next token matches the specified keyword
  5493. function matchKeyword(keyword) {
  5494. return lookahead.type === Token.Keyword && lookahead.value === keyword;
  5495. }
  5496. // Return true if the next token is an assignment operator
  5497. function matchAssign() {
  5498. var op;
  5499. if (lookahead.type !== Token.Punctuator) {
  5500. return false;
  5501. }
  5502. op = lookahead.value;
  5503. return op === '=' ||
  5504. op === '*=' ||
  5505. op === '/=' ||
  5506. op === '%=' ||
  5507. op === '+=' ||
  5508. op === '-=' ||
  5509. op === '<<=' ||
  5510. op === '>>=' ||
  5511. op === '>>>=' ||
  5512. op === '&=' ||
  5513. op === '^=' ||
  5514. op === '|=';
  5515. }
  5516. function consumeSemicolon() {
  5517. var line;
  5518. // Catch the very common case first: immediately a semicolon (U+003B).
  5519. if (source.charCodeAt(index) === 0x3B || match(';')) {
  5520. lex();
  5521. return;
  5522. }
  5523. line = lineNumber;
  5524. skipComment();
  5525. if (lineNumber !== line) {
  5526. return;
  5527. }
  5528. if (lookahead.type !== Token.EOF && !match('}')) {
  5529. throwUnexpected(lookahead);
  5530. }
  5531. }
  5532. // Return true if provided expression is LeftHandSideExpression
  5533. function isLeftHandSide(expr) {
  5534. return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  5535. }
  5536. // 11.1.4 Array Initialiser
  5537. function parseArrayInitialiser() {
  5538. var elements = [], startToken;
  5539. startToken = lookahead;
  5540. expect('[');
  5541. while (!match(']')) {
  5542. if (match(',')) {
  5543. lex();
  5544. elements.push(null);
  5545. } else {
  5546. elements.push(parseAssignmentExpression());
  5547. if (!match(']')) {
  5548. expect(',');
  5549. }
  5550. }
  5551. }
  5552. lex();
  5553. return delegate.markEnd(delegate.createArrayExpression(elements), startToken);
  5554. }
  5555. // 11.1.5 Object Initialiser
  5556. function parsePropertyFunction(param, first) {
  5557. var previousStrict, body, startToken;
  5558. previousStrict = strict;
  5559. startToken = lookahead;
  5560. body = parseFunctionSourceElements();
  5561. if (first && strict && isRestrictedWord(param[0].name)) {
  5562. throwErrorTolerant(first, Messages.StrictParamName);
  5563. }
  5564. strict = previousStrict;
  5565. return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken);
  5566. }
  5567. function parseObjectPropertyKey() {
  5568. var token, startToken;
  5569. startToken = lookahead;
  5570. token = lex();
  5571. // Note: This function is called only from parseObjectProperty(), where
  5572. // EOF and Punctuator tokens are already filtered out.
  5573. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
  5574. if (strict && token.octal) {
  5575. throwErrorTolerant(token, Messages.StrictOctalLiteral);
  5576. }
  5577. return delegate.markEnd(delegate.createLiteral(token), startToken);
  5578. }
  5579. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  5580. }
  5581. function parseObjectProperty() {
  5582. var token, key, id, value, param, startToken;
  5583. token = lookahead;
  5584. startToken = lookahead;
  5585. if (token.type === Token.Identifier) {
  5586. id = parseObjectPropertyKey();
  5587. // Property Assignment: Getter and Setter.
  5588. if (token.value === 'get' && !match(':')) {
  5589. key = parseObjectPropertyKey();
  5590. expect('(');
  5591. expect(')');
  5592. value = parsePropertyFunction([]);
  5593. return delegate.markEnd(delegate.createProperty('get', key, value), startToken);
  5594. }
  5595. if (token.value === 'set' && !match(':')) {
  5596. key = parseObjectPropertyKey();
  5597. expect('(');
  5598. token = lookahead;
  5599. if (token.type !== Token.Identifier) {
  5600. expect(')');
  5601. throwErrorTolerant(token, Messages.UnexpectedToken, token.value);
  5602. value = parsePropertyFunction([]);
  5603. } else {
  5604. param = [ parseVariableIdentifier() ];
  5605. expect(')');
  5606. value = parsePropertyFunction(param, token);
  5607. }
  5608. return delegate.markEnd(delegate.createProperty('set', key, value), startToken);
  5609. }
  5610. expect(':');
  5611. value = parseAssignmentExpression();
  5612. return delegate.markEnd(delegate.createProperty('init', id, value), startToken);
  5613. }
  5614. if (token.type === Token.EOF || token.type === Token.Punctuator) {
  5615. throwUnexpected(token);
  5616. } else {
  5617. key = parseObjectPropertyKey();
  5618. expect(':');
  5619. value = parseAssignmentExpression();
  5620. return delegate.markEnd(delegate.createProperty('init', key, value), startToken);
  5621. }
  5622. }
  5623. function parseObjectInitialiser() {
  5624. var properties = [], property, name, key, kind, map = {}, toString = String, startToken;
  5625. startToken = lookahead;
  5626. expect('{');
  5627. while (!match('}')) {
  5628. property = parseObjectProperty();
  5629. if (property.key.type === Syntax.Identifier) {
  5630. name = property.key.name;
  5631. } else {
  5632. name = toString(property.key.value);
  5633. }
  5634. kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
  5635. key = '$' + name;
  5636. if (Object.prototype.hasOwnProperty.call(map, key)) {
  5637. if (map[key] === PropertyKind.Data) {
  5638. if (strict && kind === PropertyKind.Data) {
  5639. throwErrorTolerant({}, Messages.StrictDuplicateProperty);
  5640. } else if (kind !== PropertyKind.Data) {
  5641. throwErrorTolerant({}, Messages.AccessorDataProperty);
  5642. }
  5643. } else {
  5644. if (kind === PropertyKind.Data) {
  5645. throwErrorTolerant({}, Messages.AccessorDataProperty);
  5646. } else if (map[key] & kind) {
  5647. throwErrorTolerant({}, Messages.AccessorGetSet);
  5648. }
  5649. }
  5650. map[key] |= kind;
  5651. } else {
  5652. map[key] = kind;
  5653. }
  5654. properties.push(property);
  5655. if (!match('}')) {
  5656. expect(',');
  5657. }
  5658. }
  5659. expect('}');
  5660. return delegate.markEnd(delegate.createObjectExpression(properties), startToken);
  5661. }
  5662. // 11.1.6 The Grouping Operator
  5663. function parseGroupExpression() {
  5664. var expr;
  5665. expect('(');
  5666. expr = parseExpression();
  5667. expect(')');
  5668. return expr;
  5669. }
  5670. // 11.1 Primary Expressions
  5671. function parsePrimaryExpression() {
  5672. var type, token, expr, startToken;
  5673. if (match('(')) {
  5674. return parseGroupExpression();
  5675. }
  5676. if (match('[')) {
  5677. return parseArrayInitialiser();
  5678. }
  5679. if (match('{')) {
  5680. return parseObjectInitialiser();
  5681. }
  5682. type = lookahead.type;
  5683. startToken = lookahead;
  5684. if (type === Token.Identifier) {
  5685. expr = delegate.createIdentifier(lex().value);
  5686. } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  5687. if (strict && lookahead.octal) {
  5688. throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
  5689. }
  5690. expr = delegate.createLiteral(lex());
  5691. } else if (type === Token.Keyword) {
  5692. if (matchKeyword('function')) {
  5693. return parseFunctionExpression();
  5694. }
  5695. if (matchKeyword('this')) {
  5696. lex();
  5697. expr = delegate.createThisExpression();
  5698. } else {
  5699. throwUnexpected(lex());
  5700. }
  5701. } else if (type === Token.BooleanLiteral) {
  5702. token = lex();
  5703. token.value = (token.value === 'true');
  5704. expr = delegate.createLiteral(token);
  5705. } else if (type === Token.NullLiteral) {
  5706. token = lex();
  5707. token.value = null;
  5708. expr = delegate.createLiteral(token);
  5709. } else if (match('/') || match('/=')) {
  5710. if (typeof extra.tokens !== 'undefined') {
  5711. expr = delegate.createLiteral(collectRegex());
  5712. } else {
  5713. expr = delegate.createLiteral(scanRegExp());
  5714. }
  5715. peek();
  5716. } else {
  5717. throwUnexpected(lex());
  5718. }
  5719. return delegate.markEnd(expr, startToken);
  5720. }
  5721. // 11.2 Left-Hand-Side Expressions
  5722. function parseArguments() {
  5723. var args = [];
  5724. expect('(');
  5725. if (!match(')')) {
  5726. while (index < length) {
  5727. args.push(parseAssignmentExpression());
  5728. if (match(')')) {
  5729. break;
  5730. }
  5731. expect(',');
  5732. }
  5733. }
  5734. expect(')');
  5735. return args;
  5736. }
  5737. function parseNonComputedProperty() {
  5738. var token, startToken;
  5739. startToken = lookahead;
  5740. token = lex();
  5741. if (!isIdentifierName(token)) {
  5742. throwUnexpected(token);
  5743. }
  5744. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  5745. }
  5746. function parseNonComputedMember() {
  5747. expect('.');
  5748. return parseNonComputedProperty();
  5749. }
  5750. function parseComputedMember() {
  5751. var expr;
  5752. expect('[');
  5753. expr = parseExpression();
  5754. expect(']');
  5755. return expr;
  5756. }
  5757. function parseNewExpression() {
  5758. var callee, args, startToken;
  5759. startToken = lookahead;
  5760. expectKeyword('new');
  5761. callee = parseLeftHandSideExpression();
  5762. args = match('(') ? parseArguments() : [];
  5763. return delegate.markEnd(delegate.createNewExpression(callee, args), startToken);
  5764. }
  5765. function parseLeftHandSideExpressionAllowCall() {
  5766. var previousAllowIn, expr, args, property, startToken;
  5767. startToken = lookahead;
  5768. previousAllowIn = state.allowIn;
  5769. state.allowIn = true;
  5770. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  5771. state.allowIn = previousAllowIn;
  5772. for (;;) {
  5773. if (match('.')) {
  5774. property = parseNonComputedMember();
  5775. expr = delegate.createMemberExpression('.', expr, property);
  5776. } else if (match('(')) {
  5777. args = parseArguments();
  5778. expr = delegate.createCallExpression(expr, args);
  5779. } else if (match('[')) {
  5780. property = parseComputedMember();
  5781. expr = delegate.createMemberExpression('[', expr, property);
  5782. } else {
  5783. break;
  5784. }
  5785. delegate.markEnd(expr, startToken);
  5786. }
  5787. return expr;
  5788. }
  5789. function parseLeftHandSideExpression() {
  5790. var previousAllowIn, expr, property, startToken;
  5791. startToken = lookahead;
  5792. previousAllowIn = state.allowIn;
  5793. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  5794. state.allowIn = previousAllowIn;
  5795. while (match('.') || match('[')) {
  5796. if (match('[')) {
  5797. property = parseComputedMember();
  5798. expr = delegate.createMemberExpression('[', expr, property);
  5799. } else {
  5800. property = parseNonComputedMember();
  5801. expr = delegate.createMemberExpression('.', expr, property);
  5802. }
  5803. delegate.markEnd(expr, startToken);
  5804. }
  5805. return expr;
  5806. }
  5807. // 11.3 Postfix Expressions
  5808. function parsePostfixExpression() {
  5809. var expr, token, startToken = lookahead;
  5810. expr = parseLeftHandSideExpressionAllowCall();
  5811. if (lookahead.type === Token.Punctuator) {
  5812. if ((match('++') || match('--')) && !peekLineTerminator()) {
  5813. // 11.3.1, 11.3.2
  5814. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  5815. throwErrorTolerant({}, Messages.StrictLHSPostfix);
  5816. }
  5817. if (!isLeftHandSide(expr)) {
  5818. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  5819. }
  5820. token = lex();
  5821. expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken);
  5822. }
  5823. }
  5824. return expr;
  5825. }
  5826. // 11.4 Unary Operators
  5827. function parseUnaryExpression() {
  5828. var token, expr, startToken;
  5829. if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
  5830. expr = parsePostfixExpression();
  5831. } else if (match('++') || match('--')) {
  5832. startToken = lookahead;
  5833. token = lex();
  5834. expr = parseUnaryExpression();
  5835. // 11.4.4, 11.4.5
  5836. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  5837. throwErrorTolerant({}, Messages.StrictLHSPrefix);
  5838. }
  5839. if (!isLeftHandSide(expr)) {
  5840. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  5841. }
  5842. expr = delegate.createUnaryExpression(token.value, expr);
  5843. expr = delegate.markEnd(expr, startToken);
  5844. } else if (match('+') || match('-') || match('~') || match('!')) {
  5845. startToken = lookahead;
  5846. token = lex();
  5847. expr = parseUnaryExpression();
  5848. expr = delegate.createUnaryExpression(token.value, expr);
  5849. expr = delegate.markEnd(expr, startToken);
  5850. } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  5851. startToken = lookahead;
  5852. token = lex();
  5853. expr = parseUnaryExpression();
  5854. expr = delegate.createUnaryExpression(token.value, expr);
  5855. expr = delegate.markEnd(expr, startToken);
  5856. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  5857. throwErrorTolerant({}, Messages.StrictDelete);
  5858. }
  5859. } else {
  5860. expr = parsePostfixExpression();
  5861. }
  5862. return expr;
  5863. }
  5864. function binaryPrecedence(token, allowIn) {
  5865. var prec = 0;
  5866. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  5867. return 0;
  5868. }
  5869. switch (token.value) {
  5870. case '||':
  5871. prec = 1;
  5872. break;
  5873. case '&&':
  5874. prec = 2;
  5875. break;
  5876. case '|':
  5877. prec = 3;
  5878. break;
  5879. case '^':
  5880. prec = 4;
  5881. break;
  5882. case '&':
  5883. prec = 5;
  5884. break;
  5885. case '==':
  5886. case '!=':
  5887. case '===':
  5888. case '!==':
  5889. prec = 6;
  5890. break;
  5891. case '<':
  5892. case '>':
  5893. case '<=':
  5894. case '>=':
  5895. case 'instanceof':
  5896. prec = 7;
  5897. break;
  5898. case 'in':
  5899. prec = allowIn ? 7 : 0;
  5900. break;
  5901. case '<<':
  5902. case '>>':
  5903. case '>>>':
  5904. prec = 8;
  5905. break;
  5906. case '+':
  5907. case '-':
  5908. prec = 9;
  5909. break;
  5910. case '*':
  5911. case '/':
  5912. case '%':
  5913. prec = 11;
  5914. break;
  5915. default:
  5916. break;
  5917. }
  5918. return prec;
  5919. }
  5920. // 11.5 Multiplicative Operators
  5921. // 11.6 Additive Operators
  5922. // 11.7 Bitwise Shift Operators
  5923. // 11.8 Relational Operators
  5924. // 11.9 Equality Operators
  5925. // 11.10 Binary Bitwise Operators
  5926. // 11.11 Binary Logical Operators
  5927. function parseBinaryExpression() {
  5928. var marker, markers, expr, token, prec, stack, right, operator, left, i;
  5929. marker = lookahead;
  5930. left = parseUnaryExpression();
  5931. token = lookahead;
  5932. prec = binaryPrecedence(token, state.allowIn);
  5933. if (prec === 0) {
  5934. return left;
  5935. }
  5936. token.prec = prec;
  5937. lex();
  5938. markers = [marker, lookahead];
  5939. right = parseUnaryExpression();
  5940. stack = [left, token, right];
  5941. while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
  5942. // Reduce: make a binary expression from the three topmost entries.
  5943. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  5944. right = stack.pop();
  5945. operator = stack.pop().value;
  5946. left = stack.pop();
  5947. expr = delegate.createBinaryExpression(operator, left, right);
  5948. markers.pop();
  5949. marker = markers[markers.length - 1];
  5950. delegate.markEnd(expr, marker);
  5951. stack.push(expr);
  5952. }
  5953. // Shift.
  5954. token = lex();
  5955. token.prec = prec;
  5956. stack.push(token);
  5957. markers.push(lookahead);
  5958. expr = parseUnaryExpression();
  5959. stack.push(expr);
  5960. }
  5961. // Final reduce to clean-up the stack.
  5962. i = stack.length - 1;
  5963. expr = stack[i];
  5964. markers.pop();
  5965. while (i > 1) {
  5966. expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
  5967. i -= 2;
  5968. marker = markers.pop();
  5969. delegate.markEnd(expr, marker);
  5970. }
  5971. return expr;
  5972. }
  5973. // 11.12 Conditional Operator
  5974. function parseConditionalExpression() {
  5975. var expr, previousAllowIn, consequent, alternate, startToken;
  5976. startToken = lookahead;
  5977. expr = parseBinaryExpression();
  5978. if (match('?')) {
  5979. lex();
  5980. previousAllowIn = state.allowIn;
  5981. state.allowIn = true;
  5982. consequent = parseAssignmentExpression();
  5983. state.allowIn = previousAllowIn;
  5984. expect(':');
  5985. alternate = parseAssignmentExpression();
  5986. expr = delegate.createConditionalExpression(expr, consequent, alternate);
  5987. delegate.markEnd(expr, startToken);
  5988. }
  5989. return expr;
  5990. }
  5991. // 11.13 Assignment Operators
  5992. function parseAssignmentExpression() {
  5993. var token, left, right, node, startToken;
  5994. token = lookahead;
  5995. startToken = lookahead;
  5996. node = left = parseConditionalExpression();
  5997. if (matchAssign()) {
  5998. // LeftHandSideExpression
  5999. if (!isLeftHandSide(left)) {
  6000. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  6001. }
  6002. // 11.13.1
  6003. if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) {
  6004. throwErrorTolerant(token, Messages.StrictLHSAssignment);
  6005. }
  6006. token = lex();
  6007. right = parseAssignmentExpression();
  6008. node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken);
  6009. }
  6010. return node;
  6011. }
  6012. // 11.14 Comma Operator
  6013. function parseExpression() {
  6014. var expr, startToken = lookahead;
  6015. expr = parseAssignmentExpression();
  6016. if (match(',')) {
  6017. expr = delegate.createSequenceExpression([ expr ]);
  6018. while (index < length) {
  6019. if (!match(',')) {
  6020. break;
  6021. }
  6022. lex();
  6023. expr.expressions.push(parseAssignmentExpression());
  6024. }
  6025. delegate.markEnd(expr, startToken);
  6026. }
  6027. return expr;
  6028. }
  6029. // 12.1 Block
  6030. function parseStatementList() {
  6031. var list = [],
  6032. statement;
  6033. while (index < length) {
  6034. if (match('}')) {
  6035. break;
  6036. }
  6037. statement = parseSourceElement();
  6038. if (typeof statement === 'undefined') {
  6039. break;
  6040. }
  6041. list.push(statement);
  6042. }
  6043. return list;
  6044. }
  6045. function parseBlock() {
  6046. var block, startToken;
  6047. startToken = lookahead;
  6048. expect('{');
  6049. block = parseStatementList();
  6050. expect('}');
  6051. return delegate.markEnd(delegate.createBlockStatement(block), startToken);
  6052. }
  6053. // 12.2 Variable Statement
  6054. function parseVariableIdentifier() {
  6055. var token, startToken;
  6056. startToken = lookahead;
  6057. token = lex();
  6058. if (token.type !== Token.Identifier) {
  6059. throwUnexpected(token);
  6060. }
  6061. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  6062. }
  6063. function parseVariableDeclaration(kind) {
  6064. var init = null, id, startToken;
  6065. startToken = lookahead;
  6066. id = parseVariableIdentifier();
  6067. // 12.2.1
  6068. if (strict && isRestrictedWord(id.name)) {
  6069. throwErrorTolerant({}, Messages.StrictVarName);
  6070. }
  6071. if (kind === 'const') {
  6072. expect('=');
  6073. init = parseAssignmentExpression();
  6074. } else if (match('=')) {
  6075. lex();
  6076. init = parseAssignmentExpression();
  6077. }
  6078. return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken);
  6079. }
  6080. function parseVariableDeclarationList(kind) {
  6081. var list = [];
  6082. do {
  6083. list.push(parseVariableDeclaration(kind));
  6084. if (!match(',')) {
  6085. break;
  6086. }
  6087. lex();
  6088. } while (index < length);
  6089. return list;
  6090. }
  6091. function parseVariableStatement() {
  6092. var declarations;
  6093. expectKeyword('var');
  6094. declarations = parseVariableDeclarationList();
  6095. consumeSemicolon();
  6096. return delegate.createVariableDeclaration(declarations, 'var');
  6097. }
  6098. // kind may be `const` or `let`
  6099. // Both are experimental and not in the specification yet.
  6100. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  6101. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  6102. function parseConstLetDeclaration(kind) {
  6103. var declarations, startToken;
  6104. startToken = lookahead;
  6105. expectKeyword(kind);
  6106. declarations = parseVariableDeclarationList(kind);
  6107. consumeSemicolon();
  6108. return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken);
  6109. }
  6110. // 12.3 Empty Statement
  6111. function parseEmptyStatement() {
  6112. expect(';');
  6113. return delegate.createEmptyStatement();
  6114. }
  6115. // 12.4 Expression Statement
  6116. function parseExpressionStatement() {
  6117. var expr = parseExpression();
  6118. consumeSemicolon();
  6119. return delegate.createExpressionStatement(expr);
  6120. }
  6121. // 12.5 If statement
  6122. function parseIfStatement() {
  6123. var test, consequent, alternate;
  6124. expectKeyword('if');
  6125. expect('(');
  6126. test = parseExpression();
  6127. expect(')');
  6128. consequent = parseStatement();
  6129. if (matchKeyword('else')) {
  6130. lex();
  6131. alternate = parseStatement();
  6132. } else {
  6133. alternate = null;
  6134. }
  6135. return delegate.createIfStatement(test, consequent, alternate);
  6136. }
  6137. // 12.6 Iteration Statements
  6138. function parseDoWhileStatement() {
  6139. var body, test, oldInIteration;
  6140. expectKeyword('do');
  6141. oldInIteration = state.inIteration;
  6142. state.inIteration = true;
  6143. body = parseStatement();
  6144. state.inIteration = oldInIteration;
  6145. expectKeyword('while');
  6146. expect('(');
  6147. test = parseExpression();
  6148. expect(')');
  6149. if (match(';')) {
  6150. lex();
  6151. }
  6152. return delegate.createDoWhileStatement(body, test);
  6153. }
  6154. function parseWhileStatement() {
  6155. var test, body, oldInIteration;
  6156. expectKeyword('while');
  6157. expect('(');
  6158. test = parseExpression();
  6159. expect(')');
  6160. oldInIteration = state.inIteration;
  6161. state.inIteration = true;
  6162. body = parseStatement();
  6163. state.inIteration = oldInIteration;
  6164. return delegate.createWhileStatement(test, body);
  6165. }
  6166. function parseForVariableDeclaration() {
  6167. var token, declarations, startToken;
  6168. startToken = lookahead;
  6169. token = lex();
  6170. declarations = parseVariableDeclarationList();
  6171. return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken);
  6172. }
  6173. function parseForStatement() {
  6174. var init, test, update, left, right, body, oldInIteration;
  6175. init = test = update = null;
  6176. expectKeyword('for');
  6177. expect('(');
  6178. if (match(';')) {
  6179. lex();
  6180. } else {
  6181. if (matchKeyword('var') || matchKeyword('let')) {
  6182. state.allowIn = false;
  6183. init = parseForVariableDeclaration();
  6184. state.allowIn = true;
  6185. if (init.declarations.length === 1 && matchKeyword('in')) {
  6186. lex();
  6187. left = init;
  6188. right = parseExpression();
  6189. init = null;
  6190. }
  6191. } else {
  6192. state.allowIn = false;
  6193. init = parseExpression();
  6194. state.allowIn = true;
  6195. if (matchKeyword('in')) {
  6196. // LeftHandSideExpression
  6197. if (!isLeftHandSide(init)) {
  6198. throwErrorTolerant({}, Messages.InvalidLHSInForIn);
  6199. }
  6200. lex();
  6201. left = init;
  6202. right = parseExpression();
  6203. init = null;
  6204. }
  6205. }
  6206. if (typeof left === 'undefined') {
  6207. expect(';');
  6208. }
  6209. }
  6210. if (typeof left === 'undefined') {
  6211. if (!match(';')) {
  6212. test = parseExpression();
  6213. }
  6214. expect(';');
  6215. if (!match(')')) {
  6216. update = parseExpression();
  6217. }
  6218. }
  6219. expect(')');
  6220. oldInIteration = state.inIteration;
  6221. state.inIteration = true;
  6222. body = parseStatement();
  6223. state.inIteration = oldInIteration;
  6224. return (typeof left === 'undefined') ?
  6225. delegate.createForStatement(init, test, update, body) :
  6226. delegate.createForInStatement(left, right, body);
  6227. }
  6228. // 12.7 The continue statement
  6229. function parseContinueStatement() {
  6230. var label = null, key;
  6231. expectKeyword('continue');
  6232. // Optimize the most common form: 'continue;'.
  6233. if (source.charCodeAt(index) === 0x3B) {
  6234. lex();
  6235. if (!state.inIteration) {
  6236. throwError({}, Messages.IllegalContinue);
  6237. }
  6238. return delegate.createContinueStatement(null);
  6239. }
  6240. if (peekLineTerminator()) {
  6241. if (!state.inIteration) {
  6242. throwError({}, Messages.IllegalContinue);
  6243. }
  6244. return delegate.createContinueStatement(null);
  6245. }
  6246. if (lookahead.type === Token.Identifier) {
  6247. label = parseVariableIdentifier();
  6248. key = '$' + label.name;
  6249. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6250. throwError({}, Messages.UnknownLabel, label.name);
  6251. }
  6252. }
  6253. consumeSemicolon();
  6254. if (label === null && !state.inIteration) {
  6255. throwError({}, Messages.IllegalContinue);
  6256. }
  6257. return delegate.createContinueStatement(label);
  6258. }
  6259. // 12.8 The break statement
  6260. function parseBreakStatement() {
  6261. var label = null, key;
  6262. expectKeyword('break');
  6263. // Catch the very common case first: immediately a semicolon (U+003B).
  6264. if (source.charCodeAt(index) === 0x3B) {
  6265. lex();
  6266. if (!(state.inIteration || state.inSwitch)) {
  6267. throwError({}, Messages.IllegalBreak);
  6268. }
  6269. return delegate.createBreakStatement(null);
  6270. }
  6271. if (peekLineTerminator()) {
  6272. if (!(state.inIteration || state.inSwitch)) {
  6273. throwError({}, Messages.IllegalBreak);
  6274. }
  6275. return delegate.createBreakStatement(null);
  6276. }
  6277. if (lookahead.type === Token.Identifier) {
  6278. label = parseVariableIdentifier();
  6279. key = '$' + label.name;
  6280. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6281. throwError({}, Messages.UnknownLabel, label.name);
  6282. }
  6283. }
  6284. consumeSemicolon();
  6285. if (label === null && !(state.inIteration || state.inSwitch)) {
  6286. throwError({}, Messages.IllegalBreak);
  6287. }
  6288. return delegate.createBreakStatement(label);
  6289. }
  6290. // 12.9 The return statement
  6291. function parseReturnStatement() {
  6292. var argument = null;
  6293. expectKeyword('return');
  6294. if (!state.inFunctionBody) {
  6295. throwErrorTolerant({}, Messages.IllegalReturn);
  6296. }
  6297. // 'return' followed by a space and an identifier is very common.
  6298. if (source.charCodeAt(index) === 0x20) {
  6299. if (isIdentifierStart(source.charCodeAt(index + 1))) {
  6300. argument = parseExpression();
  6301. consumeSemicolon();
  6302. return delegate.createReturnStatement(argument);
  6303. }
  6304. }
  6305. if (peekLineTerminator()) {
  6306. return delegate.createReturnStatement(null);
  6307. }
  6308. if (!match(';')) {
  6309. if (!match('}') && lookahead.type !== Token.EOF) {
  6310. argument = parseExpression();
  6311. }
  6312. }
  6313. consumeSemicolon();
  6314. return delegate.createReturnStatement(argument);
  6315. }
  6316. // 12.10 The with statement
  6317. function parseWithStatement() {
  6318. var object, body;
  6319. if (strict) {
  6320. // TODO(ikarienator): Should we update the test cases instead?
  6321. skipComment();
  6322. throwErrorTolerant({}, Messages.StrictModeWith);
  6323. }
  6324. expectKeyword('with');
  6325. expect('(');
  6326. object = parseExpression();
  6327. expect(')');
  6328. body = parseStatement();
  6329. return delegate.createWithStatement(object, body);
  6330. }
  6331. // 12.10 The swith statement
  6332. function parseSwitchCase() {
  6333. var test, consequent = [], statement, startToken;
  6334. startToken = lookahead;
  6335. if (matchKeyword('default')) {
  6336. lex();
  6337. test = null;
  6338. } else {
  6339. expectKeyword('case');
  6340. test = parseExpression();
  6341. }
  6342. expect(':');
  6343. while (index < length) {
  6344. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  6345. break;
  6346. }
  6347. statement = parseStatement();
  6348. consequent.push(statement);
  6349. }
  6350. return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken);
  6351. }
  6352. function parseSwitchStatement() {
  6353. var discriminant, cases, clause, oldInSwitch, defaultFound;
  6354. expectKeyword('switch');
  6355. expect('(');
  6356. discriminant = parseExpression();
  6357. expect(')');
  6358. expect('{');
  6359. cases = [];
  6360. if (match('}')) {
  6361. lex();
  6362. return delegate.createSwitchStatement(discriminant, cases);
  6363. }
  6364. oldInSwitch = state.inSwitch;
  6365. state.inSwitch = true;
  6366. defaultFound = false;
  6367. while (index < length) {
  6368. if (match('}')) {
  6369. break;
  6370. }
  6371. clause = parseSwitchCase();
  6372. if (clause.test === null) {
  6373. if (defaultFound) {
  6374. throwError({}, Messages.MultipleDefaultsInSwitch);
  6375. }
  6376. defaultFound = true;
  6377. }
  6378. cases.push(clause);
  6379. }
  6380. state.inSwitch = oldInSwitch;
  6381. expect('}');
  6382. return delegate.createSwitchStatement(discriminant, cases);
  6383. }
  6384. // 12.13 The throw statement
  6385. function parseThrowStatement() {
  6386. var argument;
  6387. expectKeyword('throw');
  6388. if (peekLineTerminator()) {
  6389. throwError({}, Messages.NewlineAfterThrow);
  6390. }
  6391. argument = parseExpression();
  6392. consumeSemicolon();
  6393. return delegate.createThrowStatement(argument);
  6394. }
  6395. // 12.14 The try statement
  6396. function parseCatchClause() {
  6397. var param, body, startToken;
  6398. startToken = lookahead;
  6399. expectKeyword('catch');
  6400. expect('(');
  6401. if (match(')')) {
  6402. throwUnexpected(lookahead);
  6403. }
  6404. param = parseVariableIdentifier();
  6405. // 12.14.1
  6406. if (strict && isRestrictedWord(param.name)) {
  6407. throwErrorTolerant({}, Messages.StrictCatchVariable);
  6408. }
  6409. expect(')');
  6410. body = parseBlock();
  6411. return delegate.markEnd(delegate.createCatchClause(param, body), startToken);
  6412. }
  6413. function parseTryStatement() {
  6414. var block, handlers = [], finalizer = null;
  6415. expectKeyword('try');
  6416. block = parseBlock();
  6417. if (matchKeyword('catch')) {
  6418. handlers.push(parseCatchClause());
  6419. }
  6420. if (matchKeyword('finally')) {
  6421. lex();
  6422. finalizer = parseBlock();
  6423. }
  6424. if (handlers.length === 0 && !finalizer) {
  6425. throwError({}, Messages.NoCatchOrFinally);
  6426. }
  6427. return delegate.createTryStatement(block, [], handlers, finalizer);
  6428. }
  6429. // 12.15 The debugger statement
  6430. function parseDebuggerStatement() {
  6431. expectKeyword('debugger');
  6432. consumeSemicolon();
  6433. return delegate.createDebuggerStatement();
  6434. }
  6435. // 12 Statements
  6436. function parseStatement() {
  6437. var type = lookahead.type,
  6438. expr,
  6439. labeledBody,
  6440. key,
  6441. startToken;
  6442. if (type === Token.EOF) {
  6443. throwUnexpected(lookahead);
  6444. }
  6445. if (type === Token.Punctuator && lookahead.value === '{') {
  6446. return parseBlock();
  6447. }
  6448. startToken = lookahead;
  6449. if (type === Token.Punctuator) {
  6450. switch (lookahead.value) {
  6451. case ';':
  6452. return delegate.markEnd(parseEmptyStatement(), startToken);
  6453. case '(':
  6454. return delegate.markEnd(parseExpressionStatement(), startToken);
  6455. default:
  6456. break;
  6457. }
  6458. }
  6459. if (type === Token.Keyword) {
  6460. switch (lookahead.value) {
  6461. case 'break':
  6462. return delegate.markEnd(parseBreakStatement(), startToken);
  6463. case 'continue':
  6464. return delegate.markEnd(parseContinueStatement(), startToken);
  6465. case 'debugger':
  6466. return delegate.markEnd(parseDebuggerStatement(), startToken);
  6467. case 'do':
  6468. return delegate.markEnd(parseDoWhileStatement(), startToken);
  6469. case 'for':
  6470. return delegate.markEnd(parseForStatement(), startToken);
  6471. case 'function':
  6472. return delegate.markEnd(parseFunctionDeclaration(), startToken);
  6473. case 'if':
  6474. return delegate.markEnd(parseIfStatement(), startToken);
  6475. case 'return':
  6476. return delegate.markEnd(parseReturnStatement(), startToken);
  6477. case 'switch':
  6478. return delegate.markEnd(parseSwitchStatement(), startToken);
  6479. case 'throw':
  6480. return delegate.markEnd(parseThrowStatement(), startToken);
  6481. case 'try':
  6482. return delegate.markEnd(parseTryStatement(), startToken);
  6483. case 'var':
  6484. return delegate.markEnd(parseVariableStatement(), startToken);
  6485. case 'while':
  6486. return delegate.markEnd(parseWhileStatement(), startToken);
  6487. case 'with':
  6488. return delegate.markEnd(parseWithStatement(), startToken);
  6489. default:
  6490. break;
  6491. }
  6492. }
  6493. expr = parseExpression();
  6494. // 12.12 Labelled Statements
  6495. if ((expr.type === Syntax.Identifier) && match(':')) {
  6496. lex();
  6497. key = '$' + expr.name;
  6498. if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6499. throwError({}, Messages.Redeclaration, 'Label', expr.name);
  6500. }
  6501. state.labelSet[key] = true;
  6502. labeledBody = parseStatement();
  6503. delete state.labelSet[key];
  6504. return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken);
  6505. }
  6506. consumeSemicolon();
  6507. return delegate.markEnd(delegate.createExpressionStatement(expr), startToken);
  6508. }
  6509. // 13 Function Definition
  6510. function parseFunctionSourceElements() {
  6511. var sourceElement, sourceElements = [], token, directive, firstRestricted,
  6512. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken;
  6513. startToken = lookahead;
  6514. expect('{');
  6515. while (index < length) {
  6516. if (lookahead.type !== Token.StringLiteral) {
  6517. break;
  6518. }
  6519. token = lookahead;
  6520. sourceElement = parseSourceElement();
  6521. sourceElements.push(sourceElement);
  6522. if (sourceElement.expression.type !== Syntax.Literal) {
  6523. // this is not directive
  6524. break;
  6525. }
  6526. directive = source.slice(token.start + 1, token.end - 1);
  6527. if (directive === 'use strict') {
  6528. strict = true;
  6529. if (firstRestricted) {
  6530. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  6531. }
  6532. } else {
  6533. if (!firstRestricted && token.octal) {
  6534. firstRestricted = token;
  6535. }
  6536. }
  6537. }
  6538. oldLabelSet = state.labelSet;
  6539. oldInIteration = state.inIteration;
  6540. oldInSwitch = state.inSwitch;
  6541. oldInFunctionBody = state.inFunctionBody;
  6542. state.labelSet = {};
  6543. state.inIteration = false;
  6544. state.inSwitch = false;
  6545. state.inFunctionBody = true;
  6546. while (index < length) {
  6547. if (match('}')) {
  6548. break;
  6549. }
  6550. sourceElement = parseSourceElement();
  6551. if (typeof sourceElement === 'undefined') {
  6552. break;
  6553. }
  6554. sourceElements.push(sourceElement);
  6555. }
  6556. expect('}');
  6557. state.labelSet = oldLabelSet;
  6558. state.inIteration = oldInIteration;
  6559. state.inSwitch = oldInSwitch;
  6560. state.inFunctionBody = oldInFunctionBody;
  6561. return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken);
  6562. }
  6563. function parseParams(firstRestricted) {
  6564. var param, params = [], token, stricted, paramSet, key, message;
  6565. expect('(');
  6566. if (!match(')')) {
  6567. paramSet = {};
  6568. while (index < length) {
  6569. token = lookahead;
  6570. param = parseVariableIdentifier();
  6571. key = '$' + token.value;
  6572. if (strict) {
  6573. if (isRestrictedWord(token.value)) {
  6574. stricted = token;
  6575. message = Messages.StrictParamName;
  6576. }
  6577. if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
  6578. stricted = token;
  6579. message = Messages.StrictParamDupe;
  6580. }
  6581. } else if (!firstRestricted) {
  6582. if (isRestrictedWord(token.value)) {
  6583. firstRestricted = token;
  6584. message = Messages.StrictParamName;
  6585. } else if (isStrictModeReservedWord(token.value)) {
  6586. firstRestricted = token;
  6587. message = Messages.StrictReservedWord;
  6588. } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
  6589. firstRestricted = token;
  6590. message = Messages.StrictParamDupe;
  6591. }
  6592. }
  6593. params.push(param);
  6594. paramSet[key] = true;
  6595. if (match(')')) {
  6596. break;
  6597. }
  6598. expect(',');
  6599. }
  6600. }
  6601. expect(')');
  6602. return {
  6603. params: params,
  6604. stricted: stricted,
  6605. firstRestricted: firstRestricted,
  6606. message: message
  6607. };
  6608. }
  6609. function parseFunctionDeclaration() {
  6610. var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken;
  6611. startToken = lookahead;
  6612. expectKeyword('function');
  6613. token = lookahead;
  6614. id = parseVariableIdentifier();
  6615. if (strict) {
  6616. if (isRestrictedWord(token.value)) {
  6617. throwErrorTolerant(token, Messages.StrictFunctionName);
  6618. }
  6619. } else {
  6620. if (isRestrictedWord(token.value)) {
  6621. firstRestricted = token;
  6622. message = Messages.StrictFunctionName;
  6623. } else if (isStrictModeReservedWord(token.value)) {
  6624. firstRestricted = token;
  6625. message = Messages.StrictReservedWord;
  6626. }
  6627. }
  6628. tmp = parseParams(firstRestricted);
  6629. params = tmp.params;
  6630. stricted = tmp.stricted;
  6631. firstRestricted = tmp.firstRestricted;
  6632. if (tmp.message) {
  6633. message = tmp.message;
  6634. }
  6635. previousStrict = strict;
  6636. body = parseFunctionSourceElements();
  6637. if (strict && firstRestricted) {
  6638. throwError(firstRestricted, message);
  6639. }
  6640. if (strict && stricted) {
  6641. throwErrorTolerant(stricted, message);
  6642. }
  6643. strict = previousStrict;
  6644. return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken);
  6645. }
  6646. function parseFunctionExpression() {
  6647. var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken;
  6648. startToken = lookahead;
  6649. expectKeyword('function');
  6650. if (!match('(')) {
  6651. token = lookahead;
  6652. id = parseVariableIdentifier();
  6653. if (strict) {
  6654. if (isRestrictedWord(token.value)) {
  6655. throwErrorTolerant(token, Messages.StrictFunctionName);
  6656. }
  6657. } else {
  6658. if (isRestrictedWord(token.value)) {
  6659. firstRestricted = token;
  6660. message = Messages.StrictFunctionName;
  6661. } else if (isStrictModeReservedWord(token.value)) {
  6662. firstRestricted = token;
  6663. message = Messages.StrictReservedWord;
  6664. }
  6665. }
  6666. }
  6667. tmp = parseParams(firstRestricted);
  6668. params = tmp.params;
  6669. stricted = tmp.stricted;
  6670. firstRestricted = tmp.firstRestricted;
  6671. if (tmp.message) {
  6672. message = tmp.message;
  6673. }
  6674. previousStrict = strict;
  6675. body = parseFunctionSourceElements();
  6676. if (strict && firstRestricted) {
  6677. throwError(firstRestricted, message);
  6678. }
  6679. if (strict && stricted) {
  6680. throwErrorTolerant(stricted, message);
  6681. }
  6682. strict = previousStrict;
  6683. return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken);
  6684. }
  6685. // 14 Program
  6686. function parseSourceElement() {
  6687. if (lookahead.type === Token.Keyword) {
  6688. switch (lookahead.value) {
  6689. case 'const':
  6690. case 'let':
  6691. return parseConstLetDeclaration(lookahead.value);
  6692. case 'function':
  6693. return parseFunctionDeclaration();
  6694. default:
  6695. return parseStatement();
  6696. }
  6697. }
  6698. if (lookahead.type !== Token.EOF) {
  6699. return parseStatement();
  6700. }
  6701. }
  6702. function parseSourceElements() {
  6703. var sourceElement, sourceElements = [], token, directive, firstRestricted;
  6704. while (index < length) {
  6705. token = lookahead;
  6706. if (token.type !== Token.StringLiteral) {
  6707. break;
  6708. }
  6709. sourceElement = parseSourceElement();
  6710. sourceElements.push(sourceElement);
  6711. if (sourceElement.expression.type !== Syntax.Literal) {
  6712. // this is not directive
  6713. break;
  6714. }
  6715. directive = source.slice(token.start + 1, token.end - 1);
  6716. if (directive === 'use strict') {
  6717. strict = true;
  6718. if (firstRestricted) {
  6719. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  6720. }
  6721. } else {
  6722. if (!firstRestricted && token.octal) {
  6723. firstRestricted = token;
  6724. }
  6725. }
  6726. }
  6727. while (index < length) {
  6728. sourceElement = parseSourceElement();
  6729. /* istanbul ignore if */
  6730. if (typeof sourceElement === 'undefined') {
  6731. break;
  6732. }
  6733. sourceElements.push(sourceElement);
  6734. }
  6735. return sourceElements;
  6736. }
  6737. function parseProgram() {
  6738. var body, startToken;
  6739. skipComment();
  6740. peek();
  6741. startToken = lookahead;
  6742. strict = false;
  6743. body = parseSourceElements();
  6744. return delegate.markEnd(delegate.createProgram(body), startToken);
  6745. }
  6746. function filterTokenLocation() {
  6747. var i, entry, token, tokens = [];
  6748. for (i = 0; i < extra.tokens.length; ++i) {
  6749. entry = extra.tokens[i];
  6750. token = {
  6751. type: entry.type,
  6752. value: entry.value
  6753. };
  6754. if (extra.range) {
  6755. token.range = entry.range;
  6756. }
  6757. if (extra.loc) {
  6758. token.loc = entry.loc;
  6759. }
  6760. tokens.push(token);
  6761. }
  6762. extra.tokens = tokens;
  6763. }
  6764. function tokenize(code, options) {
  6765. var toString,
  6766. token,
  6767. tokens;
  6768. toString = String;
  6769. if (typeof code !== 'string' && !(code instanceof String)) {
  6770. code = toString(code);
  6771. }
  6772. delegate = SyntaxTreeDelegate;
  6773. source = code;
  6774. index = 0;
  6775. lineNumber = (source.length > 0) ? 1 : 0;
  6776. lineStart = 0;
  6777. length = source.length;
  6778. lookahead = null;
  6779. state = {
  6780. allowIn: true,
  6781. labelSet: {},
  6782. inFunctionBody: false,
  6783. inIteration: false,
  6784. inSwitch: false,
  6785. lastCommentStart: -1
  6786. };
  6787. extra = {};
  6788. // Options matching.
  6789. options = options || {};
  6790. // Of course we collect tokens here.
  6791. options.tokens = true;
  6792. extra.tokens = [];
  6793. extra.tokenize = true;
  6794. // The following two fields are necessary to compute the Regex tokens.
  6795. extra.openParenToken = -1;
  6796. extra.openCurlyToken = -1;
  6797. extra.range = (typeof options.range === 'boolean') && options.range;
  6798. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  6799. if (typeof options.comment === 'boolean' && options.comment) {
  6800. extra.comments = [];
  6801. }
  6802. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  6803. extra.errors = [];
  6804. }
  6805. try {
  6806. peek();
  6807. if (lookahead.type === Token.EOF) {
  6808. return extra.tokens;
  6809. }
  6810. token = lex();
  6811. while (lookahead.type !== Token.EOF) {
  6812. try {
  6813. token = lex();
  6814. } catch (lexError) {
  6815. token = lookahead;
  6816. if (extra.errors) {
  6817. extra.errors.push(lexError);
  6818. // We have to break on the first error
  6819. // to avoid infinite loops.
  6820. break;
  6821. } else {
  6822. throw lexError;
  6823. }
  6824. }
  6825. }
  6826. filterTokenLocation();
  6827. tokens = extra.tokens;
  6828. if (typeof extra.comments !== 'undefined') {
  6829. tokens.comments = extra.comments;
  6830. }
  6831. if (typeof extra.errors !== 'undefined') {
  6832. tokens.errors = extra.errors;
  6833. }
  6834. } catch (e) {
  6835. throw e;
  6836. } finally {
  6837. extra = {};
  6838. }
  6839. return tokens;
  6840. }
  6841. function parse(code, options) {
  6842. var program, toString;
  6843. toString = String;
  6844. if (typeof code !== 'string' && !(code instanceof String)) {
  6845. code = toString(code);
  6846. }
  6847. delegate = SyntaxTreeDelegate;
  6848. source = code;
  6849. index = 0;
  6850. lineNumber = (source.length > 0) ? 1 : 0;
  6851. lineStart = 0;
  6852. length = source.length;
  6853. lookahead = null;
  6854. state = {
  6855. allowIn: true,
  6856. labelSet: {},
  6857. inFunctionBody: false,
  6858. inIteration: false,
  6859. inSwitch: false,
  6860. lastCommentStart: -1
  6861. };
  6862. extra = {};
  6863. if (typeof options !== 'undefined') {
  6864. extra.range = (typeof options.range === 'boolean') && options.range;
  6865. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  6866. extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
  6867. if (extra.loc && options.source !== null && options.source !== undefined) {
  6868. extra.source = toString(options.source);
  6869. }
  6870. if (typeof options.tokens === 'boolean' && options.tokens) {
  6871. extra.tokens = [];
  6872. }
  6873. if (typeof options.comment === 'boolean' && options.comment) {
  6874. extra.comments = [];
  6875. }
  6876. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  6877. extra.errors = [];
  6878. }
  6879. if (extra.attachComment) {
  6880. extra.range = true;
  6881. extra.comments = [];
  6882. extra.bottomRightStack = [];
  6883. extra.trailingComments = [];
  6884. extra.leadingComments = [];
  6885. }
  6886. }
  6887. try {
  6888. program = parseProgram();
  6889. if (typeof extra.comments !== 'undefined') {
  6890. program.comments = extra.comments;
  6891. }
  6892. if (typeof extra.tokens !== 'undefined') {
  6893. filterTokenLocation();
  6894. program.tokens = extra.tokens;
  6895. }
  6896. if (typeof extra.errors !== 'undefined') {
  6897. program.errors = extra.errors;
  6898. }
  6899. } catch (e) {
  6900. throw e;
  6901. } finally {
  6902. extra = {};
  6903. }
  6904. return program;
  6905. }
  6906. // Sync with *.json manifests.
  6907. exports.version = '1.2.2';
  6908. exports.tokenize = tokenize;
  6909. exports.parse = parse;
  6910. // Deep copy.
  6911. /* istanbul ignore next */
  6912. exports.Syntax = (function () {
  6913. var name, types = {};
  6914. if (typeof Object.create === 'function') {
  6915. types = Object.create(null);
  6916. }
  6917. for (name in Syntax) {
  6918. if (Syntax.hasOwnProperty(name)) {
  6919. types[name] = Syntax[name];
  6920. }
  6921. }
  6922. if (typeof Object.freeze === 'function') {
  6923. Object.freeze(types);
  6924. }
  6925. return types;
  6926. }());
  6927. }));
  6928. /* vim: set sw=4 ts=4 et tw=80 : */
  6929. /**
  6930. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  6931. * Available via the MIT or new BSD license.
  6932. * see: http://github.com/jrburke/requirejs for details
  6933. */
  6934. /*global define, Reflect */
  6935. /*
  6936. * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
  6937. * and the recursive nature of esprima can cause it to overflow pretty
  6938. * quickly. So favor it built in Reflect parser:
  6939. * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  6940. */
  6941. define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
  6942. if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
  6943. return Reflect;
  6944. } else {
  6945. return esprima;
  6946. }
  6947. });
  6948. define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
  6949. /**
  6950. * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
  6951. * All rights reserved.
  6952. *
  6953. * Redistribution and use in source and binary forms, with or without
  6954. * modification, are permitted provided that the following conditions
  6955. * are met:
  6956. *
  6957. * * Redistributions of source code must retain the above
  6958. * copyright notice, this list of conditions and the following
  6959. * disclaimer.
  6960. *
  6961. * * Redistributions in binary form must reproduce the above
  6962. * copyright notice, this list of conditions and the following
  6963. * disclaimer in the documentation and/or other materials
  6964. * provided with the distribution.
  6965. *
  6966. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
  6967. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6968. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  6969. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  6970. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  6971. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  6972. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  6973. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6974. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  6975. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  6976. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6977. * SUCH DAMAGE.
  6978. */
  6979. /**
  6980. * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
  6981. * >UglifyJS</a> with consolidation of null, Boolean, and String values.
  6982. * <p>Also known as aliasing, this feature has been deprecated in <a href=
  6983. * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
  6984. * initial release, where it is unavailable from the <abbr title=
  6985. * "command line interface">CLI</a>. The Closure Compiler allows one to log and
  6986. * influence this process. In contrast, this implementation does not introduce
  6987. * any variable declarations in global code and derives String values from
  6988. * identifier names used as property accessors.</p>
  6989. * <p>Consolidating literals may worsen the data compression ratio when an <a
  6990. * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
  6991. * transformation</a> is applied. For instance, <a href=
  6992. * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
  6993. * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
  6994. * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
  6995. * then compressed to 33154 bytes (13.36% of the original) using <a href=
  6996. * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
  6997. * version of UglifyJS 1.2.5 patched with the implementation of consolidation
  6998. * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
  6999. * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
  7000. * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
  7001. * 33154 bytes).</p>
  7002. * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
  7003. * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
  7004. * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
  7005. * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
  7006. * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
  7007. * discouraged use of the {@code function} tag and the {@code namespace} tag).
  7008. * 100% typed for the <a href=
  7009. * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
  7010. * >Closure Compiler Version 1741</a>.</p>
  7011. * <p>Should you find this software useful, please consider <a href=
  7012. * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
  7013. * >a donation</a>.</p>
  7014. * @author follow.me@RGustBardon (Robert Gust-Bardon)
  7015. * @supported Tested with:
  7016. * <ul>
  7017. * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
  7018. * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
  7019. * v1.2.5</a>.</li>
  7020. * </ul>
  7021. */
  7022. /*global console:false, exports:true, module:false, require:false */
  7023. /*jshint sub:true */
  7024. /**
  7025. * Consolidates null, Boolean, and String values found inside an <abbr title=
  7026. * "abstract syntax tree">AST</abbr>.
  7027. * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
  7028. * representing an <abbr title="abstract syntax tree">AST</abbr>.
  7029. * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
  7030. * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
  7031. * String values consolidated.
  7032. */
  7033. // TODO(user) Consolidation of mathematical values found in numeric literals.
  7034. // TODO(user) Unconsolidation.
  7035. // TODO(user) Consolidation of ECMA-262 6th Edition programs.
  7036. // TODO(user) Rewrite in ECMA-262 6th Edition.
  7037. exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
  7038. 'use strict';
  7039. /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
  7040. latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
  7041. onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
  7042. sub:false, trailing:true */
  7043. var _,
  7044. /**
  7045. * A record consisting of data about one or more source elements.
  7046. * @constructor
  7047. * @nosideeffects
  7048. */
  7049. TSourceElementsData = function() {
  7050. /**
  7051. * The category of the elements.
  7052. * @type {number}
  7053. * @see ESourceElementCategories
  7054. */
  7055. this.nCategory = ESourceElementCategories.N_OTHER;
  7056. /**
  7057. * The number of occurrences (within the elements) of each primitive
  7058. * value that could be consolidated.
  7059. * @type {!Array.<!Object.<string, number>>}
  7060. */
  7061. this.aCount = [];
  7062. this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
  7063. this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
  7064. this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
  7065. {};
  7066. /**
  7067. * Identifier names found within the elements.
  7068. * @type {!Array.<string>}
  7069. */
  7070. this.aIdentifiers = [];
  7071. /**
  7072. * Prefixed representation Strings of each primitive value that could be
  7073. * consolidated within the elements.
  7074. * @type {!Array.<string>}
  7075. */
  7076. this.aPrimitiveValues = [];
  7077. },
  7078. /**
  7079. * A record consisting of data about a primitive value that could be
  7080. * consolidated.
  7081. * @constructor
  7082. * @nosideeffects
  7083. */
  7084. TPrimitiveValue = function() {
  7085. /**
  7086. * The difference in the number of terminal symbols between the original
  7087. * source text and the one with the primitive value consolidated. If the
  7088. * difference is positive, the primitive value is considered worthwhile.
  7089. * @type {number}
  7090. */
  7091. this.nSaving = 0;
  7092. /**
  7093. * An identifier name of the variable that will be declared and assigned
  7094. * the primitive value if the primitive value is consolidated.
  7095. * @type {string}
  7096. */
  7097. this.sName = '';
  7098. },
  7099. /**
  7100. * A record consisting of data on what to consolidate within the range of
  7101. * source elements that is currently being considered.
  7102. * @constructor
  7103. * @nosideeffects
  7104. */
  7105. TSolution = function() {
  7106. /**
  7107. * An object whose keys are prefixed representation Strings of each
  7108. * primitive value that could be consolidated within the elements and
  7109. * whose values are corresponding data about those primitive values.
  7110. * @type {!Object.<string, {nSaving: number, sName: string}>}
  7111. * @see TPrimitiveValue
  7112. */
  7113. this.oPrimitiveValues = {};
  7114. /**
  7115. * The difference in the number of terminal symbols between the original
  7116. * source text and the one with all the worthwhile primitive values
  7117. * consolidated.
  7118. * @type {number}
  7119. * @see TPrimitiveValue#nSaving
  7120. */
  7121. this.nSavings = 0;
  7122. },
  7123. /**
  7124. * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
  7125. * in UglifyJS.
  7126. * @namespace
  7127. * @type {!TProcessor}
  7128. */
  7129. oProcessor = (/** @type {!TProcessor} */ require('./process')),
  7130. /**
  7131. * A record consisting of a number of constants that represent the
  7132. * difference in the number of terminal symbols between a source text with
  7133. * a modified syntactic code unit and the original one.
  7134. * @namespace
  7135. * @type {!Object.<string, number>}
  7136. */
  7137. oWeights = {
  7138. /**
  7139. * The difference in the number of punctuators required by the bracket
  7140. * notation and the dot notation.
  7141. * <p><code>'[]'.length - '.'.length</code></p>
  7142. * @const
  7143. * @type {number}
  7144. */
  7145. N_PROPERTY_ACCESSOR: 1,
  7146. /**
  7147. * The number of punctuators required by a variable declaration with an
  7148. * initialiser.
  7149. * <p><code>':'.length + ';'.length</code></p>
  7150. * @const
  7151. * @type {number}
  7152. */
  7153. N_VARIABLE_DECLARATION: 2,
  7154. /**
  7155. * The number of terminal symbols required to introduce a variable
  7156. * statement (excluding its variable declaration list).
  7157. * <p><code>'var '.length</code></p>
  7158. * @const
  7159. * @type {number}
  7160. */
  7161. N_VARIABLE_STATEMENT_AFFIXATION: 4,
  7162. /**
  7163. * The number of terminal symbols needed to enclose source elements
  7164. * within a function call with no argument values to a function with an
  7165. * empty parameter list.
  7166. * <p><code>'(function(){}());'.length</code></p>
  7167. * @const
  7168. * @type {number}
  7169. */
  7170. N_CLOSURE: 17
  7171. },
  7172. /**
  7173. * Categories of primary expressions from which primitive values that
  7174. * could be consolidated are derivable.
  7175. * @namespace
  7176. * @enum {number}
  7177. */
  7178. EPrimaryExpressionCategories = {
  7179. /**
  7180. * Identifier names used as property accessors.
  7181. * @type {number}
  7182. */
  7183. N_IDENTIFIER_NAMES: 0,
  7184. /**
  7185. * String literals.
  7186. * @type {number}
  7187. */
  7188. N_STRING_LITERALS: 1,
  7189. /**
  7190. * Null and Boolean literals.
  7191. * @type {number}
  7192. */
  7193. N_NULL_AND_BOOLEAN_LITERALS: 2
  7194. },
  7195. /**
  7196. * Prefixes of primitive values that could be consolidated.
  7197. * The String values of the prefixes must have same number of characters.
  7198. * The prefixes must not be used in any properties defined in any version
  7199. * of <a href=
  7200. * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
  7201. * >ECMA-262</a>.
  7202. * @namespace
  7203. * @enum {string}
  7204. */
  7205. EValuePrefixes = {
  7206. /**
  7207. * Identifies String values.
  7208. * @type {string}
  7209. */
  7210. S_STRING: '#S',
  7211. /**
  7212. * Identifies null and Boolean values.
  7213. * @type {string}
  7214. */
  7215. S_SYMBOLIC: '#O'
  7216. },
  7217. /**
  7218. * Categories of source elements in terms of their appropriateness of
  7219. * having their primitive values consolidated.
  7220. * @namespace
  7221. * @enum {number}
  7222. */
  7223. ESourceElementCategories = {
  7224. /**
  7225. * Identifies a source element that includes the <a href=
  7226. * "http://es5.github.com/#x12.10">{@code with}</a> statement.
  7227. * @type {number}
  7228. */
  7229. N_WITH: 0,
  7230. /**
  7231. * Identifies a source element that includes the <a href=
  7232. * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
  7233. * @type {number}
  7234. */
  7235. N_EVAL: 1,
  7236. /**
  7237. * Identifies a source element that must be excluded from the process
  7238. * unless its whole scope is examined.
  7239. * @type {number}
  7240. */
  7241. N_EXCLUDABLE: 2,
  7242. /**
  7243. * Identifies source elements not posing any problems.
  7244. * @type {number}
  7245. */
  7246. N_OTHER: 3
  7247. },
  7248. /**
  7249. * The list of literals (other than the String ones) whose primitive
  7250. * values can be consolidated.
  7251. * @const
  7252. * @type {!Array.<string>}
  7253. */
  7254. A_OTHER_SUBSTITUTABLE_LITERALS = [
  7255. 'null', // The null literal.
  7256. 'false', // The Boolean literal {@code false}.
  7257. 'true' // The Boolean literal {@code true}.
  7258. ];
  7259. (/**
  7260. * Consolidates all worthwhile primitive values in a syntactic code unit.
  7261. * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
  7262. * representing the branch of the abstract syntax tree representing the
  7263. * syntactic code unit along with its scope.
  7264. * @see TPrimitiveValue#nSaving
  7265. */
  7266. function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
  7267. var _,
  7268. /**
  7269. * Indicates whether the syntactic code unit represents global code.
  7270. * @type {boolean}
  7271. */
  7272. bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
  7273. /**
  7274. * Indicates whether the whole scope is being examined.
  7275. * @type {boolean}
  7276. */
  7277. bIsWhollyExaminable = !bIsGlobal,
  7278. /**
  7279. * An array-like object representing source elements that constitute a
  7280. * syntactic code unit.
  7281. * @type {!TSyntacticCodeUnit}
  7282. */
  7283. oSourceElements,
  7284. /**
  7285. * A record consisting of data about the source element that is
  7286. * currently being examined.
  7287. * @type {!TSourceElementsData}
  7288. */
  7289. oSourceElementData,
  7290. /**
  7291. * The scope of the syntactic code unit.
  7292. * @type {!TScope}
  7293. */
  7294. oScope,
  7295. /**
  7296. * An instance of an object that allows the traversal of an <abbr
  7297. * title="abstract syntax tree">AST</abbr>.
  7298. * @type {!TWalker}
  7299. */
  7300. oWalker,
  7301. /**
  7302. * An object encompassing collections of functions used during the
  7303. * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
  7304. * @namespace
  7305. * @type {!Object.<string, !Object.<string, function(...[*])>>}
  7306. */
  7307. oWalkers = {
  7308. /**
  7309. * A collection of functions used during the surveyance of source
  7310. * elements.
  7311. * @namespace
  7312. * @type {!Object.<string, function(...[*])>}
  7313. */
  7314. oSurveySourceElement: {
  7315. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7316. /**
  7317. * Classifies the source element as excludable if it does not
  7318. * contain a {@code with} statement or the {@code eval} identifier
  7319. * name. Adds the identifier of the function and its formal
  7320. * parameters to the list of identifier names found.
  7321. * @param {string} sIdentifier The identifier of the function.
  7322. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7323. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7324. */
  7325. 'defun': function(
  7326. sIdentifier,
  7327. aFormalParameterList,
  7328. oFunctionBody) {
  7329. fClassifyAsExcludable();
  7330. fAddIdentifier(sIdentifier);
  7331. aFormalParameterList.forEach(fAddIdentifier);
  7332. },
  7333. /**
  7334. * Increments the count of the number of occurrences of the String
  7335. * value that is equivalent to the sequence of terminal symbols
  7336. * that constitute the encountered identifier name.
  7337. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  7338. * MemberExpression.
  7339. * @param {string} sIdentifierName The identifier name used as the
  7340. * property accessor.
  7341. * @return {!Array} The encountered branch of an <abbr title=
  7342. * "abstract syntax tree">AST</abbr> with its nonterminal
  7343. * MemberExpression traversed.
  7344. */
  7345. 'dot': function(oExpression, sIdentifierName) {
  7346. fCountPrimaryExpression(
  7347. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
  7348. EValuePrefixes.S_STRING + sIdentifierName);
  7349. return ['dot', oWalker.walk(oExpression), sIdentifierName];
  7350. },
  7351. /**
  7352. * Adds the optional identifier of the function and its formal
  7353. * parameters to the list of identifier names found.
  7354. * @param {?string} sIdentifier The optional identifier of the
  7355. * function.
  7356. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7357. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7358. */
  7359. 'function': function(
  7360. sIdentifier,
  7361. aFormalParameterList,
  7362. oFunctionBody) {
  7363. if ('string' === typeof sIdentifier) {
  7364. fAddIdentifier(sIdentifier);
  7365. }
  7366. aFormalParameterList.forEach(fAddIdentifier);
  7367. },
  7368. /**
  7369. * Either increments the count of the number of occurrences of the
  7370. * encountered null or Boolean value or classifies a source element
  7371. * as containing the {@code eval} identifier name.
  7372. * @param {string} sIdentifier The identifier encountered.
  7373. */
  7374. 'name': function(sIdentifier) {
  7375. if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
  7376. fCountPrimaryExpression(
  7377. EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
  7378. EValuePrefixes.S_SYMBOLIC + sIdentifier);
  7379. } else {
  7380. if ('eval' === sIdentifier) {
  7381. oSourceElementData.nCategory =
  7382. ESourceElementCategories.N_EVAL;
  7383. }
  7384. fAddIdentifier(sIdentifier);
  7385. }
  7386. },
  7387. /**
  7388. * Classifies the source element as excludable if it does not
  7389. * contain a {@code with} statement or the {@code eval} identifier
  7390. * name.
  7391. * @param {TSyntacticCodeUnit} oExpression The expression whose
  7392. * value is to be returned.
  7393. */
  7394. 'return': function(oExpression) {
  7395. fClassifyAsExcludable();
  7396. },
  7397. /**
  7398. * Increments the count of the number of occurrences of the
  7399. * encountered String value.
  7400. * @param {string} sStringValue The String value of the string
  7401. * literal encountered.
  7402. */
  7403. 'string': function(sStringValue) {
  7404. if (sStringValue.length > 0) {
  7405. fCountPrimaryExpression(
  7406. EPrimaryExpressionCategories.N_STRING_LITERALS,
  7407. EValuePrefixes.S_STRING + sStringValue);
  7408. }
  7409. },
  7410. /**
  7411. * Adds the identifier reserved for an exception to the list of
  7412. * identifier names found.
  7413. * @param {!TSyntacticCodeUnit} oTry A block of code in which an
  7414. * exception can occur.
  7415. * @param {Array} aCatch The identifier reserved for an exception
  7416. * and a block of code to handle the exception.
  7417. * @param {TSyntacticCodeUnit} oFinally An optional block of code
  7418. * to be evaluated regardless of whether an exception occurs.
  7419. */
  7420. 'try': function(oTry, aCatch, oFinally) {
  7421. if (Array.isArray(aCatch)) {
  7422. fAddIdentifier(aCatch[0]);
  7423. }
  7424. },
  7425. /**
  7426. * Classifies the source element as excludable if it does not
  7427. * contain a {@code with} statement or the {@code eval} identifier
  7428. * name. Adds the identifier of each declared variable to the list
  7429. * of identifier names found.
  7430. * @param {!Array.<!Array>} aVariableDeclarationList Variable
  7431. * declarations.
  7432. */
  7433. 'var': function(aVariableDeclarationList) {
  7434. fClassifyAsExcludable();
  7435. aVariableDeclarationList.forEach(fAddVariable);
  7436. },
  7437. /**
  7438. * Classifies a source element as containing the {@code with}
  7439. * statement.
  7440. * @param {!TSyntacticCodeUnit} oExpression An expression whose
  7441. * value is to be converted to a value of type Object and
  7442. * become the binding object of a new object environment
  7443. * record of a new lexical environment in which the statement
  7444. * is to be executed.
  7445. * @param {!TSyntacticCodeUnit} oStatement The statement to be
  7446. * executed in the augmented lexical environment.
  7447. * @return {!Array} An empty array to stop the traversal.
  7448. */
  7449. 'with': function(oExpression, oStatement) {
  7450. oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
  7451. return [];
  7452. }
  7453. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7454. },
  7455. /**
  7456. * A collection of functions used while looking for nested functions.
  7457. * @namespace
  7458. * @type {!Object.<string, function(...[*])>}
  7459. */
  7460. oExamineFunctions: {
  7461. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7462. /**
  7463. * Orders an examination of a nested function declaration.
  7464. * @this {!TSyntacticCodeUnit} An array-like object representing
  7465. * the branch of an <abbr title="abstract syntax tree"
  7466. * >AST</abbr> representing the syntactic code unit along with
  7467. * its scope.
  7468. * @return {!Array} An empty array to stop the traversal.
  7469. */
  7470. 'defun': function() {
  7471. fExamineSyntacticCodeUnit(this);
  7472. return [];
  7473. },
  7474. /**
  7475. * Orders an examination of a nested function expression.
  7476. * @this {!TSyntacticCodeUnit} An array-like object representing
  7477. * the branch of an <abbr title="abstract syntax tree"
  7478. * >AST</abbr> representing the syntactic code unit along with
  7479. * its scope.
  7480. * @return {!Array} An empty array to stop the traversal.
  7481. */
  7482. 'function': function() {
  7483. fExamineSyntacticCodeUnit(this);
  7484. return [];
  7485. }
  7486. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7487. }
  7488. },
  7489. /**
  7490. * Records containing data about source elements.
  7491. * @type {Array.<TSourceElementsData>}
  7492. */
  7493. aSourceElementsData = [],
  7494. /**
  7495. * The index (in the source text order) of the source element
  7496. * immediately following a <a href="http://es5.github.com/#x14.1"
  7497. * >Directive Prologue</a>.
  7498. * @type {number}
  7499. */
  7500. nAfterDirectivePrologue = 0,
  7501. /**
  7502. * The index (in the source text order) of the source element that is
  7503. * currently being considered.
  7504. * @type {number}
  7505. */
  7506. nPosition,
  7507. /**
  7508. * The index (in the source text order) of the source element that is
  7509. * the last element of the range of source elements that is currently
  7510. * being considered.
  7511. * @type {(undefined|number)}
  7512. */
  7513. nTo,
  7514. /**
  7515. * Initiates the traversal of a source element.
  7516. * @param {!TWalker} oWalker An instance of an object that allows the
  7517. * traversal of an abstract syntax tree.
  7518. * @param {!TSyntacticCodeUnit} oSourceElement A source element from
  7519. * which the traversal should commence.
  7520. * @return {function(): !TSyntacticCodeUnit} A function that is able to
  7521. * initiate the traversal from a given source element.
  7522. */
  7523. cContext = function(oWalker, oSourceElement) {
  7524. /**
  7525. * @return {!TSyntacticCodeUnit} A function that is able to
  7526. * initiate the traversal from a given source element.
  7527. */
  7528. var fLambda = function() {
  7529. return oWalker.walk(oSourceElement);
  7530. };
  7531. return fLambda;
  7532. },
  7533. /**
  7534. * Classifies the source element as excludable if it does not
  7535. * contain a {@code with} statement or the {@code eval} identifier
  7536. * name.
  7537. */
  7538. fClassifyAsExcludable = function() {
  7539. if (oSourceElementData.nCategory ===
  7540. ESourceElementCategories.N_OTHER) {
  7541. oSourceElementData.nCategory =
  7542. ESourceElementCategories.N_EXCLUDABLE;
  7543. }
  7544. },
  7545. /**
  7546. * Adds an identifier to the list of identifier names found.
  7547. * @param {string} sIdentifier The identifier to be added.
  7548. */
  7549. fAddIdentifier = function(sIdentifier) {
  7550. if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
  7551. oSourceElementData.aIdentifiers.push(sIdentifier);
  7552. }
  7553. },
  7554. /**
  7555. * Adds the identifier of a variable to the list of identifier names
  7556. * found.
  7557. * @param {!Array} aVariableDeclaration A variable declaration.
  7558. */
  7559. fAddVariable = function(aVariableDeclaration) {
  7560. fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
  7561. },
  7562. /**
  7563. * Increments the count of the number of occurrences of the prefixed
  7564. * String representation attributed to the primary expression.
  7565. * @param {number} nCategory The category of the primary expression.
  7566. * @param {string} sName The prefixed String representation attributed
  7567. * to the primary expression.
  7568. */
  7569. fCountPrimaryExpression = function(nCategory, sName) {
  7570. if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
  7571. oSourceElementData.aCount[nCategory][sName] = 0;
  7572. if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
  7573. oSourceElementData.aPrimitiveValues.push(sName);
  7574. }
  7575. }
  7576. oSourceElementData.aCount[nCategory][sName] += 1;
  7577. },
  7578. /**
  7579. * Consolidates all worthwhile primitive values in a range of source
  7580. * elements.
  7581. * @param {number} nFrom The index (in the source text order) of the
  7582. * source element that is the first element of the range.
  7583. * @param {number} nTo The index (in the source text order) of the
  7584. * source element that is the last element of the range.
  7585. * @param {boolean} bEnclose Indicates whether the range should be
  7586. * enclosed within a function call with no argument values to a
  7587. * function with an empty parameter list if any primitive values
  7588. * are consolidated.
  7589. * @see TPrimitiveValue#nSaving
  7590. */
  7591. fExamineSourceElements = function(nFrom, nTo, bEnclose) {
  7592. var _,
  7593. /**
  7594. * The index of the last mangled name.
  7595. * @type {number}
  7596. */
  7597. nIndex = oScope.cname,
  7598. /**
  7599. * The index of the source element that is currently being
  7600. * considered.
  7601. * @type {number}
  7602. */
  7603. nPosition,
  7604. /**
  7605. * A collection of functions used during the consolidation of
  7606. * primitive values and identifier names used as property
  7607. * accessors.
  7608. * @namespace
  7609. * @type {!Object.<string, function(...[*])>}
  7610. */
  7611. oWalkersTransformers = {
  7612. /**
  7613. * If the String value that is equivalent to the sequence of
  7614. * terminal symbols that constitute the encountered identifier
  7615. * name is worthwhile, a syntactic conversion from the dot
  7616. * notation to the bracket notation ensues with that sequence
  7617. * being substituted by an identifier name to which the value
  7618. * is assigned.
  7619. * Applies to property accessors that use the dot notation.
  7620. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  7621. * MemberExpression.
  7622. * @param {string} sIdentifierName The identifier name used as
  7623. * the property accessor.
  7624. * @return {!Array} A syntactic code unit that is equivalent to
  7625. * the one encountered.
  7626. * @see TPrimitiveValue#nSaving
  7627. */
  7628. 'dot': function(oExpression, sIdentifierName) {
  7629. /**
  7630. * The prefixed String value that is equivalent to the
  7631. * sequence of terminal symbols that constitute the
  7632. * encountered identifier name.
  7633. * @type {string}
  7634. */
  7635. var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
  7636. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  7637. sPrefixed) &&
  7638. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7639. ['sub',
  7640. oWalker.walk(oExpression),
  7641. ['name',
  7642. oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
  7643. ['dot', oWalker.walk(oExpression), sIdentifierName];
  7644. },
  7645. /**
  7646. * If the encountered identifier is a null or Boolean literal
  7647. * and its value is worthwhile, the identifier is substituted
  7648. * by an identifier name to which that value is assigned.
  7649. * Applies to identifier names.
  7650. * @param {string} sIdentifier The identifier encountered.
  7651. * @return {!Array} A syntactic code unit that is equivalent to
  7652. * the one encountered.
  7653. * @see TPrimitiveValue#nSaving
  7654. */
  7655. 'name': function(sIdentifier) {
  7656. /**
  7657. * The prefixed representation String of the identifier.
  7658. * @type {string}
  7659. */
  7660. var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
  7661. return [
  7662. 'name',
  7663. oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
  7664. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7665. oSolutionBest.oPrimitiveValues[sPrefixed].sName :
  7666. sIdentifier
  7667. ];
  7668. },
  7669. /**
  7670. * If the encountered String value is worthwhile, it is
  7671. * substituted by an identifier name to which that value is
  7672. * assigned.
  7673. * Applies to String values.
  7674. * @param {string} sStringValue The String value of the string
  7675. * literal encountered.
  7676. * @return {!Array} A syntactic code unit that is equivalent to
  7677. * the one encountered.
  7678. * @see TPrimitiveValue#nSaving
  7679. */
  7680. 'string': function(sStringValue) {
  7681. /**
  7682. * The prefixed representation String of the primitive value
  7683. * of the literal.
  7684. * @type {string}
  7685. */
  7686. var sPrefixed =
  7687. EValuePrefixes.S_STRING + sStringValue;
  7688. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  7689. sPrefixed) &&
  7690. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7691. ['name',
  7692. oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
  7693. ['string', sStringValue];
  7694. }
  7695. },
  7696. /**
  7697. * Such data on what to consolidate within the range of source
  7698. * elements that is currently being considered that lead to the
  7699. * greatest known reduction of the number of the terminal symbols
  7700. * in comparison to the original source text.
  7701. * @type {!TSolution}
  7702. */
  7703. oSolutionBest = new TSolution(),
  7704. /**
  7705. * Data representing an ongoing attempt to find a better
  7706. * reduction of the number of the terminal symbols in comparison
  7707. * to the original source text than the best one that is
  7708. * currently known.
  7709. * @type {!TSolution}
  7710. * @see oSolutionBest
  7711. */
  7712. oSolutionCandidate = new TSolution(),
  7713. /**
  7714. * A record consisting of data about the range of source elements
  7715. * that is currently being examined.
  7716. * @type {!TSourceElementsData}
  7717. */
  7718. oSourceElementsData = new TSourceElementsData(),
  7719. /**
  7720. * Variable declarations for each primitive value that is to be
  7721. * consolidated within the elements.
  7722. * @type {!Array.<!Array>}
  7723. */
  7724. aVariableDeclarations = [],
  7725. /**
  7726. * Augments a list with a prefixed representation String.
  7727. * @param {!Array.<string>} aList A list that is to be augmented.
  7728. * @return {function(string)} A function that augments a list
  7729. * with a prefixed representation String.
  7730. */
  7731. cAugmentList = function(aList) {
  7732. /**
  7733. * @param {string} sPrefixed Prefixed representation String of
  7734. * a primitive value that could be consolidated within the
  7735. * elements.
  7736. */
  7737. var fLambda = function(sPrefixed) {
  7738. if (-1 === aList.indexOf(sPrefixed)) {
  7739. aList.push(sPrefixed);
  7740. }
  7741. };
  7742. return fLambda;
  7743. },
  7744. /**
  7745. * Adds the number of occurrences of a primitive value of a given
  7746. * category that could be consolidated in the source element with
  7747. * a given index to the count of occurrences of that primitive
  7748. * value within the range of source elements that is currently
  7749. * being considered.
  7750. * @param {number} nPosition The index (in the source text order)
  7751. * of a source element.
  7752. * @param {number} nCategory The category of the primary
  7753. * expression from which the primitive value is derived.
  7754. * @return {function(string)} A function that performs the
  7755. * addition.
  7756. * @see cAddOccurrencesInCategory
  7757. */
  7758. cAddOccurrences = function(nPosition, nCategory) {
  7759. /**
  7760. * @param {string} sPrefixed The prefixed representation String
  7761. * of a primitive value.
  7762. */
  7763. var fLambda = function(sPrefixed) {
  7764. if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
  7765. sPrefixed)) {
  7766. oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
  7767. }
  7768. oSourceElementsData.aCount[nCategory][sPrefixed] +=
  7769. aSourceElementsData[nPosition].aCount[nCategory][
  7770. sPrefixed];
  7771. };
  7772. return fLambda;
  7773. },
  7774. /**
  7775. * Adds the number of occurrences of each primitive value of a
  7776. * given category that could be consolidated in the source
  7777. * element with a given index to the count of occurrences of that
  7778. * primitive values within the range of source elements that is
  7779. * currently being considered.
  7780. * @param {number} nPosition The index (in the source text order)
  7781. * of a source element.
  7782. * @return {function(number)} A function that performs the
  7783. * addition.
  7784. * @see fAddOccurrences
  7785. */
  7786. cAddOccurrencesInCategory = function(nPosition) {
  7787. /**
  7788. * @param {number} nCategory The category of the primary
  7789. * expression from which the primitive value is derived.
  7790. */
  7791. var fLambda = function(nCategory) {
  7792. Object.keys(
  7793. aSourceElementsData[nPosition].aCount[nCategory]
  7794. ).forEach(cAddOccurrences(nPosition, nCategory));
  7795. };
  7796. return fLambda;
  7797. },
  7798. /**
  7799. * Adds the number of occurrences of each primitive value that
  7800. * could be consolidated in the source element with a given index
  7801. * to the count of occurrences of that primitive values within
  7802. * the range of source elements that is currently being
  7803. * considered.
  7804. * @param {number} nPosition The index (in the source text order)
  7805. * of a source element.
  7806. */
  7807. fAddOccurrences = function(nPosition) {
  7808. Object.keys(aSourceElementsData[nPosition].aCount).forEach(
  7809. cAddOccurrencesInCategory(nPosition));
  7810. },
  7811. /**
  7812. * Creates a variable declaration for a primitive value if that
  7813. * primitive value is to be consolidated within the elements.
  7814. * @param {string} sPrefixed Prefixed representation String of a
  7815. * primitive value that could be consolidated within the
  7816. * elements.
  7817. * @see aVariableDeclarations
  7818. */
  7819. cAugmentVariableDeclarations = function(sPrefixed) {
  7820. if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
  7821. aVariableDeclarations.push([
  7822. oSolutionBest.oPrimitiveValues[sPrefixed].sName,
  7823. [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
  7824. 'name' : 'string',
  7825. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
  7826. ]);
  7827. }
  7828. },
  7829. /**
  7830. * Sorts primitive values with regard to the difference in the
  7831. * number of terminal symbols between the original source text
  7832. * and the one with those primitive values consolidated.
  7833. * @param {string} sPrefixed0 The prefixed representation String
  7834. * of the first of the two primitive values that are being
  7835. * compared.
  7836. * @param {string} sPrefixed1 The prefixed representation String
  7837. * of the second of the two primitive values that are being
  7838. * compared.
  7839. * @return {number}
  7840. * <dl>
  7841. * <dt>-1</dt>
  7842. * <dd>if the first primitive value must be placed before
  7843. * the other one,</dd>
  7844. * <dt>0</dt>
  7845. * <dd>if the first primitive value may be placed before
  7846. * the other one,</dd>
  7847. * <dt>1</dt>
  7848. * <dd>if the first primitive value must not be placed
  7849. * before the other one.</dd>
  7850. * </dl>
  7851. * @see TSolution.oPrimitiveValues
  7852. */
  7853. cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
  7854. /**
  7855. * The difference between:
  7856. * <ol>
  7857. * <li>the difference in the number of terminal symbols
  7858. * between the original source text and the one with the
  7859. * first primitive value consolidated, and</li>
  7860. * <li>the difference in the number of terminal symbols
  7861. * between the original source text and the one with the
  7862. * second primitive value consolidated.</li>
  7863. * </ol>
  7864. * @type {number}
  7865. */
  7866. var nDifference =
  7867. oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
  7868. oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
  7869. return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
  7870. },
  7871. /**
  7872. * Assigns an identifier name to a primitive value and calculates
  7873. * whether instances of that primitive value are worth
  7874. * consolidating.
  7875. * @param {string} sPrefixed The prefixed representation String
  7876. * of a primitive value that is being evaluated.
  7877. */
  7878. fEvaluatePrimitiveValue = function(sPrefixed) {
  7879. var _,
  7880. /**
  7881. * The index of the last mangled name.
  7882. * @type {number}
  7883. */
  7884. nIndex,
  7885. /**
  7886. * The representation String of the primitive value that is
  7887. * being evaluated.
  7888. * @type {string}
  7889. */
  7890. sName =
  7891. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
  7892. /**
  7893. * The number of source characters taken up by the
  7894. * representation String of the primitive value that is
  7895. * being evaluated.
  7896. * @type {number}
  7897. */
  7898. nLengthOriginal = sName.length,
  7899. /**
  7900. * The number of source characters taken up by the
  7901. * identifier name that could substitute the primitive
  7902. * value that is being evaluated.
  7903. * substituted.
  7904. * @type {number}
  7905. */
  7906. nLengthSubstitution,
  7907. /**
  7908. * The number of source characters taken up by by the
  7909. * representation String of the primitive value that is
  7910. * being evaluated when it is represented by a string
  7911. * literal.
  7912. * @type {number}
  7913. */
  7914. nLengthString = oProcessor.make_string(sName).length;
  7915. oSolutionCandidate.oPrimitiveValues[sPrefixed] =
  7916. new TPrimitiveValue();
  7917. do { // Find an identifier unused in this or any nested scope.
  7918. nIndex = oScope.cname;
  7919. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
  7920. oScope.next_mangled();
  7921. } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
  7922. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
  7923. nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
  7924. sPrefixed].sName.length;
  7925. if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
  7926. // foo:null, or foo:null;
  7927. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  7928. nLengthSubstitution + nLengthOriginal +
  7929. oWeights.N_VARIABLE_DECLARATION;
  7930. // null vs foo
  7931. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7932. oSourceElementsData.aCount[
  7933. EPrimaryExpressionCategories.
  7934. N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
  7935. (nLengthOriginal - nLengthSubstitution);
  7936. } else {
  7937. // foo:'fromCharCode';
  7938. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  7939. nLengthSubstitution + nLengthString +
  7940. oWeights.N_VARIABLE_DECLARATION;
  7941. // .fromCharCode vs [foo]
  7942. if (oSourceElementsData.aCount[
  7943. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  7944. ].hasOwnProperty(sPrefixed)) {
  7945. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7946. oSourceElementsData.aCount[
  7947. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  7948. ][sPrefixed] *
  7949. (nLengthOriginal - nLengthSubstitution -
  7950. oWeights.N_PROPERTY_ACCESSOR);
  7951. }
  7952. // 'fromCharCode' vs foo
  7953. if (oSourceElementsData.aCount[
  7954. EPrimaryExpressionCategories.N_STRING_LITERALS
  7955. ].hasOwnProperty(sPrefixed)) {
  7956. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7957. oSourceElementsData.aCount[
  7958. EPrimaryExpressionCategories.N_STRING_LITERALS
  7959. ][sPrefixed] *
  7960. (nLengthString - nLengthSubstitution);
  7961. }
  7962. }
  7963. if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
  7964. 0) {
  7965. oSolutionCandidate.nSavings +=
  7966. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
  7967. } else {
  7968. oScope.cname = nIndex; // Free the identifier name.
  7969. }
  7970. },
  7971. /**
  7972. * Adds a variable declaration to an existing variable statement.
  7973. * @param {!Array} aVariableDeclaration A variable declaration
  7974. * with an initialiser.
  7975. */
  7976. cAddVariableDeclaration = function(aVariableDeclaration) {
  7977. (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
  7978. aVariableDeclaration);
  7979. };
  7980. if (nFrom > nTo) {
  7981. return;
  7982. }
  7983. // If the range is a closure, reuse the closure.
  7984. if (nFrom === nTo &&
  7985. 'stat' === oSourceElements[nFrom][0] &&
  7986. 'call' === oSourceElements[nFrom][1][0] &&
  7987. 'function' === oSourceElements[nFrom][1][1][0]) {
  7988. fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
  7989. return;
  7990. }
  7991. // Create a list of all derived primitive values within the range.
  7992. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  7993. aSourceElementsData[nPosition].aPrimitiveValues.forEach(
  7994. cAugmentList(oSourceElementsData.aPrimitiveValues));
  7995. }
  7996. if (0 === oSourceElementsData.aPrimitiveValues.length) {
  7997. return;
  7998. }
  7999. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  8000. // Add the number of occurrences to the total count.
  8001. fAddOccurrences(nPosition);
  8002. // Add identifiers of this or any nested scope to the list.
  8003. aSourceElementsData[nPosition].aIdentifiers.forEach(
  8004. cAugmentList(oSourceElementsData.aIdentifiers));
  8005. }
  8006. // Distribute identifier names among derived primitive values.
  8007. do { // If there was any progress, find a better distribution.
  8008. oSolutionBest = oSolutionCandidate;
  8009. if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
  8010. // Sort primitive values descending by their worthwhileness.
  8011. oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
  8012. }
  8013. oSolutionCandidate = new TSolution();
  8014. oSourceElementsData.aPrimitiveValues.forEach(
  8015. fEvaluatePrimitiveValue);
  8016. oScope.cname = nIndex;
  8017. } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
  8018. // Take the necessity of adding a variable statement into account.
  8019. if ('var' !== oSourceElements[nFrom][0]) {
  8020. oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
  8021. }
  8022. if (bEnclose) {
  8023. // Take the necessity of forming a closure into account.
  8024. oSolutionBest.nSavings -= oWeights.N_CLOSURE;
  8025. }
  8026. if (oSolutionBest.nSavings > 0) {
  8027. // Create variable declarations suitable for UglifyJS.
  8028. Object.keys(oSolutionBest.oPrimitiveValues).forEach(
  8029. cAugmentVariableDeclarations);
  8030. // Rewrite expressions that contain worthwhile primitive values.
  8031. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  8032. oWalker = oProcessor.ast_walker();
  8033. oSourceElements[nPosition] =
  8034. oWalker.with_walkers(
  8035. oWalkersTransformers,
  8036. cContext(oWalker, oSourceElements[nPosition]));
  8037. }
  8038. if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
  8039. (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
  8040. )).forEach(cAddVariableDeclaration);
  8041. } else { // Add a variable statement.
  8042. Array.prototype.splice.call(
  8043. oSourceElements,
  8044. nFrom,
  8045. 0,
  8046. ['var', aVariableDeclarations]);
  8047. nTo += 1;
  8048. }
  8049. if (bEnclose) {
  8050. // Add a closure.
  8051. Array.prototype.splice.call(
  8052. oSourceElements,
  8053. nFrom,
  8054. 0,
  8055. ['stat', ['call', ['function', null, [], []], []]]);
  8056. // Copy source elements into the closure.
  8057. for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
  8058. Array.prototype.unshift.call(
  8059. oSourceElements[nFrom][1][1][3],
  8060. oSourceElements[nPosition]);
  8061. }
  8062. // Remove source elements outside the closure.
  8063. Array.prototype.splice.call(
  8064. oSourceElements,
  8065. nFrom + 1,
  8066. nTo - nFrom + 1);
  8067. }
  8068. }
  8069. if (bEnclose) {
  8070. // Restore the availability of identifier names.
  8071. oScope.cname = nIndex;
  8072. }
  8073. };
  8074. oSourceElements = (/** @type {!TSyntacticCodeUnit} */
  8075. oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
  8076. if (0 === oSourceElements.length) {
  8077. return;
  8078. }
  8079. oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
  8080. // Skip a Directive Prologue.
  8081. while (nAfterDirectivePrologue < oSourceElements.length &&
  8082. 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
  8083. nAfterDirectivePrologue += 1;
  8084. aSourceElementsData.push(null);
  8085. }
  8086. if (oSourceElements.length === nAfterDirectivePrologue) {
  8087. return;
  8088. }
  8089. for (nPosition = nAfterDirectivePrologue;
  8090. nPosition < oSourceElements.length;
  8091. nPosition += 1) {
  8092. oSourceElementData = new TSourceElementsData();
  8093. oWalker = oProcessor.ast_walker();
  8094. // Classify a source element.
  8095. // Find its derived primitive values and count their occurrences.
  8096. // Find all identifiers used (including nested scopes).
  8097. oWalker.with_walkers(
  8098. oWalkers.oSurveySourceElement,
  8099. cContext(oWalker, oSourceElements[nPosition]));
  8100. // Establish whether the scope is still wholly examinable.
  8101. bIsWhollyExaminable = bIsWhollyExaminable &&
  8102. ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
  8103. ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
  8104. aSourceElementsData.push(oSourceElementData);
  8105. }
  8106. if (bIsWhollyExaminable) { // Examine the whole scope.
  8107. fExamineSourceElements(
  8108. nAfterDirectivePrologue,
  8109. oSourceElements.length - 1,
  8110. false);
  8111. } else { // Examine unexcluded ranges of source elements.
  8112. for (nPosition = oSourceElements.length - 1;
  8113. nPosition >= nAfterDirectivePrologue;
  8114. nPosition -= 1) {
  8115. oSourceElementData = (/** @type {!TSourceElementsData} */
  8116. aSourceElementsData[nPosition]);
  8117. if (ESourceElementCategories.N_OTHER ===
  8118. oSourceElementData.nCategory) {
  8119. if ('undefined' === typeof nTo) {
  8120. nTo = nPosition; // Indicate the end of a range.
  8121. }
  8122. // Examine the range if it immediately follows a Directive Prologue.
  8123. if (nPosition === nAfterDirectivePrologue) {
  8124. fExamineSourceElements(nPosition, nTo, true);
  8125. }
  8126. } else {
  8127. if ('undefined' !== typeof nTo) {
  8128. // Examine the range that immediately follows this source element.
  8129. fExamineSourceElements(nPosition + 1, nTo, true);
  8130. nTo = void 0; // Obliterate the range.
  8131. }
  8132. // Examine nested functions.
  8133. oWalker = oProcessor.ast_walker();
  8134. oWalker.with_walkers(
  8135. oWalkers.oExamineFunctions,
  8136. cContext(oWalker, oSourceElements[nPosition]));
  8137. }
  8138. }
  8139. }
  8140. }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
  8141. return oAbstractSyntaxTree;
  8142. };
  8143. /*jshint sub:false */
  8144. /* Local Variables: */
  8145. /* mode: js */
  8146. /* coding: utf-8 */
  8147. /* indent-tabs-mode: nil */
  8148. /* tab-width: 2 */
  8149. /* End: */
  8150. /* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
  8151. /* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
  8152. });
  8153. define('uglifyjs/parse-js', ["exports"], function(exports) {
  8154. /***********************************************************************
  8155. A JavaScript tokenizer / parser / beautifier / compressor.
  8156. This version is suitable for Node.js. With minimal changes (the
  8157. exports stuff) it should work on any JS platform.
  8158. This file contains the tokenizer/parser. It is a port to JavaScript
  8159. of parse-js [1], a JavaScript parser library written in Common Lisp
  8160. by Marijn Haverbeke. Thank you Marijn!
  8161. [1] http://marijn.haverbeke.nl/parse-js/
  8162. Exported functions:
  8163. - tokenizer(code) -- returns a function. Call the returned
  8164. function to fetch the next token.
  8165. - parse(code) -- returns an AST of the given JavaScript code.
  8166. -------------------------------- (C) ---------------------------------
  8167. Author: Mihai Bazon
  8168. <mihai.bazon@gmail.com>
  8169. http://mihai.bazon.net/blog
  8170. Distributed under the BSD license:
  8171. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  8172. Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  8173. Redistribution and use in source and binary forms, with or without
  8174. modification, are permitted provided that the following conditions
  8175. are met:
  8176. * Redistributions of source code must retain the above
  8177. copyright notice, this list of conditions and the following
  8178. disclaimer.
  8179. * Redistributions in binary form must reproduce the above
  8180. copyright notice, this list of conditions and the following
  8181. disclaimer in the documentation and/or other materials
  8182. provided with the distribution.
  8183. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  8184. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8185. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  8186. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  8187. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  8188. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  8189. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  8190. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8191. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  8192. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  8193. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  8194. SUCH DAMAGE.
  8195. ***********************************************************************/
  8196. /* -----[ Tokenizer (constants) ]----- */
  8197. var KEYWORDS = array_to_hash([
  8198. "break",
  8199. "case",
  8200. "catch",
  8201. "const",
  8202. "continue",
  8203. "debugger",
  8204. "default",
  8205. "delete",
  8206. "do",
  8207. "else",
  8208. "finally",
  8209. "for",
  8210. "function",
  8211. "if",
  8212. "in",
  8213. "instanceof",
  8214. "new",
  8215. "return",
  8216. "switch",
  8217. "throw",
  8218. "try",
  8219. "typeof",
  8220. "var",
  8221. "void",
  8222. "while",
  8223. "with"
  8224. ]);
  8225. var RESERVED_WORDS = array_to_hash([
  8226. "abstract",
  8227. "boolean",
  8228. "byte",
  8229. "char",
  8230. "class",
  8231. "double",
  8232. "enum",
  8233. "export",
  8234. "extends",
  8235. "final",
  8236. "float",
  8237. "goto",
  8238. "implements",
  8239. "import",
  8240. "int",
  8241. "interface",
  8242. "long",
  8243. "native",
  8244. "package",
  8245. "private",
  8246. "protected",
  8247. "public",
  8248. "short",
  8249. "static",
  8250. "super",
  8251. "synchronized",
  8252. "throws",
  8253. "transient",
  8254. "volatile"
  8255. ]);
  8256. var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
  8257. "return",
  8258. "new",
  8259. "delete",
  8260. "throw",
  8261. "else",
  8262. "case"
  8263. ]);
  8264. var KEYWORDS_ATOM = array_to_hash([
  8265. "false",
  8266. "null",
  8267. "true",
  8268. "undefined"
  8269. ]);
  8270. var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
  8271. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  8272. var RE_OCT_NUMBER = /^0[0-7]+$/;
  8273. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  8274. var OPERATORS = array_to_hash([
  8275. "in",
  8276. "instanceof",
  8277. "typeof",
  8278. "new",
  8279. "void",
  8280. "delete",
  8281. "++",
  8282. "--",
  8283. "+",
  8284. "-",
  8285. "!",
  8286. "~",
  8287. "&",
  8288. "|",
  8289. "^",
  8290. "*",
  8291. "/",
  8292. "%",
  8293. ">>",
  8294. "<<",
  8295. ">>>",
  8296. "<",
  8297. ">",
  8298. "<=",
  8299. ">=",
  8300. "==",
  8301. "===",
  8302. "!=",
  8303. "!==",
  8304. "?",
  8305. "=",
  8306. "+=",
  8307. "-=",
  8308. "/=",
  8309. "*=",
  8310. "%=",
  8311. ">>=",
  8312. "<<=",
  8313. ">>>=",
  8314. "|=",
  8315. "^=",
  8316. "&=",
  8317. "&&",
  8318. "||"
  8319. ]);
  8320. var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"));
  8321. var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
  8322. var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
  8323. var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
  8324. /* -----[ Tokenizer ]----- */
  8325. var UNICODE = { // Unicode 6.1
  8326. 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-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\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\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\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-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\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-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\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-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\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]"),
  8327. combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  8328. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
  8329. digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
  8330. };
  8331. function is_letter(ch) {
  8332. return UNICODE.letter.test(ch);
  8333. };
  8334. function is_digit(ch) {
  8335. ch = ch.charCodeAt(0);
  8336. return ch >= 48 && ch <= 57;
  8337. };
  8338. function is_unicode_digit(ch) {
  8339. return UNICODE.digit.test(ch);
  8340. }
  8341. function is_alphanumeric_char(ch) {
  8342. return is_digit(ch) || is_letter(ch);
  8343. };
  8344. function is_unicode_combining_mark(ch) {
  8345. return UNICODE.combining_mark.test(ch);
  8346. };
  8347. function is_unicode_connector_punctuation(ch) {
  8348. return UNICODE.connector_punctuation.test(ch);
  8349. };
  8350. function is_identifier_start(ch) {
  8351. return ch == "$" || ch == "_" || is_letter(ch);
  8352. };
  8353. function is_identifier_char(ch) {
  8354. return is_identifier_start(ch)
  8355. || is_unicode_combining_mark(ch)
  8356. || is_unicode_digit(ch)
  8357. || is_unicode_connector_punctuation(ch)
  8358. || ch == "\u200c" // zero-width non-joiner <ZWNJ>
  8359. || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  8360. ;
  8361. };
  8362. function parse_js_number(num) {
  8363. if (RE_HEX_NUMBER.test(num)) {
  8364. return parseInt(num.substr(2), 16);
  8365. } else if (RE_OCT_NUMBER.test(num)) {
  8366. return parseInt(num.substr(1), 8);
  8367. } else if (RE_DEC_NUMBER.test(num)) {
  8368. return parseFloat(num);
  8369. }
  8370. };
  8371. function JS_Parse_Error(message, line, col, pos) {
  8372. this.message = message;
  8373. this.line = line + 1;
  8374. this.col = col + 1;
  8375. this.pos = pos + 1;
  8376. this.stack = new Error().stack;
  8377. };
  8378. JS_Parse_Error.prototype.toString = function() {
  8379. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  8380. };
  8381. function js_error(message, line, col, pos) {
  8382. throw new JS_Parse_Error(message, line, col, pos);
  8383. };
  8384. function is_token(token, type, val) {
  8385. return token.type == type && (val == null || token.value == val);
  8386. };
  8387. var EX_EOF = {};
  8388. function tokenizer($TEXT) {
  8389. var S = {
  8390. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
  8391. pos : 0,
  8392. tokpos : 0,
  8393. line : 0,
  8394. tokline : 0,
  8395. col : 0,
  8396. tokcol : 0,
  8397. newline_before : false,
  8398. regex_allowed : false,
  8399. comments_before : []
  8400. };
  8401. function peek() { return S.text.charAt(S.pos); };
  8402. function next(signal_eof, in_string) {
  8403. var ch = S.text.charAt(S.pos++);
  8404. if (signal_eof && !ch)
  8405. throw EX_EOF;
  8406. if (ch == "\n") {
  8407. S.newline_before = S.newline_before || !in_string;
  8408. ++S.line;
  8409. S.col = 0;
  8410. } else {
  8411. ++S.col;
  8412. }
  8413. return ch;
  8414. };
  8415. function eof() {
  8416. return !S.peek();
  8417. };
  8418. function find(what, signal_eof) {
  8419. var pos = S.text.indexOf(what, S.pos);
  8420. if (signal_eof && pos == -1) throw EX_EOF;
  8421. return pos;
  8422. };
  8423. function start_token() {
  8424. S.tokline = S.line;
  8425. S.tokcol = S.col;
  8426. S.tokpos = S.pos;
  8427. };
  8428. function token(type, value, is_comment) {
  8429. S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
  8430. (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
  8431. (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
  8432. var ret = {
  8433. type : type,
  8434. value : value,
  8435. line : S.tokline,
  8436. col : S.tokcol,
  8437. pos : S.tokpos,
  8438. endpos : S.pos,
  8439. nlb : S.newline_before
  8440. };
  8441. if (!is_comment) {
  8442. ret.comments_before = S.comments_before;
  8443. S.comments_before = [];
  8444. // make note of any newlines in the comments that came before
  8445. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  8446. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  8447. }
  8448. }
  8449. S.newline_before = false;
  8450. return ret;
  8451. };
  8452. function skip_whitespace() {
  8453. while (HOP(WHITESPACE_CHARS, peek()))
  8454. next();
  8455. };
  8456. function read_while(pred) {
  8457. var ret = "", ch = peek(), i = 0;
  8458. while (ch && pred(ch, i++)) {
  8459. ret += next();
  8460. ch = peek();
  8461. }
  8462. return ret;
  8463. };
  8464. function parse_error(err) {
  8465. js_error(err, S.tokline, S.tokcol, S.tokpos);
  8466. };
  8467. function read_num(prefix) {
  8468. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  8469. var num = read_while(function(ch, i){
  8470. if (ch == "x" || ch == "X") {
  8471. if (has_x) return false;
  8472. return has_x = true;
  8473. }
  8474. if (!has_x && (ch == "E" || ch == "e")) {
  8475. if (has_e) return false;
  8476. return has_e = after_e = true;
  8477. }
  8478. if (ch == "-") {
  8479. if (after_e || (i == 0 && !prefix)) return true;
  8480. return false;
  8481. }
  8482. if (ch == "+") return after_e;
  8483. after_e = false;
  8484. if (ch == ".") {
  8485. if (!has_dot && !has_x && !has_e)
  8486. return has_dot = true;
  8487. return false;
  8488. }
  8489. return is_alphanumeric_char(ch);
  8490. });
  8491. if (prefix)
  8492. num = prefix + num;
  8493. var valid = parse_js_number(num);
  8494. if (!isNaN(valid)) {
  8495. return token("num", valid);
  8496. } else {
  8497. parse_error("Invalid syntax: " + num);
  8498. }
  8499. };
  8500. function read_escaped_char(in_string) {
  8501. var ch = next(true, in_string);
  8502. switch (ch) {
  8503. case "n" : return "\n";
  8504. case "r" : return "\r";
  8505. case "t" : return "\t";
  8506. case "b" : return "\b";
  8507. case "v" : return "\u000b";
  8508. case "f" : return "\f";
  8509. case "0" : return "\0";
  8510. case "x" : return String.fromCharCode(hex_bytes(2));
  8511. case "u" : return String.fromCharCode(hex_bytes(4));
  8512. case "\n": return "";
  8513. default : return ch;
  8514. }
  8515. };
  8516. function hex_bytes(n) {
  8517. var num = 0;
  8518. for (; n > 0; --n) {
  8519. var digit = parseInt(next(true), 16);
  8520. if (isNaN(digit))
  8521. parse_error("Invalid hex-character pattern in string");
  8522. num = (num << 4) | digit;
  8523. }
  8524. return num;
  8525. };
  8526. function read_string() {
  8527. return with_eof_error("Unterminated string constant", function(){
  8528. var quote = next(), ret = "";
  8529. for (;;) {
  8530. var ch = next(true);
  8531. if (ch == "\\") {
  8532. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  8533. // https://github.com/mishoo/UglifyJS/issues/178
  8534. var octal_len = 0, first = null;
  8535. ch = read_while(function(ch){
  8536. if (ch >= "0" && ch <= "7") {
  8537. if (!first) {
  8538. first = ch;
  8539. return ++octal_len;
  8540. }
  8541. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  8542. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  8543. }
  8544. return false;
  8545. });
  8546. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  8547. else ch = read_escaped_char(true);
  8548. }
  8549. else if (ch == quote) break;
  8550. else if (ch == "\n") throw EX_EOF;
  8551. ret += ch;
  8552. }
  8553. return token("string", ret);
  8554. });
  8555. };
  8556. function read_line_comment() {
  8557. next();
  8558. var i = find("\n"), ret;
  8559. if (i == -1) {
  8560. ret = S.text.substr(S.pos);
  8561. S.pos = S.text.length;
  8562. } else {
  8563. ret = S.text.substring(S.pos, i);
  8564. S.pos = i;
  8565. }
  8566. return token("comment1", ret, true);
  8567. };
  8568. function read_multiline_comment() {
  8569. next();
  8570. return with_eof_error("Unterminated multiline comment", function(){
  8571. var i = find("*/", true),
  8572. text = S.text.substring(S.pos, i);
  8573. S.pos = i + 2;
  8574. S.line += text.split("\n").length - 1;
  8575. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  8576. // https://github.com/mishoo/UglifyJS/issues/#issue/100
  8577. if (/^@cc_on/i.test(text)) {
  8578. warn("WARNING: at line " + S.line);
  8579. warn("*** Found \"conditional comment\": " + text);
  8580. warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
  8581. }
  8582. return token("comment2", text, true);
  8583. });
  8584. };
  8585. function read_name() {
  8586. var backslash = false, name = "", ch, escaped = false, hex;
  8587. while ((ch = peek()) != null) {
  8588. if (!backslash) {
  8589. if (ch == "\\") escaped = backslash = true, next();
  8590. else if (is_identifier_char(ch)) name += next();
  8591. else break;
  8592. }
  8593. else {
  8594. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  8595. ch = read_escaped_char();
  8596. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  8597. name += ch;
  8598. backslash = false;
  8599. }
  8600. }
  8601. if (HOP(KEYWORDS, name) && escaped) {
  8602. hex = name.charCodeAt(0).toString(16).toUpperCase();
  8603. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  8604. }
  8605. return name;
  8606. };
  8607. function read_regexp(regexp) {
  8608. return with_eof_error("Unterminated regular expression", function(){
  8609. var prev_backslash = false, ch, in_class = false;
  8610. while ((ch = next(true))) if (prev_backslash) {
  8611. regexp += "\\" + ch;
  8612. prev_backslash = false;
  8613. } else if (ch == "[") {
  8614. in_class = true;
  8615. regexp += ch;
  8616. } else if (ch == "]" && in_class) {
  8617. in_class = false;
  8618. regexp += ch;
  8619. } else if (ch == "/" && !in_class) {
  8620. break;
  8621. } else if (ch == "\\") {
  8622. prev_backslash = true;
  8623. } else {
  8624. regexp += ch;
  8625. }
  8626. var mods = read_name();
  8627. return token("regexp", [ regexp, mods ]);
  8628. });
  8629. };
  8630. function read_operator(prefix) {
  8631. function grow(op) {
  8632. if (!peek()) return op;
  8633. var bigger = op + peek();
  8634. if (HOP(OPERATORS, bigger)) {
  8635. next();
  8636. return grow(bigger);
  8637. } else {
  8638. return op;
  8639. }
  8640. };
  8641. return token("operator", grow(prefix || next()));
  8642. };
  8643. function handle_slash() {
  8644. next();
  8645. var regex_allowed = S.regex_allowed;
  8646. switch (peek()) {
  8647. case "/":
  8648. S.comments_before.push(read_line_comment());
  8649. S.regex_allowed = regex_allowed;
  8650. return next_token();
  8651. case "*":
  8652. S.comments_before.push(read_multiline_comment());
  8653. S.regex_allowed = regex_allowed;
  8654. return next_token();
  8655. }
  8656. return S.regex_allowed ? read_regexp("") : read_operator("/");
  8657. };
  8658. function handle_dot() {
  8659. next();
  8660. return is_digit(peek())
  8661. ? read_num(".")
  8662. : token("punc", ".");
  8663. };
  8664. function read_word() {
  8665. var word = read_name();
  8666. return !HOP(KEYWORDS, word)
  8667. ? token("name", word)
  8668. : HOP(OPERATORS, word)
  8669. ? token("operator", word)
  8670. : HOP(KEYWORDS_ATOM, word)
  8671. ? token("atom", word)
  8672. : token("keyword", word);
  8673. };
  8674. function with_eof_error(eof_error, cont) {
  8675. try {
  8676. return cont();
  8677. } catch(ex) {
  8678. if (ex === EX_EOF) parse_error(eof_error);
  8679. else throw ex;
  8680. }
  8681. };
  8682. function next_token(force_regexp) {
  8683. if (force_regexp != null)
  8684. return read_regexp(force_regexp);
  8685. skip_whitespace();
  8686. start_token();
  8687. var ch = peek();
  8688. if (!ch) return token("eof");
  8689. if (is_digit(ch)) return read_num();
  8690. if (ch == '"' || ch == "'") return read_string();
  8691. if (HOP(PUNC_CHARS, ch)) return token("punc", next());
  8692. if (ch == ".") return handle_dot();
  8693. if (ch == "/") return handle_slash();
  8694. if (HOP(OPERATOR_CHARS, ch)) return read_operator();
  8695. if (ch == "\\" || is_identifier_start(ch)) return read_word();
  8696. parse_error("Unexpected character '" + ch + "'");
  8697. };
  8698. next_token.context = function(nc) {
  8699. if (nc) S = nc;
  8700. return S;
  8701. };
  8702. return next_token;
  8703. };
  8704. /* -----[ Parser (constants) ]----- */
  8705. var UNARY_PREFIX = array_to_hash([
  8706. "typeof",
  8707. "void",
  8708. "delete",
  8709. "--",
  8710. "++",
  8711. "!",
  8712. "~",
  8713. "-",
  8714. "+"
  8715. ]);
  8716. var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
  8717. var ASSIGNMENT = (function(a, ret, i){
  8718. while (i < a.length) {
  8719. ret[a[i]] = a[i].substr(0, a[i].length - 1);
  8720. i++;
  8721. }
  8722. return ret;
  8723. })(
  8724. ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
  8725. { "=": true },
  8726. 0
  8727. );
  8728. var PRECEDENCE = (function(a, ret){
  8729. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  8730. var b = a[i];
  8731. for (var j = 0; j < b.length; ++j) {
  8732. ret[b[j]] = n;
  8733. }
  8734. }
  8735. return ret;
  8736. })(
  8737. [
  8738. ["||"],
  8739. ["&&"],
  8740. ["|"],
  8741. ["^"],
  8742. ["&"],
  8743. ["==", "===", "!=", "!=="],
  8744. ["<", ">", "<=", ">=", "in", "instanceof"],
  8745. [">>", "<<", ">>>"],
  8746. ["+", "-"],
  8747. ["*", "/", "%"]
  8748. ],
  8749. {}
  8750. );
  8751. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  8752. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  8753. /* -----[ Parser ]----- */
  8754. function NodeWithToken(str, start, end) {
  8755. this.name = str;
  8756. this.start = start;
  8757. this.end = end;
  8758. };
  8759. NodeWithToken.prototype.toString = function() { return this.name; };
  8760. function parse($TEXT, exigent_mode, embed_tokens) {
  8761. var S = {
  8762. input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
  8763. token : null,
  8764. prev : null,
  8765. peeked : null,
  8766. in_function : 0,
  8767. in_directives : true,
  8768. in_loop : 0,
  8769. labels : []
  8770. };
  8771. S.token = next();
  8772. function is(type, value) {
  8773. return is_token(S.token, type, value);
  8774. };
  8775. function peek() { return S.peeked || (S.peeked = S.input()); };
  8776. function next() {
  8777. S.prev = S.token;
  8778. if (S.peeked) {
  8779. S.token = S.peeked;
  8780. S.peeked = null;
  8781. } else {
  8782. S.token = S.input();
  8783. }
  8784. S.in_directives = S.in_directives && (
  8785. S.token.type == "string" || is("punc", ";")
  8786. );
  8787. return S.token;
  8788. };
  8789. function prev() {
  8790. return S.prev;
  8791. };
  8792. function croak(msg, line, col, pos) {
  8793. var ctx = S.input.context();
  8794. js_error(msg,
  8795. line != null ? line : ctx.tokline,
  8796. col != null ? col : ctx.tokcol,
  8797. pos != null ? pos : ctx.tokpos);
  8798. };
  8799. function token_error(token, msg) {
  8800. croak(msg, token.line, token.col);
  8801. };
  8802. function unexpected(token) {
  8803. if (token == null)
  8804. token = S.token;
  8805. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  8806. };
  8807. function expect_token(type, val) {
  8808. if (is(type, val)) {
  8809. return next();
  8810. }
  8811. token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
  8812. };
  8813. function expect(punc) { return expect_token("punc", punc); };
  8814. function can_insert_semicolon() {
  8815. return !exigent_mode && (
  8816. S.token.nlb || is("eof") || is("punc", "}")
  8817. );
  8818. };
  8819. function semicolon() {
  8820. if (is("punc", ";")) next();
  8821. else if (!can_insert_semicolon()) unexpected();
  8822. };
  8823. function as() {
  8824. return slice(arguments);
  8825. };
  8826. function parenthesised() {
  8827. expect("(");
  8828. var ex = expression();
  8829. expect(")");
  8830. return ex;
  8831. };
  8832. function add_tokens(str, start, end) {
  8833. return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
  8834. };
  8835. function maybe_embed_tokens(parser) {
  8836. if (embed_tokens) return function() {
  8837. var start = S.token;
  8838. var ast = parser.apply(this, arguments);
  8839. ast[0] = add_tokens(ast[0], start, prev());
  8840. return ast;
  8841. };
  8842. else return parser;
  8843. };
  8844. var statement = maybe_embed_tokens(function() {
  8845. if (is("operator", "/") || is("operator", "/=")) {
  8846. S.peeked = null;
  8847. S.token = S.input(S.token.value.substr(1)); // force regexp
  8848. }
  8849. switch (S.token.type) {
  8850. case "string":
  8851. var dir = S.in_directives, stat = simple_statement();
  8852. if (dir && stat[1][0] == "string" && !is("punc", ","))
  8853. return as("directive", stat[1][1]);
  8854. return stat;
  8855. case "num":
  8856. case "regexp":
  8857. case "operator":
  8858. case "atom":
  8859. return simple_statement();
  8860. case "name":
  8861. return is_token(peek(), "punc", ":")
  8862. ? labeled_statement(prog1(S.token.value, next, next))
  8863. : simple_statement();
  8864. case "punc":
  8865. switch (S.token.value) {
  8866. case "{":
  8867. return as("block", block_());
  8868. case "[":
  8869. case "(":
  8870. return simple_statement();
  8871. case ";":
  8872. next();
  8873. return as("block");
  8874. default:
  8875. unexpected();
  8876. }
  8877. case "keyword":
  8878. switch (prog1(S.token.value, next)) {
  8879. case "break":
  8880. return break_cont("break");
  8881. case "continue":
  8882. return break_cont("continue");
  8883. case "debugger":
  8884. semicolon();
  8885. return as("debugger");
  8886. case "do":
  8887. return (function(body){
  8888. expect_token("keyword", "while");
  8889. return as("do", prog1(parenthesised, semicolon), body);
  8890. })(in_loop(statement));
  8891. case "for":
  8892. return for_();
  8893. case "function":
  8894. return function_(true);
  8895. case "if":
  8896. return if_();
  8897. case "return":
  8898. if (S.in_function == 0)
  8899. croak("'return' outside of function");
  8900. return as("return",
  8901. is("punc", ";")
  8902. ? (next(), null)
  8903. : can_insert_semicolon()
  8904. ? null
  8905. : prog1(expression, semicolon));
  8906. case "switch":
  8907. return as("switch", parenthesised(), switch_block_());
  8908. case "throw":
  8909. if (S.token.nlb)
  8910. croak("Illegal newline after 'throw'");
  8911. return as("throw", prog1(expression, semicolon));
  8912. case "try":
  8913. return try_();
  8914. case "var":
  8915. return prog1(var_, semicolon);
  8916. case "const":
  8917. return prog1(const_, semicolon);
  8918. case "while":
  8919. return as("while", parenthesised(), in_loop(statement));
  8920. case "with":
  8921. return as("with", parenthesised(), statement());
  8922. default:
  8923. unexpected();
  8924. }
  8925. }
  8926. });
  8927. function labeled_statement(label) {
  8928. S.labels.push(label);
  8929. var start = S.token, stat = statement();
  8930. if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
  8931. unexpected(start);
  8932. S.labels.pop();
  8933. return as("label", label, stat);
  8934. };
  8935. function simple_statement() {
  8936. return as("stat", prog1(expression, semicolon));
  8937. };
  8938. function break_cont(type) {
  8939. var name;
  8940. if (!can_insert_semicolon()) {
  8941. name = is("name") ? S.token.value : null;
  8942. }
  8943. if (name != null) {
  8944. next();
  8945. if (!member(name, S.labels))
  8946. croak("Label " + name + " without matching loop or statement");
  8947. }
  8948. else if (S.in_loop == 0)
  8949. croak(type + " not inside a loop or switch");
  8950. semicolon();
  8951. return as(type, name);
  8952. };
  8953. function for_() {
  8954. expect("(");
  8955. var init = null;
  8956. if (!is("punc", ";")) {
  8957. init = is("keyword", "var")
  8958. ? (next(), var_(true))
  8959. : expression(true, true);
  8960. if (is("operator", "in")) {
  8961. if (init[0] == "var" && init[1].length > 1)
  8962. croak("Only one variable declaration allowed in for..in loop");
  8963. return for_in(init);
  8964. }
  8965. }
  8966. return regular_for(init);
  8967. };
  8968. function regular_for(init) {
  8969. expect(";");
  8970. var test = is("punc", ";") ? null : expression();
  8971. expect(";");
  8972. var step = is("punc", ")") ? null : expression();
  8973. expect(")");
  8974. return as("for", init, test, step, in_loop(statement));
  8975. };
  8976. function for_in(init) {
  8977. var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
  8978. next();
  8979. var obj = expression();
  8980. expect(")");
  8981. return as("for-in", init, lhs, obj, in_loop(statement));
  8982. };
  8983. var function_ = function(in_statement) {
  8984. var name = is("name") ? prog1(S.token.value, next) : null;
  8985. if (in_statement && !name)
  8986. unexpected();
  8987. expect("(");
  8988. return as(in_statement ? "defun" : "function",
  8989. name,
  8990. // arguments
  8991. (function(first, a){
  8992. while (!is("punc", ")")) {
  8993. if (first) first = false; else expect(",");
  8994. if (!is("name")) unexpected();
  8995. a.push(S.token.value);
  8996. next();
  8997. }
  8998. next();
  8999. return a;
  9000. })(true, []),
  9001. // body
  9002. (function(){
  9003. ++S.in_function;
  9004. var loop = S.in_loop;
  9005. S.in_directives = true;
  9006. S.in_loop = 0;
  9007. var a = block_();
  9008. --S.in_function;
  9009. S.in_loop = loop;
  9010. return a;
  9011. })());
  9012. };
  9013. function if_() {
  9014. var cond = parenthesised(), body = statement(), belse;
  9015. if (is("keyword", "else")) {
  9016. next();
  9017. belse = statement();
  9018. }
  9019. return as("if", cond, body, belse);
  9020. };
  9021. function block_() {
  9022. expect("{");
  9023. var a = [];
  9024. while (!is("punc", "}")) {
  9025. if (is("eof")) unexpected();
  9026. a.push(statement());
  9027. }
  9028. next();
  9029. return a;
  9030. };
  9031. var switch_block_ = curry(in_loop, function(){
  9032. expect("{");
  9033. var a = [], cur = null;
  9034. while (!is("punc", "}")) {
  9035. if (is("eof")) unexpected();
  9036. if (is("keyword", "case")) {
  9037. next();
  9038. cur = [];
  9039. a.push([ expression(), cur ]);
  9040. expect(":");
  9041. }
  9042. else if (is("keyword", "default")) {
  9043. next();
  9044. expect(":");
  9045. cur = [];
  9046. a.push([ null, cur ]);
  9047. }
  9048. else {
  9049. if (!cur) unexpected();
  9050. cur.push(statement());
  9051. }
  9052. }
  9053. next();
  9054. return a;
  9055. });
  9056. function try_() {
  9057. var body = block_(), bcatch, bfinally;
  9058. if (is("keyword", "catch")) {
  9059. next();
  9060. expect("(");
  9061. if (!is("name"))
  9062. croak("Name expected");
  9063. var name = S.token.value;
  9064. next();
  9065. expect(")");
  9066. bcatch = [ name, block_() ];
  9067. }
  9068. if (is("keyword", "finally")) {
  9069. next();
  9070. bfinally = block_();
  9071. }
  9072. if (!bcatch && !bfinally)
  9073. croak("Missing catch/finally blocks");
  9074. return as("try", body, bcatch, bfinally);
  9075. };
  9076. function vardefs(no_in) {
  9077. var a = [];
  9078. for (;;) {
  9079. if (!is("name"))
  9080. unexpected();
  9081. var name = S.token.value;
  9082. next();
  9083. if (is("operator", "=")) {
  9084. next();
  9085. a.push([ name, expression(false, no_in) ]);
  9086. } else {
  9087. a.push([ name ]);
  9088. }
  9089. if (!is("punc", ","))
  9090. break;
  9091. next();
  9092. }
  9093. return a;
  9094. };
  9095. function var_(no_in) {
  9096. return as("var", vardefs(no_in));
  9097. };
  9098. function const_() {
  9099. return as("const", vardefs());
  9100. };
  9101. function new_() {
  9102. var newexp = expr_atom(false), args;
  9103. if (is("punc", "(")) {
  9104. next();
  9105. args = expr_list(")");
  9106. } else {
  9107. args = [];
  9108. }
  9109. return subscripts(as("new", newexp, args), true);
  9110. };
  9111. var expr_atom = maybe_embed_tokens(function(allow_calls) {
  9112. if (is("operator", "new")) {
  9113. next();
  9114. return new_();
  9115. }
  9116. if (is("punc")) {
  9117. switch (S.token.value) {
  9118. case "(":
  9119. next();
  9120. return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
  9121. case "[":
  9122. next();
  9123. return subscripts(array_(), allow_calls);
  9124. case "{":
  9125. next();
  9126. return subscripts(object_(), allow_calls);
  9127. }
  9128. unexpected();
  9129. }
  9130. if (is("keyword", "function")) {
  9131. next();
  9132. return subscripts(function_(false), allow_calls);
  9133. }
  9134. if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
  9135. var atom = S.token.type == "regexp"
  9136. ? as("regexp", S.token.value[0], S.token.value[1])
  9137. : as(S.token.type, S.token.value);
  9138. return subscripts(prog1(atom, next), allow_calls);
  9139. }
  9140. unexpected();
  9141. });
  9142. function expr_list(closing, allow_trailing_comma, allow_empty) {
  9143. var first = true, a = [];
  9144. while (!is("punc", closing)) {
  9145. if (first) first = false; else expect(",");
  9146. if (allow_trailing_comma && is("punc", closing)) break;
  9147. if (is("punc", ",") && allow_empty) {
  9148. a.push([ "atom", "undefined" ]);
  9149. } else {
  9150. a.push(expression(false));
  9151. }
  9152. }
  9153. next();
  9154. return a;
  9155. };
  9156. function array_() {
  9157. return as("array", expr_list("]", !exigent_mode, true));
  9158. };
  9159. function object_() {
  9160. var first = true, a = [];
  9161. while (!is("punc", "}")) {
  9162. if (first) first = false; else expect(",");
  9163. if (!exigent_mode && is("punc", "}"))
  9164. // allow trailing comma
  9165. break;
  9166. var type = S.token.type;
  9167. var name = as_property_name();
  9168. if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
  9169. a.push([ as_name(), function_(false), name ]);
  9170. } else {
  9171. expect(":");
  9172. a.push([ name, expression(false) ]);
  9173. }
  9174. }
  9175. next();
  9176. return as("object", a);
  9177. };
  9178. function as_property_name() {
  9179. switch (S.token.type) {
  9180. case "num":
  9181. case "string":
  9182. return prog1(S.token.value, next);
  9183. }
  9184. return as_name();
  9185. };
  9186. function as_name() {
  9187. switch (S.token.type) {
  9188. case "name":
  9189. case "operator":
  9190. case "keyword":
  9191. case "atom":
  9192. return prog1(S.token.value, next);
  9193. default:
  9194. unexpected();
  9195. }
  9196. };
  9197. function subscripts(expr, allow_calls) {
  9198. if (is("punc", ".")) {
  9199. next();
  9200. return subscripts(as("dot", expr, as_name()), allow_calls);
  9201. }
  9202. if (is("punc", "[")) {
  9203. next();
  9204. return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
  9205. }
  9206. if (allow_calls && is("punc", "(")) {
  9207. next();
  9208. return subscripts(as("call", expr, expr_list(")")), true);
  9209. }
  9210. return expr;
  9211. };
  9212. function maybe_unary(allow_calls) {
  9213. if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
  9214. return make_unary("unary-prefix",
  9215. prog1(S.token.value, next),
  9216. maybe_unary(allow_calls));
  9217. }
  9218. var val = expr_atom(allow_calls);
  9219. while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
  9220. val = make_unary("unary-postfix", S.token.value, val);
  9221. next();
  9222. }
  9223. return val;
  9224. };
  9225. function make_unary(tag, op, expr) {
  9226. if ((op == "++" || op == "--") && !is_assignable(expr))
  9227. croak("Invalid use of " + op + " operator");
  9228. return as(tag, op, expr);
  9229. };
  9230. function expr_op(left, min_prec, no_in) {
  9231. var op = is("operator") ? S.token.value : null;
  9232. if (op && op == "in" && no_in) op = null;
  9233. var prec = op != null ? PRECEDENCE[op] : null;
  9234. if (prec != null && prec > min_prec) {
  9235. next();
  9236. var right = expr_op(maybe_unary(true), prec, no_in);
  9237. return expr_op(as("binary", op, left, right), min_prec, no_in);
  9238. }
  9239. return left;
  9240. };
  9241. function expr_ops(no_in) {
  9242. return expr_op(maybe_unary(true), 0, no_in);
  9243. };
  9244. function maybe_conditional(no_in) {
  9245. var expr = expr_ops(no_in);
  9246. if (is("operator", "?")) {
  9247. next();
  9248. var yes = expression(false);
  9249. expect(":");
  9250. return as("conditional", expr, yes, expression(false, no_in));
  9251. }
  9252. return expr;
  9253. };
  9254. function is_assignable(expr) {
  9255. if (!exigent_mode) return true;
  9256. switch (expr[0]+"") {
  9257. case "dot":
  9258. case "sub":
  9259. case "new":
  9260. case "call":
  9261. return true;
  9262. case "name":
  9263. return expr[1] != "this";
  9264. }
  9265. };
  9266. function maybe_assign(no_in) {
  9267. var left = maybe_conditional(no_in), val = S.token.value;
  9268. if (is("operator") && HOP(ASSIGNMENT, val)) {
  9269. if (is_assignable(left)) {
  9270. next();
  9271. return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
  9272. }
  9273. croak("Invalid assignment");
  9274. }
  9275. return left;
  9276. };
  9277. var expression = maybe_embed_tokens(function(commas, no_in) {
  9278. if (arguments.length == 0)
  9279. commas = true;
  9280. var expr = maybe_assign(no_in);
  9281. if (commas && is("punc", ",")) {
  9282. next();
  9283. return as("seq", expr, expression(true, no_in));
  9284. }
  9285. return expr;
  9286. });
  9287. function in_loop(cont) {
  9288. try {
  9289. ++S.in_loop;
  9290. return cont();
  9291. } finally {
  9292. --S.in_loop;
  9293. }
  9294. };
  9295. return as("toplevel", (function(a){
  9296. while (!is("eof"))
  9297. a.push(statement());
  9298. return a;
  9299. })([]));
  9300. };
  9301. /* -----[ Utilities ]----- */
  9302. function curry(f) {
  9303. var args = slice(arguments, 1);
  9304. return function() { return f.apply(this, args.concat(slice(arguments))); };
  9305. };
  9306. function prog1(ret) {
  9307. if (ret instanceof Function)
  9308. ret = ret();
  9309. for (var i = 1, n = arguments.length; --n > 0; ++i)
  9310. arguments[i]();
  9311. return ret;
  9312. };
  9313. function array_to_hash(a) {
  9314. var ret = {};
  9315. for (var i = 0; i < a.length; ++i)
  9316. ret[a[i]] = true;
  9317. return ret;
  9318. };
  9319. function slice(a, start) {
  9320. return Array.prototype.slice.call(a, start || 0);
  9321. };
  9322. function characters(str) {
  9323. return str.split("");
  9324. };
  9325. function member(name, array) {
  9326. for (var i = array.length; --i >= 0;)
  9327. if (array[i] == name)
  9328. return true;
  9329. return false;
  9330. };
  9331. function HOP(obj, prop) {
  9332. return Object.prototype.hasOwnProperty.call(obj, prop);
  9333. };
  9334. var warn = function() {};
  9335. /* -----[ Exports ]----- */
  9336. exports.tokenizer = tokenizer;
  9337. exports.parse = parse;
  9338. exports.slice = slice;
  9339. exports.curry = curry;
  9340. exports.member = member;
  9341. exports.array_to_hash = array_to_hash;
  9342. exports.PRECEDENCE = PRECEDENCE;
  9343. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  9344. exports.RESERVED_WORDS = RESERVED_WORDS;
  9345. exports.KEYWORDS = KEYWORDS;
  9346. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  9347. exports.OPERATORS = OPERATORS;
  9348. exports.is_alphanumeric_char = is_alphanumeric_char;
  9349. exports.is_identifier_start = is_identifier_start;
  9350. exports.is_identifier_char = is_identifier_char;
  9351. exports.set_logger = function(logger) {
  9352. warn = logger;
  9353. };
  9354. // Local variables:
  9355. // js-indent-level: 4
  9356. // End:
  9357. });define('uglifyjs/squeeze-more', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  9358. var jsp = require("./parse-js"),
  9359. pro = require("./process"),
  9360. slice = jsp.slice,
  9361. member = jsp.member,
  9362. curry = jsp.curry,
  9363. MAP = pro.MAP,
  9364. PRECEDENCE = jsp.PRECEDENCE,
  9365. OPERATORS = jsp.OPERATORS;
  9366. function ast_squeeze_more(ast) {
  9367. var w = pro.ast_walker(), walk = w.walk, scope;
  9368. function with_scope(s, cont) {
  9369. var save = scope, ret;
  9370. scope = s;
  9371. ret = cont();
  9372. scope = save;
  9373. return ret;
  9374. };
  9375. function _lambda(name, args, body) {
  9376. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  9377. };
  9378. return w.with_walkers({
  9379. "toplevel": function(body) {
  9380. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  9381. },
  9382. "function": _lambda,
  9383. "defun": _lambda,
  9384. "new": function(ctor, args) {
  9385. if (ctor[0] == "name") {
  9386. if (ctor[1] == "Array" && !scope.has("Array")) {
  9387. if (args.length != 1) {
  9388. return [ "array", args ];
  9389. } else {
  9390. return walk([ "call", [ "name", "Array" ], args ]);
  9391. }
  9392. } else if (ctor[1] == "Object" && !scope.has("Object")) {
  9393. if (!args.length) {
  9394. return [ "object", [] ];
  9395. } else {
  9396. return walk([ "call", [ "name", "Object" ], args ]);
  9397. }
  9398. } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
  9399. return walk([ "call", [ "name", ctor[1] ], args]);
  9400. }
  9401. }
  9402. },
  9403. "call": function(expr, args) {
  9404. if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
  9405. && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
  9406. return [ "call", [ "dot", expr[1], "slice"], args];
  9407. }
  9408. if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
  9409. // foo.toString() ==> foo+""
  9410. if (expr[1][0] == "string") return expr[1];
  9411. return [ "binary", "+", expr[1], [ "string", "" ]];
  9412. }
  9413. if (expr[0] == "name") {
  9414. if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
  9415. return [ "array", args ];
  9416. }
  9417. if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
  9418. return [ "object", [] ];
  9419. }
  9420. if (expr[1] == "String" && !scope.has("String")) {
  9421. return [ "binary", "+", args[0], [ "string", "" ]];
  9422. }
  9423. }
  9424. }
  9425. }, function() {
  9426. return walk(pro.ast_add_scope(ast));
  9427. });
  9428. };
  9429. exports.ast_squeeze_more = ast_squeeze_more;
  9430. // Local variables:
  9431. // js-indent-level: 4
  9432. // End:
  9433. });
  9434. define('uglifyjs/process', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  9435. /***********************************************************************
  9436. A JavaScript tokenizer / parser / beautifier / compressor.
  9437. This version is suitable for Node.js. With minimal changes (the
  9438. exports stuff) it should work on any JS platform.
  9439. This file implements some AST processors. They work on data built
  9440. by parse-js.
  9441. Exported functions:
  9442. - ast_mangle(ast, options) -- mangles the variable/function names
  9443. in the AST. Returns an AST.
  9444. - ast_squeeze(ast) -- employs various optimizations to make the
  9445. final generated code even smaller. Returns an AST.
  9446. - gen_code(ast, options) -- generates JS code from the AST. Pass
  9447. true (or an object, see the code for some options) as second
  9448. argument to get "pretty" (indented) code.
  9449. -------------------------------- (C) ---------------------------------
  9450. Author: Mihai Bazon
  9451. <mihai.bazon@gmail.com>
  9452. http://mihai.bazon.net/blog
  9453. Distributed under the BSD license:
  9454. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  9455. Redistribution and use in source and binary forms, with or without
  9456. modification, are permitted provided that the following conditions
  9457. are met:
  9458. * Redistributions of source code must retain the above
  9459. copyright notice, this list of conditions and the following
  9460. disclaimer.
  9461. * Redistributions in binary form must reproduce the above
  9462. copyright notice, this list of conditions and the following
  9463. disclaimer in the documentation and/or other materials
  9464. provided with the distribution.
  9465. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  9466. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  9467. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  9468. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  9469. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  9470. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  9471. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  9472. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9473. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  9474. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  9475. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  9476. SUCH DAMAGE.
  9477. ***********************************************************************/
  9478. var jsp = require("./parse-js"),
  9479. curry = jsp.curry,
  9480. slice = jsp.slice,
  9481. member = jsp.member,
  9482. is_identifier_char = jsp.is_identifier_char,
  9483. PRECEDENCE = jsp.PRECEDENCE,
  9484. OPERATORS = jsp.OPERATORS;
  9485. /* -----[ helper for AST traversal ]----- */
  9486. function ast_walker() {
  9487. function _vardefs(defs) {
  9488. return [ this[0], MAP(defs, function(def){
  9489. var a = [ def[0] ];
  9490. if (def.length > 1)
  9491. a[1] = walk(def[1]);
  9492. return a;
  9493. }) ];
  9494. };
  9495. function _block(statements) {
  9496. var out = [ this[0] ];
  9497. if (statements != null)
  9498. out.push(MAP(statements, walk));
  9499. return out;
  9500. };
  9501. var walkers = {
  9502. "string": function(str) {
  9503. return [ this[0], str ];
  9504. },
  9505. "num": function(num) {
  9506. return [ this[0], num ];
  9507. },
  9508. "name": function(name) {
  9509. return [ this[0], name ];
  9510. },
  9511. "toplevel": function(statements) {
  9512. return [ this[0], MAP(statements, walk) ];
  9513. },
  9514. "block": _block,
  9515. "splice": _block,
  9516. "var": _vardefs,
  9517. "const": _vardefs,
  9518. "try": function(t, c, f) {
  9519. return [
  9520. this[0],
  9521. MAP(t, walk),
  9522. c != null ? [ c[0], MAP(c[1], walk) ] : null,
  9523. f != null ? MAP(f, walk) : null
  9524. ];
  9525. },
  9526. "throw": function(expr) {
  9527. return [ this[0], walk(expr) ];
  9528. },
  9529. "new": function(ctor, args) {
  9530. return [ this[0], walk(ctor), MAP(args, walk) ];
  9531. },
  9532. "switch": function(expr, body) {
  9533. return [ this[0], walk(expr), MAP(body, function(branch){
  9534. return [ branch[0] ? walk(branch[0]) : null,
  9535. MAP(branch[1], walk) ];
  9536. }) ];
  9537. },
  9538. "break": function(label) {
  9539. return [ this[0], label ];
  9540. },
  9541. "continue": function(label) {
  9542. return [ this[0], label ];
  9543. },
  9544. "conditional": function(cond, t, e) {
  9545. return [ this[0], walk(cond), walk(t), walk(e) ];
  9546. },
  9547. "assign": function(op, lvalue, rvalue) {
  9548. return [ this[0], op, walk(lvalue), walk(rvalue) ];
  9549. },
  9550. "dot": function(expr) {
  9551. return [ this[0], walk(expr) ].concat(slice(arguments, 1));
  9552. },
  9553. "call": function(expr, args) {
  9554. return [ this[0], walk(expr), MAP(args, walk) ];
  9555. },
  9556. "function": function(name, args, body) {
  9557. return [ this[0], name, args.slice(), MAP(body, walk) ];
  9558. },
  9559. "debugger": function() {
  9560. return [ this[0] ];
  9561. },
  9562. "defun": function(name, args, body) {
  9563. return [ this[0], name, args.slice(), MAP(body, walk) ];
  9564. },
  9565. "if": function(conditional, t, e) {
  9566. return [ this[0], walk(conditional), walk(t), walk(e) ];
  9567. },
  9568. "for": function(init, cond, step, block) {
  9569. return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
  9570. },
  9571. "for-in": function(vvar, key, hash, block) {
  9572. return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
  9573. },
  9574. "while": function(cond, block) {
  9575. return [ this[0], walk(cond), walk(block) ];
  9576. },
  9577. "do": function(cond, block) {
  9578. return [ this[0], walk(cond), walk(block) ];
  9579. },
  9580. "return": function(expr) {
  9581. return [ this[0], walk(expr) ];
  9582. },
  9583. "binary": function(op, left, right) {
  9584. return [ this[0], op, walk(left), walk(right) ];
  9585. },
  9586. "unary-prefix": function(op, expr) {
  9587. return [ this[0], op, walk(expr) ];
  9588. },
  9589. "unary-postfix": function(op, expr) {
  9590. return [ this[0], op, walk(expr) ];
  9591. },
  9592. "sub": function(expr, subscript) {
  9593. return [ this[0], walk(expr), walk(subscript) ];
  9594. },
  9595. "object": function(props) {
  9596. return [ this[0], MAP(props, function(p){
  9597. return p.length == 2
  9598. ? [ p[0], walk(p[1]) ]
  9599. : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
  9600. }) ];
  9601. },
  9602. "regexp": function(rx, mods) {
  9603. return [ this[0], rx, mods ];
  9604. },
  9605. "array": function(elements) {
  9606. return [ this[0], MAP(elements, walk) ];
  9607. },
  9608. "stat": function(stat) {
  9609. return [ this[0], walk(stat) ];
  9610. },
  9611. "seq": function() {
  9612. return [ this[0] ].concat(MAP(slice(arguments), walk));
  9613. },
  9614. "label": function(name, block) {
  9615. return [ this[0], name, walk(block) ];
  9616. },
  9617. "with": function(expr, block) {
  9618. return [ this[0], walk(expr), walk(block) ];
  9619. },
  9620. "atom": function(name) {
  9621. return [ this[0], name ];
  9622. },
  9623. "directive": function(dir) {
  9624. return [ this[0], dir ];
  9625. }
  9626. };
  9627. var user = {};
  9628. var stack = [];
  9629. function walk(ast) {
  9630. if (ast == null)
  9631. return null;
  9632. try {
  9633. stack.push(ast);
  9634. var type = ast[0];
  9635. var gen = user[type];
  9636. if (gen) {
  9637. var ret = gen.apply(ast, ast.slice(1));
  9638. if (ret != null)
  9639. return ret;
  9640. }
  9641. gen = walkers[type];
  9642. return gen.apply(ast, ast.slice(1));
  9643. } finally {
  9644. stack.pop();
  9645. }
  9646. };
  9647. function dive(ast) {
  9648. if (ast == null)
  9649. return null;
  9650. try {
  9651. stack.push(ast);
  9652. return walkers[ast[0]].apply(ast, ast.slice(1));
  9653. } finally {
  9654. stack.pop();
  9655. }
  9656. };
  9657. function with_walkers(walkers, cont){
  9658. var save = {}, i;
  9659. for (i in walkers) if (HOP(walkers, i)) {
  9660. save[i] = user[i];
  9661. user[i] = walkers[i];
  9662. }
  9663. var ret = cont();
  9664. for (i in save) if (HOP(save, i)) {
  9665. if (!save[i]) delete user[i];
  9666. else user[i] = save[i];
  9667. }
  9668. return ret;
  9669. };
  9670. return {
  9671. walk: walk,
  9672. dive: dive,
  9673. with_walkers: with_walkers,
  9674. parent: function() {
  9675. return stack[stack.length - 2]; // last one is current node
  9676. },
  9677. stack: function() {
  9678. return stack;
  9679. }
  9680. };
  9681. };
  9682. /* -----[ Scope and mangling ]----- */
  9683. function Scope(parent) {
  9684. this.names = {}; // names defined in this scope
  9685. this.mangled = {}; // mangled names (orig.name => mangled)
  9686. this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
  9687. this.cname = -1; // current mangled name
  9688. this.refs = {}; // names referenced from this scope
  9689. this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
  9690. this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
  9691. this.directives = []; // directives activated from this scope
  9692. this.parent = parent; // parent scope
  9693. this.children = []; // sub-scopes
  9694. if (parent) {
  9695. this.level = parent.level + 1;
  9696. parent.children.push(this);
  9697. } else {
  9698. this.level = 0;
  9699. }
  9700. };
  9701. function base54_digits() {
  9702. if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
  9703. return DIGITS_OVERRIDE_FOR_TESTING;
  9704. else
  9705. return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
  9706. }
  9707. var base54 = (function(){
  9708. var DIGITS = base54_digits();
  9709. return function(num) {
  9710. var ret = "", base = 54;
  9711. do {
  9712. ret += DIGITS.charAt(num % base);
  9713. num = Math.floor(num / base);
  9714. base = 64;
  9715. } while (num > 0);
  9716. return ret;
  9717. };
  9718. })();
  9719. Scope.prototype = {
  9720. has: function(name) {
  9721. for (var s = this; s; s = s.parent)
  9722. if (HOP(s.names, name))
  9723. return s;
  9724. },
  9725. has_mangled: function(mname) {
  9726. for (var s = this; s; s = s.parent)
  9727. if (HOP(s.rev_mangled, mname))
  9728. return s;
  9729. },
  9730. toJSON: function() {
  9731. return {
  9732. names: this.names,
  9733. uses_eval: this.uses_eval,
  9734. uses_with: this.uses_with
  9735. };
  9736. },
  9737. next_mangled: function() {
  9738. // we must be careful that the new mangled name:
  9739. //
  9740. // 1. doesn't shadow a mangled name from a parent
  9741. // scope, unless we don't reference the original
  9742. // name from this scope OR from any sub-scopes!
  9743. // This will get slow.
  9744. //
  9745. // 2. doesn't shadow an original name from a parent
  9746. // scope, in the event that the name is not mangled
  9747. // in the parent scope and we reference that name
  9748. // here OR IN ANY SUBSCOPES!
  9749. //
  9750. // 3. doesn't shadow a name that is referenced but not
  9751. // defined (possibly global defined elsewhere).
  9752. for (;;) {
  9753. var m = base54(++this.cname), prior;
  9754. // case 1.
  9755. prior = this.has_mangled(m);
  9756. if (prior && this.refs[prior.rev_mangled[m]] === prior)
  9757. continue;
  9758. // case 2.
  9759. prior = this.has(m);
  9760. if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
  9761. continue;
  9762. // case 3.
  9763. if (HOP(this.refs, m) && this.refs[m] == null)
  9764. continue;
  9765. // I got "do" once. :-/
  9766. if (!is_identifier(m))
  9767. continue;
  9768. return m;
  9769. }
  9770. },
  9771. set_mangle: function(name, m) {
  9772. this.rev_mangled[m] = name;
  9773. return this.mangled[name] = m;
  9774. },
  9775. get_mangled: function(name, newMangle) {
  9776. if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
  9777. var s = this.has(name);
  9778. if (!s) return name; // not in visible scope, no mangle
  9779. if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
  9780. if (!newMangle) return name; // not found and no mangling requested
  9781. return s.set_mangle(name, s.next_mangled());
  9782. },
  9783. references: function(name) {
  9784. return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
  9785. },
  9786. define: function(name, type) {
  9787. if (name != null) {
  9788. if (type == "var" || !HOP(this.names, name))
  9789. this.names[name] = type || "var";
  9790. return name;
  9791. }
  9792. },
  9793. active_directive: function(dir) {
  9794. return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
  9795. }
  9796. };
  9797. function ast_add_scope(ast) {
  9798. var current_scope = null;
  9799. var w = ast_walker(), walk = w.walk;
  9800. var having_eval = [];
  9801. function with_new_scope(cont) {
  9802. current_scope = new Scope(current_scope);
  9803. current_scope.labels = new Scope();
  9804. var ret = current_scope.body = cont();
  9805. ret.scope = current_scope;
  9806. current_scope = current_scope.parent;
  9807. return ret;
  9808. };
  9809. function define(name, type) {
  9810. return current_scope.define(name, type);
  9811. };
  9812. function reference(name) {
  9813. current_scope.refs[name] = true;
  9814. };
  9815. function _lambda(name, args, body) {
  9816. var is_defun = this[0] == "defun";
  9817. return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
  9818. if (!is_defun) define(name, "lambda");
  9819. MAP(args, function(name){ define(name, "arg") });
  9820. return MAP(body, walk);
  9821. })];
  9822. };
  9823. function _vardefs(type) {
  9824. return function(defs) {
  9825. MAP(defs, function(d){
  9826. define(d[0], type);
  9827. if (d[1]) reference(d[0]);
  9828. });
  9829. };
  9830. };
  9831. function _breacont(label) {
  9832. if (label)
  9833. current_scope.labels.refs[label] = true;
  9834. };
  9835. return with_new_scope(function(){
  9836. // process AST
  9837. var ret = w.with_walkers({
  9838. "function": _lambda,
  9839. "defun": _lambda,
  9840. "label": function(name, stat) { current_scope.labels.define(name) },
  9841. "break": _breacont,
  9842. "continue": _breacont,
  9843. "with": function(expr, block) {
  9844. for (var s = current_scope; s; s = s.parent)
  9845. s.uses_with = true;
  9846. },
  9847. "var": _vardefs("var"),
  9848. "const": _vardefs("const"),
  9849. "try": function(t, c, f) {
  9850. if (c != null) return [
  9851. this[0],
  9852. MAP(t, walk),
  9853. [ define(c[0], "catch"), MAP(c[1], walk) ],
  9854. f != null ? MAP(f, walk) : null
  9855. ];
  9856. },
  9857. "name": function(name) {
  9858. if (name == "eval")
  9859. having_eval.push(current_scope);
  9860. reference(name);
  9861. }
  9862. }, function(){
  9863. return walk(ast);
  9864. });
  9865. // the reason why we need an additional pass here is
  9866. // that names can be used prior to their definition.
  9867. // scopes where eval was detected and their parents
  9868. // are marked with uses_eval, unless they define the
  9869. // "eval" name.
  9870. MAP(having_eval, function(scope){
  9871. if (!scope.has("eval")) while (scope) {
  9872. scope.uses_eval = true;
  9873. scope = scope.parent;
  9874. }
  9875. });
  9876. // for referenced names it might be useful to know
  9877. // their origin scope. current_scope here is the
  9878. // toplevel one.
  9879. function fixrefs(scope, i) {
  9880. // do children first; order shouldn't matter
  9881. for (i = scope.children.length; --i >= 0;)
  9882. fixrefs(scope.children[i]);
  9883. for (i in scope.refs) if (HOP(scope.refs, i)) {
  9884. // find origin scope and propagate the reference to origin
  9885. for (var origin = scope.has(i), s = scope; s; s = s.parent) {
  9886. s.refs[i] = origin;
  9887. if (s === origin) break;
  9888. }
  9889. }
  9890. };
  9891. fixrefs(current_scope);
  9892. return ret;
  9893. });
  9894. };
  9895. /* -----[ mangle names ]----- */
  9896. function ast_mangle(ast, options) {
  9897. var w = ast_walker(), walk = w.walk, scope;
  9898. options = defaults(options, {
  9899. mangle : true,
  9900. toplevel : false,
  9901. defines : null,
  9902. except : null,
  9903. no_functions : false
  9904. });
  9905. function get_mangled(name, newMangle) {
  9906. if (!options.mangle) return name;
  9907. if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
  9908. if (options.except && member(name, options.except))
  9909. return name;
  9910. if (options.no_functions && HOP(scope.names, name) &&
  9911. (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
  9912. return name;
  9913. return scope.get_mangled(name, newMangle);
  9914. };
  9915. function get_define(name) {
  9916. if (options.defines) {
  9917. // we always lookup a defined symbol for the current scope FIRST, so declared
  9918. // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
  9919. if (!scope.has(name)) {
  9920. if (HOP(options.defines, name)) {
  9921. return options.defines[name];
  9922. }
  9923. }
  9924. return null;
  9925. }
  9926. };
  9927. function _lambda(name, args, body) {
  9928. if (!options.no_functions && options.mangle) {
  9929. var is_defun = this[0] == "defun", extra;
  9930. if (name) {
  9931. if (is_defun) name = get_mangled(name);
  9932. else if (body.scope.references(name)) {
  9933. extra = {};
  9934. if (!(scope.uses_eval || scope.uses_with))
  9935. name = extra[name] = scope.next_mangled();
  9936. else
  9937. extra[name] = name;
  9938. }
  9939. else name = null;
  9940. }
  9941. }
  9942. body = with_scope(body.scope, function(){
  9943. args = MAP(args, function(name){ return get_mangled(name) });
  9944. return MAP(body, walk);
  9945. }, extra);
  9946. return [ this[0], name, args, body ];
  9947. };
  9948. function with_scope(s, cont, extra) {
  9949. var _scope = scope;
  9950. scope = s;
  9951. if (extra) for (var i in extra) if (HOP(extra, i)) {
  9952. s.set_mangle(i, extra[i]);
  9953. }
  9954. for (var i in s.names) if (HOP(s.names, i)) {
  9955. get_mangled(i, true);
  9956. }
  9957. var ret = cont();
  9958. ret.scope = s;
  9959. scope = _scope;
  9960. return ret;
  9961. };
  9962. function _vardefs(defs) {
  9963. return [ this[0], MAP(defs, function(d){
  9964. return [ get_mangled(d[0]), walk(d[1]) ];
  9965. }) ];
  9966. };
  9967. function _breacont(label) {
  9968. if (label) return [ this[0], scope.labels.get_mangled(label) ];
  9969. };
  9970. return w.with_walkers({
  9971. "function": _lambda,
  9972. "defun": function() {
  9973. // move function declarations to the top when
  9974. // they are not in some block.
  9975. var ast = _lambda.apply(this, arguments);
  9976. switch (w.parent()[0]) {
  9977. case "toplevel":
  9978. case "function":
  9979. case "defun":
  9980. return MAP.at_top(ast);
  9981. }
  9982. return ast;
  9983. },
  9984. "label": function(label, stat) {
  9985. if (scope.labels.refs[label]) return [
  9986. this[0],
  9987. scope.labels.get_mangled(label, true),
  9988. walk(stat)
  9989. ];
  9990. return walk(stat);
  9991. },
  9992. "break": _breacont,
  9993. "continue": _breacont,
  9994. "var": _vardefs,
  9995. "const": _vardefs,
  9996. "name": function(name) {
  9997. return get_define(name) || [ this[0], get_mangled(name) ];
  9998. },
  9999. "try": function(t, c, f) {
  10000. return [ this[0],
  10001. MAP(t, walk),
  10002. c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
  10003. f != null ? MAP(f, walk) : null ];
  10004. },
  10005. "toplevel": function(body) {
  10006. var self = this;
  10007. return with_scope(self.scope, function(){
  10008. return [ self[0], MAP(body, walk) ];
  10009. });
  10010. },
  10011. "directive": function() {
  10012. return MAP.at_top(this);
  10013. }
  10014. }, function() {
  10015. return walk(ast_add_scope(ast));
  10016. });
  10017. };
  10018. /* -----[
  10019. - compress foo["bar"] into foo.bar,
  10020. - remove block brackets {} where possible
  10021. - join consecutive var declarations
  10022. - various optimizations for IFs:
  10023. - if (cond) foo(); else bar(); ==> cond?foo():bar();
  10024. - if (cond) foo(); ==> cond&&foo();
  10025. - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
  10026. - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
  10027. ]----- */
  10028. var warn = function(){};
  10029. function best_of(ast1, ast2) {
  10030. return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
  10031. };
  10032. function last_stat(b) {
  10033. if (b[0] == "block" && b[1] && b[1].length > 0)
  10034. return b[1][b[1].length - 1];
  10035. return b;
  10036. }
  10037. function aborts(t) {
  10038. if (t) switch (last_stat(t)[0]) {
  10039. case "return":
  10040. case "break":
  10041. case "continue":
  10042. case "throw":
  10043. return true;
  10044. }
  10045. };
  10046. function boolean_expr(expr) {
  10047. return ( (expr[0] == "unary-prefix"
  10048. && member(expr[1], [ "!", "delete" ])) ||
  10049. (expr[0] == "binary"
  10050. && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
  10051. (expr[0] == "binary"
  10052. && member(expr[1], [ "&&", "||" ])
  10053. && boolean_expr(expr[2])
  10054. && boolean_expr(expr[3])) ||
  10055. (expr[0] == "conditional"
  10056. && boolean_expr(expr[2])
  10057. && boolean_expr(expr[3])) ||
  10058. (expr[0] == "assign"
  10059. && expr[1] === true
  10060. && boolean_expr(expr[3])) ||
  10061. (expr[0] == "seq"
  10062. && boolean_expr(expr[expr.length - 1]))
  10063. );
  10064. };
  10065. function empty(b) {
  10066. return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
  10067. };
  10068. function is_string(node) {
  10069. return (node[0] == "string" ||
  10070. node[0] == "unary-prefix" && node[1] == "typeof" ||
  10071. node[0] == "binary" && node[1] == "+" &&
  10072. (is_string(node[2]) || is_string(node[3])));
  10073. };
  10074. var when_constant = (function(){
  10075. var $NOT_CONSTANT = {};
  10076. // this can only evaluate constant expressions. If it finds anything
  10077. // not constant, it throws $NOT_CONSTANT.
  10078. function evaluate(expr) {
  10079. switch (expr[0]) {
  10080. case "string":
  10081. case "num":
  10082. return expr[1];
  10083. case "name":
  10084. case "atom":
  10085. switch (expr[1]) {
  10086. case "true": return true;
  10087. case "false": return false;
  10088. case "null": return null;
  10089. }
  10090. break;
  10091. case "unary-prefix":
  10092. switch (expr[1]) {
  10093. case "!": return !evaluate(expr[2]);
  10094. case "typeof": return typeof evaluate(expr[2]);
  10095. case "~": return ~evaluate(expr[2]);
  10096. case "-": return -evaluate(expr[2]);
  10097. case "+": return +evaluate(expr[2]);
  10098. }
  10099. break;
  10100. case "binary":
  10101. var left = expr[2], right = expr[3];
  10102. switch (expr[1]) {
  10103. case "&&" : return evaluate(left) && evaluate(right);
  10104. case "||" : return evaluate(left) || evaluate(right);
  10105. case "|" : return evaluate(left) | evaluate(right);
  10106. case "&" : return evaluate(left) & evaluate(right);
  10107. case "^" : return evaluate(left) ^ evaluate(right);
  10108. case "+" : return evaluate(left) + evaluate(right);
  10109. case "*" : return evaluate(left) * evaluate(right);
  10110. case "/" : return evaluate(left) / evaluate(right);
  10111. case "%" : return evaluate(left) % evaluate(right);
  10112. case "-" : return evaluate(left) - evaluate(right);
  10113. case "<<" : return evaluate(left) << evaluate(right);
  10114. case ">>" : return evaluate(left) >> evaluate(right);
  10115. case ">>>" : return evaluate(left) >>> evaluate(right);
  10116. case "==" : return evaluate(left) == evaluate(right);
  10117. case "===" : return evaluate(left) === evaluate(right);
  10118. case "!=" : return evaluate(left) != evaluate(right);
  10119. case "!==" : return evaluate(left) !== evaluate(right);
  10120. case "<" : return evaluate(left) < evaluate(right);
  10121. case "<=" : return evaluate(left) <= evaluate(right);
  10122. case ">" : return evaluate(left) > evaluate(right);
  10123. case ">=" : return evaluate(left) >= evaluate(right);
  10124. case "in" : return evaluate(left) in evaluate(right);
  10125. case "instanceof" : return evaluate(left) instanceof evaluate(right);
  10126. }
  10127. }
  10128. throw $NOT_CONSTANT;
  10129. };
  10130. return function(expr, yes, no) {
  10131. try {
  10132. var val = evaluate(expr), ast;
  10133. switch (typeof val) {
  10134. case "string": ast = [ "string", val ]; break;
  10135. case "number": ast = [ "num", val ]; break;
  10136. case "boolean": ast = [ "name", String(val) ]; break;
  10137. default:
  10138. if (val === null) { ast = [ "atom", "null" ]; break; }
  10139. throw new Error("Can't handle constant of type: " + (typeof val));
  10140. }
  10141. return yes.call(expr, ast, val);
  10142. } catch(ex) {
  10143. if (ex === $NOT_CONSTANT) {
  10144. if (expr[0] == "binary"
  10145. && (expr[1] == "===" || expr[1] == "!==")
  10146. && ((is_string(expr[2]) && is_string(expr[3]))
  10147. || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
  10148. expr[1] = expr[1].substr(0, 2);
  10149. }
  10150. else if (no && expr[0] == "binary"
  10151. && (expr[1] == "||" || expr[1] == "&&")) {
  10152. // the whole expression is not constant but the lval may be...
  10153. try {
  10154. var lval = evaluate(expr[2]);
  10155. expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
  10156. (expr[1] == "||" && (lval ? lval : expr[3])) ||
  10157. expr);
  10158. } catch(ex2) {
  10159. // IGNORE... lval is not constant
  10160. }
  10161. }
  10162. return no ? no.call(expr, expr) : null;
  10163. }
  10164. else throw ex;
  10165. }
  10166. };
  10167. })();
  10168. function warn_unreachable(ast) {
  10169. if (!empty(ast))
  10170. warn("Dropping unreachable code: " + gen_code(ast, true));
  10171. };
  10172. function prepare_ifs(ast) {
  10173. var w = ast_walker(), walk = w.walk;
  10174. // In this first pass, we rewrite ifs which abort with no else with an
  10175. // if-else. For example:
  10176. //
  10177. // if (x) {
  10178. // blah();
  10179. // return y;
  10180. // }
  10181. // foobar();
  10182. //
  10183. // is rewritten into:
  10184. //
  10185. // if (x) {
  10186. // blah();
  10187. // return y;
  10188. // } else {
  10189. // foobar();
  10190. // }
  10191. function redo_if(statements) {
  10192. statements = MAP(statements, walk);
  10193. for (var i = 0; i < statements.length; ++i) {
  10194. var fi = statements[i];
  10195. if (fi[0] != "if") continue;
  10196. if (fi[3]) continue;
  10197. var t = fi[2];
  10198. if (!aborts(t)) continue;
  10199. var conditional = walk(fi[1]);
  10200. var e_body = redo_if(statements.slice(i + 1));
  10201. var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
  10202. return statements.slice(0, i).concat([ [
  10203. fi[0], // "if"
  10204. conditional, // conditional
  10205. t, // then
  10206. e // else
  10207. ] ]);
  10208. }
  10209. return statements;
  10210. };
  10211. function redo_if_lambda(name, args, body) {
  10212. body = redo_if(body);
  10213. return [ this[0], name, args, body ];
  10214. };
  10215. function redo_if_block(statements) {
  10216. return [ this[0], statements != null ? redo_if(statements) : null ];
  10217. };
  10218. return w.with_walkers({
  10219. "defun": redo_if_lambda,
  10220. "function": redo_if_lambda,
  10221. "block": redo_if_block,
  10222. "splice": redo_if_block,
  10223. "toplevel": function(statements) {
  10224. return [ this[0], redo_if(statements) ];
  10225. },
  10226. "try": function(t, c, f) {
  10227. return [
  10228. this[0],
  10229. redo_if(t),
  10230. c != null ? [ c[0], redo_if(c[1]) ] : null,
  10231. f != null ? redo_if(f) : null
  10232. ];
  10233. }
  10234. }, function() {
  10235. return walk(ast);
  10236. });
  10237. };
  10238. function for_side_effects(ast, handler) {
  10239. var w = ast_walker(), walk = w.walk;
  10240. var $stop = {}, $restart = {};
  10241. function stop() { throw $stop };
  10242. function restart() { throw $restart };
  10243. function found(){ return handler.call(this, this, w, stop, restart) };
  10244. function unary(op) {
  10245. if (op == "++" || op == "--")
  10246. return found.apply(this, arguments);
  10247. };
  10248. function binary(op) {
  10249. if (op == "&&" || op == "||")
  10250. return found.apply(this, arguments);
  10251. };
  10252. return w.with_walkers({
  10253. "try": found,
  10254. "throw": found,
  10255. "return": found,
  10256. "new": found,
  10257. "switch": found,
  10258. "break": found,
  10259. "continue": found,
  10260. "assign": found,
  10261. "call": found,
  10262. "if": found,
  10263. "for": found,
  10264. "for-in": found,
  10265. "while": found,
  10266. "do": found,
  10267. "return": found,
  10268. "unary-prefix": unary,
  10269. "unary-postfix": unary,
  10270. "conditional": found,
  10271. "binary": binary,
  10272. "defun": found
  10273. }, function(){
  10274. while (true) try {
  10275. walk(ast);
  10276. break;
  10277. } catch(ex) {
  10278. if (ex === $stop) break;
  10279. if (ex === $restart) continue;
  10280. throw ex;
  10281. }
  10282. });
  10283. };
  10284. function ast_lift_variables(ast) {
  10285. var w = ast_walker(), walk = w.walk, scope;
  10286. function do_body(body, env) {
  10287. var _scope = scope;
  10288. scope = env;
  10289. body = MAP(body, walk);
  10290. var hash = {}, names = MAP(env.names, function(type, name){
  10291. if (type != "var") return MAP.skip;
  10292. if (!env.references(name)) return MAP.skip;
  10293. hash[name] = true;
  10294. return [ name ];
  10295. });
  10296. if (names.length > 0) {
  10297. // looking for assignments to any of these variables.
  10298. // we can save considerable space by moving the definitions
  10299. // in the var declaration.
  10300. for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
  10301. if (ast[0] == "assign"
  10302. && ast[1] === true
  10303. && ast[2][0] == "name"
  10304. && HOP(hash, ast[2][1])) {
  10305. // insert the definition into the var declaration
  10306. for (var i = names.length; --i >= 0;) {
  10307. if (names[i][0] == ast[2][1]) {
  10308. if (names[i][1]) // this name already defined, we must stop
  10309. stop();
  10310. names[i][1] = ast[3]; // definition
  10311. names.push(names.splice(i, 1)[0]);
  10312. break;
  10313. }
  10314. }
  10315. // remove this assignment from the AST.
  10316. var p = walker.parent();
  10317. if (p[0] == "seq") {
  10318. var a = p[2];
  10319. a.unshift(0, p.length);
  10320. p.splice.apply(p, a);
  10321. }
  10322. else if (p[0] == "stat") {
  10323. p.splice(0, p.length, "block"); // empty statement
  10324. }
  10325. else {
  10326. stop();
  10327. }
  10328. restart();
  10329. }
  10330. stop();
  10331. });
  10332. body.unshift([ "var", names ]);
  10333. }
  10334. scope = _scope;
  10335. return body;
  10336. };
  10337. function _vardefs(defs) {
  10338. var ret = null;
  10339. for (var i = defs.length; --i >= 0;) {
  10340. var d = defs[i];
  10341. if (!d[1]) continue;
  10342. d = [ "assign", true, [ "name", d[0] ], d[1] ];
  10343. if (ret == null) ret = d;
  10344. else ret = [ "seq", d, ret ];
  10345. }
  10346. if (ret == null && w.parent()[0] != "for") {
  10347. if (w.parent()[0] == "for-in")
  10348. return [ "name", defs[0][0] ];
  10349. return MAP.skip;
  10350. }
  10351. return [ "stat", ret ];
  10352. };
  10353. function _toplevel(body) {
  10354. return [ this[0], do_body(body, this.scope) ];
  10355. };
  10356. return w.with_walkers({
  10357. "function": function(name, args, body){
  10358. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10359. args.pop();
  10360. if (!body.scope.references(name)) name = null;
  10361. return [ this[0], name, args, do_body(body, body.scope) ];
  10362. },
  10363. "defun": function(name, args, body){
  10364. if (!scope.references(name)) return MAP.skip;
  10365. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10366. args.pop();
  10367. return [ this[0], name, args, do_body(body, body.scope) ];
  10368. },
  10369. "var": _vardefs,
  10370. "toplevel": _toplevel
  10371. }, function(){
  10372. return walk(ast_add_scope(ast));
  10373. });
  10374. };
  10375. function ast_squeeze(ast, options) {
  10376. ast = squeeze_1(ast, options);
  10377. ast = squeeze_2(ast, options);
  10378. return ast;
  10379. };
  10380. function squeeze_1(ast, options) {
  10381. options = defaults(options, {
  10382. make_seqs : true,
  10383. dead_code : true,
  10384. no_warnings : false,
  10385. keep_comps : true,
  10386. unsafe : false
  10387. });
  10388. var w = ast_walker(), walk = w.walk, scope;
  10389. function negate(c) {
  10390. var not_c = [ "unary-prefix", "!", c ];
  10391. switch (c[0]) {
  10392. case "unary-prefix":
  10393. return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
  10394. case "seq":
  10395. c = slice(c);
  10396. c[c.length - 1] = negate(c[c.length - 1]);
  10397. return c;
  10398. case "conditional":
  10399. return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
  10400. case "binary":
  10401. var op = c[1], left = c[2], right = c[3];
  10402. if (!options.keep_comps) switch (op) {
  10403. case "<=" : return [ "binary", ">", left, right ];
  10404. case "<" : return [ "binary", ">=", left, right ];
  10405. case ">=" : return [ "binary", "<", left, right ];
  10406. case ">" : return [ "binary", "<=", left, right ];
  10407. }
  10408. switch (op) {
  10409. case "==" : return [ "binary", "!=", left, right ];
  10410. case "!=" : return [ "binary", "==", left, right ];
  10411. case "===" : return [ "binary", "!==", left, right ];
  10412. case "!==" : return [ "binary", "===", left, right ];
  10413. case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
  10414. case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
  10415. }
  10416. break;
  10417. }
  10418. return not_c;
  10419. };
  10420. function make_conditional(c, t, e) {
  10421. var make_real_conditional = function() {
  10422. if (c[0] == "unary-prefix" && c[1] == "!") {
  10423. return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
  10424. } else {
  10425. return e ? best_of(
  10426. [ "conditional", c, t, e ],
  10427. [ "conditional", negate(c), e, t ]
  10428. ) : [ "binary", "&&", c, t ];
  10429. }
  10430. };
  10431. // shortcut the conditional if the expression has a constant value
  10432. return when_constant(c, function(ast, val){
  10433. warn_unreachable(val ? e : t);
  10434. return (val ? t : e);
  10435. }, make_real_conditional);
  10436. };
  10437. function rmblock(block) {
  10438. if (block != null && block[0] == "block" && block[1]) {
  10439. if (block[1].length == 1)
  10440. block = block[1][0];
  10441. else if (block[1].length == 0)
  10442. block = [ "block" ];
  10443. }
  10444. return block;
  10445. };
  10446. function _lambda(name, args, body) {
  10447. return [ this[0], name, args, tighten(body, "lambda") ];
  10448. };
  10449. // this function does a few things:
  10450. // 1. discard useless blocks
  10451. // 2. join consecutive var declarations
  10452. // 3. remove obviously dead code
  10453. // 4. transform consecutive statements using the comma operator
  10454. // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
  10455. function tighten(statements, block_type) {
  10456. statements = MAP(statements, walk);
  10457. statements = statements.reduce(function(a, stat){
  10458. if (stat[0] == "block") {
  10459. if (stat[1]) {
  10460. a.push.apply(a, stat[1]);
  10461. }
  10462. } else {
  10463. a.push(stat);
  10464. }
  10465. return a;
  10466. }, []);
  10467. statements = (function(a, prev){
  10468. statements.forEach(function(cur){
  10469. if (prev && ((cur[0] == "var" && prev[0] == "var") ||
  10470. (cur[0] == "const" && prev[0] == "const"))) {
  10471. prev[1] = prev[1].concat(cur[1]);
  10472. } else {
  10473. a.push(cur);
  10474. prev = cur;
  10475. }
  10476. });
  10477. return a;
  10478. })([]);
  10479. if (options.dead_code) statements = (function(a, has_quit){
  10480. statements.forEach(function(st){
  10481. if (has_quit) {
  10482. if (st[0] == "function" || st[0] == "defun") {
  10483. a.push(st);
  10484. }
  10485. else if (st[0] == "var" || st[0] == "const") {
  10486. if (!options.no_warnings)
  10487. warn("Variables declared in unreachable code");
  10488. st[1] = MAP(st[1], function(def){
  10489. if (def[1] && !options.no_warnings)
  10490. warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
  10491. return [ def[0] ];
  10492. });
  10493. a.push(st);
  10494. }
  10495. else if (!options.no_warnings)
  10496. warn_unreachable(st);
  10497. }
  10498. else {
  10499. a.push(st);
  10500. if (member(st[0], [ "return", "throw", "break", "continue" ]))
  10501. has_quit = true;
  10502. }
  10503. });
  10504. return a;
  10505. })([]);
  10506. if (options.make_seqs) statements = (function(a, prev) {
  10507. statements.forEach(function(cur){
  10508. if (prev && prev[0] == "stat" && cur[0] == "stat") {
  10509. prev[1] = [ "seq", prev[1], cur[1] ];
  10510. } else {
  10511. a.push(cur);
  10512. prev = cur;
  10513. }
  10514. });
  10515. if (a.length >= 2
  10516. && a[a.length-2][0] == "stat"
  10517. && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
  10518. && a[a.length-1][1])
  10519. {
  10520. a.splice(a.length - 2, 2,
  10521. [ a[a.length-1][0],
  10522. [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
  10523. }
  10524. return a;
  10525. })([]);
  10526. // this increases jQuery by 1K. Probably not such a good idea after all..
  10527. // part of this is done in prepare_ifs anyway.
  10528. // if (block_type == "lambda") statements = (function(i, a, stat){
  10529. // while (i < statements.length) {
  10530. // stat = statements[i++];
  10531. // if (stat[0] == "if" && !stat[3]) {
  10532. // if (stat[2][0] == "return" && stat[2][1] == null) {
  10533. // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
  10534. // break;
  10535. // }
  10536. // var last = last_stat(stat[2]);
  10537. // if (last[0] == "return" && last[1] == null) {
  10538. // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
  10539. // break;
  10540. // }
  10541. // }
  10542. // a.push(stat);
  10543. // }
  10544. // return a;
  10545. // })(0, []);
  10546. return statements;
  10547. };
  10548. function make_if(c, t, e) {
  10549. return when_constant(c, function(ast, val){
  10550. if (val) {
  10551. t = walk(t);
  10552. warn_unreachable(e);
  10553. return t || [ "block" ];
  10554. } else {
  10555. e = walk(e);
  10556. warn_unreachable(t);
  10557. return e || [ "block" ];
  10558. }
  10559. }, function() {
  10560. return make_real_if(c, t, e);
  10561. });
  10562. };
  10563. function abort_else(c, t, e) {
  10564. var ret = [ [ "if", negate(c), e ] ];
  10565. if (t[0] == "block") {
  10566. if (t[1]) ret = ret.concat(t[1]);
  10567. } else {
  10568. ret.push(t);
  10569. }
  10570. return walk([ "block", ret ]);
  10571. };
  10572. function make_real_if(c, t, e) {
  10573. c = walk(c);
  10574. t = walk(t);
  10575. e = walk(e);
  10576. if (empty(e) && empty(t))
  10577. return [ "stat", c ];
  10578. if (empty(t)) {
  10579. c = negate(c);
  10580. t = e;
  10581. e = null;
  10582. } else if (empty(e)) {
  10583. e = null;
  10584. } else {
  10585. // if we have both else and then, maybe it makes sense to switch them?
  10586. (function(){
  10587. var a = gen_code(c);
  10588. var n = negate(c);
  10589. var b = gen_code(n);
  10590. if (b.length < a.length) {
  10591. var tmp = t;
  10592. t = e;
  10593. e = tmp;
  10594. c = n;
  10595. }
  10596. })();
  10597. }
  10598. var ret = [ "if", c, t, e ];
  10599. if (t[0] == "if" && empty(t[3]) && empty(e)) {
  10600. ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
  10601. }
  10602. else if (t[0] == "stat") {
  10603. if (e) {
  10604. if (e[0] == "stat")
  10605. ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
  10606. else if (aborts(e))
  10607. ret = abort_else(c, t, e);
  10608. }
  10609. else {
  10610. ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
  10611. }
  10612. }
  10613. else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
  10614. ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
  10615. }
  10616. else if (e && aborts(t)) {
  10617. ret = [ [ "if", c, t ] ];
  10618. if (e[0] == "block") {
  10619. if (e[1]) ret = ret.concat(e[1]);
  10620. }
  10621. else {
  10622. ret.push(e);
  10623. }
  10624. ret = walk([ "block", ret ]);
  10625. }
  10626. else if (t && aborts(e)) {
  10627. ret = abort_else(c, t, e);
  10628. }
  10629. return ret;
  10630. };
  10631. function _do_while(cond, body) {
  10632. return when_constant(cond, function(cond, val){
  10633. if (!val) {
  10634. warn_unreachable(body);
  10635. return [ "block" ];
  10636. } else {
  10637. return [ "for", null, null, null, walk(body) ];
  10638. }
  10639. });
  10640. };
  10641. return w.with_walkers({
  10642. "sub": function(expr, subscript) {
  10643. if (subscript[0] == "string") {
  10644. var name = subscript[1];
  10645. if (is_identifier(name))
  10646. return [ "dot", walk(expr), name ];
  10647. else if (/^[1-9][0-9]*$/.test(name) || name === "0")
  10648. return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
  10649. }
  10650. },
  10651. "if": make_if,
  10652. "toplevel": function(body) {
  10653. return [ "toplevel", tighten(body) ];
  10654. },
  10655. "switch": function(expr, body) {
  10656. var last = body.length - 1;
  10657. return [ "switch", walk(expr), MAP(body, function(branch, i){
  10658. var block = tighten(branch[1]);
  10659. if (i == last && block.length > 0) {
  10660. var node = block[block.length - 1];
  10661. if (node[0] == "break" && !node[1])
  10662. block.pop();
  10663. }
  10664. return [ branch[0] ? walk(branch[0]) : null, block ];
  10665. }) ];
  10666. },
  10667. "function": _lambda,
  10668. "defun": _lambda,
  10669. "block": function(body) {
  10670. if (body) return rmblock([ "block", tighten(body) ]);
  10671. },
  10672. "binary": function(op, left, right) {
  10673. return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
  10674. return best_of(walk(c), this);
  10675. }, function no() {
  10676. return function(){
  10677. if(op != "==" && op != "!=") return;
  10678. var l = walk(left), r = walk(right);
  10679. if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
  10680. left = ['num', +!l[2][1]];
  10681. else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
  10682. right = ['num', +!r[2][1]];
  10683. return ["binary", op, left, right];
  10684. }() || this;
  10685. });
  10686. },
  10687. "conditional": function(c, t, e) {
  10688. return make_conditional(walk(c), walk(t), walk(e));
  10689. },
  10690. "try": function(t, c, f) {
  10691. return [
  10692. "try",
  10693. tighten(t),
  10694. c != null ? [ c[0], tighten(c[1]) ] : null,
  10695. f != null ? tighten(f) : null
  10696. ];
  10697. },
  10698. "unary-prefix": function(op, expr) {
  10699. expr = walk(expr);
  10700. var ret = [ "unary-prefix", op, expr ];
  10701. if (op == "!")
  10702. ret = best_of(ret, negate(expr));
  10703. return when_constant(ret, function(ast, val){
  10704. return walk(ast); // it's either true or false, so minifies to !0 or !1
  10705. }, function() { return ret });
  10706. },
  10707. "name": function(name) {
  10708. switch (name) {
  10709. case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
  10710. case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
  10711. }
  10712. },
  10713. "while": _do_while,
  10714. "assign": function(op, lvalue, rvalue) {
  10715. lvalue = walk(lvalue);
  10716. rvalue = walk(rvalue);
  10717. var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  10718. if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
  10719. ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
  10720. rvalue[2][1] === lvalue[1]) {
  10721. return [ this[0], rvalue[1], lvalue, rvalue[3] ]
  10722. }
  10723. return [ this[0], op, lvalue, rvalue ];
  10724. },
  10725. "call": function(expr, args) {
  10726. expr = walk(expr);
  10727. if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
  10728. return expr[1];
  10729. }
  10730. return [ this[0], expr, MAP(args, walk) ];
  10731. },
  10732. "num": function (num) {
  10733. if (!isFinite(num))
  10734. return [ "binary", "/", num === 1 / 0
  10735. ? [ "num", 1 ] : num === -1 / 0
  10736. ? [ "unary-prefix", "-", [ "num", 1 ] ]
  10737. : [ "num", 0 ], [ "num", 0 ] ];
  10738. return [ this[0], num ];
  10739. }
  10740. }, function() {
  10741. return walk(prepare_ifs(walk(prepare_ifs(ast))));
  10742. });
  10743. };
  10744. function squeeze_2(ast, options) {
  10745. var w = ast_walker(), walk = w.walk, scope;
  10746. function with_scope(s, cont) {
  10747. var save = scope, ret;
  10748. scope = s;
  10749. ret = cont();
  10750. scope = save;
  10751. return ret;
  10752. };
  10753. function lambda(name, args, body) {
  10754. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  10755. };
  10756. return w.with_walkers({
  10757. "directive": function(dir) {
  10758. if (scope.active_directive(dir))
  10759. return [ "block" ];
  10760. scope.directives.push(dir);
  10761. },
  10762. "toplevel": function(body) {
  10763. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  10764. },
  10765. "function": lambda,
  10766. "defun": lambda
  10767. }, function(){
  10768. return walk(ast_add_scope(ast));
  10769. });
  10770. };
  10771. /* -----[ re-generate code from the AST ]----- */
  10772. var DOT_CALL_NO_PARENS = jsp.array_to_hash([
  10773. "name",
  10774. "array",
  10775. "object",
  10776. "string",
  10777. "dot",
  10778. "sub",
  10779. "call",
  10780. "regexp",
  10781. "defun"
  10782. ]);
  10783. function make_string(str, ascii_only) {
  10784. var dq = 0, sq = 0;
  10785. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  10786. switch (s) {
  10787. case "\\": return "\\\\";
  10788. case "\b": return "\\b";
  10789. case "\f": return "\\f";
  10790. case "\n": return "\\n";
  10791. case "\r": return "\\r";
  10792. case "\u2028": return "\\u2028";
  10793. case "\u2029": return "\\u2029";
  10794. case '"': ++dq; return '"';
  10795. case "'": ++sq; return "'";
  10796. case "\0": return "\\0";
  10797. }
  10798. return s;
  10799. });
  10800. if (ascii_only) str = to_ascii(str);
  10801. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  10802. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  10803. };
  10804. function to_ascii(str) {
  10805. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  10806. var code = ch.charCodeAt(0).toString(16);
  10807. while (code.length < 4) code = "0" + code;
  10808. return "\\u" + code;
  10809. });
  10810. };
  10811. var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
  10812. function gen_code(ast, options) {
  10813. options = defaults(options, {
  10814. indent_start : 0,
  10815. indent_level : 4,
  10816. quote_keys : false,
  10817. space_colon : false,
  10818. beautify : false,
  10819. ascii_only : false,
  10820. inline_script: false
  10821. });
  10822. var beautify = !!options.beautify;
  10823. var indentation = 0,
  10824. newline = beautify ? "\n" : "",
  10825. space = beautify ? " " : "";
  10826. function encode_string(str) {
  10827. var ret = make_string(str, options.ascii_only);
  10828. if (options.inline_script)
  10829. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  10830. return ret;
  10831. };
  10832. function make_name(name) {
  10833. name = name.toString();
  10834. if (options.ascii_only)
  10835. name = to_ascii(name);
  10836. return name;
  10837. };
  10838. function indent(line) {
  10839. if (line == null)
  10840. line = "";
  10841. if (beautify)
  10842. line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
  10843. return line;
  10844. };
  10845. function with_indent(cont, incr) {
  10846. if (incr == null) incr = 1;
  10847. indentation += incr;
  10848. try { return cont.apply(null, slice(arguments, 1)); }
  10849. finally { indentation -= incr; }
  10850. };
  10851. function last_char(str) {
  10852. str = str.toString();
  10853. return str.charAt(str.length - 1);
  10854. };
  10855. function first_char(str) {
  10856. return str.toString().charAt(0);
  10857. };
  10858. function add_spaces(a) {
  10859. if (beautify)
  10860. return a.join(" ");
  10861. var b = [];
  10862. for (var i = 0; i < a.length; ++i) {
  10863. var next = a[i + 1];
  10864. b.push(a[i]);
  10865. if (next &&
  10866. ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
  10867. || first_char(next) == "\\")) ||
  10868. (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString()) ||
  10869. last_char(a[i]) == "/" && first_char(next) == "/"))) {
  10870. b.push(" ");
  10871. }
  10872. }
  10873. return b.join("");
  10874. };
  10875. function add_commas(a) {
  10876. return a.join("," + space);
  10877. };
  10878. function parenthesize(expr) {
  10879. var gen = make(expr);
  10880. for (var i = 1; i < arguments.length; ++i) {
  10881. var el = arguments[i];
  10882. if ((el instanceof Function && el(expr)) || expr[0] == el)
  10883. return "(" + gen + ")";
  10884. }
  10885. return gen;
  10886. };
  10887. function best_of(a) {
  10888. if (a.length == 1) {
  10889. return a[0];
  10890. }
  10891. if (a.length == 2) {
  10892. var b = a[1];
  10893. a = a[0];
  10894. return a.length <= b.length ? a : b;
  10895. }
  10896. return best_of([ a[0], best_of(a.slice(1)) ]);
  10897. };
  10898. function needs_parens(expr) {
  10899. if (expr[0] == "function" || expr[0] == "object") {
  10900. // dot/call on a literal function requires the
  10901. // function literal itself to be parenthesized
  10902. // only if it's the first "thing" in a
  10903. // statement. This means that the parent is
  10904. // "stat", but it could also be a "seq" and
  10905. // we're the first in this "seq" and the
  10906. // parent is "stat", and so on. Messy stuff,
  10907. // but it worths the trouble.
  10908. var a = slice(w.stack()), self = a.pop(), p = a.pop();
  10909. while (p) {
  10910. if (p[0] == "stat") return true;
  10911. if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
  10912. ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
  10913. self = p;
  10914. p = a.pop();
  10915. } else {
  10916. return false;
  10917. }
  10918. }
  10919. }
  10920. return !HOP(DOT_CALL_NO_PARENS, expr[0]);
  10921. };
  10922. function make_num(num) {
  10923. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  10924. if (Math.floor(num) === num) {
  10925. if (num >= 0) {
  10926. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  10927. "0" + num.toString(8)); // same.
  10928. } else {
  10929. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  10930. "-0" + (-num).toString(8)); // same.
  10931. }
  10932. if ((m = /^(.*?)(0+)$/.exec(num))) {
  10933. a.push(m[1] + "e" + m[2].length);
  10934. }
  10935. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  10936. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  10937. str.substr(str.indexOf(".")));
  10938. }
  10939. return best_of(a);
  10940. };
  10941. var w = ast_walker();
  10942. var make = w.walk;
  10943. return w.with_walkers({
  10944. "string": encode_string,
  10945. "num": make_num,
  10946. "name": make_name,
  10947. "debugger": function(){ return "debugger;" },
  10948. "toplevel": function(statements) {
  10949. return make_block_statements(statements)
  10950. .join(newline + newline);
  10951. },
  10952. "splice": function(statements) {
  10953. var parent = w.parent();
  10954. if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
  10955. // we need block brackets in this case
  10956. return make_block.apply(this, arguments);
  10957. } else {
  10958. return MAP(make_block_statements(statements, true),
  10959. function(line, i) {
  10960. // the first line is already indented
  10961. return i > 0 ? indent(line) : line;
  10962. }).join(newline);
  10963. }
  10964. },
  10965. "block": make_block,
  10966. "var": function(defs) {
  10967. return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
  10968. },
  10969. "const": function(defs) {
  10970. return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
  10971. },
  10972. "try": function(tr, ca, fi) {
  10973. var out = [ "try", make_block(tr) ];
  10974. if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
  10975. if (fi) out.push("finally", make_block(fi));
  10976. return add_spaces(out);
  10977. },
  10978. "throw": function(expr) {
  10979. return add_spaces([ "throw", make(expr) ]) + ";";
  10980. },
  10981. "new": function(ctor, args) {
  10982. args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
  10983. return parenthesize(expr, "seq");
  10984. })) + ")" : "";
  10985. return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
  10986. var w = ast_walker(), has_call = {};
  10987. try {
  10988. w.with_walkers({
  10989. "call": function() { throw has_call },
  10990. "function": function() { return this }
  10991. }, function(){
  10992. w.walk(expr);
  10993. });
  10994. } catch(ex) {
  10995. if (ex === has_call)
  10996. return true;
  10997. throw ex;
  10998. }
  10999. }) + args ]);
  11000. },
  11001. "switch": function(expr, body) {
  11002. return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
  11003. },
  11004. "break": function(label) {
  11005. var out = "break";
  11006. if (label != null)
  11007. out += " " + make_name(label);
  11008. return out + ";";
  11009. },
  11010. "continue": function(label) {
  11011. var out = "continue";
  11012. if (label != null)
  11013. out += " " + make_name(label);
  11014. return out + ";";
  11015. },
  11016. "conditional": function(co, th, el) {
  11017. return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
  11018. parenthesize(th, "seq"), ":",
  11019. parenthesize(el, "seq") ]);
  11020. },
  11021. "assign": function(op, lvalue, rvalue) {
  11022. if (op && op !== true) op += "=";
  11023. else op = "=";
  11024. return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
  11025. },
  11026. "dot": function(expr) {
  11027. var out = make(expr), i = 1;
  11028. if (expr[0] == "num") {
  11029. if (!/[a-f.]/i.test(out))
  11030. out += ".";
  11031. } else if (expr[0] != "function" && needs_parens(expr))
  11032. out = "(" + out + ")";
  11033. while (i < arguments.length)
  11034. out += "." + make_name(arguments[i++]);
  11035. return out;
  11036. },
  11037. "call": function(func, args) {
  11038. var f = make(func);
  11039. if (f.charAt(0) != "(" && needs_parens(func))
  11040. f = "(" + f + ")";
  11041. return f + "(" + add_commas(MAP(args, function(expr){
  11042. return parenthesize(expr, "seq");
  11043. })) + ")";
  11044. },
  11045. "function": make_function,
  11046. "defun": make_function,
  11047. "if": function(co, th, el) {
  11048. var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
  11049. if (el) {
  11050. out.push("else", make(el));
  11051. }
  11052. return add_spaces(out);
  11053. },
  11054. "for": function(init, cond, step, block) {
  11055. var out = [ "for" ];
  11056. init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
  11057. cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
  11058. step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
  11059. var args = init + cond + step;
  11060. if (args == "; ; ") args = ";;";
  11061. out.push("(" + args + ")", make(block));
  11062. return add_spaces(out);
  11063. },
  11064. "for-in": function(vvar, key, hash, block) {
  11065. return add_spaces([ "for", "(" +
  11066. (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
  11067. "in",
  11068. make(hash) + ")", make(block) ]);
  11069. },
  11070. "while": function(condition, block) {
  11071. return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
  11072. },
  11073. "do": function(condition, block) {
  11074. return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
  11075. },
  11076. "return": function(expr) {
  11077. var out = [ "return" ];
  11078. if (expr != null) out.push(make(expr));
  11079. return add_spaces(out) + ";";
  11080. },
  11081. "binary": function(operator, lvalue, rvalue) {
  11082. var left = make(lvalue), right = make(rvalue);
  11083. // XXX: I'm pretty sure other cases will bite here.
  11084. // we need to be smarter.
  11085. // adding parens all the time is the safest bet.
  11086. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
  11087. lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
  11088. lvalue[0] == "function" && needs_parens(this)) {
  11089. left = "(" + left + ")";
  11090. }
  11091. if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
  11092. rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
  11093. !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
  11094. right = "(" + right + ")";
  11095. }
  11096. else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
  11097. && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
  11098. right = " " + right;
  11099. }
  11100. return add_spaces([ left, operator, right ]);
  11101. },
  11102. "unary-prefix": function(operator, expr) {
  11103. var val = make(expr);
  11104. if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  11105. val = "(" + val + ")";
  11106. return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
  11107. },
  11108. "unary-postfix": function(operator, expr) {
  11109. var val = make(expr);
  11110. if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  11111. val = "(" + val + ")";
  11112. return val + operator;
  11113. },
  11114. "sub": function(expr, subscript) {
  11115. var hash = make(expr);
  11116. if (needs_parens(expr))
  11117. hash = "(" + hash + ")";
  11118. return hash + "[" + make(subscript) + "]";
  11119. },
  11120. "object": function(props) {
  11121. var obj_needs_parens = needs_parens(this);
  11122. if (props.length == 0)
  11123. return obj_needs_parens ? "({})" : "{}";
  11124. var out = "{" + newline + with_indent(function(){
  11125. return MAP(props, function(p){
  11126. if (p.length == 3) {
  11127. // getter/setter. The name is in p[0], the arg.list in p[1][2], the
  11128. // body in p[1][3] and type ("get" / "set") in p[2].
  11129. return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
  11130. }
  11131. var key = p[0], val = parenthesize(p[1], "seq");
  11132. if (options.quote_keys) {
  11133. key = encode_string(key);
  11134. } else if ((typeof key == "number" || !beautify && +key + "" == key)
  11135. && parseFloat(key) >= 0) {
  11136. key = make_num(+key);
  11137. } else if (!is_identifier(key)) {
  11138. key = encode_string(key);
  11139. }
  11140. return indent(add_spaces(beautify && options.space_colon
  11141. ? [ key, ":", val ]
  11142. : [ key + ":", val ]));
  11143. }).join("," + newline);
  11144. }) + newline + indent("}");
  11145. return obj_needs_parens ? "(" + out + ")" : out;
  11146. },
  11147. "regexp": function(rx, mods) {
  11148. if (options.ascii_only) rx = to_ascii(rx);
  11149. return "/" + rx + "/" + mods;
  11150. },
  11151. "array": function(elements) {
  11152. if (elements.length == 0) return "[]";
  11153. return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
  11154. if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
  11155. return parenthesize(el, "seq");
  11156. })), "]" ]);
  11157. },
  11158. "stat": function(stmt) {
  11159. return stmt != null
  11160. ? make(stmt).replace(/;*\s*$/, ";")
  11161. : ";";
  11162. },
  11163. "seq": function() {
  11164. return add_commas(MAP(slice(arguments), make));
  11165. },
  11166. "label": function(name, block) {
  11167. return add_spaces([ make_name(name), ":", make(block) ]);
  11168. },
  11169. "with": function(expr, block) {
  11170. return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
  11171. },
  11172. "atom": function(name) {
  11173. return make_name(name);
  11174. },
  11175. "directive": function(dir) {
  11176. return make_string(dir) + ";";
  11177. }
  11178. }, function(){ return make(ast) });
  11179. // The squeezer replaces "block"-s that contain only a single
  11180. // statement with the statement itself; technically, the AST
  11181. // is correct, but this can create problems when we output an
  11182. // IF having an ELSE clause where the THEN clause ends in an
  11183. // IF *without* an ELSE block (then the outer ELSE would refer
  11184. // to the inner IF). This function checks for this case and
  11185. // adds the block brackets if needed.
  11186. function make_then(th) {
  11187. if (th == null) return ";";
  11188. if (th[0] == "do") {
  11189. // https://github.com/mishoo/UglifyJS/issues/#issue/57
  11190. // IE croaks with "syntax error" on code like this:
  11191. // if (foo) do ... while(cond); else ...
  11192. // we need block brackets around do/while
  11193. return make_block([ th ]);
  11194. }
  11195. var b = th;
  11196. while (true) {
  11197. var type = b[0];
  11198. if (type == "if") {
  11199. if (!b[3])
  11200. // no else, we must add the block
  11201. return make([ "block", [ th ]]);
  11202. b = b[3];
  11203. }
  11204. else if (type == "while" || type == "do") b = b[2];
  11205. else if (type == "for" || type == "for-in") b = b[4];
  11206. else break;
  11207. }
  11208. return make(th);
  11209. };
  11210. function make_function(name, args, body, keyword, no_parens) {
  11211. var out = keyword || "function";
  11212. if (name) {
  11213. out += " " + make_name(name);
  11214. }
  11215. out += "(" + add_commas(MAP(args, make_name)) + ")";
  11216. out = add_spaces([ out, make_block(body) ]);
  11217. return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
  11218. };
  11219. function must_has_semicolon(node) {
  11220. switch (node[0]) {
  11221. case "with":
  11222. case "while":
  11223. return empty(node[2]) || must_has_semicolon(node[2]);
  11224. case "for":
  11225. case "for-in":
  11226. return empty(node[4]) || must_has_semicolon(node[4]);
  11227. case "if":
  11228. if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
  11229. if (node[3]) {
  11230. if (empty(node[3])) return true; // `else' present but empty
  11231. return must_has_semicolon(node[3]); // dive into the `else' branch
  11232. }
  11233. return must_has_semicolon(node[2]); // dive into the `then' branch
  11234. case "directive":
  11235. return true;
  11236. }
  11237. };
  11238. function make_block_statements(statements, noindent) {
  11239. for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
  11240. var stat = statements[i];
  11241. var code = make(stat);
  11242. if (code != ";") {
  11243. if (!beautify && i == last && !must_has_semicolon(stat)) {
  11244. code = code.replace(/;+\s*$/, "");
  11245. }
  11246. a.push(code);
  11247. }
  11248. }
  11249. return noindent ? a : MAP(a, indent);
  11250. };
  11251. function make_switch_block(body) {
  11252. var n = body.length;
  11253. if (n == 0) return "{}";
  11254. return "{" + newline + MAP(body, function(branch, i){
  11255. var has_body = branch[1].length > 0, code = with_indent(function(){
  11256. return indent(branch[0]
  11257. ? add_spaces([ "case", make(branch[0]) + ":" ])
  11258. : "default:");
  11259. }, 0.5) + (has_body ? newline + with_indent(function(){
  11260. return make_block_statements(branch[1]).join(newline);
  11261. }) : "");
  11262. if (!beautify && has_body && i < n - 1)
  11263. code += ";";
  11264. return code;
  11265. }).join(newline) + newline + indent("}");
  11266. };
  11267. function make_block(statements) {
  11268. if (!statements) return ";";
  11269. if (statements.length == 0) return "{}";
  11270. return "{" + newline + with_indent(function(){
  11271. return make_block_statements(statements).join(newline);
  11272. }) + newline + indent("}");
  11273. };
  11274. function make_1vardef(def) {
  11275. var name = def[0], val = def[1];
  11276. if (val != null)
  11277. name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
  11278. return name;
  11279. };
  11280. };
  11281. function split_lines(code, max_line_length) {
  11282. var splits = [ 0 ];
  11283. jsp.parse(function(){
  11284. var next_token = jsp.tokenizer(code);
  11285. var last_split = 0;
  11286. var prev_token;
  11287. function current_length(tok) {
  11288. return tok.pos - last_split;
  11289. };
  11290. function split_here(tok) {
  11291. last_split = tok.pos;
  11292. splits.push(last_split);
  11293. };
  11294. function custom(){
  11295. var tok = next_token.apply(this, arguments);
  11296. out: {
  11297. if (prev_token) {
  11298. if (prev_token.type == "keyword") break out;
  11299. }
  11300. if (current_length(tok) > max_line_length) {
  11301. switch (tok.type) {
  11302. case "keyword":
  11303. case "atom":
  11304. case "name":
  11305. case "punc":
  11306. split_here(tok);
  11307. break out;
  11308. }
  11309. }
  11310. }
  11311. prev_token = tok;
  11312. return tok;
  11313. };
  11314. custom.context = function() {
  11315. return next_token.context.apply(this, arguments);
  11316. };
  11317. return custom;
  11318. }());
  11319. return splits.map(function(pos, i){
  11320. return code.substring(pos, splits[i + 1] || code.length);
  11321. }).join("\n");
  11322. };
  11323. /* -----[ Utilities ]----- */
  11324. function repeat_string(str, i) {
  11325. if (i <= 0) return "";
  11326. if (i == 1) return str;
  11327. var d = repeat_string(str, i >> 1);
  11328. d += d;
  11329. if (i & 1) d += str;
  11330. return d;
  11331. };
  11332. function defaults(args, defs) {
  11333. var ret = {};
  11334. if (args === true)
  11335. args = {};
  11336. for (var i in defs) if (HOP(defs, i)) {
  11337. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  11338. }
  11339. return ret;
  11340. };
  11341. function is_identifier(name) {
  11342. return /^[a-z_$][a-z0-9_$]*$/i.test(name)
  11343. && name != "this"
  11344. && !HOP(jsp.KEYWORDS_ATOM, name)
  11345. && !HOP(jsp.RESERVED_WORDS, name)
  11346. && !HOP(jsp.KEYWORDS, name);
  11347. };
  11348. function HOP(obj, prop) {
  11349. return Object.prototype.hasOwnProperty.call(obj, prop);
  11350. };
  11351. // some utilities
  11352. var MAP;
  11353. (function(){
  11354. MAP = function(a, f, o) {
  11355. var ret = [], top = [], i;
  11356. function doit() {
  11357. var val = f.call(o, a[i], i);
  11358. if (val instanceof AtTop) {
  11359. val = val.v;
  11360. if (val instanceof Splice) {
  11361. top.push.apply(top, val.v);
  11362. } else {
  11363. top.push(val);
  11364. }
  11365. }
  11366. else if (val != skip) {
  11367. if (val instanceof Splice) {
  11368. ret.push.apply(ret, val.v);
  11369. } else {
  11370. ret.push(val);
  11371. }
  11372. }
  11373. };
  11374. if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
  11375. else for (i in a) if (HOP(a, i)) doit();
  11376. return top.concat(ret);
  11377. };
  11378. MAP.at_top = function(val) { return new AtTop(val) };
  11379. MAP.splice = function(val) { return new Splice(val) };
  11380. var skip = MAP.skip = {};
  11381. function AtTop(val) { this.v = val };
  11382. function Splice(val) { this.v = val };
  11383. })();
  11384. /* -----[ Exports ]----- */
  11385. exports.ast_walker = ast_walker;
  11386. exports.ast_mangle = ast_mangle;
  11387. exports.ast_squeeze = ast_squeeze;
  11388. exports.ast_lift_variables = ast_lift_variables;
  11389. exports.gen_code = gen_code;
  11390. exports.ast_add_scope = ast_add_scope;
  11391. exports.set_logger = function(logger) { warn = logger };
  11392. exports.make_string = make_string;
  11393. exports.split_lines = split_lines;
  11394. exports.MAP = MAP;
  11395. // keep this last!
  11396. exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
  11397. // Local variables:
  11398. // js-indent-level: 4
  11399. // End:
  11400. });
  11401. define('uglifyjs/index', ["require", "exports", "module", "./parse-js", "./process", "./consolidator"], function(require, exports, module) {
  11402. //convienence function(src, [options]);
  11403. function uglify(orig_code, options){
  11404. options || (options = {});
  11405. var jsp = uglify.parser;
  11406. var pro = uglify.uglify;
  11407. var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
  11408. ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
  11409. ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
  11410. var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
  11411. return final_code;
  11412. };
  11413. uglify.parser = require("./parse-js");
  11414. uglify.uglify = require("./process");
  11415. uglify.consolidator = require("./consolidator");
  11416. module.exports = uglify
  11417. });/* -*- Mode: js; js-indent-level: 2; -*- */
  11418. /*
  11419. * Copyright 2011 Mozilla Foundation and contributors
  11420. * Licensed under the New BSD license. See LICENSE or:
  11421. * http://opensource.org/licenses/BSD-3-Clause
  11422. */
  11423. define('source-map/array-set', function (require, exports, module) {
  11424. var util = require('./util');
  11425. /**
  11426. * A data structure which is a combination of an array and a set. Adding a new
  11427. * member is O(1), testing for membership is O(1), and finding the index of an
  11428. * element is O(1). Removing elements from the set is not supported. Only
  11429. * strings are supported for membership.
  11430. */
  11431. function ArraySet() {
  11432. this._array = [];
  11433. this._set = {};
  11434. }
  11435. /**
  11436. * Static method for creating ArraySet instances from an existing array.
  11437. */
  11438. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  11439. var set = new ArraySet();
  11440. for (var i = 0, len = aArray.length; i < len; i++) {
  11441. set.add(aArray[i], aAllowDuplicates);
  11442. }
  11443. return set;
  11444. };
  11445. /**
  11446. * Add the given string to this set.
  11447. *
  11448. * @param String aStr
  11449. */
  11450. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  11451. var isDuplicate = this.has(aStr);
  11452. var idx = this._array.length;
  11453. if (!isDuplicate || aAllowDuplicates) {
  11454. this._array.push(aStr);
  11455. }
  11456. if (!isDuplicate) {
  11457. this._set[util.toSetString(aStr)] = idx;
  11458. }
  11459. };
  11460. /**
  11461. * Is the given string a member of this set?
  11462. *
  11463. * @param String aStr
  11464. */
  11465. ArraySet.prototype.has = function ArraySet_has(aStr) {
  11466. return Object.prototype.hasOwnProperty.call(this._set,
  11467. util.toSetString(aStr));
  11468. };
  11469. /**
  11470. * What is the index of the given string in the array?
  11471. *
  11472. * @param String aStr
  11473. */
  11474. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  11475. if (this.has(aStr)) {
  11476. return this._set[util.toSetString(aStr)];
  11477. }
  11478. throw new Error('"' + aStr + '" is not in the set.');
  11479. };
  11480. /**
  11481. * What is the element at the given index?
  11482. *
  11483. * @param Number aIdx
  11484. */
  11485. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  11486. if (aIdx >= 0 && aIdx < this._array.length) {
  11487. return this._array[aIdx];
  11488. }
  11489. throw new Error('No element indexed by ' + aIdx);
  11490. };
  11491. /**
  11492. * Returns the array representation of this set (which has the proper indices
  11493. * indicated by indexOf). Note that this is a copy of the internal array used
  11494. * for storing the members so that no one can mess with internal state.
  11495. */
  11496. ArraySet.prototype.toArray = function ArraySet_toArray() {
  11497. return this._array.slice();
  11498. };
  11499. exports.ArraySet = ArraySet;
  11500. });
  11501. /* -*- Mode: js; js-indent-level: 2; -*- */
  11502. /*
  11503. * Copyright 2011 Mozilla Foundation and contributors
  11504. * Licensed under the New BSD license. See LICENSE or:
  11505. * http://opensource.org/licenses/BSD-3-Clause
  11506. *
  11507. * Based on the Base 64 VLQ implementation in Closure Compiler:
  11508. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  11509. *
  11510. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  11511. * Redistribution and use in source and binary forms, with or without
  11512. * modification, are permitted provided that the following conditions are
  11513. * met:
  11514. *
  11515. * * Redistributions of source code must retain the above copyright
  11516. * notice, this list of conditions and the following disclaimer.
  11517. * * Redistributions in binary form must reproduce the above
  11518. * copyright notice, this list of conditions and the following
  11519. * disclaimer in the documentation and/or other materials provided
  11520. * with the distribution.
  11521. * * Neither the name of Google Inc. nor the names of its
  11522. * contributors may be used to endorse or promote products derived
  11523. * from this software without specific prior written permission.
  11524. *
  11525. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11526. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11527. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11528. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11529. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11530. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11531. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11532. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11533. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11534. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11535. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11536. */
  11537. define('source-map/base64-vlq', function (require, exports, module) {
  11538. var base64 = require('./base64');
  11539. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  11540. // length quantities we use in the source map spec, the first bit is the sign,
  11541. // the next four bits are the actual value, and the 6th bit is the
  11542. // continuation bit. The continuation bit tells us whether there are more
  11543. // digits in this value following this digit.
  11544. //
  11545. // Continuation
  11546. // | Sign
  11547. // | |
  11548. // V V
  11549. // 101011
  11550. var VLQ_BASE_SHIFT = 5;
  11551. // binary: 100000
  11552. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  11553. // binary: 011111
  11554. var VLQ_BASE_MASK = VLQ_BASE - 1;
  11555. // binary: 100000
  11556. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  11557. /**
  11558. * Converts from a two-complement value to a value where the sign bit is
  11559. * is placed in the least significant bit. For example, as decimals:
  11560. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  11561. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  11562. */
  11563. function toVLQSigned(aValue) {
  11564. return aValue < 0
  11565. ? ((-aValue) << 1) + 1
  11566. : (aValue << 1) + 0;
  11567. }
  11568. /**
  11569. * Converts to a two-complement value from a value where the sign bit is
  11570. * is placed in the least significant bit. For example, as decimals:
  11571. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  11572. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  11573. */
  11574. function fromVLQSigned(aValue) {
  11575. var isNegative = (aValue & 1) === 1;
  11576. var shifted = aValue >> 1;
  11577. return isNegative
  11578. ? -shifted
  11579. : shifted;
  11580. }
  11581. /**
  11582. * Returns the base 64 VLQ encoded value.
  11583. */
  11584. exports.encode = function base64VLQ_encode(aValue) {
  11585. var encoded = "";
  11586. var digit;
  11587. var vlq = toVLQSigned(aValue);
  11588. do {
  11589. digit = vlq & VLQ_BASE_MASK;
  11590. vlq >>>= VLQ_BASE_SHIFT;
  11591. if (vlq > 0) {
  11592. // There are still more digits in this value, so we must make sure the
  11593. // continuation bit is marked.
  11594. digit |= VLQ_CONTINUATION_BIT;
  11595. }
  11596. encoded += base64.encode(digit);
  11597. } while (vlq > 0);
  11598. return encoded;
  11599. };
  11600. /**
  11601. * Decodes the next base 64 VLQ value from the given string and returns the
  11602. * value and the rest of the string.
  11603. */
  11604. exports.decode = function base64VLQ_decode(aStr) {
  11605. var i = 0;
  11606. var strLen = aStr.length;
  11607. var result = 0;
  11608. var shift = 0;
  11609. var continuation, digit;
  11610. do {
  11611. if (i >= strLen) {
  11612. throw new Error("Expected more digits in base 64 VLQ value.");
  11613. }
  11614. digit = base64.decode(aStr.charAt(i++));
  11615. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  11616. digit &= VLQ_BASE_MASK;
  11617. result = result + (digit << shift);
  11618. shift += VLQ_BASE_SHIFT;
  11619. } while (continuation);
  11620. return {
  11621. value: fromVLQSigned(result),
  11622. rest: aStr.slice(i)
  11623. };
  11624. };
  11625. });
  11626. /* -*- Mode: js; js-indent-level: 2; -*- */
  11627. /*
  11628. * Copyright 2011 Mozilla Foundation and contributors
  11629. * Licensed under the New BSD license. See LICENSE or:
  11630. * http://opensource.org/licenses/BSD-3-Clause
  11631. */
  11632. define('source-map/base64', function (require, exports, module) {
  11633. var charToIntMap = {};
  11634. var intToCharMap = {};
  11635. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  11636. .split('')
  11637. .forEach(function (ch, index) {
  11638. charToIntMap[ch] = index;
  11639. intToCharMap[index] = ch;
  11640. });
  11641. /**
  11642. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  11643. */
  11644. exports.encode = function base64_encode(aNumber) {
  11645. if (aNumber in intToCharMap) {
  11646. return intToCharMap[aNumber];
  11647. }
  11648. throw new TypeError("Must be between 0 and 63: " + aNumber);
  11649. };
  11650. /**
  11651. * Decode a single base 64 digit to an integer.
  11652. */
  11653. exports.decode = function base64_decode(aChar) {
  11654. if (aChar in charToIntMap) {
  11655. return charToIntMap[aChar];
  11656. }
  11657. throw new TypeError("Not a valid base 64 digit: " + aChar);
  11658. };
  11659. });
  11660. /* -*- Mode: js; js-indent-level: 2; -*- */
  11661. /*
  11662. * Copyright 2011 Mozilla Foundation and contributors
  11663. * Licensed under the New BSD license. See LICENSE or:
  11664. * http://opensource.org/licenses/BSD-3-Clause
  11665. */
  11666. define('source-map/binary-search', function (require, exports, module) {
  11667. /**
  11668. * Recursive implementation of binary search.
  11669. *
  11670. * @param aLow Indices here and lower do not contain the needle.
  11671. * @param aHigh Indices here and higher do not contain the needle.
  11672. * @param aNeedle The element being searched for.
  11673. * @param aHaystack The non-empty array being searched.
  11674. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  11675. */
  11676. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
  11677. // This function terminates when one of the following is true:
  11678. //
  11679. // 1. We find the exact element we are looking for.
  11680. //
  11681. // 2. We did not find the exact element, but we can return the next
  11682. // closest element that is less than that element.
  11683. //
  11684. // 3. We did not find the exact element, and there is no next-closest
  11685. // element which is less than the one we are searching for, so we
  11686. // return null.
  11687. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  11688. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  11689. if (cmp === 0) {
  11690. // Found the element we are looking for.
  11691. return aHaystack[mid];
  11692. }
  11693. else if (cmp > 0) {
  11694. // aHaystack[mid] is greater than our needle.
  11695. if (aHigh - mid > 1) {
  11696. // The element is in the upper half.
  11697. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
  11698. }
  11699. // We did not find an exact match, return the next closest one
  11700. // (termination case 2).
  11701. return aHaystack[mid];
  11702. }
  11703. else {
  11704. // aHaystack[mid] is less than our needle.
  11705. if (mid - aLow > 1) {
  11706. // The element is in the lower half.
  11707. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
  11708. }
  11709. // The exact needle element was not found in this haystack. Determine if
  11710. // we are in termination case (2) or (3) and return the appropriate thing.
  11711. return aLow < 0
  11712. ? null
  11713. : aHaystack[aLow];
  11714. }
  11715. }
  11716. /**
  11717. * This is an implementation of binary search which will always try and return
  11718. * the next lowest value checked if there is no exact hit. This is because
  11719. * mappings between original and generated line/col pairs are single points,
  11720. * and there is an implicit region between each of them, so a miss just means
  11721. * that you aren't on the very start of a region.
  11722. *
  11723. * @param aNeedle The element you are looking for.
  11724. * @param aHaystack The array that is being searched.
  11725. * @param aCompare A function which takes the needle and an element in the
  11726. * array and returns -1, 0, or 1 depending on whether the needle is less
  11727. * than, equal to, or greater than the element, respectively.
  11728. */
  11729. exports.search = function search(aNeedle, aHaystack, aCompare) {
  11730. return aHaystack.length > 0
  11731. ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
  11732. : null;
  11733. };
  11734. });
  11735. /* -*- Mode: js; js-indent-level: 2; -*- */
  11736. /*
  11737. * Copyright 2011 Mozilla Foundation and contributors
  11738. * Licensed under the New BSD license. See LICENSE or:
  11739. * http://opensource.org/licenses/BSD-3-Clause
  11740. */
  11741. define('source-map/source-map-consumer', function (require, exports, module) {
  11742. var util = require('./util');
  11743. var binarySearch = require('./binary-search');
  11744. var ArraySet = require('./array-set').ArraySet;
  11745. var base64VLQ = require('./base64-vlq');
  11746. /**
  11747. * A SourceMapConsumer instance represents a parsed source map which we can
  11748. * query for information about the original file positions by giving it a file
  11749. * position in the generated source.
  11750. *
  11751. * The only parameter is the raw source map (either as a JSON string, or
  11752. * already parsed to an object). According to the spec, source maps have the
  11753. * following attributes:
  11754. *
  11755. * - version: Which version of the source map spec this map is following.
  11756. * - sources: An array of URLs to the original source files.
  11757. * - names: An array of identifiers which can be referrenced by individual mappings.
  11758. * - sourceRoot: Optional. The URL root from which all sources are relative.
  11759. * - sourcesContent: Optional. An array of contents of the original source files.
  11760. * - mappings: A string of base64 VLQs which contain the actual mappings.
  11761. * - file: Optional. The generated file this source map is associated with.
  11762. *
  11763. * Here is an example source map, taken from the source map spec[0]:
  11764. *
  11765. * {
  11766. * version : 3,
  11767. * file: "out.js",
  11768. * sourceRoot : "",
  11769. * sources: ["foo.js", "bar.js"],
  11770. * names: ["src", "maps", "are", "fun"],
  11771. * mappings: "AA,AB;;ABCDE;"
  11772. * }
  11773. *
  11774. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  11775. */
  11776. function SourceMapConsumer(aSourceMap) {
  11777. var sourceMap = aSourceMap;
  11778. if (typeof aSourceMap === 'string') {
  11779. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  11780. }
  11781. var version = util.getArg(sourceMap, 'version');
  11782. var sources = util.getArg(sourceMap, 'sources');
  11783. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  11784. // requires the array) to play nice here.
  11785. var names = util.getArg(sourceMap, 'names', []);
  11786. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  11787. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  11788. var mappings = util.getArg(sourceMap, 'mappings');
  11789. var file = util.getArg(sourceMap, 'file', null);
  11790. // Once again, Sass deviates from the spec and supplies the version as a
  11791. // string rather than a number, so we use loose equality checking here.
  11792. if (version != this._version) {
  11793. throw new Error('Unsupported version: ' + version);
  11794. }
  11795. // Pass `true` below to allow duplicate names and sources. While source maps
  11796. // are intended to be compressed and deduplicated, the TypeScript compiler
  11797. // sometimes generates source maps with duplicates in them. See Github issue
  11798. // #72 and bugzil.la/889492.
  11799. this._names = ArraySet.fromArray(names, true);
  11800. this._sources = ArraySet.fromArray(sources, true);
  11801. this.sourceRoot = sourceRoot;
  11802. this.sourcesContent = sourcesContent;
  11803. this._mappings = mappings;
  11804. this.file = file;
  11805. }
  11806. /**
  11807. * Create a SourceMapConsumer from a SourceMapGenerator.
  11808. *
  11809. * @param SourceMapGenerator aSourceMap
  11810. * The source map that will be consumed.
  11811. * @returns SourceMapConsumer
  11812. */
  11813. SourceMapConsumer.fromSourceMap =
  11814. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  11815. var smc = Object.create(SourceMapConsumer.prototype);
  11816. smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  11817. smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  11818. smc.sourceRoot = aSourceMap._sourceRoot;
  11819. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  11820. smc.sourceRoot);
  11821. smc.file = aSourceMap._file;
  11822. smc.__generatedMappings = aSourceMap._mappings.slice()
  11823. .sort(util.compareByGeneratedPositions);
  11824. smc.__originalMappings = aSourceMap._mappings.slice()
  11825. .sort(util.compareByOriginalPositions);
  11826. return smc;
  11827. };
  11828. /**
  11829. * The version of the source mapping spec that we are consuming.
  11830. */
  11831. SourceMapConsumer.prototype._version = 3;
  11832. /**
  11833. * The list of original sources.
  11834. */
  11835. Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
  11836. get: function () {
  11837. return this._sources.toArray().map(function (s) {
  11838. return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
  11839. }, this);
  11840. }
  11841. });
  11842. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  11843. // parsed mapping coordinates from the source map's "mappings" attribute. They
  11844. // are lazily instantiated, accessed via the `_generatedMappings` and
  11845. // `_originalMappings` getters respectively, and we only parse the mappings
  11846. // and create these arrays once queried for a source location. We jump through
  11847. // these hoops because there can be many thousands of mappings, and parsing
  11848. // them is expensive, so we only want to do it if we must.
  11849. //
  11850. // Each object in the arrays is of the form:
  11851. //
  11852. // {
  11853. // generatedLine: The line number in the generated code,
  11854. // generatedColumn: The column number in the generated code,
  11855. // source: The path to the original source file that generated this
  11856. // chunk of code,
  11857. // originalLine: The line number in the original source that
  11858. // corresponds to this chunk of generated code,
  11859. // originalColumn: The column number in the original source that
  11860. // corresponds to this chunk of generated code,
  11861. // name: The name of the original symbol which generated this chunk of
  11862. // code.
  11863. // }
  11864. //
  11865. // All properties except for `generatedLine` and `generatedColumn` can be
  11866. // `null`.
  11867. //
  11868. // `_generatedMappings` is ordered by the generated positions.
  11869. //
  11870. // `_originalMappings` is ordered by the original positions.
  11871. SourceMapConsumer.prototype.__generatedMappings = null;
  11872. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  11873. get: function () {
  11874. if (!this.__generatedMappings) {
  11875. this.__generatedMappings = [];
  11876. this.__originalMappings = [];
  11877. this._parseMappings(this._mappings, this.sourceRoot);
  11878. }
  11879. return this.__generatedMappings;
  11880. }
  11881. });
  11882. SourceMapConsumer.prototype.__originalMappings = null;
  11883. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  11884. get: function () {
  11885. if (!this.__originalMappings) {
  11886. this.__generatedMappings = [];
  11887. this.__originalMappings = [];
  11888. this._parseMappings(this._mappings, this.sourceRoot);
  11889. }
  11890. return this.__originalMappings;
  11891. }
  11892. });
  11893. /**
  11894. * Parse the mappings in a string in to a data structure which we can easily
  11895. * query (the ordered arrays in the `this.__generatedMappings` and
  11896. * `this.__originalMappings` properties).
  11897. */
  11898. SourceMapConsumer.prototype._parseMappings =
  11899. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  11900. var generatedLine = 1;
  11901. var previousGeneratedColumn = 0;
  11902. var previousOriginalLine = 0;
  11903. var previousOriginalColumn = 0;
  11904. var previousSource = 0;
  11905. var previousName = 0;
  11906. var mappingSeparator = /^[,;]/;
  11907. var str = aStr;
  11908. var mapping;
  11909. var temp;
  11910. while (str.length > 0) {
  11911. if (str.charAt(0) === ';') {
  11912. generatedLine++;
  11913. str = str.slice(1);
  11914. previousGeneratedColumn = 0;
  11915. }
  11916. else if (str.charAt(0) === ',') {
  11917. str = str.slice(1);
  11918. }
  11919. else {
  11920. mapping = {};
  11921. mapping.generatedLine = generatedLine;
  11922. // Generated column.
  11923. temp = base64VLQ.decode(str);
  11924. mapping.generatedColumn = previousGeneratedColumn + temp.value;
  11925. previousGeneratedColumn = mapping.generatedColumn;
  11926. str = temp.rest;
  11927. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  11928. // Original source.
  11929. temp = base64VLQ.decode(str);
  11930. mapping.source = this._sources.at(previousSource + temp.value);
  11931. previousSource += temp.value;
  11932. str = temp.rest;
  11933. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  11934. throw new Error('Found a source, but no line and column');
  11935. }
  11936. // Original line.
  11937. temp = base64VLQ.decode(str);
  11938. mapping.originalLine = previousOriginalLine + temp.value;
  11939. previousOriginalLine = mapping.originalLine;
  11940. // Lines are stored 0-based
  11941. mapping.originalLine += 1;
  11942. str = temp.rest;
  11943. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  11944. throw new Error('Found a source and line, but no column');
  11945. }
  11946. // Original column.
  11947. temp = base64VLQ.decode(str);
  11948. mapping.originalColumn = previousOriginalColumn + temp.value;
  11949. previousOriginalColumn = mapping.originalColumn;
  11950. str = temp.rest;
  11951. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  11952. // Original name.
  11953. temp = base64VLQ.decode(str);
  11954. mapping.name = this._names.at(previousName + temp.value);
  11955. previousName += temp.value;
  11956. str = temp.rest;
  11957. }
  11958. }
  11959. this.__generatedMappings.push(mapping);
  11960. if (typeof mapping.originalLine === 'number') {
  11961. this.__originalMappings.push(mapping);
  11962. }
  11963. }
  11964. }
  11965. this.__generatedMappings.sort(util.compareByGeneratedPositions);
  11966. this.__originalMappings.sort(util.compareByOriginalPositions);
  11967. };
  11968. /**
  11969. * Find the mapping that best matches the hypothetical "needle" mapping that
  11970. * we are searching for in the given "haystack" of mappings.
  11971. */
  11972. SourceMapConsumer.prototype._findMapping =
  11973. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  11974. aColumnName, aComparator) {
  11975. // To return the position we are searching for, we must first find the
  11976. // mapping for the given position and then return the opposite position it
  11977. // points to. Because the mappings are sorted, we can use binary search to
  11978. // find the best mapping.
  11979. if (aNeedle[aLineName] <= 0) {
  11980. throw new TypeError('Line must be greater than or equal to 1, got '
  11981. + aNeedle[aLineName]);
  11982. }
  11983. if (aNeedle[aColumnName] < 0) {
  11984. throw new TypeError('Column must be greater than or equal to 0, got '
  11985. + aNeedle[aColumnName]);
  11986. }
  11987. return binarySearch.search(aNeedle, aMappings, aComparator);
  11988. };
  11989. /**
  11990. * Returns the original source, line, and column information for the generated
  11991. * source's line and column positions provided. The only argument is an object
  11992. * with the following properties:
  11993. *
  11994. * - line: The line number in the generated source.
  11995. * - column: The column number in the generated source.
  11996. *
  11997. * and an object is returned with the following properties:
  11998. *
  11999. * - source: The original source file, or null.
  12000. * - line: The line number in the original source, or null.
  12001. * - column: The column number in the original source, or null.
  12002. * - name: The original identifier, or null.
  12003. */
  12004. SourceMapConsumer.prototype.originalPositionFor =
  12005. function SourceMapConsumer_originalPositionFor(aArgs) {
  12006. var needle = {
  12007. generatedLine: util.getArg(aArgs, 'line'),
  12008. generatedColumn: util.getArg(aArgs, 'column')
  12009. };
  12010. var mapping = this._findMapping(needle,
  12011. this._generatedMappings,
  12012. "generatedLine",
  12013. "generatedColumn",
  12014. util.compareByGeneratedPositions);
  12015. if (mapping && mapping.generatedLine === needle.generatedLine) {
  12016. var source = util.getArg(mapping, 'source', null);
  12017. if (source && this.sourceRoot) {
  12018. source = util.join(this.sourceRoot, source);
  12019. }
  12020. return {
  12021. source: source,
  12022. line: util.getArg(mapping, 'originalLine', null),
  12023. column: util.getArg(mapping, 'originalColumn', null),
  12024. name: util.getArg(mapping, 'name', null)
  12025. };
  12026. }
  12027. return {
  12028. source: null,
  12029. line: null,
  12030. column: null,
  12031. name: null
  12032. };
  12033. };
  12034. /**
  12035. * Returns the original source content. The only argument is the url of the
  12036. * original source file. Returns null if no original source content is
  12037. * availible.
  12038. */
  12039. SourceMapConsumer.prototype.sourceContentFor =
  12040. function SourceMapConsumer_sourceContentFor(aSource) {
  12041. if (!this.sourcesContent) {
  12042. return null;
  12043. }
  12044. if (this.sourceRoot) {
  12045. aSource = util.relative(this.sourceRoot, aSource);
  12046. }
  12047. if (this._sources.has(aSource)) {
  12048. return this.sourcesContent[this._sources.indexOf(aSource)];
  12049. }
  12050. var url;
  12051. if (this.sourceRoot
  12052. && (url = util.urlParse(this.sourceRoot))) {
  12053. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  12054. // many users. We can help them out when they expect file:// URIs to
  12055. // behave like it would if they were running a local HTTP server. See
  12056. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  12057. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  12058. if (url.scheme == "file"
  12059. && this._sources.has(fileUriAbsPath)) {
  12060. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  12061. }
  12062. if ((!url.path || url.path == "/")
  12063. && this._sources.has("/" + aSource)) {
  12064. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  12065. }
  12066. }
  12067. throw new Error('"' + aSource + '" is not in the SourceMap.');
  12068. };
  12069. /**
  12070. * Returns the generated line and column information for the original source,
  12071. * line, and column positions provided. The only argument is an object with
  12072. * the following properties:
  12073. *
  12074. * - source: The filename of the original source.
  12075. * - line: The line number in the original source.
  12076. * - column: The column number in the original source.
  12077. *
  12078. * and an object is returned with the following properties:
  12079. *
  12080. * - line: The line number in the generated source, or null.
  12081. * - column: The column number in the generated source, or null.
  12082. */
  12083. SourceMapConsumer.prototype.generatedPositionFor =
  12084. function SourceMapConsumer_generatedPositionFor(aArgs) {
  12085. var needle = {
  12086. source: util.getArg(aArgs, 'source'),
  12087. originalLine: util.getArg(aArgs, 'line'),
  12088. originalColumn: util.getArg(aArgs, 'column')
  12089. };
  12090. if (this.sourceRoot) {
  12091. needle.source = util.relative(this.sourceRoot, needle.source);
  12092. }
  12093. var mapping = this._findMapping(needle,
  12094. this._originalMappings,
  12095. "originalLine",
  12096. "originalColumn",
  12097. util.compareByOriginalPositions);
  12098. if (mapping) {
  12099. return {
  12100. line: util.getArg(mapping, 'generatedLine', null),
  12101. column: util.getArg(mapping, 'generatedColumn', null)
  12102. };
  12103. }
  12104. return {
  12105. line: null,
  12106. column: null
  12107. };
  12108. };
  12109. SourceMapConsumer.GENERATED_ORDER = 1;
  12110. SourceMapConsumer.ORIGINAL_ORDER = 2;
  12111. /**
  12112. * Iterate over each mapping between an original source/line/column and a
  12113. * generated line/column in this source map.
  12114. *
  12115. * @param Function aCallback
  12116. * The function that is called with each mapping.
  12117. * @param Object aContext
  12118. * Optional. If specified, this object will be the value of `this` every
  12119. * time that `aCallback` is called.
  12120. * @param aOrder
  12121. * Either `SourceMapConsumer.GENERATED_ORDER` or
  12122. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  12123. * iterate over the mappings sorted by the generated file's line/column
  12124. * order or the original's source/line/column order, respectively. Defaults to
  12125. * `SourceMapConsumer.GENERATED_ORDER`.
  12126. */
  12127. SourceMapConsumer.prototype.eachMapping =
  12128. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  12129. var context = aContext || null;
  12130. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  12131. var mappings;
  12132. switch (order) {
  12133. case SourceMapConsumer.GENERATED_ORDER:
  12134. mappings = this._generatedMappings;
  12135. break;
  12136. case SourceMapConsumer.ORIGINAL_ORDER:
  12137. mappings = this._originalMappings;
  12138. break;
  12139. default:
  12140. throw new Error("Unknown order of iteration.");
  12141. }
  12142. var sourceRoot = this.sourceRoot;
  12143. mappings.map(function (mapping) {
  12144. var source = mapping.source;
  12145. if (source && sourceRoot) {
  12146. source = util.join(sourceRoot, source);
  12147. }
  12148. return {
  12149. source: source,
  12150. generatedLine: mapping.generatedLine,
  12151. generatedColumn: mapping.generatedColumn,
  12152. originalLine: mapping.originalLine,
  12153. originalColumn: mapping.originalColumn,
  12154. name: mapping.name
  12155. };
  12156. }).forEach(aCallback, context);
  12157. };
  12158. exports.SourceMapConsumer = SourceMapConsumer;
  12159. });
  12160. /* -*- Mode: js; js-indent-level: 2; -*- */
  12161. /*
  12162. * Copyright 2011 Mozilla Foundation and contributors
  12163. * Licensed under the New BSD license. See LICENSE or:
  12164. * http://opensource.org/licenses/BSD-3-Clause
  12165. */
  12166. define('source-map/source-map-generator', function (require, exports, module) {
  12167. var base64VLQ = require('./base64-vlq');
  12168. var util = require('./util');
  12169. var ArraySet = require('./array-set').ArraySet;
  12170. /**
  12171. * An instance of the SourceMapGenerator represents a source map which is
  12172. * being built incrementally. You may pass an object with the following
  12173. * properties:
  12174. *
  12175. * - file: The filename of the generated source.
  12176. * - sourceRoot: A root for all relative URLs in this source map.
  12177. */
  12178. function SourceMapGenerator(aArgs) {
  12179. if (!aArgs) {
  12180. aArgs = {};
  12181. }
  12182. this._file = util.getArg(aArgs, 'file', null);
  12183. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  12184. this._sources = new ArraySet();
  12185. this._names = new ArraySet();
  12186. this._mappings = [];
  12187. this._sourcesContents = null;
  12188. }
  12189. SourceMapGenerator.prototype._version = 3;
  12190. /**
  12191. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  12192. *
  12193. * @param aSourceMapConsumer The SourceMap.
  12194. */
  12195. SourceMapGenerator.fromSourceMap =
  12196. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  12197. var sourceRoot = aSourceMapConsumer.sourceRoot;
  12198. var generator = new SourceMapGenerator({
  12199. file: aSourceMapConsumer.file,
  12200. sourceRoot: sourceRoot
  12201. });
  12202. aSourceMapConsumer.eachMapping(function (mapping) {
  12203. var newMapping = {
  12204. generated: {
  12205. line: mapping.generatedLine,
  12206. column: mapping.generatedColumn
  12207. }
  12208. };
  12209. if (mapping.source) {
  12210. newMapping.source = mapping.source;
  12211. if (sourceRoot) {
  12212. newMapping.source = util.relative(sourceRoot, newMapping.source);
  12213. }
  12214. newMapping.original = {
  12215. line: mapping.originalLine,
  12216. column: mapping.originalColumn
  12217. };
  12218. if (mapping.name) {
  12219. newMapping.name = mapping.name;
  12220. }
  12221. }
  12222. generator.addMapping(newMapping);
  12223. });
  12224. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12225. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12226. if (content) {
  12227. generator.setSourceContent(sourceFile, content);
  12228. }
  12229. });
  12230. return generator;
  12231. };
  12232. /**
  12233. * Add a single mapping from original source line and column to the generated
  12234. * source's line and column for this source map being created. The mapping
  12235. * object should have the following properties:
  12236. *
  12237. * - generated: An object with the generated line and column positions.
  12238. * - original: An object with the original line and column positions.
  12239. * - source: The original source file (relative to the sourceRoot).
  12240. * - name: An optional original token name for this mapping.
  12241. */
  12242. SourceMapGenerator.prototype.addMapping =
  12243. function SourceMapGenerator_addMapping(aArgs) {
  12244. var generated = util.getArg(aArgs, 'generated');
  12245. var original = util.getArg(aArgs, 'original', null);
  12246. var source = util.getArg(aArgs, 'source', null);
  12247. var name = util.getArg(aArgs, 'name', null);
  12248. this._validateMapping(generated, original, source, name);
  12249. if (source && !this._sources.has(source)) {
  12250. this._sources.add(source);
  12251. }
  12252. if (name && !this._names.has(name)) {
  12253. this._names.add(name);
  12254. }
  12255. this._mappings.push({
  12256. generatedLine: generated.line,
  12257. generatedColumn: generated.column,
  12258. originalLine: original != null && original.line,
  12259. originalColumn: original != null && original.column,
  12260. source: source,
  12261. name: name
  12262. });
  12263. };
  12264. /**
  12265. * Set the source content for a source file.
  12266. */
  12267. SourceMapGenerator.prototype.setSourceContent =
  12268. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  12269. var source = aSourceFile;
  12270. if (this._sourceRoot) {
  12271. source = util.relative(this._sourceRoot, source);
  12272. }
  12273. if (aSourceContent !== null) {
  12274. // Add the source content to the _sourcesContents map.
  12275. // Create a new _sourcesContents map if the property is null.
  12276. if (!this._sourcesContents) {
  12277. this._sourcesContents = {};
  12278. }
  12279. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  12280. } else {
  12281. // Remove the source file from the _sourcesContents map.
  12282. // If the _sourcesContents map is empty, set the property to null.
  12283. delete this._sourcesContents[util.toSetString(source)];
  12284. if (Object.keys(this._sourcesContents).length === 0) {
  12285. this._sourcesContents = null;
  12286. }
  12287. }
  12288. };
  12289. /**
  12290. * Applies the mappings of a sub-source-map for a specific source file to the
  12291. * source map being generated. Each mapping to the supplied source file is
  12292. * rewritten using the supplied source map. Note: The resolution for the
  12293. * resulting mappings is the minimium of this map and the supplied map.
  12294. *
  12295. * @param aSourceMapConsumer The source map to be applied.
  12296. * @param aSourceFile Optional. The filename of the source file.
  12297. * If omitted, SourceMapConsumer's file property will be used.
  12298. * @param aSourceMapPath Optional. The dirname of the path to the source map
  12299. * to be applied. If relative, it is relative to the SourceMapConsumer.
  12300. * This parameter is needed when the two source maps aren't in the same
  12301. * directory, and the source map to be applied contains relative source
  12302. * paths. If so, those relative source paths need to be rewritten
  12303. * relative to the SourceMapGenerator.
  12304. */
  12305. SourceMapGenerator.prototype.applySourceMap =
  12306. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  12307. // If aSourceFile is omitted, we will use the file property of the SourceMap
  12308. if (!aSourceFile) {
  12309. if (!aSourceMapConsumer.file) {
  12310. throw new Error(
  12311. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  12312. 'or the source map\'s "file" property. Both were omitted.'
  12313. );
  12314. }
  12315. aSourceFile = aSourceMapConsumer.file;
  12316. }
  12317. var sourceRoot = this._sourceRoot;
  12318. // Make "aSourceFile" relative if an absolute Url is passed.
  12319. if (sourceRoot) {
  12320. aSourceFile = util.relative(sourceRoot, aSourceFile);
  12321. }
  12322. // Applying the SourceMap can add and remove items from the sources and
  12323. // the names array.
  12324. var newSources = new ArraySet();
  12325. var newNames = new ArraySet();
  12326. // Find mappings for the "aSourceFile"
  12327. this._mappings.forEach(function (mapping) {
  12328. if (mapping.source === aSourceFile && mapping.originalLine) {
  12329. // Check if it can be mapped by the source map, then update the mapping.
  12330. var original = aSourceMapConsumer.originalPositionFor({
  12331. line: mapping.originalLine,
  12332. column: mapping.originalColumn
  12333. });
  12334. if (original.source !== null) {
  12335. // Copy mapping
  12336. mapping.source = original.source;
  12337. if (aSourceMapPath) {
  12338. mapping.source = util.join(aSourceMapPath, mapping.source)
  12339. }
  12340. if (sourceRoot) {
  12341. mapping.source = util.relative(sourceRoot, mapping.source);
  12342. }
  12343. mapping.originalLine = original.line;
  12344. mapping.originalColumn = original.column;
  12345. if (original.name !== null && mapping.name !== null) {
  12346. // Only use the identifier name if it's an identifier
  12347. // in both SourceMaps
  12348. mapping.name = original.name;
  12349. }
  12350. }
  12351. }
  12352. var source = mapping.source;
  12353. if (source && !newSources.has(source)) {
  12354. newSources.add(source);
  12355. }
  12356. var name = mapping.name;
  12357. if (name && !newNames.has(name)) {
  12358. newNames.add(name);
  12359. }
  12360. }, this);
  12361. this._sources = newSources;
  12362. this._names = newNames;
  12363. // Copy sourcesContents of applied map.
  12364. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12365. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12366. if (content) {
  12367. if (sourceRoot) {
  12368. sourceFile = util.relative(sourceRoot, sourceFile);
  12369. }
  12370. this.setSourceContent(sourceFile, content);
  12371. }
  12372. }, this);
  12373. };
  12374. /**
  12375. * A mapping can have one of the three levels of data:
  12376. *
  12377. * 1. Just the generated position.
  12378. * 2. The Generated position, original position, and original source.
  12379. * 3. Generated and original position, original source, as well as a name
  12380. * token.
  12381. *
  12382. * To maintain consistency, we validate that any new mapping being added falls
  12383. * in to one of these categories.
  12384. */
  12385. SourceMapGenerator.prototype._validateMapping =
  12386. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  12387. aName) {
  12388. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  12389. && aGenerated.line > 0 && aGenerated.column >= 0
  12390. && !aOriginal && !aSource && !aName) {
  12391. // Case 1.
  12392. return;
  12393. }
  12394. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  12395. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  12396. && aGenerated.line > 0 && aGenerated.column >= 0
  12397. && aOriginal.line > 0 && aOriginal.column >= 0
  12398. && aSource) {
  12399. // Cases 2 and 3.
  12400. return;
  12401. }
  12402. else {
  12403. throw new Error('Invalid mapping: ' + JSON.stringify({
  12404. generated: aGenerated,
  12405. source: aSource,
  12406. original: aOriginal,
  12407. name: aName
  12408. }));
  12409. }
  12410. };
  12411. /**
  12412. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  12413. * specified by the source map format.
  12414. */
  12415. SourceMapGenerator.prototype._serializeMappings =
  12416. function SourceMapGenerator_serializeMappings() {
  12417. var previousGeneratedColumn = 0;
  12418. var previousGeneratedLine = 1;
  12419. var previousOriginalColumn = 0;
  12420. var previousOriginalLine = 0;
  12421. var previousName = 0;
  12422. var previousSource = 0;
  12423. var result = '';
  12424. var mapping;
  12425. // The mappings must be guaranteed to be in sorted order before we start
  12426. // serializing them or else the generated line numbers (which are defined
  12427. // via the ';' separators) will be all messed up. Note: it might be more
  12428. // performant to maintain the sorting as we insert them, rather than as we
  12429. // serialize them, but the big O is the same either way.
  12430. this._mappings.sort(util.compareByGeneratedPositions);
  12431. for (var i = 0, len = this._mappings.length; i < len; i++) {
  12432. mapping = this._mappings[i];
  12433. if (mapping.generatedLine !== previousGeneratedLine) {
  12434. previousGeneratedColumn = 0;
  12435. while (mapping.generatedLine !== previousGeneratedLine) {
  12436. result += ';';
  12437. previousGeneratedLine++;
  12438. }
  12439. }
  12440. else {
  12441. if (i > 0) {
  12442. if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
  12443. continue;
  12444. }
  12445. result += ',';
  12446. }
  12447. }
  12448. result += base64VLQ.encode(mapping.generatedColumn
  12449. - previousGeneratedColumn);
  12450. previousGeneratedColumn = mapping.generatedColumn;
  12451. if (mapping.source) {
  12452. result += base64VLQ.encode(this._sources.indexOf(mapping.source)
  12453. - previousSource);
  12454. previousSource = this._sources.indexOf(mapping.source);
  12455. // lines are stored 0-based in SourceMap spec version 3
  12456. result += base64VLQ.encode(mapping.originalLine - 1
  12457. - previousOriginalLine);
  12458. previousOriginalLine = mapping.originalLine - 1;
  12459. result += base64VLQ.encode(mapping.originalColumn
  12460. - previousOriginalColumn);
  12461. previousOriginalColumn = mapping.originalColumn;
  12462. if (mapping.name) {
  12463. result += base64VLQ.encode(this._names.indexOf(mapping.name)
  12464. - previousName);
  12465. previousName = this._names.indexOf(mapping.name);
  12466. }
  12467. }
  12468. }
  12469. return result;
  12470. };
  12471. SourceMapGenerator.prototype._generateSourcesContent =
  12472. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  12473. return aSources.map(function (source) {
  12474. if (!this._sourcesContents) {
  12475. return null;
  12476. }
  12477. if (aSourceRoot) {
  12478. source = util.relative(aSourceRoot, source);
  12479. }
  12480. var key = util.toSetString(source);
  12481. return Object.prototype.hasOwnProperty.call(this._sourcesContents,
  12482. key)
  12483. ? this._sourcesContents[key]
  12484. : null;
  12485. }, this);
  12486. };
  12487. /**
  12488. * Externalize the source map.
  12489. */
  12490. SourceMapGenerator.prototype.toJSON =
  12491. function SourceMapGenerator_toJSON() {
  12492. var map = {
  12493. version: this._version,
  12494. file: this._file,
  12495. sources: this._sources.toArray(),
  12496. names: this._names.toArray(),
  12497. mappings: this._serializeMappings()
  12498. };
  12499. if (this._sourceRoot) {
  12500. map.sourceRoot = this._sourceRoot;
  12501. }
  12502. if (this._sourcesContents) {
  12503. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  12504. }
  12505. return map;
  12506. };
  12507. /**
  12508. * Render the source map being generated to a string.
  12509. */
  12510. SourceMapGenerator.prototype.toString =
  12511. function SourceMapGenerator_toString() {
  12512. return JSON.stringify(this);
  12513. };
  12514. exports.SourceMapGenerator = SourceMapGenerator;
  12515. });
  12516. /* -*- Mode: js; js-indent-level: 2; -*- */
  12517. /*
  12518. * Copyright 2011 Mozilla Foundation and contributors
  12519. * Licensed under the New BSD license. See LICENSE or:
  12520. * http://opensource.org/licenses/BSD-3-Clause
  12521. */
  12522. define('source-map/source-node', function (require, exports, module) {
  12523. var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
  12524. var util = require('./util');
  12525. /**
  12526. * SourceNodes provide a way to abstract over interpolating/concatenating
  12527. * snippets of generated JavaScript source code while maintaining the line and
  12528. * column information associated with the original source code.
  12529. *
  12530. * @param aLine The original line number.
  12531. * @param aColumn The original column number.
  12532. * @param aSource The original source's filename.
  12533. * @param aChunks Optional. An array of strings which are snippets of
  12534. * generated JS, or other SourceNodes.
  12535. * @param aName The original identifier.
  12536. */
  12537. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  12538. this.children = [];
  12539. this.sourceContents = {};
  12540. this.line = aLine === undefined ? null : aLine;
  12541. this.column = aColumn === undefined ? null : aColumn;
  12542. this.source = aSource === undefined ? null : aSource;
  12543. this.name = aName === undefined ? null : aName;
  12544. if (aChunks != null) this.add(aChunks);
  12545. }
  12546. /**
  12547. * Creates a SourceNode from generated code and a SourceMapConsumer.
  12548. *
  12549. * @param aGeneratedCode The generated code
  12550. * @param aSourceMapConsumer The SourceMap for the generated code
  12551. */
  12552. SourceNode.fromStringWithSourceMap =
  12553. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
  12554. // The SourceNode we want to fill with the generated code
  12555. // and the SourceMap
  12556. var node = new SourceNode();
  12557. // The generated code
  12558. // Processed fragments are removed from this array.
  12559. var remainingLines = aGeneratedCode.split('\n');
  12560. // We need to remember the position of "remainingLines"
  12561. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  12562. // The generate SourceNodes we need a code range.
  12563. // To extract it current and last mapping is used.
  12564. // Here we store the last mapping.
  12565. var lastMapping = null;
  12566. aSourceMapConsumer.eachMapping(function (mapping) {
  12567. if (lastMapping !== null) {
  12568. // We add the code from "lastMapping" to "mapping":
  12569. // First check if there is a new line in between.
  12570. if (lastGeneratedLine < mapping.generatedLine) {
  12571. var code = "";
  12572. // Associate first line with "lastMapping"
  12573. addMappingWithCode(lastMapping, remainingLines.shift() + "\n");
  12574. lastGeneratedLine++;
  12575. lastGeneratedColumn = 0;
  12576. // The remaining code is added without mapping
  12577. } else {
  12578. // There is no new line in between.
  12579. // Associate the code between "lastGeneratedColumn" and
  12580. // "mapping.generatedColumn" with "lastMapping"
  12581. var nextLine = remainingLines[0];
  12582. var code = nextLine.substr(0, mapping.generatedColumn -
  12583. lastGeneratedColumn);
  12584. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  12585. lastGeneratedColumn);
  12586. lastGeneratedColumn = mapping.generatedColumn;
  12587. addMappingWithCode(lastMapping, code);
  12588. // No more remaining code, continue
  12589. lastMapping = mapping;
  12590. return;
  12591. }
  12592. }
  12593. // We add the generated code until the first mapping
  12594. // to the SourceNode without any mapping.
  12595. // Each line is added as separate string.
  12596. while (lastGeneratedLine < mapping.generatedLine) {
  12597. node.add(remainingLines.shift() + "\n");
  12598. lastGeneratedLine++;
  12599. }
  12600. if (lastGeneratedColumn < mapping.generatedColumn) {
  12601. var nextLine = remainingLines[0];
  12602. node.add(nextLine.substr(0, mapping.generatedColumn));
  12603. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  12604. lastGeneratedColumn = mapping.generatedColumn;
  12605. }
  12606. lastMapping = mapping;
  12607. }, this);
  12608. // We have processed all mappings.
  12609. if (remainingLines.length > 0) {
  12610. if (lastMapping) {
  12611. // Associate the remaining code in the current line with "lastMapping"
  12612. var lastLine = remainingLines.shift();
  12613. if (remainingLines.length > 0) lastLine += "\n";
  12614. addMappingWithCode(lastMapping, lastLine);
  12615. }
  12616. // and add the remaining lines without any mapping
  12617. node.add(remainingLines.join("\n"));
  12618. }
  12619. // Copy sourcesContent into SourceNode
  12620. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12621. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12622. if (content) {
  12623. node.setSourceContent(sourceFile, content);
  12624. }
  12625. });
  12626. return node;
  12627. function addMappingWithCode(mapping, code) {
  12628. if (mapping === null || mapping.source === undefined) {
  12629. node.add(code);
  12630. } else {
  12631. node.add(new SourceNode(mapping.originalLine,
  12632. mapping.originalColumn,
  12633. mapping.source,
  12634. code,
  12635. mapping.name));
  12636. }
  12637. }
  12638. };
  12639. /**
  12640. * Add a chunk of generated JS to this source node.
  12641. *
  12642. * @param aChunk A string snippet of generated JS code, another instance of
  12643. * SourceNode, or an array where each member is one of those things.
  12644. */
  12645. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  12646. if (Array.isArray(aChunk)) {
  12647. aChunk.forEach(function (chunk) {
  12648. this.add(chunk);
  12649. }, this);
  12650. }
  12651. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  12652. if (aChunk) {
  12653. this.children.push(aChunk);
  12654. }
  12655. }
  12656. else {
  12657. throw new TypeError(
  12658. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12659. );
  12660. }
  12661. return this;
  12662. };
  12663. /**
  12664. * Add a chunk of generated JS to the beginning of this source node.
  12665. *
  12666. * @param aChunk A string snippet of generated JS code, another instance of
  12667. * SourceNode, or an array where each member is one of those things.
  12668. */
  12669. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  12670. if (Array.isArray(aChunk)) {
  12671. for (var i = aChunk.length-1; i >= 0; i--) {
  12672. this.prepend(aChunk[i]);
  12673. }
  12674. }
  12675. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  12676. this.children.unshift(aChunk);
  12677. }
  12678. else {
  12679. throw new TypeError(
  12680. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12681. );
  12682. }
  12683. return this;
  12684. };
  12685. /**
  12686. * Walk over the tree of JS snippets in this node and its children. The
  12687. * walking function is called once for each snippet of JS and is passed that
  12688. * snippet and the its original associated source's line/column location.
  12689. *
  12690. * @param aFn The traversal function.
  12691. */
  12692. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  12693. var chunk;
  12694. for (var i = 0, len = this.children.length; i < len; i++) {
  12695. chunk = this.children[i];
  12696. if (chunk instanceof SourceNode) {
  12697. chunk.walk(aFn);
  12698. }
  12699. else {
  12700. if (chunk !== '') {
  12701. aFn(chunk, { source: this.source,
  12702. line: this.line,
  12703. column: this.column,
  12704. name: this.name });
  12705. }
  12706. }
  12707. }
  12708. };
  12709. /**
  12710. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  12711. * each of `this.children`.
  12712. *
  12713. * @param aSep The separator.
  12714. */
  12715. SourceNode.prototype.join = function SourceNode_join(aSep) {
  12716. var newChildren;
  12717. var i;
  12718. var len = this.children.length;
  12719. if (len > 0) {
  12720. newChildren = [];
  12721. for (i = 0; i < len-1; i++) {
  12722. newChildren.push(this.children[i]);
  12723. newChildren.push(aSep);
  12724. }
  12725. newChildren.push(this.children[i]);
  12726. this.children = newChildren;
  12727. }
  12728. return this;
  12729. };
  12730. /**
  12731. * Call String.prototype.replace on the very right-most source snippet. Useful
  12732. * for trimming whitespace from the end of a source node, etc.
  12733. *
  12734. * @param aPattern The pattern to replace.
  12735. * @param aReplacement The thing to replace the pattern with.
  12736. */
  12737. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  12738. var lastChild = this.children[this.children.length - 1];
  12739. if (lastChild instanceof SourceNode) {
  12740. lastChild.replaceRight(aPattern, aReplacement);
  12741. }
  12742. else if (typeof lastChild === 'string') {
  12743. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  12744. }
  12745. else {
  12746. this.children.push(''.replace(aPattern, aReplacement));
  12747. }
  12748. return this;
  12749. };
  12750. /**
  12751. * Set the source content for a source file. This will be added to the SourceMapGenerator
  12752. * in the sourcesContent field.
  12753. *
  12754. * @param aSourceFile The filename of the source file
  12755. * @param aSourceContent The content of the source file
  12756. */
  12757. SourceNode.prototype.setSourceContent =
  12758. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  12759. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  12760. };
  12761. /**
  12762. * Walk over the tree of SourceNodes. The walking function is called for each
  12763. * source file content and is passed the filename and source content.
  12764. *
  12765. * @param aFn The traversal function.
  12766. */
  12767. SourceNode.prototype.walkSourceContents =
  12768. function SourceNode_walkSourceContents(aFn) {
  12769. for (var i = 0, len = this.children.length; i < len; i++) {
  12770. if (this.children[i] instanceof SourceNode) {
  12771. this.children[i].walkSourceContents(aFn);
  12772. }
  12773. }
  12774. var sources = Object.keys(this.sourceContents);
  12775. for (var i = 0, len = sources.length; i < len; i++) {
  12776. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  12777. }
  12778. };
  12779. /**
  12780. * Return the string representation of this source node. Walks over the tree
  12781. * and concatenates all the various snippets together to one string.
  12782. */
  12783. SourceNode.prototype.toString = function SourceNode_toString() {
  12784. var str = "";
  12785. this.walk(function (chunk) {
  12786. str += chunk;
  12787. });
  12788. return str;
  12789. };
  12790. /**
  12791. * Returns the string representation of this source node along with a source
  12792. * map.
  12793. */
  12794. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  12795. var generated = {
  12796. code: "",
  12797. line: 1,
  12798. column: 0
  12799. };
  12800. var map = new SourceMapGenerator(aArgs);
  12801. var sourceMappingActive = false;
  12802. var lastOriginalSource = null;
  12803. var lastOriginalLine = null;
  12804. var lastOriginalColumn = null;
  12805. var lastOriginalName = null;
  12806. this.walk(function (chunk, original) {
  12807. generated.code += chunk;
  12808. if (original.source !== null
  12809. && original.line !== null
  12810. && original.column !== null) {
  12811. if(lastOriginalSource !== original.source
  12812. || lastOriginalLine !== original.line
  12813. || lastOriginalColumn !== original.column
  12814. || lastOriginalName !== original.name) {
  12815. map.addMapping({
  12816. source: original.source,
  12817. original: {
  12818. line: original.line,
  12819. column: original.column
  12820. },
  12821. generated: {
  12822. line: generated.line,
  12823. column: generated.column
  12824. },
  12825. name: original.name
  12826. });
  12827. }
  12828. lastOriginalSource = original.source;
  12829. lastOriginalLine = original.line;
  12830. lastOriginalColumn = original.column;
  12831. lastOriginalName = original.name;
  12832. sourceMappingActive = true;
  12833. } else if (sourceMappingActive) {
  12834. map.addMapping({
  12835. generated: {
  12836. line: generated.line,
  12837. column: generated.column
  12838. }
  12839. });
  12840. lastOriginalSource = null;
  12841. sourceMappingActive = false;
  12842. }
  12843. chunk.split('').forEach(function (ch, idx, array) {
  12844. if (ch === '\n') {
  12845. generated.line++;
  12846. generated.column = 0;
  12847. // Mappings end at eol
  12848. if (idx + 1 === array.length) {
  12849. lastOriginalSource = null;
  12850. sourceMappingActive = false;
  12851. } else if (sourceMappingActive) {
  12852. map.addMapping({
  12853. source: original.source,
  12854. original: {
  12855. line: original.line,
  12856. column: original.column
  12857. },
  12858. generated: {
  12859. line: generated.line,
  12860. column: generated.column
  12861. },
  12862. name: original.name
  12863. });
  12864. }
  12865. } else {
  12866. generated.column++;
  12867. }
  12868. });
  12869. });
  12870. this.walkSourceContents(function (sourceFile, sourceContent) {
  12871. map.setSourceContent(sourceFile, sourceContent);
  12872. });
  12873. return { code: generated.code, map: map };
  12874. };
  12875. exports.SourceNode = SourceNode;
  12876. });
  12877. /* -*- Mode: js; js-indent-level: 2; -*- */
  12878. /*
  12879. * Copyright 2011 Mozilla Foundation and contributors
  12880. * Licensed under the New BSD license. See LICENSE or:
  12881. * http://opensource.org/licenses/BSD-3-Clause
  12882. */
  12883. define('source-map/util', function (require, exports, module) {
  12884. /**
  12885. * This is a helper function for getting values from parameter/options
  12886. * objects.
  12887. *
  12888. * @param args The object we are extracting values from
  12889. * @param name The name of the property we are getting.
  12890. * @param defaultValue An optional value to return if the property is missing
  12891. * from the object. If this is not specified and the property is missing, an
  12892. * error will be thrown.
  12893. */
  12894. function getArg(aArgs, aName, aDefaultValue) {
  12895. if (aName in aArgs) {
  12896. return aArgs[aName];
  12897. } else if (arguments.length === 3) {
  12898. return aDefaultValue;
  12899. } else {
  12900. throw new Error('"' + aName + '" is a required argument.');
  12901. }
  12902. }
  12903. exports.getArg = getArg;
  12904. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  12905. var dataUrlRegexp = /^data:.+\,.+$/;
  12906. function urlParse(aUrl) {
  12907. var match = aUrl.match(urlRegexp);
  12908. if (!match) {
  12909. return null;
  12910. }
  12911. return {
  12912. scheme: match[1],
  12913. auth: match[2],
  12914. host: match[3],
  12915. port: match[4],
  12916. path: match[5]
  12917. };
  12918. }
  12919. exports.urlParse = urlParse;
  12920. function urlGenerate(aParsedUrl) {
  12921. var url = '';
  12922. if (aParsedUrl.scheme) {
  12923. url += aParsedUrl.scheme + ':';
  12924. }
  12925. url += '//';
  12926. if (aParsedUrl.auth) {
  12927. url += aParsedUrl.auth + '@';
  12928. }
  12929. if (aParsedUrl.host) {
  12930. url += aParsedUrl.host;
  12931. }
  12932. if (aParsedUrl.port) {
  12933. url += ":" + aParsedUrl.port
  12934. }
  12935. if (aParsedUrl.path) {
  12936. url += aParsedUrl.path;
  12937. }
  12938. return url;
  12939. }
  12940. exports.urlGenerate = urlGenerate;
  12941. /**
  12942. * Normalizes a path, or the path portion of a URL:
  12943. *
  12944. * - Replaces consequtive slashes with one slash.
  12945. * - Removes unnecessary '.' parts.
  12946. * - Removes unnecessary '<dir>/..' parts.
  12947. *
  12948. * Based on code in the Node.js 'path' core module.
  12949. *
  12950. * @param aPath The path or url to normalize.
  12951. */
  12952. function normalize(aPath) {
  12953. var path = aPath;
  12954. var url = urlParse(aPath);
  12955. if (url) {
  12956. if (!url.path) {
  12957. return aPath;
  12958. }
  12959. path = url.path;
  12960. }
  12961. var isAbsolute = (path.charAt(0) === '/');
  12962. var parts = path.split(/\/+/);
  12963. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  12964. part = parts[i];
  12965. if (part === '.') {
  12966. parts.splice(i, 1);
  12967. } else if (part === '..') {
  12968. up++;
  12969. } else if (up > 0) {
  12970. if (part === '') {
  12971. // The first part is blank if the path is absolute. Trying to go
  12972. // above the root is a no-op. Therefore we can remove all '..' parts
  12973. // directly after the root.
  12974. parts.splice(i + 1, up);
  12975. up = 0;
  12976. } else {
  12977. parts.splice(i, 2);
  12978. up--;
  12979. }
  12980. }
  12981. }
  12982. path = parts.join('/');
  12983. if (path === '') {
  12984. path = isAbsolute ? '/' : '.';
  12985. }
  12986. if (url) {
  12987. url.path = path;
  12988. return urlGenerate(url);
  12989. }
  12990. return path;
  12991. }
  12992. exports.normalize = normalize;
  12993. /**
  12994. * Joins two paths/URLs.
  12995. *
  12996. * @param aRoot The root path or URL.
  12997. * @param aPath The path or URL to be joined with the root.
  12998. *
  12999. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  13000. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  13001. * first.
  13002. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  13003. * is updated with the result and aRoot is returned. Otherwise the result
  13004. * is returned.
  13005. * - If aPath is absolute, the result is aPath.
  13006. * - Otherwise the two paths are joined with a slash.
  13007. * - Joining for example 'http://' and 'www.example.com' is also supported.
  13008. */
  13009. function join(aRoot, aPath) {
  13010. var aPathUrl = urlParse(aPath);
  13011. var aRootUrl = urlParse(aRoot);
  13012. if (aRootUrl) {
  13013. aRoot = aRootUrl.path || '/';
  13014. }
  13015. // `join(foo, '//www.example.org')`
  13016. if (aPathUrl && !aPathUrl.scheme) {
  13017. if (aRootUrl) {
  13018. aPathUrl.scheme = aRootUrl.scheme;
  13019. }
  13020. return urlGenerate(aPathUrl);
  13021. }
  13022. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  13023. return aPath;
  13024. }
  13025. // `join('http://', 'www.example.com')`
  13026. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  13027. aRootUrl.host = aPath;
  13028. return urlGenerate(aRootUrl);
  13029. }
  13030. var joined = aPath.charAt(0) === '/'
  13031. ? aPath
  13032. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  13033. if (aRootUrl) {
  13034. aRootUrl.path = joined;
  13035. return urlGenerate(aRootUrl);
  13036. }
  13037. return joined;
  13038. }
  13039. exports.join = join;
  13040. /**
  13041. * Because behavior goes wacky when you set `__proto__` on objects, we
  13042. * have to prefix all the strings in our set with an arbitrary character.
  13043. *
  13044. * See https://github.com/mozilla/source-map/pull/31 and
  13045. * https://github.com/mozilla/source-map/issues/30
  13046. *
  13047. * @param String aStr
  13048. */
  13049. function toSetString(aStr) {
  13050. return '$' + aStr;
  13051. }
  13052. exports.toSetString = toSetString;
  13053. function fromSetString(aStr) {
  13054. return aStr.substr(1);
  13055. }
  13056. exports.fromSetString = fromSetString;
  13057. function relative(aRoot, aPath) {
  13058. aRoot = aRoot.replace(/\/$/, '');
  13059. var url = urlParse(aRoot);
  13060. if (aPath.charAt(0) == "/" && url && url.path == "/") {
  13061. return aPath.slice(1);
  13062. }
  13063. return aPath.indexOf(aRoot + '/') === 0
  13064. ? aPath.substr(aRoot.length + 1)
  13065. : aPath;
  13066. }
  13067. exports.relative = relative;
  13068. function strcmp(aStr1, aStr2) {
  13069. var s1 = aStr1 || "";
  13070. var s2 = aStr2 || "";
  13071. return (s1 > s2) - (s1 < s2);
  13072. }
  13073. /**
  13074. * Comparator between two mappings where the original positions are compared.
  13075. *
  13076. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  13077. * mappings with the same original source/line/column, but different generated
  13078. * line and column the same. Useful when searching for a mapping with a
  13079. * stubbed out mapping.
  13080. */
  13081. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  13082. var cmp;
  13083. cmp = strcmp(mappingA.source, mappingB.source);
  13084. if (cmp) {
  13085. return cmp;
  13086. }
  13087. cmp = mappingA.originalLine - mappingB.originalLine;
  13088. if (cmp) {
  13089. return cmp;
  13090. }
  13091. cmp = mappingA.originalColumn - mappingB.originalColumn;
  13092. if (cmp || onlyCompareOriginal) {
  13093. return cmp;
  13094. }
  13095. cmp = strcmp(mappingA.name, mappingB.name);
  13096. if (cmp) {
  13097. return cmp;
  13098. }
  13099. cmp = mappingA.generatedLine - mappingB.generatedLine;
  13100. if (cmp) {
  13101. return cmp;
  13102. }
  13103. return mappingA.generatedColumn - mappingB.generatedColumn;
  13104. };
  13105. exports.compareByOriginalPositions = compareByOriginalPositions;
  13106. /**
  13107. * Comparator between two mappings where the generated positions are
  13108. * compared.
  13109. *
  13110. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  13111. * mappings with the same generated line and column, but different
  13112. * source/name/original line and column the same. Useful when searching for a
  13113. * mapping with a stubbed out mapping.
  13114. */
  13115. function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
  13116. var cmp;
  13117. cmp = mappingA.generatedLine - mappingB.generatedLine;
  13118. if (cmp) {
  13119. return cmp;
  13120. }
  13121. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  13122. if (cmp || onlyCompareGenerated) {
  13123. return cmp;
  13124. }
  13125. cmp = strcmp(mappingA.source, mappingB.source);
  13126. if (cmp) {
  13127. return cmp;
  13128. }
  13129. cmp = mappingA.originalLine - mappingB.originalLine;
  13130. if (cmp) {
  13131. return cmp;
  13132. }
  13133. cmp = mappingA.originalColumn - mappingB.originalColumn;
  13134. if (cmp) {
  13135. return cmp;
  13136. }
  13137. return strcmp(mappingA.name, mappingB.name);
  13138. };
  13139. exports.compareByGeneratedPositions = compareByGeneratedPositions;
  13140. });
  13141. define('source-map', function (require, exports, module) {
  13142. /*
  13143. * Copyright 2009-2011 Mozilla Foundation and contributors
  13144. * Licensed under the New BSD license. See LICENSE.txt or:
  13145. * http://opensource.org/licenses/BSD-3-Clause
  13146. */
  13147. exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
  13148. exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
  13149. exports.SourceNode = require('./source-map/source-node').SourceNode;
  13150. });
  13151. //Distributed under the BSD license:
  13152. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13153. define('uglifyjs2', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
  13154. /***********************************************************************
  13155. A JavaScript tokenizer / parser / beautifier / compressor.
  13156. https://github.com/mishoo/UglifyJS2
  13157. -------------------------------- (C) ---------------------------------
  13158. Author: Mihai Bazon
  13159. <mihai.bazon@gmail.com>
  13160. http://mihai.bazon.net/blog
  13161. Distributed under the BSD license:
  13162. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13163. Redistribution and use in source and binary forms, with or without
  13164. modification, are permitted provided that the following conditions
  13165. are met:
  13166. * Redistributions of source code must retain the above
  13167. copyright notice, this list of conditions and the following
  13168. disclaimer.
  13169. * Redistributions in binary form must reproduce the above
  13170. copyright notice, this list of conditions and the following
  13171. disclaimer in the documentation and/or other materials
  13172. provided with the distribution.
  13173. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13174. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13175. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13176. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13177. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13178. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13179. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13180. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13181. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13182. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13183. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13184. SUCH DAMAGE.
  13185. ***********************************************************************/
  13186. "use strict";
  13187. function array_to_hash(a) {
  13188. var ret = Object.create(null);
  13189. for (var i = 0; i < a.length; ++i)
  13190. ret[a[i]] = true;
  13191. return ret;
  13192. };
  13193. function slice(a, start) {
  13194. return Array.prototype.slice.call(a, start || 0);
  13195. };
  13196. function characters(str) {
  13197. return str.split("");
  13198. };
  13199. function member(name, array) {
  13200. for (var i = array.length; --i >= 0;)
  13201. if (array[i] == name)
  13202. return true;
  13203. return false;
  13204. };
  13205. function find_if(func, array) {
  13206. for (var i = 0, n = array.length; i < n; ++i) {
  13207. if (func(array[i]))
  13208. return array[i];
  13209. }
  13210. };
  13211. function repeat_string(str, i) {
  13212. if (i <= 0) return "";
  13213. if (i == 1) return str;
  13214. var d = repeat_string(str, i >> 1);
  13215. d += d;
  13216. if (i & 1) d += str;
  13217. return d;
  13218. };
  13219. function DefaultsError(msg, defs) {
  13220. Error.call(this, msg);
  13221. this.msg = msg;
  13222. this.defs = defs;
  13223. };
  13224. DefaultsError.prototype = Object.create(Error.prototype);
  13225. DefaultsError.prototype.constructor = DefaultsError;
  13226. DefaultsError.croak = function(msg, defs) {
  13227. throw new DefaultsError(msg, defs);
  13228. };
  13229. function defaults(args, defs, croak) {
  13230. if (args === true)
  13231. args = {};
  13232. var ret = args || {};
  13233. if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
  13234. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  13235. for (var i in defs) if (defs.hasOwnProperty(i)) {
  13236. ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
  13237. }
  13238. return ret;
  13239. };
  13240. function merge(obj, ext) {
  13241. for (var i in ext) if (ext.hasOwnProperty(i)) {
  13242. obj[i] = ext[i];
  13243. }
  13244. return obj;
  13245. };
  13246. function noop() {};
  13247. var MAP = (function(){
  13248. function MAP(a, f, backwards) {
  13249. var ret = [], top = [], i;
  13250. function doit() {
  13251. var val = f(a[i], i);
  13252. var is_last = val instanceof Last;
  13253. if (is_last) val = val.v;
  13254. if (val instanceof AtTop) {
  13255. val = val.v;
  13256. if (val instanceof Splice) {
  13257. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  13258. } else {
  13259. top.push(val);
  13260. }
  13261. }
  13262. else if (val !== skip) {
  13263. if (val instanceof Splice) {
  13264. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  13265. } else {
  13266. ret.push(val);
  13267. }
  13268. }
  13269. return is_last;
  13270. };
  13271. if (a instanceof Array) {
  13272. if (backwards) {
  13273. for (i = a.length; --i >= 0;) if (doit()) break;
  13274. ret.reverse();
  13275. top.reverse();
  13276. } else {
  13277. for (i = 0; i < a.length; ++i) if (doit()) break;
  13278. }
  13279. }
  13280. else {
  13281. for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
  13282. }
  13283. return top.concat(ret);
  13284. };
  13285. MAP.at_top = function(val) { return new AtTop(val) };
  13286. MAP.splice = function(val) { return new Splice(val) };
  13287. MAP.last = function(val) { return new Last(val) };
  13288. var skip = MAP.skip = {};
  13289. function AtTop(val) { this.v = val };
  13290. function Splice(val) { this.v = val };
  13291. function Last(val) { this.v = val };
  13292. return MAP;
  13293. })();
  13294. function push_uniq(array, el) {
  13295. if (array.indexOf(el) < 0)
  13296. array.push(el);
  13297. };
  13298. function string_template(text, props) {
  13299. return text.replace(/\{(.+?)\}/g, function(str, p){
  13300. return props[p];
  13301. });
  13302. };
  13303. function remove(array, el) {
  13304. for (var i = array.length; --i >= 0;) {
  13305. if (array[i] === el) array.splice(i, 1);
  13306. }
  13307. };
  13308. function mergeSort(array, cmp) {
  13309. if (array.length < 2) return array.slice();
  13310. function merge(a, b) {
  13311. var r = [], ai = 0, bi = 0, i = 0;
  13312. while (ai < a.length && bi < b.length) {
  13313. cmp(a[ai], b[bi]) <= 0
  13314. ? r[i++] = a[ai++]
  13315. : r[i++] = b[bi++];
  13316. }
  13317. if (ai < a.length) r.push.apply(r, a.slice(ai));
  13318. if (bi < b.length) r.push.apply(r, b.slice(bi));
  13319. return r;
  13320. };
  13321. function _ms(a) {
  13322. if (a.length <= 1)
  13323. return a;
  13324. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  13325. left = _ms(left);
  13326. right = _ms(right);
  13327. return merge(left, right);
  13328. };
  13329. return _ms(array);
  13330. };
  13331. function set_difference(a, b) {
  13332. return a.filter(function(el){
  13333. return b.indexOf(el) < 0;
  13334. });
  13335. };
  13336. function set_intersection(a, b) {
  13337. return a.filter(function(el){
  13338. return b.indexOf(el) >= 0;
  13339. });
  13340. };
  13341. // this function is taken from Acorn [1], written by Marijn Haverbeke
  13342. // [1] https://github.com/marijnh/acorn
  13343. function makePredicate(words) {
  13344. if (!(words instanceof Array)) words = words.split(" ");
  13345. var f = "", cats = [];
  13346. out: for (var i = 0; i < words.length; ++i) {
  13347. for (var j = 0; j < cats.length; ++j)
  13348. if (cats[j][0].length == words[i].length) {
  13349. cats[j].push(words[i]);
  13350. continue out;
  13351. }
  13352. cats.push([words[i]]);
  13353. }
  13354. function compareTo(arr) {
  13355. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  13356. f += "switch(str){";
  13357. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  13358. f += "return true}return false;";
  13359. }
  13360. // When there are more than three length categories, an outer
  13361. // switch first dispatches on the lengths, to save on comparisons.
  13362. if (cats.length > 3) {
  13363. cats.sort(function(a, b) {return b.length - a.length;});
  13364. f += "switch(str.length){";
  13365. for (var i = 0; i < cats.length; ++i) {
  13366. var cat = cats[i];
  13367. f += "case " + cat[0].length + ":";
  13368. compareTo(cat);
  13369. }
  13370. f += "}";
  13371. // Otherwise, simply generate a flat `switch` statement.
  13372. } else {
  13373. compareTo(words);
  13374. }
  13375. return new Function("str", f);
  13376. };
  13377. function all(array, predicate) {
  13378. for (var i = array.length; --i >= 0;)
  13379. if (!predicate(array[i]))
  13380. return false;
  13381. return true;
  13382. };
  13383. function Dictionary() {
  13384. this._values = Object.create(null);
  13385. this._size = 0;
  13386. };
  13387. Dictionary.prototype = {
  13388. set: function(key, val) {
  13389. if (!this.has(key)) ++this._size;
  13390. this._values["$" + key] = val;
  13391. return this;
  13392. },
  13393. add: function(key, val) {
  13394. if (this.has(key)) {
  13395. this.get(key).push(val);
  13396. } else {
  13397. this.set(key, [ val ]);
  13398. }
  13399. return this;
  13400. },
  13401. get: function(key) { return this._values["$" + key] },
  13402. del: function(key) {
  13403. if (this.has(key)) {
  13404. --this._size;
  13405. delete this._values["$" + key];
  13406. }
  13407. return this;
  13408. },
  13409. has: function(key) { return ("$" + key) in this._values },
  13410. each: function(f) {
  13411. for (var i in this._values)
  13412. f(this._values[i], i.substr(1));
  13413. },
  13414. size: function() {
  13415. return this._size;
  13416. },
  13417. map: function(f) {
  13418. var ret = [];
  13419. for (var i in this._values)
  13420. ret.push(f(this._values[i], i.substr(1)));
  13421. return ret;
  13422. }
  13423. };
  13424. /***********************************************************************
  13425. A JavaScript tokenizer / parser / beautifier / compressor.
  13426. https://github.com/mishoo/UglifyJS2
  13427. -------------------------------- (C) ---------------------------------
  13428. Author: Mihai Bazon
  13429. <mihai.bazon@gmail.com>
  13430. http://mihai.bazon.net/blog
  13431. Distributed under the BSD license:
  13432. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13433. Redistribution and use in source and binary forms, with or without
  13434. modification, are permitted provided that the following conditions
  13435. are met:
  13436. * Redistributions of source code must retain the above
  13437. copyright notice, this list of conditions and the following
  13438. disclaimer.
  13439. * Redistributions in binary form must reproduce the above
  13440. copyright notice, this list of conditions and the following
  13441. disclaimer in the documentation and/or other materials
  13442. provided with the distribution.
  13443. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13444. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13445. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13446. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13447. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13448. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13449. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13450. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13451. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13452. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13453. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13454. SUCH DAMAGE.
  13455. ***********************************************************************/
  13456. "use strict";
  13457. function DEFNODE(type, props, methods, base) {
  13458. if (arguments.length < 4) base = AST_Node;
  13459. if (!props) props = [];
  13460. else props = props.split(/\s+/);
  13461. var self_props = props;
  13462. if (base && base.PROPS)
  13463. props = props.concat(base.PROPS);
  13464. var code = "return function AST_" + type + "(props){ if (props) { ";
  13465. for (var i = props.length; --i >= 0;) {
  13466. code += "this." + props[i] + " = props." + props[i] + ";";
  13467. }
  13468. var proto = base && new base;
  13469. if (proto && proto.initialize || (methods && methods.initialize))
  13470. code += "this.initialize();";
  13471. code += "}}";
  13472. var ctor = new Function(code)();
  13473. if (proto) {
  13474. ctor.prototype = proto;
  13475. ctor.BASE = base;
  13476. }
  13477. if (base) base.SUBCLASSES.push(ctor);
  13478. ctor.prototype.CTOR = ctor;
  13479. ctor.PROPS = props || null;
  13480. ctor.SELF_PROPS = self_props;
  13481. ctor.SUBCLASSES = [];
  13482. if (type) {
  13483. ctor.prototype.TYPE = ctor.TYPE = type;
  13484. }
  13485. if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
  13486. if (/^\$/.test(i)) {
  13487. ctor[i.substr(1)] = methods[i];
  13488. } else {
  13489. ctor.prototype[i] = methods[i];
  13490. }
  13491. }
  13492. ctor.DEFMETHOD = function(name, method) {
  13493. this.prototype[name] = method;
  13494. };
  13495. return ctor;
  13496. };
  13497. var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
  13498. }, null);
  13499. var AST_Node = DEFNODE("Node", "start end", {
  13500. clone: function() {
  13501. return new this.CTOR(this);
  13502. },
  13503. $documentation: "Base class of all AST nodes",
  13504. $propdoc: {
  13505. start: "[AST_Token] The first token of this node",
  13506. end: "[AST_Token] The last token of this node"
  13507. },
  13508. _walk: function(visitor) {
  13509. return visitor._visit(this);
  13510. },
  13511. walk: function(visitor) {
  13512. return this._walk(visitor); // not sure the indirection will be any help
  13513. }
  13514. }, null);
  13515. AST_Node.warn_function = null;
  13516. AST_Node.warn = function(txt, props) {
  13517. if (AST_Node.warn_function)
  13518. AST_Node.warn_function(string_template(txt, props));
  13519. };
  13520. /* -----[ statements ]----- */
  13521. var AST_Statement = DEFNODE("Statement", null, {
  13522. $documentation: "Base class of all statements",
  13523. });
  13524. var AST_Debugger = DEFNODE("Debugger", null, {
  13525. $documentation: "Represents a debugger statement",
  13526. }, AST_Statement);
  13527. var AST_Directive = DEFNODE("Directive", "value scope", {
  13528. $documentation: "Represents a directive, like \"use strict\";",
  13529. $propdoc: {
  13530. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  13531. scope: "[AST_Scope/S] The scope that this directive affects"
  13532. },
  13533. }, AST_Statement);
  13534. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  13535. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  13536. $propdoc: {
  13537. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  13538. },
  13539. _walk: function(visitor) {
  13540. return visitor._visit(this, function(){
  13541. this.body._walk(visitor);
  13542. });
  13543. }
  13544. }, AST_Statement);
  13545. function walk_body(node, visitor) {
  13546. if (node.body instanceof AST_Statement) {
  13547. node.body._walk(visitor);
  13548. }
  13549. else node.body.forEach(function(stat){
  13550. stat._walk(visitor);
  13551. });
  13552. };
  13553. var AST_Block = DEFNODE("Block", "body", {
  13554. $documentation: "A body of statements (usually bracketed)",
  13555. $propdoc: {
  13556. body: "[AST_Statement*] an array of statements"
  13557. },
  13558. _walk: function(visitor) {
  13559. return visitor._visit(this, function(){
  13560. walk_body(this, visitor);
  13561. });
  13562. }
  13563. }, AST_Statement);
  13564. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  13565. $documentation: "A block statement",
  13566. }, AST_Block);
  13567. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  13568. $documentation: "The empty statement (empty block or simply a semicolon)",
  13569. _walk: function(visitor) {
  13570. return visitor._visit(this);
  13571. }
  13572. }, AST_Statement);
  13573. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  13574. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  13575. $propdoc: {
  13576. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  13577. },
  13578. _walk: function(visitor) {
  13579. return visitor._visit(this, function(){
  13580. this.body._walk(visitor);
  13581. });
  13582. }
  13583. }, AST_Statement);
  13584. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  13585. $documentation: "Statement with a label",
  13586. $propdoc: {
  13587. label: "[AST_Label] a label definition"
  13588. },
  13589. _walk: function(visitor) {
  13590. return visitor._visit(this, function(){
  13591. this.label._walk(visitor);
  13592. this.body._walk(visitor);
  13593. });
  13594. }
  13595. }, AST_StatementWithBody);
  13596. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  13597. $documentation: "Internal class. All loops inherit from it."
  13598. }, AST_StatementWithBody);
  13599. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  13600. $documentation: "Base class for do/while statements",
  13601. $propdoc: {
  13602. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  13603. },
  13604. _walk: function(visitor) {
  13605. return visitor._visit(this, function(){
  13606. this.condition._walk(visitor);
  13607. this.body._walk(visitor);
  13608. });
  13609. }
  13610. }, AST_IterationStatement);
  13611. var AST_Do = DEFNODE("Do", null, {
  13612. $documentation: "A `do` statement",
  13613. }, AST_DWLoop);
  13614. var AST_While = DEFNODE("While", null, {
  13615. $documentation: "A `while` statement",
  13616. }, AST_DWLoop);
  13617. var AST_For = DEFNODE("For", "init condition step", {
  13618. $documentation: "A `for` statement",
  13619. $propdoc: {
  13620. init: "[AST_Node?] the `for` initialization code, or null if empty",
  13621. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  13622. step: "[AST_Node?] the `for` update clause, or null if empty"
  13623. },
  13624. _walk: function(visitor) {
  13625. return visitor._visit(this, function(){
  13626. if (this.init) this.init._walk(visitor);
  13627. if (this.condition) this.condition._walk(visitor);
  13628. if (this.step) this.step._walk(visitor);
  13629. this.body._walk(visitor);
  13630. });
  13631. }
  13632. }, AST_IterationStatement);
  13633. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  13634. $documentation: "A `for ... in` statement",
  13635. $propdoc: {
  13636. init: "[AST_Node] the `for/in` initialization code",
  13637. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  13638. object: "[AST_Node] the object that we're looping through"
  13639. },
  13640. _walk: function(visitor) {
  13641. return visitor._visit(this, function(){
  13642. this.init._walk(visitor);
  13643. this.object._walk(visitor);
  13644. this.body._walk(visitor);
  13645. });
  13646. }
  13647. }, AST_IterationStatement);
  13648. var AST_With = DEFNODE("With", "expression", {
  13649. $documentation: "A `with` statement",
  13650. $propdoc: {
  13651. expression: "[AST_Node] the `with` expression"
  13652. },
  13653. _walk: function(visitor) {
  13654. return visitor._visit(this, function(){
  13655. this.expression._walk(visitor);
  13656. this.body._walk(visitor);
  13657. });
  13658. }
  13659. }, AST_StatementWithBody);
  13660. /* -----[ scope and functions ]----- */
  13661. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  13662. $documentation: "Base class for all statements introducing a lexical scope",
  13663. $propdoc: {
  13664. directives: "[string*/S] an array of directives declared in this scope",
  13665. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  13666. functions: "[Object/S] like `variables`, but only lists function declarations",
  13667. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  13668. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  13669. parent_scope: "[AST_Scope?/S] link to the parent scope",
  13670. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  13671. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  13672. },
  13673. }, AST_Block);
  13674. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  13675. $documentation: "The toplevel scope",
  13676. $propdoc: {
  13677. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  13678. },
  13679. wrap_enclose: function(arg_parameter_pairs) {
  13680. var self = this;
  13681. var args = [];
  13682. var parameters = [];
  13683. arg_parameter_pairs.forEach(function(pair) {
  13684. var split = pair.split(":");
  13685. args.push(split[0]);
  13686. parameters.push(split[1]);
  13687. });
  13688. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  13689. wrapped_tl = parse(wrapped_tl);
  13690. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  13691. if (node instanceof AST_Directive && node.value == "$ORIG") {
  13692. return MAP.splice(self.body);
  13693. }
  13694. }));
  13695. return wrapped_tl;
  13696. },
  13697. wrap_commonjs: function(name, export_all) {
  13698. var self = this;
  13699. var to_export = [];
  13700. if (export_all) {
  13701. self.figure_out_scope();
  13702. self.walk(new TreeWalker(function(node){
  13703. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  13704. if (!find_if(function(n){ return n.name == node.name }, to_export))
  13705. to_export.push(node);
  13706. }
  13707. }));
  13708. }
  13709. var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
  13710. wrapped_tl = parse(wrapped_tl);
  13711. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  13712. if (node instanceof AST_SimpleStatement) {
  13713. node = node.body;
  13714. if (node instanceof AST_String) switch (node.getValue()) {
  13715. case "$ORIG":
  13716. return MAP.splice(self.body);
  13717. case "$EXPORTS":
  13718. var body = [];
  13719. to_export.forEach(function(sym){
  13720. body.push(new AST_SimpleStatement({
  13721. body: new AST_Assign({
  13722. left: new AST_Sub({
  13723. expression: new AST_SymbolRef({ name: "exports" }),
  13724. property: new AST_String({ value: sym.name }),
  13725. }),
  13726. operator: "=",
  13727. right: new AST_SymbolRef(sym),
  13728. }),
  13729. }));
  13730. });
  13731. return MAP.splice(body);
  13732. }
  13733. }
  13734. }));
  13735. return wrapped_tl;
  13736. }
  13737. }, AST_Scope);
  13738. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  13739. $documentation: "Base class for functions",
  13740. $propdoc: {
  13741. name: "[AST_SymbolDeclaration?] the name of this function",
  13742. argnames: "[AST_SymbolFunarg*] array of function arguments",
  13743. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  13744. },
  13745. _walk: function(visitor) {
  13746. return visitor._visit(this, function(){
  13747. if (this.name) this.name._walk(visitor);
  13748. this.argnames.forEach(function(arg){
  13749. arg._walk(visitor);
  13750. });
  13751. walk_body(this, visitor);
  13752. });
  13753. }
  13754. }, AST_Scope);
  13755. var AST_Accessor = DEFNODE("Accessor", null, {
  13756. $documentation: "A setter/getter function. The `name` property is always null."
  13757. }, AST_Lambda);
  13758. var AST_Function = DEFNODE("Function", null, {
  13759. $documentation: "A function expression"
  13760. }, AST_Lambda);
  13761. var AST_Defun = DEFNODE("Defun", null, {
  13762. $documentation: "A function definition"
  13763. }, AST_Lambda);
  13764. /* -----[ JUMPS ]----- */
  13765. var AST_Jump = DEFNODE("Jump", null, {
  13766. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  13767. }, AST_Statement);
  13768. var AST_Exit = DEFNODE("Exit", "value", {
  13769. $documentation: "Base class for “exits” (`return` and `throw`)",
  13770. $propdoc: {
  13771. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  13772. },
  13773. _walk: function(visitor) {
  13774. return visitor._visit(this, this.value && function(){
  13775. this.value._walk(visitor);
  13776. });
  13777. }
  13778. }, AST_Jump);
  13779. var AST_Return = DEFNODE("Return", null, {
  13780. $documentation: "A `return` statement"
  13781. }, AST_Exit);
  13782. var AST_Throw = DEFNODE("Throw", null, {
  13783. $documentation: "A `throw` statement"
  13784. }, AST_Exit);
  13785. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  13786. $documentation: "Base class for loop control statements (`break` and `continue`)",
  13787. $propdoc: {
  13788. label: "[AST_LabelRef?] the label, or null if none",
  13789. },
  13790. _walk: function(visitor) {
  13791. return visitor._visit(this, this.label && function(){
  13792. this.label._walk(visitor);
  13793. });
  13794. }
  13795. }, AST_Jump);
  13796. var AST_Break = DEFNODE("Break", null, {
  13797. $documentation: "A `break` statement"
  13798. }, AST_LoopControl);
  13799. var AST_Continue = DEFNODE("Continue", null, {
  13800. $documentation: "A `continue` statement"
  13801. }, AST_LoopControl);
  13802. /* -----[ IF ]----- */
  13803. var AST_If = DEFNODE("If", "condition alternative", {
  13804. $documentation: "A `if` statement",
  13805. $propdoc: {
  13806. condition: "[AST_Node] the `if` condition",
  13807. alternative: "[AST_Statement?] the `else` part, or null if not present"
  13808. },
  13809. _walk: function(visitor) {
  13810. return visitor._visit(this, function(){
  13811. this.condition._walk(visitor);
  13812. this.body._walk(visitor);
  13813. if (this.alternative) this.alternative._walk(visitor);
  13814. });
  13815. }
  13816. }, AST_StatementWithBody);
  13817. /* -----[ SWITCH ]----- */
  13818. var AST_Switch = DEFNODE("Switch", "expression", {
  13819. $documentation: "A `switch` statement",
  13820. $propdoc: {
  13821. expression: "[AST_Node] the `switch` “discriminant”"
  13822. },
  13823. _walk: function(visitor) {
  13824. return visitor._visit(this, function(){
  13825. this.expression._walk(visitor);
  13826. walk_body(this, visitor);
  13827. });
  13828. }
  13829. }, AST_Block);
  13830. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  13831. $documentation: "Base class for `switch` branches",
  13832. }, AST_Block);
  13833. var AST_Default = DEFNODE("Default", null, {
  13834. $documentation: "A `default` switch branch",
  13835. }, AST_SwitchBranch);
  13836. var AST_Case = DEFNODE("Case", "expression", {
  13837. $documentation: "A `case` switch branch",
  13838. $propdoc: {
  13839. expression: "[AST_Node] the `case` expression"
  13840. },
  13841. _walk: function(visitor) {
  13842. return visitor._visit(this, function(){
  13843. this.expression._walk(visitor);
  13844. walk_body(this, visitor);
  13845. });
  13846. }
  13847. }, AST_SwitchBranch);
  13848. /* -----[ EXCEPTIONS ]----- */
  13849. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  13850. $documentation: "A `try` statement",
  13851. $propdoc: {
  13852. bcatch: "[AST_Catch?] the catch block, or null if not present",
  13853. bfinally: "[AST_Finally?] the finally block, or null if not present"
  13854. },
  13855. _walk: function(visitor) {
  13856. return visitor._visit(this, function(){
  13857. walk_body(this, visitor);
  13858. if (this.bcatch) this.bcatch._walk(visitor);
  13859. if (this.bfinally) this.bfinally._walk(visitor);
  13860. });
  13861. }
  13862. }, AST_Block);
  13863. var AST_Catch = DEFNODE("Catch", "argname", {
  13864. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  13865. $propdoc: {
  13866. argname: "[AST_SymbolCatch] symbol for the exception"
  13867. },
  13868. _walk: function(visitor) {
  13869. return visitor._visit(this, function(){
  13870. this.argname._walk(visitor);
  13871. walk_body(this, visitor);
  13872. });
  13873. }
  13874. }, AST_Block);
  13875. var AST_Finally = DEFNODE("Finally", null, {
  13876. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  13877. }, AST_Block);
  13878. /* -----[ VAR/CONST ]----- */
  13879. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  13880. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  13881. $propdoc: {
  13882. definitions: "[AST_VarDef*] array of variable definitions"
  13883. },
  13884. _walk: function(visitor) {
  13885. return visitor._visit(this, function(){
  13886. this.definitions.forEach(function(def){
  13887. def._walk(visitor);
  13888. });
  13889. });
  13890. }
  13891. }, AST_Statement);
  13892. var AST_Var = DEFNODE("Var", null, {
  13893. $documentation: "A `var` statement"
  13894. }, AST_Definitions);
  13895. var AST_Const = DEFNODE("Const", null, {
  13896. $documentation: "A `const` statement"
  13897. }, AST_Definitions);
  13898. var AST_VarDef = DEFNODE("VarDef", "name value", {
  13899. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  13900. $propdoc: {
  13901. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  13902. value: "[AST_Node?] initializer, or null of there's no initializer"
  13903. },
  13904. _walk: function(visitor) {
  13905. return visitor._visit(this, function(){
  13906. this.name._walk(visitor);
  13907. if (this.value) this.value._walk(visitor);
  13908. });
  13909. }
  13910. });
  13911. /* -----[ OTHER ]----- */
  13912. var AST_Call = DEFNODE("Call", "expression args", {
  13913. $documentation: "A function call expression",
  13914. $propdoc: {
  13915. expression: "[AST_Node] expression to invoke as function",
  13916. args: "[AST_Node*] array of arguments"
  13917. },
  13918. _walk: function(visitor) {
  13919. return visitor._visit(this, function(){
  13920. this.expression._walk(visitor);
  13921. this.args.forEach(function(arg){
  13922. arg._walk(visitor);
  13923. });
  13924. });
  13925. }
  13926. });
  13927. var AST_New = DEFNODE("New", null, {
  13928. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  13929. }, AST_Call);
  13930. var AST_Seq = DEFNODE("Seq", "car cdr", {
  13931. $documentation: "A sequence expression (two comma-separated expressions)",
  13932. $propdoc: {
  13933. car: "[AST_Node] first element in sequence",
  13934. cdr: "[AST_Node] second element in sequence"
  13935. },
  13936. $cons: function(x, y) {
  13937. var seq = new AST_Seq(x);
  13938. seq.car = x;
  13939. seq.cdr = y;
  13940. return seq;
  13941. },
  13942. $from_array: function(array) {
  13943. if (array.length == 0) return null;
  13944. if (array.length == 1) return array[0].clone();
  13945. var list = null;
  13946. for (var i = array.length; --i >= 0;) {
  13947. list = AST_Seq.cons(array[i], list);
  13948. }
  13949. var p = list;
  13950. while (p) {
  13951. if (p.cdr && !p.cdr.cdr) {
  13952. p.cdr = p.cdr.car;
  13953. break;
  13954. }
  13955. p = p.cdr;
  13956. }
  13957. return list;
  13958. },
  13959. to_array: function() {
  13960. var p = this, a = [];
  13961. while (p) {
  13962. a.push(p.car);
  13963. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  13964. a.push(p.cdr);
  13965. break;
  13966. }
  13967. p = p.cdr;
  13968. }
  13969. return a;
  13970. },
  13971. add: function(node) {
  13972. var p = this;
  13973. while (p) {
  13974. if (!(p.cdr instanceof AST_Seq)) {
  13975. var cell = AST_Seq.cons(p.cdr, node);
  13976. return p.cdr = cell;
  13977. }
  13978. p = p.cdr;
  13979. }
  13980. },
  13981. _walk: function(visitor) {
  13982. return visitor._visit(this, function(){
  13983. this.car._walk(visitor);
  13984. if (this.cdr) this.cdr._walk(visitor);
  13985. });
  13986. }
  13987. });
  13988. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  13989. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  13990. $propdoc: {
  13991. expression: "[AST_Node] the “container” expression",
  13992. 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"
  13993. }
  13994. });
  13995. var AST_Dot = DEFNODE("Dot", null, {
  13996. $documentation: "A dotted property access expression",
  13997. _walk: function(visitor) {
  13998. return visitor._visit(this, function(){
  13999. this.expression._walk(visitor);
  14000. });
  14001. }
  14002. }, AST_PropAccess);
  14003. var AST_Sub = DEFNODE("Sub", null, {
  14004. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  14005. _walk: function(visitor) {
  14006. return visitor._visit(this, function(){
  14007. this.expression._walk(visitor);
  14008. this.property._walk(visitor);
  14009. });
  14010. }
  14011. }, AST_PropAccess);
  14012. var AST_Unary = DEFNODE("Unary", "operator expression", {
  14013. $documentation: "Base class for unary expressions",
  14014. $propdoc: {
  14015. operator: "[string] the operator",
  14016. expression: "[AST_Node] expression that this unary operator applies to"
  14017. },
  14018. _walk: function(visitor) {
  14019. return visitor._visit(this, function(){
  14020. this.expression._walk(visitor);
  14021. });
  14022. }
  14023. });
  14024. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  14025. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  14026. }, AST_Unary);
  14027. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  14028. $documentation: "Unary postfix expression, i.e. `i++`"
  14029. }, AST_Unary);
  14030. var AST_Binary = DEFNODE("Binary", "left operator right", {
  14031. $documentation: "Binary expression, i.e. `a + b`",
  14032. $propdoc: {
  14033. left: "[AST_Node] left-hand side expression",
  14034. operator: "[string] the operator",
  14035. right: "[AST_Node] right-hand side expression"
  14036. },
  14037. _walk: function(visitor) {
  14038. return visitor._visit(this, function(){
  14039. this.left._walk(visitor);
  14040. this.right._walk(visitor);
  14041. });
  14042. }
  14043. });
  14044. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  14045. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  14046. $propdoc: {
  14047. condition: "[AST_Node]",
  14048. consequent: "[AST_Node]",
  14049. alternative: "[AST_Node]"
  14050. },
  14051. _walk: function(visitor) {
  14052. return visitor._visit(this, function(){
  14053. this.condition._walk(visitor);
  14054. this.consequent._walk(visitor);
  14055. this.alternative._walk(visitor);
  14056. });
  14057. }
  14058. });
  14059. var AST_Assign = DEFNODE("Assign", null, {
  14060. $documentation: "An assignment expression — `a = b + 5`",
  14061. }, AST_Binary);
  14062. /* -----[ LITERALS ]----- */
  14063. var AST_Array = DEFNODE("Array", "elements", {
  14064. $documentation: "An array literal",
  14065. $propdoc: {
  14066. elements: "[AST_Node*] array of elements"
  14067. },
  14068. _walk: function(visitor) {
  14069. return visitor._visit(this, function(){
  14070. this.elements.forEach(function(el){
  14071. el._walk(visitor);
  14072. });
  14073. });
  14074. }
  14075. });
  14076. var AST_Object = DEFNODE("Object", "properties", {
  14077. $documentation: "An object literal",
  14078. $propdoc: {
  14079. properties: "[AST_ObjectProperty*] array of properties"
  14080. },
  14081. _walk: function(visitor) {
  14082. return visitor._visit(this, function(){
  14083. this.properties.forEach(function(prop){
  14084. prop._walk(visitor);
  14085. });
  14086. });
  14087. }
  14088. });
  14089. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  14090. $documentation: "Base class for literal object properties",
  14091. $propdoc: {
  14092. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
  14093. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  14094. },
  14095. _walk: function(visitor) {
  14096. return visitor._visit(this, function(){
  14097. this.value._walk(visitor);
  14098. });
  14099. }
  14100. });
  14101. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
  14102. $documentation: "A key: value object property",
  14103. }, AST_ObjectProperty);
  14104. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  14105. $documentation: "An object setter property",
  14106. }, AST_ObjectProperty);
  14107. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  14108. $documentation: "An object getter property",
  14109. }, AST_ObjectProperty);
  14110. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  14111. $propdoc: {
  14112. name: "[string] name of this symbol",
  14113. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  14114. thedef: "[SymbolDef/S] the definition of this symbol"
  14115. },
  14116. $documentation: "Base class for all symbols",
  14117. });
  14118. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  14119. $documentation: "The name of a property accessor (setter/getter function)"
  14120. }, AST_Symbol);
  14121. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  14122. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  14123. $propdoc: {
  14124. init: "[AST_Node*/S] array of initializers for this declaration."
  14125. }
  14126. }, AST_Symbol);
  14127. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  14128. $documentation: "Symbol defining a variable",
  14129. }, AST_SymbolDeclaration);
  14130. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  14131. $documentation: "A constant declaration"
  14132. }, AST_SymbolDeclaration);
  14133. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  14134. $documentation: "Symbol naming a function argument",
  14135. }, AST_SymbolVar);
  14136. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  14137. $documentation: "Symbol defining a function",
  14138. }, AST_SymbolDeclaration);
  14139. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  14140. $documentation: "Symbol naming a function expression",
  14141. }, AST_SymbolDeclaration);
  14142. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  14143. $documentation: "Symbol naming the exception in catch",
  14144. }, AST_SymbolDeclaration);
  14145. var AST_Label = DEFNODE("Label", "references", {
  14146. $documentation: "Symbol naming a label (declaration)",
  14147. $propdoc: {
  14148. references: "[AST_LoopControl*] a list of nodes referring to this label"
  14149. },
  14150. initialize: function() {
  14151. this.references = [];
  14152. this.thedef = this;
  14153. }
  14154. }, AST_Symbol);
  14155. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  14156. $documentation: "Reference to some symbol (not definition/declaration)",
  14157. }, AST_Symbol);
  14158. var AST_LabelRef = DEFNODE("LabelRef", null, {
  14159. $documentation: "Reference to a label symbol",
  14160. }, AST_Symbol);
  14161. var AST_This = DEFNODE("This", null, {
  14162. $documentation: "The `this` symbol",
  14163. }, AST_Symbol);
  14164. var AST_Constant = DEFNODE("Constant", null, {
  14165. $documentation: "Base class for all constants",
  14166. getValue: function() {
  14167. return this.value;
  14168. }
  14169. });
  14170. var AST_String = DEFNODE("String", "value", {
  14171. $documentation: "A string literal",
  14172. $propdoc: {
  14173. value: "[string] the contents of this string"
  14174. }
  14175. }, AST_Constant);
  14176. var AST_Number = DEFNODE("Number", "value", {
  14177. $documentation: "A number literal",
  14178. $propdoc: {
  14179. value: "[number] the numeric value"
  14180. }
  14181. }, AST_Constant);
  14182. var AST_RegExp = DEFNODE("RegExp", "value", {
  14183. $documentation: "A regexp literal",
  14184. $propdoc: {
  14185. value: "[RegExp] the actual regexp"
  14186. }
  14187. }, AST_Constant);
  14188. var AST_Atom = DEFNODE("Atom", null, {
  14189. $documentation: "Base class for atoms",
  14190. }, AST_Constant);
  14191. var AST_Null = DEFNODE("Null", null, {
  14192. $documentation: "The `null` atom",
  14193. value: null
  14194. }, AST_Atom);
  14195. var AST_NaN = DEFNODE("NaN", null, {
  14196. $documentation: "The impossible value",
  14197. value: 0/0
  14198. }, AST_Atom);
  14199. var AST_Undefined = DEFNODE("Undefined", null, {
  14200. $documentation: "The `undefined` value",
  14201. value: (function(){}())
  14202. }, AST_Atom);
  14203. var AST_Hole = DEFNODE("Hole", null, {
  14204. $documentation: "A hole in an array",
  14205. value: (function(){}())
  14206. }, AST_Atom);
  14207. var AST_Infinity = DEFNODE("Infinity", null, {
  14208. $documentation: "The `Infinity` value",
  14209. value: 1/0
  14210. }, AST_Atom);
  14211. var AST_Boolean = DEFNODE("Boolean", null, {
  14212. $documentation: "Base class for booleans",
  14213. }, AST_Atom);
  14214. var AST_False = DEFNODE("False", null, {
  14215. $documentation: "The `false` atom",
  14216. value: false
  14217. }, AST_Boolean);
  14218. var AST_True = DEFNODE("True", null, {
  14219. $documentation: "The `true` atom",
  14220. value: true
  14221. }, AST_Boolean);
  14222. /* -----[ TreeWalker ]----- */
  14223. function TreeWalker(callback) {
  14224. this.visit = callback;
  14225. this.stack = [];
  14226. };
  14227. TreeWalker.prototype = {
  14228. _visit: function(node, descend) {
  14229. this.stack.push(node);
  14230. var ret = this.visit(node, descend ? function(){
  14231. descend.call(node);
  14232. } : noop);
  14233. if (!ret && descend) {
  14234. descend.call(node);
  14235. }
  14236. this.stack.pop();
  14237. return ret;
  14238. },
  14239. parent: function(n) {
  14240. return this.stack[this.stack.length - 2 - (n || 0)];
  14241. },
  14242. push: function (node) {
  14243. this.stack.push(node);
  14244. },
  14245. pop: function() {
  14246. return this.stack.pop();
  14247. },
  14248. self: function() {
  14249. return this.stack[this.stack.length - 1];
  14250. },
  14251. find_parent: function(type) {
  14252. var stack = this.stack;
  14253. for (var i = stack.length; --i >= 0;) {
  14254. var x = stack[i];
  14255. if (x instanceof type) return x;
  14256. }
  14257. },
  14258. has_directive: function(type) {
  14259. return this.find_parent(AST_Scope).has_directive(type);
  14260. },
  14261. in_boolean_context: function() {
  14262. var stack = this.stack;
  14263. var i = stack.length, self = stack[--i];
  14264. while (i > 0) {
  14265. var p = stack[--i];
  14266. if ((p instanceof AST_If && p.condition === self) ||
  14267. (p instanceof AST_Conditional && p.condition === self) ||
  14268. (p instanceof AST_DWLoop && p.condition === self) ||
  14269. (p instanceof AST_For && p.condition === self) ||
  14270. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  14271. {
  14272. return true;
  14273. }
  14274. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  14275. return false;
  14276. self = p;
  14277. }
  14278. },
  14279. loopcontrol_target: function(label) {
  14280. var stack = this.stack;
  14281. if (label) for (var i = stack.length; --i >= 0;) {
  14282. var x = stack[i];
  14283. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  14284. return x.body;
  14285. }
  14286. } else for (var i = stack.length; --i >= 0;) {
  14287. var x = stack[i];
  14288. if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
  14289. return x;
  14290. }
  14291. }
  14292. };
  14293. /***********************************************************************
  14294. A JavaScript tokenizer / parser / beautifier / compressor.
  14295. https://github.com/mishoo/UglifyJS2
  14296. -------------------------------- (C) ---------------------------------
  14297. Author: Mihai Bazon
  14298. <mihai.bazon@gmail.com>
  14299. http://mihai.bazon.net/blog
  14300. Distributed under the BSD license:
  14301. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14302. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  14303. Redistribution and use in source and binary forms, with or without
  14304. modification, are permitted provided that the following conditions
  14305. are met:
  14306. * Redistributions of source code must retain the above
  14307. copyright notice, this list of conditions and the following
  14308. disclaimer.
  14309. * Redistributions in binary form must reproduce the above
  14310. copyright notice, this list of conditions and the following
  14311. disclaimer in the documentation and/or other materials
  14312. provided with the distribution.
  14313. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14314. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14315. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14316. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14317. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14318. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14319. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14320. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14321. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14322. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14323. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14324. SUCH DAMAGE.
  14325. ***********************************************************************/
  14326. "use strict";
  14327. 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';
  14328. var KEYWORDS_ATOM = 'false null true';
  14329. 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'
  14330. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  14331. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  14332. KEYWORDS = makePredicate(KEYWORDS);
  14333. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  14334. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  14335. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  14336. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  14337. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  14338. var RE_OCT_NUMBER = /^0[0-7]+$/;
  14339. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  14340. var OPERATORS = makePredicate([
  14341. "in",
  14342. "instanceof",
  14343. "typeof",
  14344. "new",
  14345. "void",
  14346. "delete",
  14347. "++",
  14348. "--",
  14349. "+",
  14350. "-",
  14351. "!",
  14352. "~",
  14353. "&",
  14354. "|",
  14355. "^",
  14356. "*",
  14357. "/",
  14358. "%",
  14359. ">>",
  14360. "<<",
  14361. ">>>",
  14362. "<",
  14363. ">",
  14364. "<=",
  14365. ">=",
  14366. "==",
  14367. "===",
  14368. "!=",
  14369. "!==",
  14370. "?",
  14371. "=",
  14372. "+=",
  14373. "-=",
  14374. "/=",
  14375. "*=",
  14376. "%=",
  14377. ">>=",
  14378. "<<=",
  14379. ">>>=",
  14380. "|=",
  14381. "^=",
  14382. "&=",
  14383. "&&",
  14384. "||"
  14385. ]);
  14386. 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"));
  14387. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  14388. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  14389. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  14390. /* -----[ Tokenizer ]----- */
  14391. // regexps adapted from http://xregexp.com/plugins/#unicode
  14392. var UNICODE = {
  14393. 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]"),
  14394. 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]"),
  14395. 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]"),
  14396. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  14397. };
  14398. function is_letter(code) {
  14399. return (code >= 97 && code <= 122)
  14400. || (code >= 65 && code <= 90)
  14401. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  14402. };
  14403. function is_digit(code) {
  14404. return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
  14405. };
  14406. function is_alphanumeric_char(code) {
  14407. return is_digit(code) || is_letter(code);
  14408. };
  14409. function is_unicode_combining_mark(ch) {
  14410. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  14411. };
  14412. function is_unicode_connector_punctuation(ch) {
  14413. return UNICODE.connector_punctuation.test(ch);
  14414. };
  14415. function is_identifier(name) {
  14416. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  14417. };
  14418. function is_identifier_start(code) {
  14419. return code == 36 || code == 95 || is_letter(code);
  14420. };
  14421. function is_identifier_char(ch) {
  14422. var code = ch.charCodeAt(0);
  14423. return is_identifier_start(code)
  14424. || is_digit(code)
  14425. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  14426. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  14427. || is_unicode_combining_mark(ch)
  14428. || is_unicode_connector_punctuation(ch)
  14429. ;
  14430. };
  14431. function is_identifier_string(str){
  14432. var i = str.length;
  14433. if (i == 0) return false;
  14434. if (!is_identifier_start(str.charCodeAt(0))) return false;
  14435. while (--i >= 0) {
  14436. if (!is_identifier_char(str.charAt(i)))
  14437. return false;
  14438. }
  14439. return true;
  14440. };
  14441. function parse_js_number(num) {
  14442. if (RE_HEX_NUMBER.test(num)) {
  14443. return parseInt(num.substr(2), 16);
  14444. } else if (RE_OCT_NUMBER.test(num)) {
  14445. return parseInt(num.substr(1), 8);
  14446. } else if (RE_DEC_NUMBER.test(num)) {
  14447. return parseFloat(num);
  14448. }
  14449. };
  14450. function JS_Parse_Error(message, line, col, pos) {
  14451. this.message = message;
  14452. this.line = line;
  14453. this.col = col;
  14454. this.pos = pos;
  14455. this.stack = new Error().stack;
  14456. };
  14457. JS_Parse_Error.prototype.toString = function() {
  14458. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  14459. };
  14460. function js_error(message, filename, line, col, pos) {
  14461. throw new JS_Parse_Error(message, line, col, pos);
  14462. };
  14463. function is_token(token, type, val) {
  14464. return token.type == type && (val == null || token.value == val);
  14465. };
  14466. var EX_EOF = {};
  14467. function tokenizer($TEXT, filename, html5_comments) {
  14468. var S = {
  14469. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''),
  14470. filename : filename,
  14471. pos : 0,
  14472. tokpos : 0,
  14473. line : 1,
  14474. tokline : 0,
  14475. col : 0,
  14476. tokcol : 0,
  14477. newline_before : false,
  14478. regex_allowed : false,
  14479. comments_before : []
  14480. };
  14481. function peek() { return S.text.charAt(S.pos); };
  14482. function next(signal_eof, in_string) {
  14483. var ch = S.text.charAt(S.pos++);
  14484. if (signal_eof && !ch)
  14485. throw EX_EOF;
  14486. if (ch == "\n") {
  14487. S.newline_before = S.newline_before || !in_string;
  14488. ++S.line;
  14489. S.col = 0;
  14490. } else {
  14491. ++S.col;
  14492. }
  14493. return ch;
  14494. };
  14495. function forward(i) {
  14496. while (i-- > 0) next();
  14497. };
  14498. function looking_at(str) {
  14499. return S.text.substr(S.pos, str.length) == str;
  14500. };
  14501. function find(what, signal_eof) {
  14502. var pos = S.text.indexOf(what, S.pos);
  14503. if (signal_eof && pos == -1) throw EX_EOF;
  14504. return pos;
  14505. };
  14506. function start_token() {
  14507. S.tokline = S.line;
  14508. S.tokcol = S.col;
  14509. S.tokpos = S.pos;
  14510. };
  14511. var prev_was_dot = false;
  14512. function token(type, value, is_comment) {
  14513. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  14514. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  14515. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  14516. prev_was_dot = (type == "punc" && value == ".");
  14517. var ret = {
  14518. type : type,
  14519. value : value,
  14520. line : S.tokline,
  14521. col : S.tokcol,
  14522. pos : S.tokpos,
  14523. endpos : S.pos,
  14524. nlb : S.newline_before,
  14525. file : filename
  14526. };
  14527. if (!is_comment) {
  14528. ret.comments_before = S.comments_before;
  14529. S.comments_before = [];
  14530. // make note of any newlines in the comments that came before
  14531. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  14532. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  14533. }
  14534. }
  14535. S.newline_before = false;
  14536. return new AST_Token(ret);
  14537. };
  14538. function skip_whitespace() {
  14539. while (WHITESPACE_CHARS(peek()))
  14540. next();
  14541. };
  14542. function read_while(pred) {
  14543. var ret = "", ch, i = 0;
  14544. while ((ch = peek()) && pred(ch, i++))
  14545. ret += next();
  14546. return ret;
  14547. };
  14548. function parse_error(err) {
  14549. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  14550. };
  14551. function read_num(prefix) {
  14552. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  14553. var num = read_while(function(ch, i){
  14554. var code = ch.charCodeAt(0);
  14555. switch (code) {
  14556. case 120: case 88: // xX
  14557. return has_x ? false : (has_x = true);
  14558. case 101: case 69: // eE
  14559. return has_x ? true : has_e ? false : (has_e = after_e = true);
  14560. case 45: // -
  14561. return after_e || (i == 0 && !prefix);
  14562. case 43: // +
  14563. return after_e;
  14564. case (after_e = false, 46): // .
  14565. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  14566. }
  14567. return is_alphanumeric_char(code);
  14568. });
  14569. if (prefix) num = prefix + num;
  14570. var valid = parse_js_number(num);
  14571. if (!isNaN(valid)) {
  14572. return token("num", valid);
  14573. } else {
  14574. parse_error("Invalid syntax: " + num);
  14575. }
  14576. };
  14577. function read_escaped_char(in_string) {
  14578. var ch = next(true, in_string);
  14579. switch (ch.charCodeAt(0)) {
  14580. case 110 : return "\n";
  14581. case 114 : return "\r";
  14582. case 116 : return "\t";
  14583. case 98 : return "\b";
  14584. case 118 : return "\u000b"; // \v
  14585. case 102 : return "\f";
  14586. case 48 : return "\0";
  14587. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  14588. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  14589. case 10 : return ""; // newline
  14590. default : return ch;
  14591. }
  14592. };
  14593. function hex_bytes(n) {
  14594. var num = 0;
  14595. for (; n > 0; --n) {
  14596. var digit = parseInt(next(true), 16);
  14597. if (isNaN(digit))
  14598. parse_error("Invalid hex-character pattern in string");
  14599. num = (num << 4) | digit;
  14600. }
  14601. return num;
  14602. };
  14603. var read_string = with_eof_error("Unterminated string constant", function(){
  14604. var quote = next(), ret = "";
  14605. for (;;) {
  14606. var ch = next(true);
  14607. if (ch == "\\") {
  14608. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  14609. // https://github.com/mishoo/UglifyJS/issues/178
  14610. var octal_len = 0, first = null;
  14611. ch = read_while(function(ch){
  14612. if (ch >= "0" && ch <= "7") {
  14613. if (!first) {
  14614. first = ch;
  14615. return ++octal_len;
  14616. }
  14617. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  14618. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  14619. }
  14620. return false;
  14621. });
  14622. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  14623. else ch = read_escaped_char(true);
  14624. }
  14625. else if (ch == quote) break;
  14626. ret += ch;
  14627. }
  14628. return token("string", ret);
  14629. });
  14630. function skip_line_comment(type) {
  14631. var regex_allowed = S.regex_allowed;
  14632. var i = find("\n"), ret;
  14633. if (i == -1) {
  14634. ret = S.text.substr(S.pos);
  14635. S.pos = S.text.length;
  14636. } else {
  14637. ret = S.text.substring(S.pos, i);
  14638. S.pos = i;
  14639. }
  14640. S.comments_before.push(token(type, ret, true));
  14641. S.regex_allowed = regex_allowed;
  14642. return next_token();
  14643. };
  14644. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
  14645. var regex_allowed = S.regex_allowed;
  14646. var i = find("*/", true);
  14647. var text = S.text.substring(S.pos, i);
  14648. var a = text.split("\n"), n = a.length;
  14649. // update stream position
  14650. S.pos = i + 2;
  14651. S.line += n - 1;
  14652. if (n > 1) S.col = a[n - 1].length;
  14653. else S.col += a[n - 1].length;
  14654. S.col += 2;
  14655. var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  14656. S.comments_before.push(token("comment2", text, true));
  14657. S.regex_allowed = regex_allowed;
  14658. S.newline_before = nlb;
  14659. return next_token();
  14660. });
  14661. function read_name() {
  14662. var backslash = false, name = "", ch, escaped = false, hex;
  14663. while ((ch = peek()) != null) {
  14664. if (!backslash) {
  14665. if (ch == "\\") escaped = backslash = true, next();
  14666. else if (is_identifier_char(ch)) name += next();
  14667. else break;
  14668. }
  14669. else {
  14670. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  14671. ch = read_escaped_char();
  14672. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  14673. name += ch;
  14674. backslash = false;
  14675. }
  14676. }
  14677. if (KEYWORDS(name) && escaped) {
  14678. hex = name.charCodeAt(0).toString(16).toUpperCase();
  14679. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  14680. }
  14681. return name;
  14682. };
  14683. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
  14684. var prev_backslash = false, ch, in_class = false;
  14685. while ((ch = next(true))) if (prev_backslash) {
  14686. regexp += "\\" + ch;
  14687. prev_backslash = false;
  14688. } else if (ch == "[") {
  14689. in_class = true;
  14690. regexp += ch;
  14691. } else if (ch == "]" && in_class) {
  14692. in_class = false;
  14693. regexp += ch;
  14694. } else if (ch == "/" && !in_class) {
  14695. break;
  14696. } else if (ch == "\\") {
  14697. prev_backslash = true;
  14698. } else {
  14699. regexp += ch;
  14700. }
  14701. var mods = read_name();
  14702. return token("regexp", new RegExp(regexp, mods));
  14703. });
  14704. function read_operator(prefix) {
  14705. function grow(op) {
  14706. if (!peek()) return op;
  14707. var bigger = op + peek();
  14708. if (OPERATORS(bigger)) {
  14709. next();
  14710. return grow(bigger);
  14711. } else {
  14712. return op;
  14713. }
  14714. };
  14715. return token("operator", grow(prefix || next()));
  14716. };
  14717. function handle_slash() {
  14718. next();
  14719. switch (peek()) {
  14720. case "/":
  14721. next();
  14722. return skip_line_comment("comment1");
  14723. case "*":
  14724. next();
  14725. return skip_multiline_comment();
  14726. }
  14727. return S.regex_allowed ? read_regexp("") : read_operator("/");
  14728. };
  14729. function handle_dot() {
  14730. next();
  14731. return is_digit(peek().charCodeAt(0))
  14732. ? read_num(".")
  14733. : token("punc", ".");
  14734. };
  14735. function read_word() {
  14736. var word = read_name();
  14737. if (prev_was_dot) return token("name", word);
  14738. return KEYWORDS_ATOM(word) ? token("atom", word)
  14739. : !KEYWORDS(word) ? token("name", word)
  14740. : OPERATORS(word) ? token("operator", word)
  14741. : token("keyword", word);
  14742. };
  14743. function with_eof_error(eof_error, cont) {
  14744. return function(x) {
  14745. try {
  14746. return cont(x);
  14747. } catch(ex) {
  14748. if (ex === EX_EOF) parse_error(eof_error);
  14749. else throw ex;
  14750. }
  14751. };
  14752. };
  14753. function next_token(force_regexp) {
  14754. if (force_regexp != null)
  14755. return read_regexp(force_regexp);
  14756. skip_whitespace();
  14757. start_token();
  14758. if (html5_comments) {
  14759. if (looking_at("<!--")) {
  14760. forward(4);
  14761. return skip_line_comment("comment3");
  14762. }
  14763. if (looking_at("-->") && S.newline_before) {
  14764. forward(3);
  14765. return skip_line_comment("comment4");
  14766. }
  14767. }
  14768. var ch = peek();
  14769. if (!ch) return token("eof");
  14770. var code = ch.charCodeAt(0);
  14771. switch (code) {
  14772. case 34: case 39: return read_string();
  14773. case 46: return handle_dot();
  14774. case 47: return handle_slash();
  14775. }
  14776. if (is_digit(code)) return read_num();
  14777. if (PUNC_CHARS(ch)) return token("punc", next());
  14778. if (OPERATOR_CHARS(ch)) return read_operator();
  14779. if (code == 92 || is_identifier_start(code)) return read_word();
  14780. parse_error("Unexpected character '" + ch + "'");
  14781. };
  14782. next_token.context = function(nc) {
  14783. if (nc) S = nc;
  14784. return S;
  14785. };
  14786. return next_token;
  14787. };
  14788. /* -----[ Parser (constants) ]----- */
  14789. var UNARY_PREFIX = makePredicate([
  14790. "typeof",
  14791. "void",
  14792. "delete",
  14793. "--",
  14794. "++",
  14795. "!",
  14796. "~",
  14797. "-",
  14798. "+"
  14799. ]);
  14800. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  14801. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  14802. var PRECEDENCE = (function(a, ret){
  14803. for (var i = 0; i < a.length; ++i) {
  14804. var b = a[i];
  14805. for (var j = 0; j < b.length; ++j) {
  14806. ret[b[j]] = i + 1;
  14807. }
  14808. }
  14809. return ret;
  14810. })(
  14811. [
  14812. ["||"],
  14813. ["&&"],
  14814. ["|"],
  14815. ["^"],
  14816. ["&"],
  14817. ["==", "===", "!=", "!=="],
  14818. ["<", ">", "<=", ">=", "in", "instanceof"],
  14819. [">>", "<<", ">>>"],
  14820. ["+", "-"],
  14821. ["*", "/", "%"]
  14822. ],
  14823. {}
  14824. );
  14825. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  14826. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  14827. /* -----[ Parser ]----- */
  14828. function parse($TEXT, options) {
  14829. options = defaults(options, {
  14830. strict : false,
  14831. filename : null,
  14832. toplevel : null,
  14833. expression : false,
  14834. html5_comments : true,
  14835. });
  14836. var S = {
  14837. input : (typeof $TEXT == "string"
  14838. ? tokenizer($TEXT, options.filename,
  14839. options.html5_comments)
  14840. : $TEXT),
  14841. token : null,
  14842. prev : null,
  14843. peeked : null,
  14844. in_function : 0,
  14845. in_directives : true,
  14846. in_loop : 0,
  14847. labels : []
  14848. };
  14849. S.token = next();
  14850. function is(type, value) {
  14851. return is_token(S.token, type, value);
  14852. };
  14853. function peek() { return S.peeked || (S.peeked = S.input()); };
  14854. function next() {
  14855. S.prev = S.token;
  14856. if (S.peeked) {
  14857. S.token = S.peeked;
  14858. S.peeked = null;
  14859. } else {
  14860. S.token = S.input();
  14861. }
  14862. S.in_directives = S.in_directives && (
  14863. S.token.type == "string" || is("punc", ";")
  14864. );
  14865. return S.token;
  14866. };
  14867. function prev() {
  14868. return S.prev;
  14869. };
  14870. function croak(msg, line, col, pos) {
  14871. var ctx = S.input.context();
  14872. js_error(msg,
  14873. ctx.filename,
  14874. line != null ? line : ctx.tokline,
  14875. col != null ? col : ctx.tokcol,
  14876. pos != null ? pos : ctx.tokpos);
  14877. };
  14878. function token_error(token, msg) {
  14879. croak(msg, token.line, token.col);
  14880. };
  14881. function unexpected(token) {
  14882. if (token == null)
  14883. token = S.token;
  14884. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  14885. };
  14886. function expect_token(type, val) {
  14887. if (is(type, val)) {
  14888. return next();
  14889. }
  14890. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  14891. };
  14892. function expect(punc) { return expect_token("punc", punc); };
  14893. function can_insert_semicolon() {
  14894. return !options.strict && (
  14895. S.token.nlb || is("eof") || is("punc", "}")
  14896. );
  14897. };
  14898. function semicolon() {
  14899. if (is("punc", ";")) next();
  14900. else if (!can_insert_semicolon()) unexpected();
  14901. };
  14902. function parenthesised() {
  14903. expect("(");
  14904. var exp = expression(true);
  14905. expect(")");
  14906. return exp;
  14907. };
  14908. function embed_tokens(parser) {
  14909. return function() {
  14910. var start = S.token;
  14911. var expr = parser();
  14912. var end = prev();
  14913. expr.start = start;
  14914. expr.end = end;
  14915. return expr;
  14916. };
  14917. };
  14918. function handle_regexp() {
  14919. if (is("operator", "/") || is("operator", "/=")) {
  14920. S.peeked = null;
  14921. S.token = S.input(S.token.value.substr(1)); // force regexp
  14922. }
  14923. };
  14924. var statement = embed_tokens(function() {
  14925. var tmp;
  14926. handle_regexp();
  14927. switch (S.token.type) {
  14928. case "string":
  14929. var dir = S.in_directives, stat = simple_statement();
  14930. // XXXv2: decide how to fix directives
  14931. if (dir && stat.body instanceof AST_String && !is("punc", ","))
  14932. return new AST_Directive({ value: stat.body.value });
  14933. return stat;
  14934. case "num":
  14935. case "regexp":
  14936. case "operator":
  14937. case "atom":
  14938. return simple_statement();
  14939. case "name":
  14940. return is_token(peek(), "punc", ":")
  14941. ? labeled_statement()
  14942. : simple_statement();
  14943. case "punc":
  14944. switch (S.token.value) {
  14945. case "{":
  14946. return new AST_BlockStatement({
  14947. start : S.token,
  14948. body : block_(),
  14949. end : prev()
  14950. });
  14951. case "[":
  14952. case "(":
  14953. return simple_statement();
  14954. case ";":
  14955. next();
  14956. return new AST_EmptyStatement();
  14957. default:
  14958. unexpected();
  14959. }
  14960. case "keyword":
  14961. switch (tmp = S.token.value, next(), tmp) {
  14962. case "break":
  14963. return break_cont(AST_Break);
  14964. case "continue":
  14965. return break_cont(AST_Continue);
  14966. case "debugger":
  14967. semicolon();
  14968. return new AST_Debugger();
  14969. case "do":
  14970. return new AST_Do({
  14971. body : in_loop(statement),
  14972. condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
  14973. });
  14974. case "while":
  14975. return new AST_While({
  14976. condition : parenthesised(),
  14977. body : in_loop(statement)
  14978. });
  14979. case "for":
  14980. return for_();
  14981. case "function":
  14982. return function_(AST_Defun);
  14983. case "if":
  14984. return if_();
  14985. case "return":
  14986. if (S.in_function == 0)
  14987. croak("'return' outside of function");
  14988. return new AST_Return({
  14989. value: ( is("punc", ";")
  14990. ? (next(), null)
  14991. : can_insert_semicolon()
  14992. ? null
  14993. : (tmp = expression(true), semicolon(), tmp) )
  14994. });
  14995. case "switch":
  14996. return new AST_Switch({
  14997. expression : parenthesised(),
  14998. body : in_loop(switch_body_)
  14999. });
  15000. case "throw":
  15001. if (S.token.nlb)
  15002. croak("Illegal newline after 'throw'");
  15003. return new AST_Throw({
  15004. value: (tmp = expression(true), semicolon(), tmp)
  15005. });
  15006. case "try":
  15007. return try_();
  15008. case "var":
  15009. return tmp = var_(), semicolon(), tmp;
  15010. case "const":
  15011. return tmp = const_(), semicolon(), tmp;
  15012. case "with":
  15013. return new AST_With({
  15014. expression : parenthesised(),
  15015. body : statement()
  15016. });
  15017. default:
  15018. unexpected();
  15019. }
  15020. }
  15021. });
  15022. function labeled_statement() {
  15023. var label = as_symbol(AST_Label);
  15024. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  15025. // ECMA-262, 12.12: An ECMAScript program is considered
  15026. // syntactically incorrect if it contains a
  15027. // LabelledStatement that is enclosed by a
  15028. // LabelledStatement with the same Identifier as label.
  15029. croak("Label " + label.name + " defined twice");
  15030. }
  15031. expect(":");
  15032. S.labels.push(label);
  15033. var stat = statement();
  15034. S.labels.pop();
  15035. if (!(stat instanceof AST_IterationStatement)) {
  15036. // check for `continue` that refers to this label.
  15037. // those should be reported as syntax errors.
  15038. // https://github.com/mishoo/UglifyJS2/issues/287
  15039. label.references.forEach(function(ref){
  15040. if (ref instanceof AST_Continue) {
  15041. ref = ref.label.start;
  15042. croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
  15043. ref.line, ref.col, ref.pos);
  15044. }
  15045. });
  15046. }
  15047. return new AST_LabeledStatement({ body: stat, label: label });
  15048. };
  15049. function simple_statement(tmp) {
  15050. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  15051. };
  15052. function break_cont(type) {
  15053. var label = null, ldef;
  15054. if (!can_insert_semicolon()) {
  15055. label = as_symbol(AST_LabelRef, true);
  15056. }
  15057. if (label != null) {
  15058. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  15059. if (!ldef)
  15060. croak("Undefined label " + label.name);
  15061. label.thedef = ldef;
  15062. }
  15063. else if (S.in_loop == 0)
  15064. croak(type.TYPE + " not inside a loop or switch");
  15065. semicolon();
  15066. var stat = new type({ label: label });
  15067. if (ldef) ldef.references.push(stat);
  15068. return stat;
  15069. };
  15070. function for_() {
  15071. expect("(");
  15072. var init = null;
  15073. if (!is("punc", ";")) {
  15074. init = is("keyword", "var")
  15075. ? (next(), var_(true))
  15076. : expression(true, true);
  15077. if (is("operator", "in")) {
  15078. if (init instanceof AST_Var && init.definitions.length > 1)
  15079. croak("Only one variable declaration allowed in for..in loop");
  15080. next();
  15081. return for_in(init);
  15082. }
  15083. }
  15084. return regular_for(init);
  15085. };
  15086. function regular_for(init) {
  15087. expect(";");
  15088. var test = is("punc", ";") ? null : expression(true);
  15089. expect(";");
  15090. var step = is("punc", ")") ? null : expression(true);
  15091. expect(")");
  15092. return new AST_For({
  15093. init : init,
  15094. condition : test,
  15095. step : step,
  15096. body : in_loop(statement)
  15097. });
  15098. };
  15099. function for_in(init) {
  15100. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  15101. var obj = expression(true);
  15102. expect(")");
  15103. return new AST_ForIn({
  15104. init : init,
  15105. name : lhs,
  15106. object : obj,
  15107. body : in_loop(statement)
  15108. });
  15109. };
  15110. var function_ = function(ctor) {
  15111. var in_statement = ctor === AST_Defun;
  15112. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  15113. if (in_statement && !name)
  15114. unexpected();
  15115. expect("(");
  15116. return new ctor({
  15117. name: name,
  15118. argnames: (function(first, a){
  15119. while (!is("punc", ")")) {
  15120. if (first) first = false; else expect(",");
  15121. a.push(as_symbol(AST_SymbolFunarg));
  15122. }
  15123. next();
  15124. return a;
  15125. })(true, []),
  15126. body: (function(loop, labels){
  15127. ++S.in_function;
  15128. S.in_directives = true;
  15129. S.in_loop = 0;
  15130. S.labels = [];
  15131. var a = block_();
  15132. --S.in_function;
  15133. S.in_loop = loop;
  15134. S.labels = labels;
  15135. return a;
  15136. })(S.in_loop, S.labels)
  15137. });
  15138. };
  15139. function if_() {
  15140. var cond = parenthesised(), body = statement(), belse = null;
  15141. if (is("keyword", "else")) {
  15142. next();
  15143. belse = statement();
  15144. }
  15145. return new AST_If({
  15146. condition : cond,
  15147. body : body,
  15148. alternative : belse
  15149. });
  15150. };
  15151. function block_() {
  15152. expect("{");
  15153. var a = [];
  15154. while (!is("punc", "}")) {
  15155. if (is("eof")) unexpected();
  15156. a.push(statement());
  15157. }
  15158. next();
  15159. return a;
  15160. };
  15161. function switch_body_() {
  15162. expect("{");
  15163. var a = [], cur = null, branch = null, tmp;
  15164. while (!is("punc", "}")) {
  15165. if (is("eof")) unexpected();
  15166. if (is("keyword", "case")) {
  15167. if (branch) branch.end = prev();
  15168. cur = [];
  15169. branch = new AST_Case({
  15170. start : (tmp = S.token, next(), tmp),
  15171. expression : expression(true),
  15172. body : cur
  15173. });
  15174. a.push(branch);
  15175. expect(":");
  15176. }
  15177. else if (is("keyword", "default")) {
  15178. if (branch) branch.end = prev();
  15179. cur = [];
  15180. branch = new AST_Default({
  15181. start : (tmp = S.token, next(), expect(":"), tmp),
  15182. body : cur
  15183. });
  15184. a.push(branch);
  15185. }
  15186. else {
  15187. if (!cur) unexpected();
  15188. cur.push(statement());
  15189. }
  15190. }
  15191. if (branch) branch.end = prev();
  15192. next();
  15193. return a;
  15194. };
  15195. function try_() {
  15196. var body = block_(), bcatch = null, bfinally = null;
  15197. if (is("keyword", "catch")) {
  15198. var start = S.token;
  15199. next();
  15200. expect("(");
  15201. var name = as_symbol(AST_SymbolCatch);
  15202. expect(")");
  15203. bcatch = new AST_Catch({
  15204. start : start,
  15205. argname : name,
  15206. body : block_(),
  15207. end : prev()
  15208. });
  15209. }
  15210. if (is("keyword", "finally")) {
  15211. var start = S.token;
  15212. next();
  15213. bfinally = new AST_Finally({
  15214. start : start,
  15215. body : block_(),
  15216. end : prev()
  15217. });
  15218. }
  15219. if (!bcatch && !bfinally)
  15220. croak("Missing catch/finally blocks");
  15221. return new AST_Try({
  15222. body : body,
  15223. bcatch : bcatch,
  15224. bfinally : bfinally
  15225. });
  15226. };
  15227. function vardefs(no_in, in_const) {
  15228. var a = [];
  15229. for (;;) {
  15230. a.push(new AST_VarDef({
  15231. start : S.token,
  15232. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  15233. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  15234. end : prev()
  15235. }));
  15236. if (!is("punc", ","))
  15237. break;
  15238. next();
  15239. }
  15240. return a;
  15241. };
  15242. var var_ = function(no_in) {
  15243. return new AST_Var({
  15244. start : prev(),
  15245. definitions : vardefs(no_in, false),
  15246. end : prev()
  15247. });
  15248. };
  15249. var const_ = function() {
  15250. return new AST_Const({
  15251. start : prev(),
  15252. definitions : vardefs(false, true),
  15253. end : prev()
  15254. });
  15255. };
  15256. var new_ = function() {
  15257. var start = S.token;
  15258. expect_token("operator", "new");
  15259. var newexp = expr_atom(false), args;
  15260. if (is("punc", "(")) {
  15261. next();
  15262. args = expr_list(")");
  15263. } else {
  15264. args = [];
  15265. }
  15266. return subscripts(new AST_New({
  15267. start : start,
  15268. expression : newexp,
  15269. args : args,
  15270. end : prev()
  15271. }), true);
  15272. };
  15273. function as_atom_node() {
  15274. var tok = S.token, ret;
  15275. switch (tok.type) {
  15276. case "name":
  15277. case "keyword":
  15278. ret = _make_symbol(AST_SymbolRef);
  15279. break;
  15280. case "num":
  15281. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  15282. break;
  15283. case "string":
  15284. ret = new AST_String({ start: tok, end: tok, value: tok.value });
  15285. break;
  15286. case "regexp":
  15287. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  15288. break;
  15289. case "atom":
  15290. switch (tok.value) {
  15291. case "false":
  15292. ret = new AST_False({ start: tok, end: tok });
  15293. break;
  15294. case "true":
  15295. ret = new AST_True({ start: tok, end: tok });
  15296. break;
  15297. case "null":
  15298. ret = new AST_Null({ start: tok, end: tok });
  15299. break;
  15300. }
  15301. break;
  15302. }
  15303. next();
  15304. return ret;
  15305. };
  15306. var expr_atom = function(allow_calls) {
  15307. if (is("operator", "new")) {
  15308. return new_();
  15309. }
  15310. var start = S.token;
  15311. if (is("punc")) {
  15312. switch (start.value) {
  15313. case "(":
  15314. next();
  15315. var ex = expression(true);
  15316. ex.start = start;
  15317. ex.end = S.token;
  15318. expect(")");
  15319. return subscripts(ex, allow_calls);
  15320. case "[":
  15321. return subscripts(array_(), allow_calls);
  15322. case "{":
  15323. return subscripts(object_(), allow_calls);
  15324. }
  15325. unexpected();
  15326. }
  15327. if (is("keyword", "function")) {
  15328. next();
  15329. var func = function_(AST_Function);
  15330. func.start = start;
  15331. func.end = prev();
  15332. return subscripts(func, allow_calls);
  15333. }
  15334. if (ATOMIC_START_TOKEN[S.token.type]) {
  15335. return subscripts(as_atom_node(), allow_calls);
  15336. }
  15337. unexpected();
  15338. };
  15339. function expr_list(closing, allow_trailing_comma, allow_empty) {
  15340. var first = true, a = [];
  15341. while (!is("punc", closing)) {
  15342. if (first) first = false; else expect(",");
  15343. if (allow_trailing_comma && is("punc", closing)) break;
  15344. if (is("punc", ",") && allow_empty) {
  15345. a.push(new AST_Hole({ start: S.token, end: S.token }));
  15346. } else {
  15347. a.push(expression(false));
  15348. }
  15349. }
  15350. next();
  15351. return a;
  15352. };
  15353. var array_ = embed_tokens(function() {
  15354. expect("[");
  15355. return new AST_Array({
  15356. elements: expr_list("]", !options.strict, true)
  15357. });
  15358. });
  15359. var object_ = embed_tokens(function() {
  15360. expect("{");
  15361. var first = true, a = [];
  15362. while (!is("punc", "}")) {
  15363. if (first) first = false; else expect(",");
  15364. if (!options.strict && is("punc", "}"))
  15365. // allow trailing comma
  15366. break;
  15367. var start = S.token;
  15368. var type = start.type;
  15369. var name = as_property_name();
  15370. if (type == "name" && !is("punc", ":")) {
  15371. if (name == "get") {
  15372. a.push(new AST_ObjectGetter({
  15373. start : start,
  15374. key : as_atom_node(),
  15375. value : function_(AST_Accessor),
  15376. end : prev()
  15377. }));
  15378. continue;
  15379. }
  15380. if (name == "set") {
  15381. a.push(new AST_ObjectSetter({
  15382. start : start,
  15383. key : as_atom_node(),
  15384. value : function_(AST_Accessor),
  15385. end : prev()
  15386. }));
  15387. continue;
  15388. }
  15389. }
  15390. expect(":");
  15391. a.push(new AST_ObjectKeyVal({
  15392. start : start,
  15393. key : name,
  15394. value : expression(false),
  15395. end : prev()
  15396. }));
  15397. }
  15398. next();
  15399. return new AST_Object({ properties: a });
  15400. });
  15401. function as_property_name() {
  15402. var tmp = S.token;
  15403. next();
  15404. switch (tmp.type) {
  15405. case "num":
  15406. case "string":
  15407. case "name":
  15408. case "operator":
  15409. case "keyword":
  15410. case "atom":
  15411. return tmp.value;
  15412. default:
  15413. unexpected();
  15414. }
  15415. };
  15416. function as_name() {
  15417. var tmp = S.token;
  15418. next();
  15419. switch (tmp.type) {
  15420. case "name":
  15421. case "operator":
  15422. case "keyword":
  15423. case "atom":
  15424. return tmp.value;
  15425. default:
  15426. unexpected();
  15427. }
  15428. };
  15429. function _make_symbol(type) {
  15430. var name = S.token.value;
  15431. return new (name == "this" ? AST_This : type)({
  15432. name : String(name),
  15433. start : S.token,
  15434. end : S.token
  15435. });
  15436. };
  15437. function as_symbol(type, noerror) {
  15438. if (!is("name")) {
  15439. if (!noerror) croak("Name expected");
  15440. return null;
  15441. }
  15442. var sym = _make_symbol(type);
  15443. next();
  15444. return sym;
  15445. };
  15446. var subscripts = function(expr, allow_calls) {
  15447. var start = expr.start;
  15448. if (is("punc", ".")) {
  15449. next();
  15450. return subscripts(new AST_Dot({
  15451. start : start,
  15452. expression : expr,
  15453. property : as_name(),
  15454. end : prev()
  15455. }), allow_calls);
  15456. }
  15457. if (is("punc", "[")) {
  15458. next();
  15459. var prop = expression(true);
  15460. expect("]");
  15461. return subscripts(new AST_Sub({
  15462. start : start,
  15463. expression : expr,
  15464. property : prop,
  15465. end : prev()
  15466. }), allow_calls);
  15467. }
  15468. if (allow_calls && is("punc", "(")) {
  15469. next();
  15470. return subscripts(new AST_Call({
  15471. start : start,
  15472. expression : expr,
  15473. args : expr_list(")"),
  15474. end : prev()
  15475. }), true);
  15476. }
  15477. return expr;
  15478. };
  15479. var maybe_unary = function(allow_calls) {
  15480. var start = S.token;
  15481. if (is("operator") && UNARY_PREFIX(start.value)) {
  15482. next();
  15483. handle_regexp();
  15484. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  15485. ex.start = start;
  15486. ex.end = prev();
  15487. return ex;
  15488. }
  15489. var val = expr_atom(allow_calls);
  15490. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  15491. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  15492. val.start = start;
  15493. val.end = S.token;
  15494. next();
  15495. }
  15496. return val;
  15497. };
  15498. function make_unary(ctor, op, expr) {
  15499. if ((op == "++" || op == "--") && !is_assignable(expr))
  15500. croak("Invalid use of " + op + " operator");
  15501. return new ctor({ operator: op, expression: expr });
  15502. };
  15503. var expr_op = function(left, min_prec, no_in) {
  15504. var op = is("operator") ? S.token.value : null;
  15505. if (op == "in" && no_in) op = null;
  15506. var prec = op != null ? PRECEDENCE[op] : null;
  15507. if (prec != null && prec > min_prec) {
  15508. next();
  15509. var right = expr_op(maybe_unary(true), prec, no_in);
  15510. return expr_op(new AST_Binary({
  15511. start : left.start,
  15512. left : left,
  15513. operator : op,
  15514. right : right,
  15515. end : right.end
  15516. }), min_prec, no_in);
  15517. }
  15518. return left;
  15519. };
  15520. function expr_ops(no_in) {
  15521. return expr_op(maybe_unary(true), 0, no_in);
  15522. };
  15523. var maybe_conditional = function(no_in) {
  15524. var start = S.token;
  15525. var expr = expr_ops(no_in);
  15526. if (is("operator", "?")) {
  15527. next();
  15528. var yes = expression(false);
  15529. expect(":");
  15530. return new AST_Conditional({
  15531. start : start,
  15532. condition : expr,
  15533. consequent : yes,
  15534. alternative : expression(false, no_in),
  15535. end : prev()
  15536. });
  15537. }
  15538. return expr;
  15539. };
  15540. function is_assignable(expr) {
  15541. if (!options.strict) return true;
  15542. if (expr instanceof AST_This) return false;
  15543. return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
  15544. };
  15545. var maybe_assign = function(no_in) {
  15546. var start = S.token;
  15547. var left = maybe_conditional(no_in), val = S.token.value;
  15548. if (is("operator") && ASSIGNMENT(val)) {
  15549. if (is_assignable(left)) {
  15550. next();
  15551. return new AST_Assign({
  15552. start : start,
  15553. left : left,
  15554. operator : val,
  15555. right : maybe_assign(no_in),
  15556. end : prev()
  15557. });
  15558. }
  15559. croak("Invalid assignment");
  15560. }
  15561. return left;
  15562. };
  15563. var expression = function(commas, no_in) {
  15564. var start = S.token;
  15565. var expr = maybe_assign(no_in);
  15566. if (commas && is("punc", ",")) {
  15567. next();
  15568. return new AST_Seq({
  15569. start : start,
  15570. car : expr,
  15571. cdr : expression(true, no_in),
  15572. end : peek()
  15573. });
  15574. }
  15575. return expr;
  15576. };
  15577. function in_loop(cont) {
  15578. ++S.in_loop;
  15579. var ret = cont();
  15580. --S.in_loop;
  15581. return ret;
  15582. };
  15583. if (options.expression) {
  15584. return expression(true);
  15585. }
  15586. return (function(){
  15587. var start = S.token;
  15588. var body = [];
  15589. while (!is("eof"))
  15590. body.push(statement());
  15591. var end = prev();
  15592. var toplevel = options.toplevel;
  15593. if (toplevel) {
  15594. toplevel.body = toplevel.body.concat(body);
  15595. toplevel.end = end;
  15596. } else {
  15597. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  15598. }
  15599. return toplevel;
  15600. })();
  15601. };
  15602. /***********************************************************************
  15603. A JavaScript tokenizer / parser / beautifier / compressor.
  15604. https://github.com/mishoo/UglifyJS2
  15605. -------------------------------- (C) ---------------------------------
  15606. Author: Mihai Bazon
  15607. <mihai.bazon@gmail.com>
  15608. http://mihai.bazon.net/blog
  15609. Distributed under the BSD license:
  15610. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  15611. Redistribution and use in source and binary forms, with or without
  15612. modification, are permitted provided that the following conditions
  15613. are met:
  15614. * Redistributions of source code must retain the above
  15615. copyright notice, this list of conditions and the following
  15616. disclaimer.
  15617. * Redistributions in binary form must reproduce the above
  15618. copyright notice, this list of conditions and the following
  15619. disclaimer in the documentation and/or other materials
  15620. provided with the distribution.
  15621. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  15622. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15623. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  15624. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  15625. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  15626. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  15627. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  15628. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15629. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  15630. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  15631. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  15632. SUCH DAMAGE.
  15633. ***********************************************************************/
  15634. "use strict";
  15635. // Tree transformer helpers.
  15636. function TreeTransformer(before, after) {
  15637. TreeWalker.call(this);
  15638. this.before = before;
  15639. this.after = after;
  15640. }
  15641. TreeTransformer.prototype = new TreeWalker;
  15642. (function(undefined){
  15643. function _(node, descend) {
  15644. node.DEFMETHOD("transform", function(tw, in_list){
  15645. var x, y;
  15646. tw.push(this);
  15647. if (tw.before) x = tw.before(this, descend, in_list);
  15648. if (x === undefined) {
  15649. if (!tw.after) {
  15650. x = this;
  15651. descend(x, tw);
  15652. } else {
  15653. tw.stack[tw.stack.length - 1] = x = this.clone();
  15654. descend(x, tw);
  15655. y = tw.after(x, in_list);
  15656. if (y !== undefined) x = y;
  15657. }
  15658. }
  15659. tw.pop();
  15660. return x;
  15661. });
  15662. };
  15663. function do_list(list, tw) {
  15664. return MAP(list, function(node){
  15665. return node.transform(tw, true);
  15666. });
  15667. };
  15668. _(AST_Node, noop);
  15669. _(AST_LabeledStatement, function(self, tw){
  15670. self.label = self.label.transform(tw);
  15671. self.body = self.body.transform(tw);
  15672. });
  15673. _(AST_SimpleStatement, function(self, tw){
  15674. self.body = self.body.transform(tw);
  15675. });
  15676. _(AST_Block, function(self, tw){
  15677. self.body = do_list(self.body, tw);
  15678. });
  15679. _(AST_DWLoop, function(self, tw){
  15680. self.condition = self.condition.transform(tw);
  15681. self.body = self.body.transform(tw);
  15682. });
  15683. _(AST_For, function(self, tw){
  15684. if (self.init) self.init = self.init.transform(tw);
  15685. if (self.condition) self.condition = self.condition.transform(tw);
  15686. if (self.step) self.step = self.step.transform(tw);
  15687. self.body = self.body.transform(tw);
  15688. });
  15689. _(AST_ForIn, function(self, tw){
  15690. self.init = self.init.transform(tw);
  15691. self.object = self.object.transform(tw);
  15692. self.body = self.body.transform(tw);
  15693. });
  15694. _(AST_With, function(self, tw){
  15695. self.expression = self.expression.transform(tw);
  15696. self.body = self.body.transform(tw);
  15697. });
  15698. _(AST_Exit, function(self, tw){
  15699. if (self.value) self.value = self.value.transform(tw);
  15700. });
  15701. _(AST_LoopControl, function(self, tw){
  15702. if (self.label) self.label = self.label.transform(tw);
  15703. });
  15704. _(AST_If, function(self, tw){
  15705. self.condition = self.condition.transform(tw);
  15706. self.body = self.body.transform(tw);
  15707. if (self.alternative) self.alternative = self.alternative.transform(tw);
  15708. });
  15709. _(AST_Switch, function(self, tw){
  15710. self.expression = self.expression.transform(tw);
  15711. self.body = do_list(self.body, tw);
  15712. });
  15713. _(AST_Case, function(self, tw){
  15714. self.expression = self.expression.transform(tw);
  15715. self.body = do_list(self.body, tw);
  15716. });
  15717. _(AST_Try, function(self, tw){
  15718. self.body = do_list(self.body, tw);
  15719. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  15720. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  15721. });
  15722. _(AST_Catch, function(self, tw){
  15723. self.argname = self.argname.transform(tw);
  15724. self.body = do_list(self.body, tw);
  15725. });
  15726. _(AST_Definitions, function(self, tw){
  15727. self.definitions = do_list(self.definitions, tw);
  15728. });
  15729. _(AST_VarDef, function(self, tw){
  15730. self.name = self.name.transform(tw);
  15731. if (self.value) self.value = self.value.transform(tw);
  15732. });
  15733. _(AST_Lambda, function(self, tw){
  15734. if (self.name) self.name = self.name.transform(tw);
  15735. self.argnames = do_list(self.argnames, tw);
  15736. self.body = do_list(self.body, tw);
  15737. });
  15738. _(AST_Call, function(self, tw){
  15739. self.expression = self.expression.transform(tw);
  15740. self.args = do_list(self.args, tw);
  15741. });
  15742. _(AST_Seq, function(self, tw){
  15743. self.car = self.car.transform(tw);
  15744. self.cdr = self.cdr.transform(tw);
  15745. });
  15746. _(AST_Dot, function(self, tw){
  15747. self.expression = self.expression.transform(tw);
  15748. });
  15749. _(AST_Sub, function(self, tw){
  15750. self.expression = self.expression.transform(tw);
  15751. self.property = self.property.transform(tw);
  15752. });
  15753. _(AST_Unary, function(self, tw){
  15754. self.expression = self.expression.transform(tw);
  15755. });
  15756. _(AST_Binary, function(self, tw){
  15757. self.left = self.left.transform(tw);
  15758. self.right = self.right.transform(tw);
  15759. });
  15760. _(AST_Conditional, function(self, tw){
  15761. self.condition = self.condition.transform(tw);
  15762. self.consequent = self.consequent.transform(tw);
  15763. self.alternative = self.alternative.transform(tw);
  15764. });
  15765. _(AST_Array, function(self, tw){
  15766. self.elements = do_list(self.elements, tw);
  15767. });
  15768. _(AST_Object, function(self, tw){
  15769. self.properties = do_list(self.properties, tw);
  15770. });
  15771. _(AST_ObjectProperty, function(self, tw){
  15772. self.value = self.value.transform(tw);
  15773. });
  15774. })();
  15775. /***********************************************************************
  15776. A JavaScript tokenizer / parser / beautifier / compressor.
  15777. https://github.com/mishoo/UglifyJS2
  15778. -------------------------------- (C) ---------------------------------
  15779. Author: Mihai Bazon
  15780. <mihai.bazon@gmail.com>
  15781. http://mihai.bazon.net/blog
  15782. Distributed under the BSD license:
  15783. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  15784. Redistribution and use in source and binary forms, with or without
  15785. modification, are permitted provided that the following conditions
  15786. are met:
  15787. * Redistributions of source code must retain the above
  15788. copyright notice, this list of conditions and the following
  15789. disclaimer.
  15790. * Redistributions in binary form must reproduce the above
  15791. copyright notice, this list of conditions and the following
  15792. disclaimer in the documentation and/or other materials
  15793. provided with the distribution.
  15794. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  15795. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15796. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  15797. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  15798. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  15799. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  15800. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  15801. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15802. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  15803. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  15804. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  15805. SUCH DAMAGE.
  15806. ***********************************************************************/
  15807. "use strict";
  15808. function SymbolDef(scope, index, orig) {
  15809. this.name = orig.name;
  15810. this.orig = [ orig ];
  15811. this.scope = scope;
  15812. this.references = [];
  15813. this.global = false;
  15814. this.mangled_name = null;
  15815. this.undeclared = false;
  15816. this.constant = false;
  15817. this.index = index;
  15818. };
  15819. SymbolDef.prototype = {
  15820. unmangleable: function(options) {
  15821. return (this.global && !(options && options.toplevel))
  15822. || this.undeclared
  15823. || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));
  15824. },
  15825. mangle: function(options) {
  15826. if (!this.mangled_name && !this.unmangleable(options)) {
  15827. var s = this.scope;
  15828. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  15829. s = s.parent_scope;
  15830. this.mangled_name = s.next_mangled(options, this);
  15831. }
  15832. }
  15833. };
  15834. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  15835. options = defaults(options, {
  15836. screw_ie8: false
  15837. });
  15838. // pass 1: setup scope chaining and handle definitions
  15839. var self = this;
  15840. var scope = self.parent_scope = null;
  15841. var defun = null;
  15842. var nesting = 0;
  15843. var tw = new TreeWalker(function(node, descend){
  15844. if (options.screw_ie8 && node instanceof AST_Catch) {
  15845. var save_scope = scope;
  15846. scope = new AST_Scope(node);
  15847. scope.init_scope_vars(nesting);
  15848. scope.parent_scope = save_scope;
  15849. descend();
  15850. scope = save_scope;
  15851. return true;
  15852. }
  15853. if (node instanceof AST_Scope) {
  15854. node.init_scope_vars(nesting);
  15855. var save_scope = node.parent_scope = scope;
  15856. var save_defun = defun;
  15857. defun = scope = node;
  15858. ++nesting; descend(); --nesting;
  15859. scope = save_scope;
  15860. defun = save_defun;
  15861. return true; // don't descend again in TreeWalker
  15862. }
  15863. if (node instanceof AST_Directive) {
  15864. node.scope = scope;
  15865. push_uniq(scope.directives, node.value);
  15866. return true;
  15867. }
  15868. if (node instanceof AST_With) {
  15869. for (var s = scope; s; s = s.parent_scope)
  15870. s.uses_with = true;
  15871. return;
  15872. }
  15873. if (node instanceof AST_Symbol) {
  15874. node.scope = scope;
  15875. }
  15876. if (node instanceof AST_SymbolLambda) {
  15877. defun.def_function(node);
  15878. }
  15879. else if (node instanceof AST_SymbolDefun) {
  15880. // Careful here, the scope where this should be defined is
  15881. // the parent scope. The reason is that we enter a new
  15882. // scope when we encounter the AST_Defun node (which is
  15883. // instanceof AST_Scope) but we get to the symbol a bit
  15884. // later.
  15885. (node.scope = defun.parent_scope).def_function(node);
  15886. }
  15887. else if (node instanceof AST_SymbolVar
  15888. || node instanceof AST_SymbolConst) {
  15889. var def = defun.def_variable(node);
  15890. def.constant = node instanceof AST_SymbolConst;
  15891. def.init = tw.parent().value;
  15892. }
  15893. else if (node instanceof AST_SymbolCatch) {
  15894. (options.screw_ie8 ? scope : defun)
  15895. .def_variable(node);
  15896. }
  15897. });
  15898. self.walk(tw);
  15899. // pass 2: find back references and eval
  15900. var func = null;
  15901. var globals = self.globals = new Dictionary();
  15902. var tw = new TreeWalker(function(node, descend){
  15903. if (node instanceof AST_Lambda) {
  15904. var prev_func = func;
  15905. func = node;
  15906. descend();
  15907. func = prev_func;
  15908. return true;
  15909. }
  15910. if (node instanceof AST_SymbolRef) {
  15911. var name = node.name;
  15912. var sym = node.scope.find_variable(name);
  15913. if (!sym) {
  15914. var g;
  15915. if (globals.has(name)) {
  15916. g = globals.get(name);
  15917. } else {
  15918. g = new SymbolDef(self, globals.size(), node);
  15919. g.undeclared = true;
  15920. g.global = true;
  15921. globals.set(name, g);
  15922. }
  15923. node.thedef = g;
  15924. if (name == "eval" && tw.parent() instanceof AST_Call) {
  15925. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
  15926. s.uses_eval = true;
  15927. }
  15928. if (func && name == "arguments") {
  15929. func.uses_arguments = true;
  15930. }
  15931. } else {
  15932. node.thedef = sym;
  15933. }
  15934. node.reference();
  15935. return true;
  15936. }
  15937. });
  15938. self.walk(tw);
  15939. });
  15940. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  15941. this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
  15942. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  15943. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  15944. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  15945. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  15946. this.parent_scope = null; // the parent scope
  15947. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  15948. this.cname = -1; // the current index for mangling functions/variables
  15949. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  15950. });
  15951. AST_Scope.DEFMETHOD("strict", function(){
  15952. return this.has_directive("use strict");
  15953. });
  15954. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  15955. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  15956. this.uses_arguments = false;
  15957. });
  15958. AST_SymbolRef.DEFMETHOD("reference", function() {
  15959. var def = this.definition();
  15960. def.references.push(this);
  15961. var s = this.scope;
  15962. while (s) {
  15963. push_uniq(s.enclosed, def);
  15964. if (s === def.scope) break;
  15965. s = s.parent_scope;
  15966. }
  15967. this.frame = this.scope.nesting - def.scope.nesting;
  15968. });
  15969. AST_Scope.DEFMETHOD("find_variable", function(name){
  15970. if (name instanceof AST_Symbol) name = name.name;
  15971. return this.variables.get(name)
  15972. || (this.parent_scope && this.parent_scope.find_variable(name));
  15973. });
  15974. AST_Scope.DEFMETHOD("has_directive", function(value){
  15975. return this.parent_scope && this.parent_scope.has_directive(value)
  15976. || (this.directives.indexOf(value) >= 0 ? this : null);
  15977. });
  15978. AST_Scope.DEFMETHOD("def_function", function(symbol){
  15979. this.functions.set(symbol.name, this.def_variable(symbol));
  15980. });
  15981. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  15982. var def;
  15983. if (!this.variables.has(symbol.name)) {
  15984. def = new SymbolDef(this, this.variables.size(), symbol);
  15985. this.variables.set(symbol.name, def);
  15986. def.global = !this.parent_scope;
  15987. } else {
  15988. def = this.variables.get(symbol.name);
  15989. def.orig.push(symbol);
  15990. }
  15991. return symbol.thedef = def;
  15992. });
  15993. AST_Scope.DEFMETHOD("next_mangled", function(options){
  15994. var ext = this.enclosed;
  15995. out: while (true) {
  15996. var m = base54(++this.cname);
  15997. if (!is_identifier(m)) continue; // skip over "do"
  15998. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  15999. // shadow a name excepted from mangling.
  16000. if (options.except.indexOf(m) >= 0) continue;
  16001. // we must ensure that the mangled name does not shadow a name
  16002. // from some parent scope that is referenced in this or in
  16003. // inner scopes.
  16004. for (var i = ext.length; --i >= 0;) {
  16005. var sym = ext[i];
  16006. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  16007. if (m == name) continue out;
  16008. }
  16009. return m;
  16010. }
  16011. });
  16012. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  16013. // #179, #326
  16014. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  16015. // a function expression's argument cannot shadow the function expression's name
  16016. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  16017. while (true) {
  16018. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  16019. if (!(tricky_def && tricky_def.mangled_name == name))
  16020. return name;
  16021. }
  16022. });
  16023. AST_Scope.DEFMETHOD("references", function(sym){
  16024. if (sym instanceof AST_Symbol) sym = sym.definition();
  16025. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  16026. });
  16027. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  16028. return this.definition().unmangleable(options);
  16029. });
  16030. // property accessors are not mangleable
  16031. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  16032. return true;
  16033. });
  16034. // labels are always mangleable
  16035. AST_Label.DEFMETHOD("unmangleable", function(){
  16036. return false;
  16037. });
  16038. AST_Symbol.DEFMETHOD("unreferenced", function(){
  16039. return this.definition().references.length == 0
  16040. && !(this.scope.uses_eval || this.scope.uses_with);
  16041. });
  16042. AST_Symbol.DEFMETHOD("undeclared", function(){
  16043. return this.definition().undeclared;
  16044. });
  16045. AST_LabelRef.DEFMETHOD("undeclared", function(){
  16046. return false;
  16047. });
  16048. AST_Label.DEFMETHOD("undeclared", function(){
  16049. return false;
  16050. });
  16051. AST_Symbol.DEFMETHOD("definition", function(){
  16052. return this.thedef;
  16053. });
  16054. AST_Symbol.DEFMETHOD("global", function(){
  16055. return this.definition().global;
  16056. });
  16057. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  16058. return defaults(options, {
  16059. except : [],
  16060. eval : false,
  16061. sort : false,
  16062. toplevel : false,
  16063. screw_ie8 : false
  16064. });
  16065. });
  16066. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  16067. options = this._default_mangler_options(options);
  16068. // We only need to mangle declaration nodes. Special logic wired
  16069. // into the code generator will display the mangled name if it's
  16070. // present (and for AST_SymbolRef-s it'll use the mangled name of
  16071. // the AST_SymbolDeclaration that it points to).
  16072. var lname = -1;
  16073. var to_mangle = [];
  16074. var tw = new TreeWalker(function(node, descend){
  16075. if (node instanceof AST_LabeledStatement) {
  16076. // lname is incremented when we get to the AST_Label
  16077. var save_nesting = lname;
  16078. descend();
  16079. lname = save_nesting;
  16080. return true; // don't descend again in TreeWalker
  16081. }
  16082. if (node instanceof AST_Scope) {
  16083. var p = tw.parent(), a = [];
  16084. node.variables.each(function(symbol){
  16085. if (options.except.indexOf(symbol.name) < 0) {
  16086. a.push(symbol);
  16087. }
  16088. });
  16089. if (options.sort) a.sort(function(a, b){
  16090. return b.references.length - a.references.length;
  16091. });
  16092. to_mangle.push.apply(to_mangle, a);
  16093. return;
  16094. }
  16095. if (node instanceof AST_Label) {
  16096. var name;
  16097. do name = base54(++lname); while (!is_identifier(name));
  16098. node.mangled_name = name;
  16099. return true;
  16100. }
  16101. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  16102. to_mangle.push(node.definition());
  16103. return;
  16104. }
  16105. });
  16106. this.walk(tw);
  16107. to_mangle.forEach(function(def){ def.mangle(options) });
  16108. });
  16109. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  16110. options = this._default_mangler_options(options);
  16111. var tw = new TreeWalker(function(node){
  16112. if (node instanceof AST_Constant)
  16113. base54.consider(node.print_to_string());
  16114. else if (node instanceof AST_Return)
  16115. base54.consider("return");
  16116. else if (node instanceof AST_Throw)
  16117. base54.consider("throw");
  16118. else if (node instanceof AST_Continue)
  16119. base54.consider("continue");
  16120. else if (node instanceof AST_Break)
  16121. base54.consider("break");
  16122. else if (node instanceof AST_Debugger)
  16123. base54.consider("debugger");
  16124. else if (node instanceof AST_Directive)
  16125. base54.consider(node.value);
  16126. else if (node instanceof AST_While)
  16127. base54.consider("while");
  16128. else if (node instanceof AST_Do)
  16129. base54.consider("do while");
  16130. else if (node instanceof AST_If) {
  16131. base54.consider("if");
  16132. if (node.alternative) base54.consider("else");
  16133. }
  16134. else if (node instanceof AST_Var)
  16135. base54.consider("var");
  16136. else if (node instanceof AST_Const)
  16137. base54.consider("const");
  16138. else if (node instanceof AST_Lambda)
  16139. base54.consider("function");
  16140. else if (node instanceof AST_For)
  16141. base54.consider("for");
  16142. else if (node instanceof AST_ForIn)
  16143. base54.consider("for in");
  16144. else if (node instanceof AST_Switch)
  16145. base54.consider("switch");
  16146. else if (node instanceof AST_Case)
  16147. base54.consider("case");
  16148. else if (node instanceof AST_Default)
  16149. base54.consider("default");
  16150. else if (node instanceof AST_With)
  16151. base54.consider("with");
  16152. else if (node instanceof AST_ObjectSetter)
  16153. base54.consider("set" + node.key);
  16154. else if (node instanceof AST_ObjectGetter)
  16155. base54.consider("get" + node.key);
  16156. else if (node instanceof AST_ObjectKeyVal)
  16157. base54.consider(node.key);
  16158. else if (node instanceof AST_New)
  16159. base54.consider("new");
  16160. else if (node instanceof AST_This)
  16161. base54.consider("this");
  16162. else if (node instanceof AST_Try)
  16163. base54.consider("try");
  16164. else if (node instanceof AST_Catch)
  16165. base54.consider("catch");
  16166. else if (node instanceof AST_Finally)
  16167. base54.consider("finally");
  16168. else if (node instanceof AST_Symbol && node.unmangleable(options))
  16169. base54.consider(node.name);
  16170. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  16171. base54.consider(node.operator);
  16172. else if (node instanceof AST_Dot)
  16173. base54.consider(node.property);
  16174. });
  16175. this.walk(tw);
  16176. base54.sort();
  16177. });
  16178. var base54 = (function() {
  16179. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  16180. var chars, frequency;
  16181. function reset() {
  16182. frequency = Object.create(null);
  16183. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  16184. chars.forEach(function(ch){ frequency[ch] = 0 });
  16185. }
  16186. base54.consider = function(str){
  16187. for (var i = str.length; --i >= 0;) {
  16188. var code = str.charCodeAt(i);
  16189. if (code in frequency) ++frequency[code];
  16190. }
  16191. };
  16192. base54.sort = function() {
  16193. chars = mergeSort(chars, function(a, b){
  16194. if (is_digit(a) && !is_digit(b)) return 1;
  16195. if (is_digit(b) && !is_digit(a)) return -1;
  16196. return frequency[b] - frequency[a];
  16197. });
  16198. };
  16199. base54.reset = reset;
  16200. reset();
  16201. base54.get = function(){ return chars };
  16202. base54.freq = function(){ return frequency };
  16203. function base54(num) {
  16204. var ret = "", base = 54;
  16205. do {
  16206. ret += String.fromCharCode(chars[num % base]);
  16207. num = Math.floor(num / base);
  16208. base = 64;
  16209. } while (num > 0);
  16210. return ret;
  16211. };
  16212. return base54;
  16213. })();
  16214. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  16215. options = defaults(options, {
  16216. undeclared : false, // this makes a lot of noise
  16217. unreferenced : true,
  16218. assign_to_global : true,
  16219. func_arguments : true,
  16220. nested_defuns : true,
  16221. eval : true
  16222. });
  16223. var tw = new TreeWalker(function(node){
  16224. if (options.undeclared
  16225. && node instanceof AST_SymbolRef
  16226. && node.undeclared())
  16227. {
  16228. // XXX: this also warns about JS standard names,
  16229. // i.e. Object, Array, parseInt etc. Should add a list of
  16230. // exceptions.
  16231. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  16232. name: node.name,
  16233. file: node.start.file,
  16234. line: node.start.line,
  16235. col: node.start.col
  16236. });
  16237. }
  16238. if (options.assign_to_global)
  16239. {
  16240. var sym = null;
  16241. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  16242. sym = node.left;
  16243. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  16244. sym = node.init;
  16245. if (sym
  16246. && (sym.undeclared()
  16247. || (sym.global() && sym.scope !== sym.definition().scope))) {
  16248. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  16249. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  16250. name: sym.name,
  16251. file: sym.start.file,
  16252. line: sym.start.line,
  16253. col: sym.start.col
  16254. });
  16255. }
  16256. }
  16257. if (options.eval
  16258. && node instanceof AST_SymbolRef
  16259. && node.undeclared()
  16260. && node.name == "eval") {
  16261. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  16262. }
  16263. if (options.unreferenced
  16264. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  16265. && node.unreferenced()) {
  16266. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  16267. type: node instanceof AST_Label ? "Label" : "Symbol",
  16268. name: node.name,
  16269. file: node.start.file,
  16270. line: node.start.line,
  16271. col: node.start.col
  16272. });
  16273. }
  16274. if (options.func_arguments
  16275. && node instanceof AST_Lambda
  16276. && node.uses_arguments) {
  16277. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  16278. name: node.name ? node.name.name : "anonymous",
  16279. file: node.start.file,
  16280. line: node.start.line,
  16281. col: node.start.col
  16282. });
  16283. }
  16284. if (options.nested_defuns
  16285. && node instanceof AST_Defun
  16286. && !(tw.parent() instanceof AST_Scope)) {
  16287. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  16288. name: node.name.name,
  16289. type: tw.parent().TYPE,
  16290. file: node.start.file,
  16291. line: node.start.line,
  16292. col: node.start.col
  16293. });
  16294. }
  16295. });
  16296. this.walk(tw);
  16297. });
  16298. /***********************************************************************
  16299. A JavaScript tokenizer / parser / beautifier / compressor.
  16300. https://github.com/mishoo/UglifyJS2
  16301. -------------------------------- (C) ---------------------------------
  16302. Author: Mihai Bazon
  16303. <mihai.bazon@gmail.com>
  16304. http://mihai.bazon.net/blog
  16305. Distributed under the BSD license:
  16306. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16307. Redistribution and use in source and binary forms, with or without
  16308. modification, are permitted provided that the following conditions
  16309. are met:
  16310. * Redistributions of source code must retain the above
  16311. copyright notice, this list of conditions and the following
  16312. disclaimer.
  16313. * Redistributions in binary form must reproduce the above
  16314. copyright notice, this list of conditions and the following
  16315. disclaimer in the documentation and/or other materials
  16316. provided with the distribution.
  16317. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16318. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16319. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16320. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16321. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16322. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16323. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16324. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16325. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16326. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16327. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16328. SUCH DAMAGE.
  16329. ***********************************************************************/
  16330. "use strict";
  16331. function OutputStream(options) {
  16332. options = defaults(options, {
  16333. indent_start : 0,
  16334. indent_level : 4,
  16335. quote_keys : false,
  16336. space_colon : true,
  16337. ascii_only : false,
  16338. unescape_regexps : false,
  16339. inline_script : false,
  16340. width : 80,
  16341. max_line_len : 32000,
  16342. beautify : false,
  16343. source_map : null,
  16344. bracketize : false,
  16345. semicolons : true,
  16346. comments : false,
  16347. preserve_line : false,
  16348. screw_ie8 : false,
  16349. preamble : null,
  16350. }, true);
  16351. var indentation = 0;
  16352. var current_col = 0;
  16353. var current_line = 1;
  16354. var current_pos = 0;
  16355. var OUTPUT = "";
  16356. function to_ascii(str, identifier) {
  16357. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  16358. var code = ch.charCodeAt(0).toString(16);
  16359. if (code.length <= 2 && !identifier) {
  16360. while (code.length < 2) code = "0" + code;
  16361. return "\\x" + code;
  16362. } else {
  16363. while (code.length < 4) code = "0" + code;
  16364. return "\\u" + code;
  16365. }
  16366. });
  16367. };
  16368. function make_string(str) {
  16369. var dq = 0, sq = 0;
  16370. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  16371. switch (s) {
  16372. case "\\": return "\\\\";
  16373. case "\b": return "\\b";
  16374. case "\f": return "\\f";
  16375. case "\n": return "\\n";
  16376. case "\r": return "\\r";
  16377. case "\u2028": return "\\u2028";
  16378. case "\u2029": return "\\u2029";
  16379. case '"': ++dq; return '"';
  16380. case "'": ++sq; return "'";
  16381. case "\0": return "\\x00";
  16382. }
  16383. return s;
  16384. });
  16385. if (options.ascii_only) str = to_ascii(str);
  16386. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  16387. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  16388. };
  16389. function encode_string(str) {
  16390. var ret = make_string(str);
  16391. if (options.inline_script)
  16392. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  16393. return ret;
  16394. };
  16395. function make_name(name) {
  16396. name = name.toString();
  16397. if (options.ascii_only)
  16398. name = to_ascii(name, true);
  16399. return name;
  16400. };
  16401. function make_indent(back) {
  16402. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  16403. };
  16404. /* -----[ beautification/minification ]----- */
  16405. var might_need_space = false;
  16406. var might_need_semicolon = false;
  16407. var last = null;
  16408. function last_char() {
  16409. return last.charAt(last.length - 1);
  16410. };
  16411. function maybe_newline() {
  16412. if (options.max_line_len && current_col > options.max_line_len)
  16413. print("\n");
  16414. };
  16415. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  16416. function print(str) {
  16417. str = String(str);
  16418. var ch = str.charAt(0);
  16419. if (might_need_semicolon) {
  16420. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  16421. if (options.semicolons || requireSemicolonChars(ch)) {
  16422. OUTPUT += ";";
  16423. current_col++;
  16424. current_pos++;
  16425. } else {
  16426. OUTPUT += "\n";
  16427. current_pos++;
  16428. current_line++;
  16429. current_col = 0;
  16430. }
  16431. if (!options.beautify)
  16432. might_need_space = false;
  16433. }
  16434. might_need_semicolon = false;
  16435. maybe_newline();
  16436. }
  16437. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  16438. var target_line = stack[stack.length - 1].start.line;
  16439. while (current_line < target_line) {
  16440. OUTPUT += "\n";
  16441. current_pos++;
  16442. current_line++;
  16443. current_col = 0;
  16444. might_need_space = false;
  16445. }
  16446. }
  16447. if (might_need_space) {
  16448. var prev = last_char();
  16449. if ((is_identifier_char(prev)
  16450. && (is_identifier_char(ch) || ch == "\\"))
  16451. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  16452. {
  16453. OUTPUT += " ";
  16454. current_col++;
  16455. current_pos++;
  16456. }
  16457. might_need_space = false;
  16458. }
  16459. var a = str.split(/\r?\n/), n = a.length - 1;
  16460. current_line += n;
  16461. if (n == 0) {
  16462. current_col += a[n].length;
  16463. } else {
  16464. current_col = a[n].length;
  16465. }
  16466. current_pos += str.length;
  16467. last = str;
  16468. OUTPUT += str;
  16469. };
  16470. var space = options.beautify ? function() {
  16471. print(" ");
  16472. } : function() {
  16473. might_need_space = true;
  16474. };
  16475. var indent = options.beautify ? function(half) {
  16476. if (options.beautify) {
  16477. print(make_indent(half ? 0.5 : 0));
  16478. }
  16479. } : noop;
  16480. var with_indent = options.beautify ? function(col, cont) {
  16481. if (col === true) col = next_indent();
  16482. var save_indentation = indentation;
  16483. indentation = col;
  16484. var ret = cont();
  16485. indentation = save_indentation;
  16486. return ret;
  16487. } : function(col, cont) { return cont() };
  16488. var newline = options.beautify ? function() {
  16489. print("\n");
  16490. } : noop;
  16491. var semicolon = options.beautify ? function() {
  16492. print(";");
  16493. } : function() {
  16494. might_need_semicolon = true;
  16495. };
  16496. function force_semicolon() {
  16497. might_need_semicolon = false;
  16498. print(";");
  16499. };
  16500. function next_indent() {
  16501. return indentation + options.indent_level;
  16502. };
  16503. function with_block(cont) {
  16504. var ret;
  16505. print("{");
  16506. newline();
  16507. with_indent(next_indent(), function(){
  16508. ret = cont();
  16509. });
  16510. indent();
  16511. print("}");
  16512. return ret;
  16513. };
  16514. function with_parens(cont) {
  16515. print("(");
  16516. //XXX: still nice to have that for argument lists
  16517. //var ret = with_indent(current_col, cont);
  16518. var ret = cont();
  16519. print(")");
  16520. return ret;
  16521. };
  16522. function with_square(cont) {
  16523. print("[");
  16524. //var ret = with_indent(current_col, cont);
  16525. var ret = cont();
  16526. print("]");
  16527. return ret;
  16528. };
  16529. function comma() {
  16530. print(",");
  16531. space();
  16532. };
  16533. function colon() {
  16534. print(":");
  16535. if (options.space_colon) space();
  16536. };
  16537. var add_mapping = options.source_map ? function(token, name) {
  16538. try {
  16539. if (token) options.source_map.add(
  16540. token.file || "?",
  16541. current_line, current_col,
  16542. token.line, token.col,
  16543. (!name && token.type == "name") ? token.value : name
  16544. );
  16545. } catch(ex) {
  16546. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  16547. file: token.file,
  16548. line: token.line,
  16549. col: token.col,
  16550. cline: current_line,
  16551. ccol: current_col,
  16552. name: name || ""
  16553. })
  16554. }
  16555. } : noop;
  16556. function get() {
  16557. return OUTPUT;
  16558. };
  16559. if (options.preamble) {
  16560. print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  16561. }
  16562. var stack = [];
  16563. return {
  16564. get : get,
  16565. toString : get,
  16566. indent : indent,
  16567. indentation : function() { return indentation },
  16568. current_width : function() { return current_col - indentation },
  16569. should_break : function() { return options.width && this.current_width() >= options.width },
  16570. newline : newline,
  16571. print : print,
  16572. space : space,
  16573. comma : comma,
  16574. colon : colon,
  16575. last : function() { return last },
  16576. semicolon : semicolon,
  16577. force_semicolon : force_semicolon,
  16578. to_ascii : to_ascii,
  16579. print_name : function(name) { print(make_name(name)) },
  16580. print_string : function(str) { print(encode_string(str)) },
  16581. next_indent : next_indent,
  16582. with_indent : with_indent,
  16583. with_block : with_block,
  16584. with_parens : with_parens,
  16585. with_square : with_square,
  16586. add_mapping : add_mapping,
  16587. option : function(opt) { return options[opt] },
  16588. line : function() { return current_line },
  16589. col : function() { return current_col },
  16590. pos : function() { return current_pos },
  16591. push_node : function(node) { stack.push(node) },
  16592. pop_node : function() { return stack.pop() },
  16593. stack : function() { return stack },
  16594. parent : function(n) {
  16595. return stack[stack.length - 2 - (n || 0)];
  16596. }
  16597. };
  16598. };
  16599. /* -----[ code generators ]----- */
  16600. (function(){
  16601. /* -----[ utils ]----- */
  16602. function DEFPRINT(nodetype, generator) {
  16603. nodetype.DEFMETHOD("_codegen", generator);
  16604. };
  16605. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  16606. var self = this, generator = self._codegen;
  16607. function doit() {
  16608. self.add_comments(stream);
  16609. self.add_source_map(stream);
  16610. generator(self, stream);
  16611. }
  16612. stream.push_node(self);
  16613. if (force_parens || self.needs_parens(stream)) {
  16614. stream.with_parens(doit);
  16615. } else {
  16616. doit();
  16617. }
  16618. stream.pop_node();
  16619. });
  16620. AST_Node.DEFMETHOD("print_to_string", function(options){
  16621. var s = OutputStream(options);
  16622. this.print(s);
  16623. return s.get();
  16624. });
  16625. /* -----[ comments ]----- */
  16626. AST_Node.DEFMETHOD("add_comments", function(output){
  16627. var c = output.option("comments"), self = this;
  16628. if (c) {
  16629. var start = self.start;
  16630. if (start && !start._comments_dumped) {
  16631. start._comments_dumped = true;
  16632. var comments = start.comments_before || [];
  16633. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  16634. // and https://github.com/mishoo/UglifyJS2/issues/372
  16635. if (self instanceof AST_Exit && self.value) {
  16636. self.value.walk(new TreeWalker(function(node){
  16637. if (node.start && node.start.comments_before) {
  16638. comments = comments.concat(node.start.comments_before);
  16639. node.start.comments_before = [];
  16640. }
  16641. if (node instanceof AST_Function ||
  16642. node instanceof AST_Array ||
  16643. node instanceof AST_Object)
  16644. {
  16645. return true; // don't go inside.
  16646. }
  16647. }));
  16648. }
  16649. if (c.test) {
  16650. comments = comments.filter(function(comment){
  16651. return c.test(comment.value);
  16652. });
  16653. } else if (typeof c == "function") {
  16654. comments = comments.filter(function(comment){
  16655. return c(self, comment);
  16656. });
  16657. }
  16658. comments.forEach(function(c){
  16659. if (/comment[134]/.test(c.type)) {
  16660. output.print("//" + c.value + "\n");
  16661. output.indent();
  16662. }
  16663. else if (c.type == "comment2") {
  16664. output.print("/*" + c.value + "*/");
  16665. if (start.nlb) {
  16666. output.print("\n");
  16667. output.indent();
  16668. } else {
  16669. output.space();
  16670. }
  16671. }
  16672. });
  16673. }
  16674. }
  16675. });
  16676. /* -----[ PARENTHESES ]----- */
  16677. function PARENS(nodetype, func) {
  16678. nodetype.DEFMETHOD("needs_parens", func);
  16679. };
  16680. PARENS(AST_Node, function(){
  16681. return false;
  16682. });
  16683. // a function expression needs parens around it when it's provably
  16684. // the first token to appear in a statement.
  16685. PARENS(AST_Function, function(output){
  16686. return first_in_statement(output);
  16687. });
  16688. // same goes for an object literal, because otherwise it would be
  16689. // interpreted as a block of code.
  16690. PARENS(AST_Object, function(output){
  16691. return first_in_statement(output);
  16692. });
  16693. PARENS(AST_Unary, function(output){
  16694. var p = output.parent();
  16695. return p instanceof AST_PropAccess && p.expression === this;
  16696. });
  16697. PARENS(AST_Seq, function(output){
  16698. var p = output.parent();
  16699. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  16700. || p instanceof AST_Unary // !(foo, bar, baz)
  16701. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  16702. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  16703. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  16704. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  16705. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  16706. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  16707. * ==> 20 (side effect, set a := 10 and b := 20) */
  16708. ;
  16709. });
  16710. PARENS(AST_Binary, function(output){
  16711. var p = output.parent();
  16712. // (foo && bar)()
  16713. if (p instanceof AST_Call && p.expression === this)
  16714. return true;
  16715. // typeof (foo && bar)
  16716. if (p instanceof AST_Unary)
  16717. return true;
  16718. // (foo && bar)["prop"], (foo && bar).prop
  16719. if (p instanceof AST_PropAccess && p.expression === this)
  16720. return true;
  16721. // this deals with precedence: 3 * (2 + 1)
  16722. if (p instanceof AST_Binary) {
  16723. var po = p.operator, pp = PRECEDENCE[po];
  16724. var so = this.operator, sp = PRECEDENCE[so];
  16725. if (pp > sp
  16726. || (pp == sp
  16727. && this === p.right)) {
  16728. return true;
  16729. }
  16730. }
  16731. });
  16732. PARENS(AST_PropAccess, function(output){
  16733. var p = output.parent();
  16734. if (p instanceof AST_New && p.expression === this) {
  16735. // i.e. new (foo.bar().baz)
  16736. //
  16737. // if there's one call into this subtree, then we need
  16738. // parens around it too, otherwise the call will be
  16739. // interpreted as passing the arguments to the upper New
  16740. // expression.
  16741. try {
  16742. this.walk(new TreeWalker(function(node){
  16743. if (node instanceof AST_Call) throw p;
  16744. }));
  16745. } catch(ex) {
  16746. if (ex !== p) throw ex;
  16747. return true;
  16748. }
  16749. }
  16750. });
  16751. PARENS(AST_Call, function(output){
  16752. var p = output.parent(), p1;
  16753. if (p instanceof AST_New && p.expression === this)
  16754. return true;
  16755. // workaround for Safari bug.
  16756. // https://bugs.webkit.org/show_bug.cgi?id=123506
  16757. return this.expression instanceof AST_Function
  16758. && p instanceof AST_PropAccess
  16759. && p.expression === this
  16760. && (p1 = output.parent(1)) instanceof AST_Assign
  16761. && p1.left === p;
  16762. });
  16763. PARENS(AST_New, function(output){
  16764. var p = output.parent();
  16765. if (no_constructor_parens(this, output)
  16766. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  16767. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  16768. return true;
  16769. });
  16770. PARENS(AST_Number, function(output){
  16771. var p = output.parent();
  16772. if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
  16773. return true;
  16774. });
  16775. PARENS(AST_NaN, function(output){
  16776. var p = output.parent();
  16777. if (p instanceof AST_PropAccess && p.expression === this)
  16778. return true;
  16779. });
  16780. function assign_and_conditional_paren_rules(output) {
  16781. var p = output.parent();
  16782. // !(a = false) → true
  16783. if (p instanceof AST_Unary)
  16784. return true;
  16785. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  16786. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  16787. return true;
  16788. // (a = func)() —or— new (a = Object)()
  16789. if (p instanceof AST_Call && p.expression === this)
  16790. return true;
  16791. // (a = foo) ? bar : baz
  16792. if (p instanceof AST_Conditional && p.condition === this)
  16793. return true;
  16794. // (a = foo)["prop"] —or— (a = foo).prop
  16795. if (p instanceof AST_PropAccess && p.expression === this)
  16796. return true;
  16797. };
  16798. PARENS(AST_Assign, assign_and_conditional_paren_rules);
  16799. PARENS(AST_Conditional, assign_and_conditional_paren_rules);
  16800. /* -----[ PRINTERS ]----- */
  16801. DEFPRINT(AST_Directive, function(self, output){
  16802. output.print_string(self.value);
  16803. output.semicolon();
  16804. });
  16805. DEFPRINT(AST_Debugger, function(self, output){
  16806. output.print("debugger");
  16807. output.semicolon();
  16808. });
  16809. /* -----[ statements ]----- */
  16810. function display_body(body, is_toplevel, output) {
  16811. var last = body.length - 1;
  16812. body.forEach(function(stmt, i){
  16813. if (!(stmt instanceof AST_EmptyStatement)) {
  16814. output.indent();
  16815. stmt.print(output);
  16816. if (!(i == last && is_toplevel)) {
  16817. output.newline();
  16818. if (is_toplevel) output.newline();
  16819. }
  16820. }
  16821. });
  16822. };
  16823. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  16824. force_statement(this.body, output);
  16825. });
  16826. DEFPRINT(AST_Statement, function(self, output){
  16827. self.body.print(output);
  16828. output.semicolon();
  16829. });
  16830. DEFPRINT(AST_Toplevel, function(self, output){
  16831. display_body(self.body, true, output);
  16832. output.print("");
  16833. });
  16834. DEFPRINT(AST_LabeledStatement, function(self, output){
  16835. self.label.print(output);
  16836. output.colon();
  16837. self.body.print(output);
  16838. });
  16839. DEFPRINT(AST_SimpleStatement, function(self, output){
  16840. self.body.print(output);
  16841. output.semicolon();
  16842. });
  16843. function print_bracketed(body, output) {
  16844. if (body.length > 0) output.with_block(function(){
  16845. display_body(body, false, output);
  16846. });
  16847. else output.print("{}");
  16848. };
  16849. DEFPRINT(AST_BlockStatement, function(self, output){
  16850. print_bracketed(self.body, output);
  16851. });
  16852. DEFPRINT(AST_EmptyStatement, function(self, output){
  16853. output.semicolon();
  16854. });
  16855. DEFPRINT(AST_Do, function(self, output){
  16856. output.print("do");
  16857. output.space();
  16858. self._do_print_body(output);
  16859. output.space();
  16860. output.print("while");
  16861. output.space();
  16862. output.with_parens(function(){
  16863. self.condition.print(output);
  16864. });
  16865. output.semicolon();
  16866. });
  16867. DEFPRINT(AST_While, function(self, output){
  16868. output.print("while");
  16869. output.space();
  16870. output.with_parens(function(){
  16871. self.condition.print(output);
  16872. });
  16873. output.space();
  16874. self._do_print_body(output);
  16875. });
  16876. DEFPRINT(AST_For, function(self, output){
  16877. output.print("for");
  16878. output.space();
  16879. output.with_parens(function(){
  16880. if (self.init) {
  16881. if (self.init instanceof AST_Definitions) {
  16882. self.init.print(output);
  16883. } else {
  16884. parenthesize_for_noin(self.init, output, true);
  16885. }
  16886. output.print(";");
  16887. output.space();
  16888. } else {
  16889. output.print(";");
  16890. }
  16891. if (self.condition) {
  16892. self.condition.print(output);
  16893. output.print(";");
  16894. output.space();
  16895. } else {
  16896. output.print(";");
  16897. }
  16898. if (self.step) {
  16899. self.step.print(output);
  16900. }
  16901. });
  16902. output.space();
  16903. self._do_print_body(output);
  16904. });
  16905. DEFPRINT(AST_ForIn, function(self, output){
  16906. output.print("for");
  16907. output.space();
  16908. output.with_parens(function(){
  16909. self.init.print(output);
  16910. output.space();
  16911. output.print("in");
  16912. output.space();
  16913. self.object.print(output);
  16914. });
  16915. output.space();
  16916. self._do_print_body(output);
  16917. });
  16918. DEFPRINT(AST_With, function(self, output){
  16919. output.print("with");
  16920. output.space();
  16921. output.with_parens(function(){
  16922. self.expression.print(output);
  16923. });
  16924. output.space();
  16925. self._do_print_body(output);
  16926. });
  16927. /* -----[ functions ]----- */
  16928. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  16929. var self = this;
  16930. if (!nokeyword) {
  16931. output.print("function");
  16932. }
  16933. if (self.name) {
  16934. output.space();
  16935. self.name.print(output);
  16936. }
  16937. output.with_parens(function(){
  16938. self.argnames.forEach(function(arg, i){
  16939. if (i) output.comma();
  16940. arg.print(output);
  16941. });
  16942. });
  16943. output.space();
  16944. print_bracketed(self.body, output);
  16945. });
  16946. DEFPRINT(AST_Lambda, function(self, output){
  16947. self._do_print(output);
  16948. });
  16949. /* -----[ exits ]----- */
  16950. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  16951. output.print(kind);
  16952. if (this.value) {
  16953. output.space();
  16954. this.value.print(output);
  16955. }
  16956. output.semicolon();
  16957. });
  16958. DEFPRINT(AST_Return, function(self, output){
  16959. self._do_print(output, "return");
  16960. });
  16961. DEFPRINT(AST_Throw, function(self, output){
  16962. self._do_print(output, "throw");
  16963. });
  16964. /* -----[ loop control ]----- */
  16965. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  16966. output.print(kind);
  16967. if (this.label) {
  16968. output.space();
  16969. this.label.print(output);
  16970. }
  16971. output.semicolon();
  16972. });
  16973. DEFPRINT(AST_Break, function(self, output){
  16974. self._do_print(output, "break");
  16975. });
  16976. DEFPRINT(AST_Continue, function(self, output){
  16977. self._do_print(output, "continue");
  16978. });
  16979. /* -----[ if ]----- */
  16980. function make_then(self, output) {
  16981. if (output.option("bracketize")) {
  16982. make_block(self.body, output);
  16983. return;
  16984. }
  16985. // The squeezer replaces "block"-s that contain only a single
  16986. // statement with the statement itself; technically, the AST
  16987. // is correct, but this can create problems when we output an
  16988. // IF having an ELSE clause where the THEN clause ends in an
  16989. // IF *without* an ELSE block (then the outer ELSE would refer
  16990. // to the inner IF). This function checks for this case and
  16991. // adds the block brackets if needed.
  16992. if (!self.body)
  16993. return output.force_semicolon();
  16994. if (self.body instanceof AST_Do
  16995. && !output.option("screw_ie8")) {
  16996. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  16997. // croaks with "syntax error" on code like this: if (foo)
  16998. // do ... while(cond); else ... we need block brackets
  16999. // around do/while
  17000. make_block(self.body, output);
  17001. return;
  17002. }
  17003. var b = self.body;
  17004. while (true) {
  17005. if (b instanceof AST_If) {
  17006. if (!b.alternative) {
  17007. make_block(self.body, output);
  17008. return;
  17009. }
  17010. b = b.alternative;
  17011. }
  17012. else if (b instanceof AST_StatementWithBody) {
  17013. b = b.body;
  17014. }
  17015. else break;
  17016. }
  17017. force_statement(self.body, output);
  17018. };
  17019. DEFPRINT(AST_If, function(self, output){
  17020. output.print("if");
  17021. output.space();
  17022. output.with_parens(function(){
  17023. self.condition.print(output);
  17024. });
  17025. output.space();
  17026. if (self.alternative) {
  17027. make_then(self, output);
  17028. output.space();
  17029. output.print("else");
  17030. output.space();
  17031. force_statement(self.alternative, output);
  17032. } else {
  17033. self._do_print_body(output);
  17034. }
  17035. });
  17036. /* -----[ switch ]----- */
  17037. DEFPRINT(AST_Switch, function(self, output){
  17038. output.print("switch");
  17039. output.space();
  17040. output.with_parens(function(){
  17041. self.expression.print(output);
  17042. });
  17043. output.space();
  17044. if (self.body.length > 0) output.with_block(function(){
  17045. self.body.forEach(function(stmt, i){
  17046. if (i) output.newline();
  17047. output.indent(true);
  17048. stmt.print(output);
  17049. });
  17050. });
  17051. else output.print("{}");
  17052. });
  17053. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  17054. if (this.body.length > 0) {
  17055. output.newline();
  17056. this.body.forEach(function(stmt){
  17057. output.indent();
  17058. stmt.print(output);
  17059. output.newline();
  17060. });
  17061. }
  17062. });
  17063. DEFPRINT(AST_Default, function(self, output){
  17064. output.print("default:");
  17065. self._do_print_body(output);
  17066. });
  17067. DEFPRINT(AST_Case, function(self, output){
  17068. output.print("case");
  17069. output.space();
  17070. self.expression.print(output);
  17071. output.print(":");
  17072. self._do_print_body(output);
  17073. });
  17074. /* -----[ exceptions ]----- */
  17075. DEFPRINT(AST_Try, function(self, output){
  17076. output.print("try");
  17077. output.space();
  17078. print_bracketed(self.body, output);
  17079. if (self.bcatch) {
  17080. output.space();
  17081. self.bcatch.print(output);
  17082. }
  17083. if (self.bfinally) {
  17084. output.space();
  17085. self.bfinally.print(output);
  17086. }
  17087. });
  17088. DEFPRINT(AST_Catch, function(self, output){
  17089. output.print("catch");
  17090. output.space();
  17091. output.with_parens(function(){
  17092. self.argname.print(output);
  17093. });
  17094. output.space();
  17095. print_bracketed(self.body, output);
  17096. });
  17097. DEFPRINT(AST_Finally, function(self, output){
  17098. output.print("finally");
  17099. output.space();
  17100. print_bracketed(self.body, output);
  17101. });
  17102. /* -----[ var/const ]----- */
  17103. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  17104. output.print(kind);
  17105. output.space();
  17106. this.definitions.forEach(function(def, i){
  17107. if (i) output.comma();
  17108. def.print(output);
  17109. });
  17110. var p = output.parent();
  17111. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  17112. var avoid_semicolon = in_for && p.init === this;
  17113. if (!avoid_semicolon)
  17114. output.semicolon();
  17115. });
  17116. DEFPRINT(AST_Var, function(self, output){
  17117. self._do_print(output, "var");
  17118. });
  17119. DEFPRINT(AST_Const, function(self, output){
  17120. self._do_print(output, "const");
  17121. });
  17122. function parenthesize_for_noin(node, output, noin) {
  17123. if (!noin) node.print(output);
  17124. else try {
  17125. // need to take some precautions here:
  17126. // https://github.com/mishoo/UglifyJS2/issues/60
  17127. node.walk(new TreeWalker(function(node){
  17128. if (node instanceof AST_Binary && node.operator == "in")
  17129. throw output;
  17130. }));
  17131. node.print(output);
  17132. } catch(ex) {
  17133. if (ex !== output) throw ex;
  17134. node.print(output, true);
  17135. }
  17136. };
  17137. DEFPRINT(AST_VarDef, function(self, output){
  17138. self.name.print(output);
  17139. if (self.value) {
  17140. output.space();
  17141. output.print("=");
  17142. output.space();
  17143. var p = output.parent(1);
  17144. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  17145. parenthesize_for_noin(self.value, output, noin);
  17146. }
  17147. });
  17148. /* -----[ other expressions ]----- */
  17149. DEFPRINT(AST_Call, function(self, output){
  17150. self.expression.print(output);
  17151. if (self instanceof AST_New && no_constructor_parens(self, output))
  17152. return;
  17153. output.with_parens(function(){
  17154. self.args.forEach(function(expr, i){
  17155. if (i) output.comma();
  17156. expr.print(output);
  17157. });
  17158. });
  17159. });
  17160. DEFPRINT(AST_New, function(self, output){
  17161. output.print("new");
  17162. output.space();
  17163. AST_Call.prototype._codegen(self, output);
  17164. });
  17165. AST_Seq.DEFMETHOD("_do_print", function(output){
  17166. this.car.print(output);
  17167. if (this.cdr) {
  17168. output.comma();
  17169. if (output.should_break()) {
  17170. output.newline();
  17171. output.indent();
  17172. }
  17173. this.cdr.print(output);
  17174. }
  17175. });
  17176. DEFPRINT(AST_Seq, function(self, output){
  17177. self._do_print(output);
  17178. // var p = output.parent();
  17179. // if (p instanceof AST_Statement) {
  17180. // output.with_indent(output.next_indent(), function(){
  17181. // self._do_print(output);
  17182. // });
  17183. // } else {
  17184. // self._do_print(output);
  17185. // }
  17186. });
  17187. DEFPRINT(AST_Dot, function(self, output){
  17188. var expr = self.expression;
  17189. expr.print(output);
  17190. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  17191. if (!/[xa-f.]/i.test(output.last())) {
  17192. output.print(".");
  17193. }
  17194. }
  17195. output.print(".");
  17196. // the name after dot would be mapped about here.
  17197. output.add_mapping(self.end);
  17198. output.print_name(self.property);
  17199. });
  17200. DEFPRINT(AST_Sub, function(self, output){
  17201. self.expression.print(output);
  17202. output.print("[");
  17203. self.property.print(output);
  17204. output.print("]");
  17205. });
  17206. DEFPRINT(AST_UnaryPrefix, function(self, output){
  17207. var op = self.operator;
  17208. output.print(op);
  17209. if (/^[a-z]/i.test(op))
  17210. output.space();
  17211. self.expression.print(output);
  17212. });
  17213. DEFPRINT(AST_UnaryPostfix, function(self, output){
  17214. self.expression.print(output);
  17215. output.print(self.operator);
  17216. });
  17217. DEFPRINT(AST_Binary, function(self, output){
  17218. self.left.print(output);
  17219. output.space();
  17220. output.print(self.operator);
  17221. if (self.operator == "<"
  17222. && self.right instanceof AST_UnaryPrefix
  17223. && self.right.operator == "!"
  17224. && self.right.expression instanceof AST_UnaryPrefix
  17225. && self.right.expression.operator == "--") {
  17226. // space is mandatory to avoid outputting <!--
  17227. // http://javascript.spec.whatwg.org/#comment-syntax
  17228. output.print(" ");
  17229. } else {
  17230. // the space is optional depending on "beautify"
  17231. output.space();
  17232. }
  17233. self.right.print(output);
  17234. });
  17235. DEFPRINT(AST_Conditional, function(self, output){
  17236. self.condition.print(output);
  17237. output.space();
  17238. output.print("?");
  17239. output.space();
  17240. self.consequent.print(output);
  17241. output.space();
  17242. output.colon();
  17243. self.alternative.print(output);
  17244. });
  17245. /* -----[ literals ]----- */
  17246. DEFPRINT(AST_Array, function(self, output){
  17247. output.with_square(function(){
  17248. var a = self.elements, len = a.length;
  17249. if (len > 0) output.space();
  17250. a.forEach(function(exp, i){
  17251. if (i) output.comma();
  17252. exp.print(output);
  17253. // If the final element is a hole, we need to make sure it
  17254. // doesn't look like a trailing comma, by inserting an actual
  17255. // trailing comma.
  17256. if (i === len - 1 && exp instanceof AST_Hole)
  17257. output.comma();
  17258. });
  17259. if (len > 0) output.space();
  17260. });
  17261. });
  17262. DEFPRINT(AST_Object, function(self, output){
  17263. if (self.properties.length > 0) output.with_block(function(){
  17264. self.properties.forEach(function(prop, i){
  17265. if (i) {
  17266. output.print(",");
  17267. output.newline();
  17268. }
  17269. output.indent();
  17270. prop.print(output);
  17271. });
  17272. output.newline();
  17273. });
  17274. else output.print("{}");
  17275. });
  17276. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  17277. var key = self.key;
  17278. if (output.option("quote_keys")) {
  17279. output.print_string(key + "");
  17280. } else if ((typeof key == "number"
  17281. || !output.option("beautify")
  17282. && +key + "" == key)
  17283. && parseFloat(key) >= 0) {
  17284. output.print(make_num(key));
  17285. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  17286. output.print_name(key);
  17287. } else {
  17288. output.print_string(key);
  17289. }
  17290. output.colon();
  17291. self.value.print(output);
  17292. });
  17293. DEFPRINT(AST_ObjectSetter, function(self, output){
  17294. output.print("set");
  17295. output.space();
  17296. self.key.print(output);
  17297. self.value._do_print(output, true);
  17298. });
  17299. DEFPRINT(AST_ObjectGetter, function(self, output){
  17300. output.print("get");
  17301. output.space();
  17302. self.key.print(output);
  17303. self.value._do_print(output, true);
  17304. });
  17305. DEFPRINT(AST_Symbol, function(self, output){
  17306. var def = self.definition();
  17307. output.print_name(def ? def.mangled_name || def.name : self.name);
  17308. });
  17309. DEFPRINT(AST_Undefined, function(self, output){
  17310. output.print("void 0");
  17311. });
  17312. DEFPRINT(AST_Hole, noop);
  17313. DEFPRINT(AST_Infinity, function(self, output){
  17314. output.print("1/0");
  17315. });
  17316. DEFPRINT(AST_NaN, function(self, output){
  17317. output.print("0/0");
  17318. });
  17319. DEFPRINT(AST_This, function(self, output){
  17320. output.print("this");
  17321. });
  17322. DEFPRINT(AST_Constant, function(self, output){
  17323. output.print(self.getValue());
  17324. });
  17325. DEFPRINT(AST_String, function(self, output){
  17326. output.print_string(self.getValue());
  17327. });
  17328. DEFPRINT(AST_Number, function(self, output){
  17329. output.print(make_num(self.getValue()));
  17330. });
  17331. function regexp_safe_literal(code) {
  17332. return [
  17333. 0x5c , // \
  17334. 0x2f , // /
  17335. 0x2e , // .
  17336. 0x2b , // +
  17337. 0x2a , // *
  17338. 0x3f , // ?
  17339. 0x28 , // (
  17340. 0x29 , // )
  17341. 0x5b , // [
  17342. 0x5d , // ]
  17343. 0x7b , // {
  17344. 0x7d , // }
  17345. 0x24 , // $
  17346. 0x5e , // ^
  17347. 0x3a , // :
  17348. 0x7c , // |
  17349. 0x21 , // !
  17350. 0x0a , // \n
  17351. 0x0d , // \r
  17352. 0x00 , // \0
  17353. 0xfeff , // Unicode BOM
  17354. 0x2028 , // unicode "line separator"
  17355. 0x2029 , // unicode "paragraph separator"
  17356. ].indexOf(code) < 0;
  17357. };
  17358. DEFPRINT(AST_RegExp, function(self, output){
  17359. var str = self.getValue().toString();
  17360. if (output.option("ascii_only")) {
  17361. str = output.to_ascii(str);
  17362. } else if (output.option("unescape_regexps")) {
  17363. str = str.split("\\\\").map(function(str){
  17364. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  17365. var code = parseInt(s.substr(2), 16);
  17366. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  17367. });
  17368. }).join("\\\\");
  17369. }
  17370. output.print(str);
  17371. var p = output.parent();
  17372. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  17373. output.print(" ");
  17374. });
  17375. function force_statement(stat, output) {
  17376. if (output.option("bracketize")) {
  17377. if (!stat || stat instanceof AST_EmptyStatement)
  17378. output.print("{}");
  17379. else if (stat instanceof AST_BlockStatement)
  17380. stat.print(output);
  17381. else output.with_block(function(){
  17382. output.indent();
  17383. stat.print(output);
  17384. output.newline();
  17385. });
  17386. } else {
  17387. if (!stat || stat instanceof AST_EmptyStatement)
  17388. output.force_semicolon();
  17389. else
  17390. stat.print(output);
  17391. }
  17392. };
  17393. // return true if the node at the top of the stack (that means the
  17394. // innermost node in the current output) is lexically the first in
  17395. // a statement.
  17396. function first_in_statement(output) {
  17397. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  17398. while (i > 0) {
  17399. if (p instanceof AST_Statement && p.body === node)
  17400. return true;
  17401. if ((p instanceof AST_Seq && p.car === node ) ||
  17402. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  17403. (p instanceof AST_Dot && p.expression === node ) ||
  17404. (p instanceof AST_Sub && p.expression === node ) ||
  17405. (p instanceof AST_Conditional && p.condition === node ) ||
  17406. (p instanceof AST_Binary && p.left === node ) ||
  17407. (p instanceof AST_UnaryPostfix && p.expression === node ))
  17408. {
  17409. node = p;
  17410. p = a[--i];
  17411. } else {
  17412. return false;
  17413. }
  17414. }
  17415. };
  17416. // self should be AST_New. decide if we want to show parens or not.
  17417. function no_constructor_parens(self, output) {
  17418. return self.args.length == 0 && !output.option("beautify");
  17419. };
  17420. function best_of(a) {
  17421. var best = a[0], len = best.length;
  17422. for (var i = 1; i < a.length; ++i) {
  17423. if (a[i].length < len) {
  17424. best = a[i];
  17425. len = best.length;
  17426. }
  17427. }
  17428. return best;
  17429. };
  17430. function make_num(num) {
  17431. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  17432. if (Math.floor(num) === num) {
  17433. if (num >= 0) {
  17434. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  17435. "0" + num.toString(8)); // same.
  17436. } else {
  17437. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  17438. "-0" + (-num).toString(8)); // same.
  17439. }
  17440. if ((m = /^(.*?)(0+)$/.exec(num))) {
  17441. a.push(m[1] + "e" + m[2].length);
  17442. }
  17443. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  17444. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  17445. str.substr(str.indexOf(".")));
  17446. }
  17447. return best_of(a);
  17448. };
  17449. function make_block(stmt, output) {
  17450. if (stmt instanceof AST_BlockStatement) {
  17451. stmt.print(output);
  17452. return;
  17453. }
  17454. output.with_block(function(){
  17455. output.indent();
  17456. stmt.print(output);
  17457. output.newline();
  17458. });
  17459. };
  17460. /* -----[ source map generators ]----- */
  17461. function DEFMAP(nodetype, generator) {
  17462. nodetype.DEFMETHOD("add_source_map", function(stream){
  17463. generator(this, stream);
  17464. });
  17465. };
  17466. // We could easily add info for ALL nodes, but it seems to me that
  17467. // would be quite wasteful, hence this noop in the base class.
  17468. DEFMAP(AST_Node, noop);
  17469. function basic_sourcemap_gen(self, output) {
  17470. output.add_mapping(self.start);
  17471. };
  17472. // XXX: I'm not exactly sure if we need it for all of these nodes,
  17473. // or if we should add even more.
  17474. DEFMAP(AST_Directive, basic_sourcemap_gen);
  17475. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  17476. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  17477. DEFMAP(AST_Jump, basic_sourcemap_gen);
  17478. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  17479. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  17480. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  17481. DEFMAP(AST_Switch, basic_sourcemap_gen);
  17482. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  17483. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  17484. DEFMAP(AST_Toplevel, noop);
  17485. DEFMAP(AST_New, basic_sourcemap_gen);
  17486. DEFMAP(AST_Try, basic_sourcemap_gen);
  17487. DEFMAP(AST_Catch, basic_sourcemap_gen);
  17488. DEFMAP(AST_Finally, basic_sourcemap_gen);
  17489. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  17490. DEFMAP(AST_Constant, basic_sourcemap_gen);
  17491. DEFMAP(AST_ObjectProperty, function(self, output){
  17492. output.add_mapping(self.start, self.key);
  17493. });
  17494. })();
  17495. /***********************************************************************
  17496. A JavaScript tokenizer / parser / beautifier / compressor.
  17497. https://github.com/mishoo/UglifyJS2
  17498. -------------------------------- (C) ---------------------------------
  17499. Author: Mihai Bazon
  17500. <mihai.bazon@gmail.com>
  17501. http://mihai.bazon.net/blog
  17502. Distributed under the BSD license:
  17503. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  17504. Redistribution and use in source and binary forms, with or without
  17505. modification, are permitted provided that the following conditions
  17506. are met:
  17507. * Redistributions of source code must retain the above
  17508. copyright notice, this list of conditions and the following
  17509. disclaimer.
  17510. * Redistributions in binary form must reproduce the above
  17511. copyright notice, this list of conditions and the following
  17512. disclaimer in the documentation and/or other materials
  17513. provided with the distribution.
  17514. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  17515. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17516. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17517. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  17518. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  17519. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  17520. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17521. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  17522. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  17523. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  17524. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  17525. SUCH DAMAGE.
  17526. ***********************************************************************/
  17527. "use strict";
  17528. function Compressor(options, false_by_default) {
  17529. if (!(this instanceof Compressor))
  17530. return new Compressor(options, false_by_default);
  17531. TreeTransformer.call(this, this.before, this.after);
  17532. this.options = defaults(options, {
  17533. sequences : !false_by_default,
  17534. properties : !false_by_default,
  17535. dead_code : !false_by_default,
  17536. drop_debugger : !false_by_default,
  17537. unsafe : false,
  17538. unsafe_comps : false,
  17539. conditionals : !false_by_default,
  17540. comparisons : !false_by_default,
  17541. evaluate : !false_by_default,
  17542. booleans : !false_by_default,
  17543. loops : !false_by_default,
  17544. unused : !false_by_default,
  17545. hoist_funs : !false_by_default,
  17546. keep_fargs : false,
  17547. hoist_vars : false,
  17548. if_return : !false_by_default,
  17549. join_vars : !false_by_default,
  17550. cascade : !false_by_default,
  17551. side_effects : !false_by_default,
  17552. pure_getters : false,
  17553. pure_funcs : null,
  17554. negate_iife : !false_by_default,
  17555. screw_ie8 : false,
  17556. drop_console : false,
  17557. angular : false,
  17558. warnings : true,
  17559. global_defs : {}
  17560. }, true);
  17561. };
  17562. Compressor.prototype = new TreeTransformer;
  17563. merge(Compressor.prototype, {
  17564. option: function(key) { return this.options[key] },
  17565. warn: function() {
  17566. if (this.options.warnings)
  17567. AST_Node.warn.apply(AST_Node, arguments);
  17568. },
  17569. before: function(node, descend, in_list) {
  17570. if (node._squeezed) return node;
  17571. var was_scope = false;
  17572. if (node instanceof AST_Scope) {
  17573. node = node.hoist_declarations(this);
  17574. was_scope = true;
  17575. }
  17576. descend(node, this);
  17577. node = node.optimize(this);
  17578. if (was_scope && node instanceof AST_Scope) {
  17579. node.drop_unused(this);
  17580. descend(node, this);
  17581. }
  17582. node._squeezed = true;
  17583. return node;
  17584. }
  17585. });
  17586. (function(){
  17587. function OPT(node, optimizer) {
  17588. node.DEFMETHOD("optimize", function(compressor){
  17589. var self = this;
  17590. if (self._optimized) return self;
  17591. var opt = optimizer(self, compressor);
  17592. opt._optimized = true;
  17593. if (opt === self) return opt;
  17594. return opt.transform(compressor);
  17595. });
  17596. };
  17597. OPT(AST_Node, function(self, compressor){
  17598. return self;
  17599. });
  17600. AST_Node.DEFMETHOD("equivalent_to", function(node){
  17601. // XXX: this is a rather expensive way to test two node's equivalence:
  17602. return this.print_to_string() == node.print_to_string();
  17603. });
  17604. function make_node(ctor, orig, props) {
  17605. if (!props) props = {};
  17606. if (orig) {
  17607. if (!props.start) props.start = orig.start;
  17608. if (!props.end) props.end = orig.end;
  17609. }
  17610. return new ctor(props);
  17611. };
  17612. function make_node_from_constant(compressor, val, orig) {
  17613. // XXX: WIP.
  17614. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  17615. // if (node instanceof AST_SymbolRef) {
  17616. // var scope = compressor.find_parent(AST_Scope);
  17617. // var def = scope.find_variable(node);
  17618. // node.thedef = def;
  17619. // return node;
  17620. // }
  17621. // })).transform(compressor);
  17622. if (val instanceof AST_Node) return val.transform(compressor);
  17623. switch (typeof val) {
  17624. case "string":
  17625. return make_node(AST_String, orig, {
  17626. value: val
  17627. }).optimize(compressor);
  17628. case "number":
  17629. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  17630. value: val
  17631. }).optimize(compressor);
  17632. case "boolean":
  17633. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  17634. case "undefined":
  17635. return make_node(AST_Undefined, orig).optimize(compressor);
  17636. default:
  17637. if (val === null) {
  17638. return make_node(AST_Null, orig).optimize(compressor);
  17639. }
  17640. if (val instanceof RegExp) {
  17641. return make_node(AST_RegExp, orig).optimize(compressor);
  17642. }
  17643. throw new Error(string_template("Can't handle constant of type: {type}", {
  17644. type: typeof val
  17645. }));
  17646. }
  17647. };
  17648. function as_statement_array(thing) {
  17649. if (thing === null) return [];
  17650. if (thing instanceof AST_BlockStatement) return thing.body;
  17651. if (thing instanceof AST_EmptyStatement) return [];
  17652. if (thing instanceof AST_Statement) return [ thing ];
  17653. throw new Error("Can't convert thing to statement array");
  17654. };
  17655. function is_empty(thing) {
  17656. if (thing === null) return true;
  17657. if (thing instanceof AST_EmptyStatement) return true;
  17658. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  17659. return false;
  17660. };
  17661. function loop_body(x) {
  17662. if (x instanceof AST_Switch) return x;
  17663. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  17664. return (x.body instanceof AST_BlockStatement ? x.body : x);
  17665. }
  17666. return x;
  17667. };
  17668. function tighten_body(statements, compressor) {
  17669. var CHANGED;
  17670. do {
  17671. CHANGED = false;
  17672. if (compressor.option("angular")) {
  17673. statements = process_for_angular(statements);
  17674. }
  17675. statements = eliminate_spurious_blocks(statements);
  17676. if (compressor.option("dead_code")) {
  17677. statements = eliminate_dead_code(statements, compressor);
  17678. }
  17679. if (compressor.option("if_return")) {
  17680. statements = handle_if_return(statements, compressor);
  17681. }
  17682. if (compressor.option("sequences")) {
  17683. statements = sequencesize(statements, compressor);
  17684. }
  17685. if (compressor.option("join_vars")) {
  17686. statements = join_consecutive_vars(statements, compressor);
  17687. }
  17688. } while (CHANGED);
  17689. if (compressor.option("negate_iife")) {
  17690. negate_iifes(statements, compressor);
  17691. }
  17692. return statements;
  17693. function process_for_angular(statements) {
  17694. function make_injector(func, name) {
  17695. return make_node(AST_SimpleStatement, func, {
  17696. body: make_node(AST_Assign, func, {
  17697. operator: "=",
  17698. left: make_node(AST_Dot, name, {
  17699. expression: make_node(AST_SymbolRef, name, name),
  17700. property: "$inject"
  17701. }),
  17702. right: make_node(AST_Array, func, {
  17703. elements: func.argnames.map(function(sym){
  17704. return make_node(AST_String, sym, { value: sym.name });
  17705. })
  17706. })
  17707. })
  17708. });
  17709. }
  17710. return statements.reduce(function(a, stat){
  17711. a.push(stat);
  17712. var token = stat.start;
  17713. var comments = token.comments_before;
  17714. if (comments && comments.length > 0) {
  17715. var last = comments.pop();
  17716. if (/@ngInject/.test(last.value)) {
  17717. // case 1: defun
  17718. if (stat instanceof AST_Defun) {
  17719. a.push(make_injector(stat, stat.name));
  17720. }
  17721. else if (stat instanceof AST_Definitions) {
  17722. stat.definitions.forEach(function(def){
  17723. if (def.value && def.value instanceof AST_Lambda) {
  17724. a.push(make_injector(def.value, def.name));
  17725. }
  17726. });
  17727. }
  17728. else {
  17729. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  17730. }
  17731. }
  17732. }
  17733. return a;
  17734. }, []);
  17735. }
  17736. function eliminate_spurious_blocks(statements) {
  17737. var seen_dirs = [];
  17738. return statements.reduce(function(a, stat){
  17739. if (stat instanceof AST_BlockStatement) {
  17740. CHANGED = true;
  17741. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  17742. } else if (stat instanceof AST_EmptyStatement) {
  17743. CHANGED = true;
  17744. } else if (stat instanceof AST_Directive) {
  17745. if (seen_dirs.indexOf(stat.value) < 0) {
  17746. a.push(stat);
  17747. seen_dirs.push(stat.value);
  17748. } else {
  17749. CHANGED = true;
  17750. }
  17751. } else {
  17752. a.push(stat);
  17753. }
  17754. return a;
  17755. }, []);
  17756. };
  17757. function handle_if_return(statements, compressor) {
  17758. var self = compressor.self();
  17759. var in_lambda = self instanceof AST_Lambda;
  17760. var ret = [];
  17761. loop: for (var i = statements.length; --i >= 0;) {
  17762. var stat = statements[i];
  17763. switch (true) {
  17764. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  17765. CHANGED = true;
  17766. // note, ret.length is probably always zero
  17767. // because we drop unreachable code before this
  17768. // step. nevertheless, it's good to check.
  17769. continue loop;
  17770. case stat instanceof AST_If:
  17771. if (stat.body instanceof AST_Return) {
  17772. //---
  17773. // pretty silly case, but:
  17774. // if (foo()) return; return; ==> foo(); return;
  17775. if (((in_lambda && ret.length == 0)
  17776. || (ret[0] instanceof AST_Return && !ret[0].value))
  17777. && !stat.body.value && !stat.alternative) {
  17778. CHANGED = true;
  17779. var cond = make_node(AST_SimpleStatement, stat.condition, {
  17780. body: stat.condition
  17781. });
  17782. ret.unshift(cond);
  17783. continue loop;
  17784. }
  17785. //---
  17786. // if (foo()) return x; return y; ==> return foo() ? x : y;
  17787. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  17788. CHANGED = true;
  17789. stat = stat.clone();
  17790. stat.alternative = ret[0];
  17791. ret[0] = stat.transform(compressor);
  17792. continue loop;
  17793. }
  17794. //---
  17795. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  17796. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  17797. CHANGED = true;
  17798. stat = stat.clone();
  17799. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  17800. value: make_node(AST_Undefined, stat)
  17801. });
  17802. ret[0] = stat.transform(compressor);
  17803. continue loop;
  17804. }
  17805. //---
  17806. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  17807. if (!stat.body.value && in_lambda) {
  17808. CHANGED = true;
  17809. stat = stat.clone();
  17810. stat.condition = stat.condition.negate(compressor);
  17811. stat.body = make_node(AST_BlockStatement, stat, {
  17812. body: as_statement_array(stat.alternative).concat(ret)
  17813. });
  17814. stat.alternative = null;
  17815. ret = [ stat.transform(compressor) ];
  17816. continue loop;
  17817. }
  17818. //---
  17819. if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  17820. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  17821. CHANGED = true;
  17822. ret.push(make_node(AST_Return, ret[0], {
  17823. value: make_node(AST_Undefined, ret[0])
  17824. }).transform(compressor));
  17825. ret = as_statement_array(stat.alternative).concat(ret);
  17826. ret.unshift(stat);
  17827. continue loop;
  17828. }
  17829. }
  17830. var ab = aborts(stat.body);
  17831. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  17832. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  17833. || (ab instanceof AST_Continue && self === loop_body(lct))
  17834. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  17835. if (ab.label) {
  17836. remove(ab.label.thedef.references, ab);
  17837. }
  17838. CHANGED = true;
  17839. var body = as_statement_array(stat.body).slice(0, -1);
  17840. stat = stat.clone();
  17841. stat.condition = stat.condition.negate(compressor);
  17842. stat.body = make_node(AST_BlockStatement, stat, {
  17843. body: as_statement_array(stat.alternative).concat(ret)
  17844. });
  17845. stat.alternative = make_node(AST_BlockStatement, stat, {
  17846. body: body
  17847. });
  17848. ret = [ stat.transform(compressor) ];
  17849. continue loop;
  17850. }
  17851. var ab = aborts(stat.alternative);
  17852. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  17853. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  17854. || (ab instanceof AST_Continue && self === loop_body(lct))
  17855. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  17856. if (ab.label) {
  17857. remove(ab.label.thedef.references, ab);
  17858. }
  17859. CHANGED = true;
  17860. stat = stat.clone();
  17861. stat.body = make_node(AST_BlockStatement, stat.body, {
  17862. body: as_statement_array(stat.body).concat(ret)
  17863. });
  17864. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  17865. body: as_statement_array(stat.alternative).slice(0, -1)
  17866. });
  17867. ret = [ stat.transform(compressor) ];
  17868. continue loop;
  17869. }
  17870. ret.unshift(stat);
  17871. break;
  17872. default:
  17873. ret.unshift(stat);
  17874. break;
  17875. }
  17876. }
  17877. return ret;
  17878. };
  17879. function eliminate_dead_code(statements, compressor) {
  17880. var has_quit = false;
  17881. var orig = statements.length;
  17882. var self = compressor.self();
  17883. statements = statements.reduce(function(a, stat){
  17884. if (has_quit) {
  17885. extract_declarations_from_unreachable_code(compressor, stat, a);
  17886. } else {
  17887. if (stat instanceof AST_LoopControl) {
  17888. var lct = compressor.loopcontrol_target(stat.label);
  17889. if ((stat instanceof AST_Break
  17890. && lct instanceof AST_BlockStatement
  17891. && loop_body(lct) === self) || (stat instanceof AST_Continue
  17892. && loop_body(lct) === self)) {
  17893. if (stat.label) {
  17894. remove(stat.label.thedef.references, stat);
  17895. }
  17896. } else {
  17897. a.push(stat);
  17898. }
  17899. } else {
  17900. a.push(stat);
  17901. }
  17902. if (aborts(stat)) has_quit = true;
  17903. }
  17904. return a;
  17905. }, []);
  17906. CHANGED = statements.length != orig;
  17907. return statements;
  17908. };
  17909. function sequencesize(statements, compressor) {
  17910. if (statements.length < 2) return statements;
  17911. var seq = [], ret = [];
  17912. function push_seq() {
  17913. seq = AST_Seq.from_array(seq);
  17914. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  17915. body: seq
  17916. }));
  17917. seq = [];
  17918. };
  17919. statements.forEach(function(stat){
  17920. if (stat instanceof AST_SimpleStatement) seq.push(stat.body);
  17921. else push_seq(), ret.push(stat);
  17922. });
  17923. push_seq();
  17924. ret = sequencesize_2(ret, compressor);
  17925. CHANGED = ret.length != statements.length;
  17926. return ret;
  17927. };
  17928. function sequencesize_2(statements, compressor) {
  17929. function cons_seq(right) {
  17930. ret.pop();
  17931. var left = prev.body;
  17932. if (left instanceof AST_Seq) {
  17933. left.add(right);
  17934. } else {
  17935. left = AST_Seq.cons(left, right);
  17936. }
  17937. return left.transform(compressor);
  17938. };
  17939. var ret = [], prev = null;
  17940. statements.forEach(function(stat){
  17941. if (prev) {
  17942. if (stat instanceof AST_For) {
  17943. var opera = {};
  17944. try {
  17945. prev.body.walk(new TreeWalker(function(node){
  17946. if (node instanceof AST_Binary && node.operator == "in")
  17947. throw opera;
  17948. }));
  17949. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  17950. stat.init = cons_seq(stat.init);
  17951. }
  17952. else if (!stat.init) {
  17953. stat.init = prev.body;
  17954. ret.pop();
  17955. }
  17956. } catch(ex) {
  17957. if (ex !== opera) throw ex;
  17958. }
  17959. }
  17960. else if (stat instanceof AST_If) {
  17961. stat.condition = cons_seq(stat.condition);
  17962. }
  17963. else if (stat instanceof AST_With) {
  17964. stat.expression = cons_seq(stat.expression);
  17965. }
  17966. else if (stat instanceof AST_Exit && stat.value) {
  17967. stat.value = cons_seq(stat.value);
  17968. }
  17969. else if (stat instanceof AST_Exit) {
  17970. stat.value = cons_seq(make_node(AST_Undefined, stat));
  17971. }
  17972. else if (stat instanceof AST_Switch) {
  17973. stat.expression = cons_seq(stat.expression);
  17974. }
  17975. }
  17976. ret.push(stat);
  17977. prev = stat instanceof AST_SimpleStatement ? stat : null;
  17978. });
  17979. return ret;
  17980. };
  17981. function join_consecutive_vars(statements, compressor) {
  17982. var prev = null;
  17983. return statements.reduce(function(a, stat){
  17984. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  17985. prev.definitions = prev.definitions.concat(stat.definitions);
  17986. CHANGED = true;
  17987. }
  17988. else if (stat instanceof AST_For
  17989. && prev instanceof AST_Definitions
  17990. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  17991. CHANGED = true;
  17992. a.pop();
  17993. if (stat.init) {
  17994. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  17995. } else {
  17996. stat.init = prev;
  17997. }
  17998. a.push(stat);
  17999. prev = stat;
  18000. }
  18001. else {
  18002. prev = stat;
  18003. a.push(stat);
  18004. }
  18005. return a;
  18006. }, []);
  18007. };
  18008. function negate_iifes(statements, compressor) {
  18009. statements.forEach(function(stat){
  18010. if (stat instanceof AST_SimpleStatement) {
  18011. stat.body = (function transform(thing) {
  18012. return thing.transform(new TreeTransformer(function(node){
  18013. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  18014. return make_node(AST_UnaryPrefix, node, {
  18015. operator: "!",
  18016. expression: node
  18017. });
  18018. }
  18019. else if (node instanceof AST_Call) {
  18020. node.expression = transform(node.expression);
  18021. }
  18022. else if (node instanceof AST_Seq) {
  18023. node.car = transform(node.car);
  18024. }
  18025. else if (node instanceof AST_Conditional) {
  18026. var expr = transform(node.condition);
  18027. if (expr !== node.condition) {
  18028. // it has been negated, reverse
  18029. node.condition = expr;
  18030. var tmp = node.consequent;
  18031. node.consequent = node.alternative;
  18032. node.alternative = tmp;
  18033. }
  18034. }
  18035. return node;
  18036. }));
  18037. })(stat.body);
  18038. }
  18039. });
  18040. };
  18041. };
  18042. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  18043. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  18044. stat.walk(new TreeWalker(function(node){
  18045. if (node instanceof AST_Definitions) {
  18046. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  18047. node.remove_initializers();
  18048. target.push(node);
  18049. return true;
  18050. }
  18051. if (node instanceof AST_Defun) {
  18052. target.push(node);
  18053. return true;
  18054. }
  18055. if (node instanceof AST_Scope) {
  18056. return true;
  18057. }
  18058. }));
  18059. };
  18060. /* -----[ boolean/negation helpers ]----- */
  18061. // methods to determine whether an expression has a boolean result type
  18062. (function (def){
  18063. var unary_bool = [ "!", "delete" ];
  18064. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  18065. def(AST_Node, function(){ return false });
  18066. def(AST_UnaryPrefix, function(){
  18067. return member(this.operator, unary_bool);
  18068. });
  18069. def(AST_Binary, function(){
  18070. return member(this.operator, binary_bool) ||
  18071. ( (this.operator == "&&" || this.operator == "||") &&
  18072. this.left.is_boolean() && this.right.is_boolean() );
  18073. });
  18074. def(AST_Conditional, function(){
  18075. return this.consequent.is_boolean() && this.alternative.is_boolean();
  18076. });
  18077. def(AST_Assign, function(){
  18078. return this.operator == "=" && this.right.is_boolean();
  18079. });
  18080. def(AST_Seq, function(){
  18081. return this.cdr.is_boolean();
  18082. });
  18083. def(AST_True, function(){ return true });
  18084. def(AST_False, function(){ return true });
  18085. })(function(node, func){
  18086. node.DEFMETHOD("is_boolean", func);
  18087. });
  18088. // methods to determine if an expression has a string result type
  18089. (function (def){
  18090. def(AST_Node, function(){ return false });
  18091. def(AST_String, function(){ return true });
  18092. def(AST_UnaryPrefix, function(){
  18093. return this.operator == "typeof";
  18094. });
  18095. def(AST_Binary, function(compressor){
  18096. return this.operator == "+" &&
  18097. (this.left.is_string(compressor) || this.right.is_string(compressor));
  18098. });
  18099. def(AST_Assign, function(compressor){
  18100. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  18101. });
  18102. def(AST_Seq, function(compressor){
  18103. return this.cdr.is_string(compressor);
  18104. });
  18105. def(AST_Conditional, function(compressor){
  18106. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  18107. });
  18108. def(AST_Call, function(compressor){
  18109. return compressor.option("unsafe")
  18110. && this.expression instanceof AST_SymbolRef
  18111. && this.expression.name == "String"
  18112. && this.expression.undeclared();
  18113. });
  18114. })(function(node, func){
  18115. node.DEFMETHOD("is_string", func);
  18116. });
  18117. function best_of(ast1, ast2) {
  18118. return ast1.print_to_string().length >
  18119. ast2.print_to_string().length
  18120. ? ast2 : ast1;
  18121. };
  18122. // methods to evaluate a constant expression
  18123. (function (def){
  18124. // The evaluate method returns an array with one or two
  18125. // elements. If the node has been successfully reduced to a
  18126. // constant, then the second element tells us the value;
  18127. // otherwise the second element is missing. The first element
  18128. // of the array is always an AST_Node descendant; if
  18129. // evaluation was successful it's a node that represents the
  18130. // constant; otherwise it's the original or a replacement node.
  18131. AST_Node.DEFMETHOD("evaluate", function(compressor){
  18132. if (!compressor.option("evaluate")) return [ this ];
  18133. try {
  18134. var val = this._eval(compressor);
  18135. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  18136. } catch(ex) {
  18137. if (ex !== def) throw ex;
  18138. return [ this ];
  18139. }
  18140. });
  18141. def(AST_Statement, function(){
  18142. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  18143. });
  18144. def(AST_Function, function(){
  18145. // XXX: AST_Function inherits from AST_Scope, which itself
  18146. // inherits from AST_Statement; however, an AST_Function
  18147. // isn't really a statement. This could byte in other
  18148. // places too. :-( Wish JS had multiple inheritance.
  18149. throw def;
  18150. });
  18151. function ev(node, compressor) {
  18152. if (!compressor) throw new Error("Compressor must be passed");
  18153. return node._eval(compressor);
  18154. };
  18155. def(AST_Node, function(){
  18156. throw def; // not constant
  18157. });
  18158. def(AST_Constant, function(){
  18159. return this.getValue();
  18160. });
  18161. def(AST_UnaryPrefix, function(compressor){
  18162. var e = this.expression;
  18163. switch (this.operator) {
  18164. case "!": return !ev(e, compressor);
  18165. case "typeof":
  18166. // Function would be evaluated to an array and so typeof would
  18167. // incorrectly return 'object'. Hence making is a special case.
  18168. if (e instanceof AST_Function) return typeof function(){};
  18169. e = ev(e, compressor);
  18170. // typeof <RegExp> returns "object" or "function" on different platforms
  18171. // so cannot evaluate reliably
  18172. if (e instanceof RegExp) throw def;
  18173. return typeof e;
  18174. case "void": return void ev(e, compressor);
  18175. case "~": return ~ev(e, compressor);
  18176. case "-":
  18177. e = ev(e, compressor);
  18178. if (e === 0) throw def;
  18179. return -e;
  18180. case "+": return +ev(e, compressor);
  18181. }
  18182. throw def;
  18183. });
  18184. def(AST_Binary, function(c){
  18185. var left = this.left, right = this.right;
  18186. switch (this.operator) {
  18187. case "&&" : return ev(left, c) && ev(right, c);
  18188. case "||" : return ev(left, c) || ev(right, c);
  18189. case "|" : return ev(left, c) | ev(right, c);
  18190. case "&" : return ev(left, c) & ev(right, c);
  18191. case "^" : return ev(left, c) ^ ev(right, c);
  18192. case "+" : return ev(left, c) + ev(right, c);
  18193. case "*" : return ev(left, c) * ev(right, c);
  18194. case "/" : return ev(left, c) / ev(right, c);
  18195. case "%" : return ev(left, c) % ev(right, c);
  18196. case "-" : return ev(left, c) - ev(right, c);
  18197. case "<<" : return ev(left, c) << ev(right, c);
  18198. case ">>" : return ev(left, c) >> ev(right, c);
  18199. case ">>>" : return ev(left, c) >>> ev(right, c);
  18200. case "==" : return ev(left, c) == ev(right, c);
  18201. case "===" : return ev(left, c) === ev(right, c);
  18202. case "!=" : return ev(left, c) != ev(right, c);
  18203. case "!==" : return ev(left, c) !== ev(right, c);
  18204. case "<" : return ev(left, c) < ev(right, c);
  18205. case "<=" : return ev(left, c) <= ev(right, c);
  18206. case ">" : return ev(left, c) > ev(right, c);
  18207. case ">=" : return ev(left, c) >= ev(right, c);
  18208. case "in" : return ev(left, c) in ev(right, c);
  18209. case "instanceof" : return ev(left, c) instanceof ev(right, c);
  18210. }
  18211. throw def;
  18212. });
  18213. def(AST_Conditional, function(compressor){
  18214. return ev(this.condition, compressor)
  18215. ? ev(this.consequent, compressor)
  18216. : ev(this.alternative, compressor);
  18217. });
  18218. def(AST_SymbolRef, function(compressor){
  18219. var d = this.definition();
  18220. if (d && d.constant && d.init) return ev(d.init, compressor);
  18221. throw def;
  18222. });
  18223. })(function(node, func){
  18224. node.DEFMETHOD("_eval", func);
  18225. });
  18226. // method to negate an expression
  18227. (function(def){
  18228. function basic_negation(exp) {
  18229. return make_node(AST_UnaryPrefix, exp, {
  18230. operator: "!",
  18231. expression: exp
  18232. });
  18233. };
  18234. def(AST_Node, function(){
  18235. return basic_negation(this);
  18236. });
  18237. def(AST_Statement, function(){
  18238. throw new Error("Cannot negate a statement");
  18239. });
  18240. def(AST_Function, function(){
  18241. return basic_negation(this);
  18242. });
  18243. def(AST_UnaryPrefix, function(){
  18244. if (this.operator == "!")
  18245. return this.expression;
  18246. return basic_negation(this);
  18247. });
  18248. def(AST_Seq, function(compressor){
  18249. var self = this.clone();
  18250. self.cdr = self.cdr.negate(compressor);
  18251. return self;
  18252. });
  18253. def(AST_Conditional, function(compressor){
  18254. var self = this.clone();
  18255. self.consequent = self.consequent.negate(compressor);
  18256. self.alternative = self.alternative.negate(compressor);
  18257. return best_of(basic_negation(this), self);
  18258. });
  18259. def(AST_Binary, function(compressor){
  18260. var self = this.clone(), op = this.operator;
  18261. if (compressor.option("unsafe_comps")) {
  18262. switch (op) {
  18263. case "<=" : self.operator = ">" ; return self;
  18264. case "<" : self.operator = ">=" ; return self;
  18265. case ">=" : self.operator = "<" ; return self;
  18266. case ">" : self.operator = "<=" ; return self;
  18267. }
  18268. }
  18269. switch (op) {
  18270. case "==" : self.operator = "!="; return self;
  18271. case "!=" : self.operator = "=="; return self;
  18272. case "===": self.operator = "!=="; return self;
  18273. case "!==": self.operator = "==="; return self;
  18274. case "&&":
  18275. self.operator = "||";
  18276. self.left = self.left.negate(compressor);
  18277. self.right = self.right.negate(compressor);
  18278. return best_of(basic_negation(this), self);
  18279. case "||":
  18280. self.operator = "&&";
  18281. self.left = self.left.negate(compressor);
  18282. self.right = self.right.negate(compressor);
  18283. return best_of(basic_negation(this), self);
  18284. }
  18285. return basic_negation(this);
  18286. });
  18287. })(function(node, func){
  18288. node.DEFMETHOD("negate", function(compressor){
  18289. return func.call(this, compressor);
  18290. });
  18291. });
  18292. // determine if expression has side effects
  18293. (function(def){
  18294. def(AST_Node, function(compressor){ return true });
  18295. def(AST_EmptyStatement, function(compressor){ return false });
  18296. def(AST_Constant, function(compressor){ return false });
  18297. def(AST_This, function(compressor){ return false });
  18298. def(AST_Call, function(compressor){
  18299. var pure = compressor.option("pure_funcs");
  18300. if (!pure) return true;
  18301. return pure.indexOf(this.expression.print_to_string()) < 0;
  18302. });
  18303. def(AST_Block, function(compressor){
  18304. for (var i = this.body.length; --i >= 0;) {
  18305. if (this.body[i].has_side_effects(compressor))
  18306. return true;
  18307. }
  18308. return false;
  18309. });
  18310. def(AST_SimpleStatement, function(compressor){
  18311. return this.body.has_side_effects(compressor);
  18312. });
  18313. def(AST_Defun, function(compressor){ return true });
  18314. def(AST_Function, function(compressor){ return false });
  18315. def(AST_Binary, function(compressor){
  18316. return this.left.has_side_effects(compressor)
  18317. || this.right.has_side_effects(compressor);
  18318. });
  18319. def(AST_Assign, function(compressor){ return true });
  18320. def(AST_Conditional, function(compressor){
  18321. return this.condition.has_side_effects(compressor)
  18322. || this.consequent.has_side_effects(compressor)
  18323. || this.alternative.has_side_effects(compressor);
  18324. });
  18325. def(AST_Unary, function(compressor){
  18326. return this.operator == "delete"
  18327. || this.operator == "++"
  18328. || this.operator == "--"
  18329. || this.expression.has_side_effects(compressor);
  18330. });
  18331. def(AST_SymbolRef, function(compressor){ return false });
  18332. def(AST_Object, function(compressor){
  18333. for (var i = this.properties.length; --i >= 0;)
  18334. if (this.properties[i].has_side_effects(compressor))
  18335. return true;
  18336. return false;
  18337. });
  18338. def(AST_ObjectProperty, function(compressor){
  18339. return this.value.has_side_effects(compressor);
  18340. });
  18341. def(AST_Array, function(compressor){
  18342. for (var i = this.elements.length; --i >= 0;)
  18343. if (this.elements[i].has_side_effects(compressor))
  18344. return true;
  18345. return false;
  18346. });
  18347. def(AST_Dot, function(compressor){
  18348. if (!compressor.option("pure_getters")) return true;
  18349. return this.expression.has_side_effects(compressor);
  18350. });
  18351. def(AST_Sub, function(compressor){
  18352. if (!compressor.option("pure_getters")) return true;
  18353. return this.expression.has_side_effects(compressor)
  18354. || this.property.has_side_effects(compressor);
  18355. });
  18356. def(AST_PropAccess, function(compressor){
  18357. return !compressor.option("pure_getters");
  18358. });
  18359. def(AST_Seq, function(compressor){
  18360. return this.car.has_side_effects(compressor)
  18361. || this.cdr.has_side_effects(compressor);
  18362. });
  18363. })(function(node, func){
  18364. node.DEFMETHOD("has_side_effects", func);
  18365. });
  18366. // tell me if a statement aborts
  18367. function aborts(thing) {
  18368. return thing && thing.aborts();
  18369. };
  18370. (function(def){
  18371. def(AST_Statement, function(){ return null });
  18372. def(AST_Jump, function(){ return this });
  18373. function block_aborts(){
  18374. var n = this.body.length;
  18375. return n > 0 && aborts(this.body[n - 1]);
  18376. };
  18377. def(AST_BlockStatement, block_aborts);
  18378. def(AST_SwitchBranch, block_aborts);
  18379. def(AST_If, function(){
  18380. return this.alternative && aborts(this.body) && aborts(this.alternative);
  18381. });
  18382. })(function(node, func){
  18383. node.DEFMETHOD("aborts", func);
  18384. });
  18385. /* -----[ optimizers ]----- */
  18386. OPT(AST_Directive, function(self, compressor){
  18387. if (self.scope.has_directive(self.value) !== self.scope) {
  18388. return make_node(AST_EmptyStatement, self);
  18389. }
  18390. return self;
  18391. });
  18392. OPT(AST_Debugger, function(self, compressor){
  18393. if (compressor.option("drop_debugger"))
  18394. return make_node(AST_EmptyStatement, self);
  18395. return self;
  18396. });
  18397. OPT(AST_LabeledStatement, function(self, compressor){
  18398. if (self.body instanceof AST_Break
  18399. && compressor.loopcontrol_target(self.body.label) === self.body) {
  18400. return make_node(AST_EmptyStatement, self);
  18401. }
  18402. return self.label.references.length == 0 ? self.body : self;
  18403. });
  18404. OPT(AST_Block, function(self, compressor){
  18405. self.body = tighten_body(self.body, compressor);
  18406. return self;
  18407. });
  18408. OPT(AST_BlockStatement, function(self, compressor){
  18409. self.body = tighten_body(self.body, compressor);
  18410. switch (self.body.length) {
  18411. case 1: return self.body[0];
  18412. case 0: return make_node(AST_EmptyStatement, self);
  18413. }
  18414. return self;
  18415. });
  18416. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  18417. var self = this;
  18418. if (compressor.option("unused")
  18419. && !(self instanceof AST_Toplevel)
  18420. && !self.uses_eval
  18421. ) {
  18422. var in_use = [];
  18423. var initializations = new Dictionary();
  18424. // pass 1: find out which symbols are directly used in
  18425. // this scope (not in nested scopes).
  18426. var scope = this;
  18427. var tw = new TreeWalker(function(node, descend){
  18428. if (node !== self) {
  18429. if (node instanceof AST_Defun) {
  18430. initializations.add(node.name.name, node);
  18431. return true; // don't go in nested scopes
  18432. }
  18433. if (node instanceof AST_Definitions && scope === self) {
  18434. node.definitions.forEach(function(def){
  18435. if (def.value) {
  18436. initializations.add(def.name.name, def.value);
  18437. if (def.value.has_side_effects(compressor)) {
  18438. def.value.walk(tw);
  18439. }
  18440. }
  18441. });
  18442. return true;
  18443. }
  18444. if (node instanceof AST_SymbolRef) {
  18445. push_uniq(in_use, node.definition());
  18446. return true;
  18447. }
  18448. if (node instanceof AST_Scope) {
  18449. var save_scope = scope;
  18450. scope = node;
  18451. descend();
  18452. scope = save_scope;
  18453. return true;
  18454. }
  18455. }
  18456. });
  18457. self.walk(tw);
  18458. // pass 2: for every used symbol we need to walk its
  18459. // initialization code to figure out if it uses other
  18460. // symbols (that may not be in_use).
  18461. for (var i = 0; i < in_use.length; ++i) {
  18462. in_use[i].orig.forEach(function(decl){
  18463. // undeclared globals will be instanceof AST_SymbolRef
  18464. var init = initializations.get(decl.name);
  18465. if (init) init.forEach(function(init){
  18466. var tw = new TreeWalker(function(node){
  18467. if (node instanceof AST_SymbolRef) {
  18468. push_uniq(in_use, node.definition());
  18469. }
  18470. });
  18471. init.walk(tw);
  18472. });
  18473. });
  18474. }
  18475. // pass 3: we should drop declarations not in_use
  18476. var tt = new TreeTransformer(
  18477. function before(node, descend, in_list) {
  18478. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  18479. if (!compressor.option("keep_fargs")) {
  18480. for (var a = node.argnames, i = a.length; --i >= 0;) {
  18481. var sym = a[i];
  18482. if (sym.unreferenced()) {
  18483. a.pop();
  18484. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  18485. name : sym.name,
  18486. file : sym.start.file,
  18487. line : sym.start.line,
  18488. col : sym.start.col
  18489. });
  18490. }
  18491. else break;
  18492. }
  18493. }
  18494. }
  18495. if (node instanceof AST_Defun && node !== self) {
  18496. if (!member(node.name.definition(), in_use)) {
  18497. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  18498. name : node.name.name,
  18499. file : node.name.start.file,
  18500. line : node.name.start.line,
  18501. col : node.name.start.col
  18502. });
  18503. return make_node(AST_EmptyStatement, node);
  18504. }
  18505. return node;
  18506. }
  18507. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  18508. var def = node.definitions.filter(function(def){
  18509. if (member(def.name.definition(), in_use)) return true;
  18510. var w = {
  18511. name : def.name.name,
  18512. file : def.name.start.file,
  18513. line : def.name.start.line,
  18514. col : def.name.start.col
  18515. };
  18516. if (def.value && def.value.has_side_effects(compressor)) {
  18517. def._unused_side_effects = true;
  18518. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  18519. return true;
  18520. }
  18521. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  18522. return false;
  18523. });
  18524. // place uninitialized names at the start
  18525. def = mergeSort(def, function(a, b){
  18526. if (!a.value && b.value) return -1;
  18527. if (!b.value && a.value) return 1;
  18528. return 0;
  18529. });
  18530. // for unused names whose initialization has
  18531. // side effects, we can cascade the init. code
  18532. // into the next one, or next statement.
  18533. var side_effects = [];
  18534. for (var i = 0; i < def.length;) {
  18535. var x = def[i];
  18536. if (x._unused_side_effects) {
  18537. side_effects.push(x.value);
  18538. def.splice(i, 1);
  18539. } else {
  18540. if (side_effects.length > 0) {
  18541. side_effects.push(x.value);
  18542. x.value = AST_Seq.from_array(side_effects);
  18543. side_effects = [];
  18544. }
  18545. ++i;
  18546. }
  18547. }
  18548. if (side_effects.length > 0) {
  18549. side_effects = make_node(AST_BlockStatement, node, {
  18550. body: [ make_node(AST_SimpleStatement, node, {
  18551. body: AST_Seq.from_array(side_effects)
  18552. }) ]
  18553. });
  18554. } else {
  18555. side_effects = null;
  18556. }
  18557. if (def.length == 0 && !side_effects) {
  18558. return make_node(AST_EmptyStatement, node);
  18559. }
  18560. if (def.length == 0) {
  18561. return side_effects;
  18562. }
  18563. node.definitions = def;
  18564. if (side_effects) {
  18565. side_effects.body.unshift(node);
  18566. node = side_effects;
  18567. }
  18568. return node;
  18569. }
  18570. if (node instanceof AST_For) {
  18571. descend(node, this);
  18572. if (node.init instanceof AST_BlockStatement) {
  18573. // certain combination of unused name + side effect leads to:
  18574. // https://github.com/mishoo/UglifyJS2/issues/44
  18575. // that's an invalid AST.
  18576. // We fix it at this stage by moving the `var` outside the `for`.
  18577. var body = node.init.body.slice(0, -1);
  18578. node.init = node.init.body.slice(-1)[0].body;
  18579. body.push(node);
  18580. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  18581. body: body
  18582. });
  18583. }
  18584. }
  18585. if (node instanceof AST_Scope && node !== self)
  18586. return node;
  18587. }
  18588. );
  18589. self.transform(tt);
  18590. }
  18591. });
  18592. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  18593. var hoist_funs = compressor.option("hoist_funs");
  18594. var hoist_vars = compressor.option("hoist_vars");
  18595. var self = this;
  18596. if (hoist_funs || hoist_vars) {
  18597. var dirs = [];
  18598. var hoisted = [];
  18599. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  18600. // let's count var_decl first, we seem to waste a lot of
  18601. // space if we hoist `var` when there's only one.
  18602. self.walk(new TreeWalker(function(node){
  18603. if (node instanceof AST_Scope && node !== self)
  18604. return true;
  18605. if (node instanceof AST_Var) {
  18606. ++var_decl;
  18607. return true;
  18608. }
  18609. }));
  18610. hoist_vars = hoist_vars && var_decl > 1;
  18611. var tt = new TreeTransformer(
  18612. function before(node) {
  18613. if (node !== self) {
  18614. if (node instanceof AST_Directive) {
  18615. dirs.push(node);
  18616. return make_node(AST_EmptyStatement, node);
  18617. }
  18618. if (node instanceof AST_Defun && hoist_funs) {
  18619. hoisted.push(node);
  18620. return make_node(AST_EmptyStatement, node);
  18621. }
  18622. if (node instanceof AST_Var && hoist_vars) {
  18623. node.definitions.forEach(function(def){
  18624. vars.set(def.name.name, def);
  18625. ++vars_found;
  18626. });
  18627. var seq = node.to_assignments();
  18628. var p = tt.parent();
  18629. if (p instanceof AST_ForIn && p.init === node) {
  18630. if (seq == null) return node.definitions[0].name;
  18631. return seq;
  18632. }
  18633. if (p instanceof AST_For && p.init === node) {
  18634. return seq;
  18635. }
  18636. if (!seq) return make_node(AST_EmptyStatement, node);
  18637. return make_node(AST_SimpleStatement, node, {
  18638. body: seq
  18639. });
  18640. }
  18641. if (node instanceof AST_Scope)
  18642. return node; // to avoid descending in nested scopes
  18643. }
  18644. }
  18645. );
  18646. self = self.transform(tt);
  18647. if (vars_found > 0) {
  18648. // collect only vars which don't show up in self's arguments list
  18649. var defs = [];
  18650. vars.each(function(def, name){
  18651. if (self instanceof AST_Lambda
  18652. && find_if(function(x){ return x.name == def.name.name },
  18653. self.argnames)) {
  18654. vars.del(name);
  18655. } else {
  18656. def = def.clone();
  18657. def.value = null;
  18658. defs.push(def);
  18659. vars.set(name, def);
  18660. }
  18661. });
  18662. if (defs.length > 0) {
  18663. // try to merge in assignments
  18664. for (var i = 0; i < self.body.length;) {
  18665. if (self.body[i] instanceof AST_SimpleStatement) {
  18666. var expr = self.body[i].body, sym, assign;
  18667. if (expr instanceof AST_Assign
  18668. && expr.operator == "="
  18669. && (sym = expr.left) instanceof AST_Symbol
  18670. && vars.has(sym.name))
  18671. {
  18672. var def = vars.get(sym.name);
  18673. if (def.value) break;
  18674. def.value = expr.right;
  18675. remove(defs, def);
  18676. defs.push(def);
  18677. self.body.splice(i, 1);
  18678. continue;
  18679. }
  18680. if (expr instanceof AST_Seq
  18681. && (assign = expr.car) instanceof AST_Assign
  18682. && assign.operator == "="
  18683. && (sym = assign.left) instanceof AST_Symbol
  18684. && vars.has(sym.name))
  18685. {
  18686. var def = vars.get(sym.name);
  18687. if (def.value) break;
  18688. def.value = assign.right;
  18689. remove(defs, def);
  18690. defs.push(def);
  18691. self.body[i].body = expr.cdr;
  18692. continue;
  18693. }
  18694. }
  18695. if (self.body[i] instanceof AST_EmptyStatement) {
  18696. self.body.splice(i, 1);
  18697. continue;
  18698. }
  18699. if (self.body[i] instanceof AST_BlockStatement) {
  18700. var tmp = [ i, 1 ].concat(self.body[i].body);
  18701. self.body.splice.apply(self.body, tmp);
  18702. continue;
  18703. }
  18704. break;
  18705. }
  18706. defs = make_node(AST_Var, self, {
  18707. definitions: defs
  18708. });
  18709. hoisted.push(defs);
  18710. };
  18711. }
  18712. self.body = dirs.concat(hoisted, self.body);
  18713. }
  18714. return self;
  18715. });
  18716. OPT(AST_SimpleStatement, function(self, compressor){
  18717. if (compressor.option("side_effects")) {
  18718. if (!self.body.has_side_effects(compressor)) {
  18719. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  18720. return make_node(AST_EmptyStatement, self);
  18721. }
  18722. }
  18723. return self;
  18724. });
  18725. OPT(AST_DWLoop, function(self, compressor){
  18726. var cond = self.condition.evaluate(compressor);
  18727. self.condition = cond[0];
  18728. if (!compressor.option("loops")) return self;
  18729. if (cond.length > 1) {
  18730. if (cond[1]) {
  18731. return make_node(AST_For, self, {
  18732. body: self.body
  18733. });
  18734. } else if (self instanceof AST_While) {
  18735. if (compressor.option("dead_code")) {
  18736. var a = [];
  18737. extract_declarations_from_unreachable_code(compressor, self.body, a);
  18738. return make_node(AST_BlockStatement, self, { body: a });
  18739. }
  18740. }
  18741. }
  18742. return self;
  18743. });
  18744. function if_break_in_loop(self, compressor) {
  18745. function drop_it(rest) {
  18746. rest = as_statement_array(rest);
  18747. if (self.body instanceof AST_BlockStatement) {
  18748. self.body = self.body.clone();
  18749. self.body.body = rest.concat(self.body.body.slice(1));
  18750. self.body = self.body.transform(compressor);
  18751. } else {
  18752. self.body = make_node(AST_BlockStatement, self.body, {
  18753. body: rest
  18754. }).transform(compressor);
  18755. }
  18756. if_break_in_loop(self, compressor);
  18757. }
  18758. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  18759. if (first instanceof AST_If) {
  18760. if (first.body instanceof AST_Break
  18761. && compressor.loopcontrol_target(first.body.label) === self) {
  18762. if (self.condition) {
  18763. self.condition = make_node(AST_Binary, self.condition, {
  18764. left: self.condition,
  18765. operator: "&&",
  18766. right: first.condition.negate(compressor),
  18767. });
  18768. } else {
  18769. self.condition = first.condition.negate(compressor);
  18770. }
  18771. drop_it(first.alternative);
  18772. }
  18773. else if (first.alternative instanceof AST_Break
  18774. && compressor.loopcontrol_target(first.alternative.label) === self) {
  18775. if (self.condition) {
  18776. self.condition = make_node(AST_Binary, self.condition, {
  18777. left: self.condition,
  18778. operator: "&&",
  18779. right: first.condition,
  18780. });
  18781. } else {
  18782. self.condition = first.condition;
  18783. }
  18784. drop_it(first.body);
  18785. }
  18786. }
  18787. };
  18788. OPT(AST_While, function(self, compressor) {
  18789. if (!compressor.option("loops")) return self;
  18790. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  18791. if (self instanceof AST_While) {
  18792. if_break_in_loop(self, compressor);
  18793. self = make_node(AST_For, self, self).transform(compressor);
  18794. }
  18795. return self;
  18796. });
  18797. OPT(AST_For, function(self, compressor){
  18798. var cond = self.condition;
  18799. if (cond) {
  18800. cond = cond.evaluate(compressor);
  18801. self.condition = cond[0];
  18802. }
  18803. if (!compressor.option("loops")) return self;
  18804. if (cond) {
  18805. if (cond.length > 1 && !cond[1]) {
  18806. if (compressor.option("dead_code")) {
  18807. var a = [];
  18808. if (self.init instanceof AST_Statement) {
  18809. a.push(self.init);
  18810. }
  18811. else if (self.init) {
  18812. a.push(make_node(AST_SimpleStatement, self.init, {
  18813. body: self.init
  18814. }));
  18815. }
  18816. extract_declarations_from_unreachable_code(compressor, self.body, a);
  18817. return make_node(AST_BlockStatement, self, { body: a });
  18818. }
  18819. }
  18820. }
  18821. if_break_in_loop(self, compressor);
  18822. return self;
  18823. });
  18824. OPT(AST_If, function(self, compressor){
  18825. if (!compressor.option("conditionals")) return self;
  18826. // if condition can be statically determined, warn and drop
  18827. // one of the blocks. note, statically determined implies
  18828. // “has no side effects”; also it doesn't work for cases like
  18829. // `x && true`, though it probably should.
  18830. var cond = self.condition.evaluate(compressor);
  18831. self.condition = cond[0];
  18832. if (cond.length > 1) {
  18833. if (cond[1]) {
  18834. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  18835. if (compressor.option("dead_code")) {
  18836. var a = [];
  18837. if (self.alternative) {
  18838. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  18839. }
  18840. a.push(self.body);
  18841. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  18842. }
  18843. } else {
  18844. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  18845. if (compressor.option("dead_code")) {
  18846. var a = [];
  18847. extract_declarations_from_unreachable_code(compressor, self.body, a);
  18848. if (self.alternative) a.push(self.alternative);
  18849. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  18850. }
  18851. }
  18852. }
  18853. if (is_empty(self.alternative)) self.alternative = null;
  18854. var negated = self.condition.negate(compressor);
  18855. var negated_is_best = best_of(self.condition, negated) === negated;
  18856. if (self.alternative && negated_is_best) {
  18857. negated_is_best = false; // because we already do the switch here.
  18858. self.condition = negated;
  18859. var tmp = self.body;
  18860. self.body = self.alternative || make_node(AST_EmptyStatement);
  18861. self.alternative = tmp;
  18862. }
  18863. if (is_empty(self.body) && is_empty(self.alternative)) {
  18864. return make_node(AST_SimpleStatement, self.condition, {
  18865. body: self.condition
  18866. }).transform(compressor);
  18867. }
  18868. if (self.body instanceof AST_SimpleStatement
  18869. && self.alternative instanceof AST_SimpleStatement) {
  18870. return make_node(AST_SimpleStatement, self, {
  18871. body: make_node(AST_Conditional, self, {
  18872. condition : self.condition,
  18873. consequent : self.body.body,
  18874. alternative : self.alternative.body
  18875. })
  18876. }).transform(compressor);
  18877. }
  18878. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  18879. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  18880. body: make_node(AST_Binary, self, {
  18881. operator : "||",
  18882. left : negated,
  18883. right : self.body.body
  18884. })
  18885. }).transform(compressor);
  18886. return make_node(AST_SimpleStatement, self, {
  18887. body: make_node(AST_Binary, self, {
  18888. operator : "&&",
  18889. left : self.condition,
  18890. right : self.body.body
  18891. })
  18892. }).transform(compressor);
  18893. }
  18894. if (self.body instanceof AST_EmptyStatement
  18895. && self.alternative
  18896. && self.alternative instanceof AST_SimpleStatement) {
  18897. return make_node(AST_SimpleStatement, self, {
  18898. body: make_node(AST_Binary, self, {
  18899. operator : "||",
  18900. left : self.condition,
  18901. right : self.alternative.body
  18902. })
  18903. }).transform(compressor);
  18904. }
  18905. if (self.body instanceof AST_Exit
  18906. && self.alternative instanceof AST_Exit
  18907. && self.body.TYPE == self.alternative.TYPE) {
  18908. return make_node(self.body.CTOR, self, {
  18909. value: make_node(AST_Conditional, self, {
  18910. condition : self.condition,
  18911. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  18912. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  18913. })
  18914. }).transform(compressor);
  18915. }
  18916. if (self.body instanceof AST_If
  18917. && !self.body.alternative
  18918. && !self.alternative) {
  18919. self.condition = make_node(AST_Binary, self.condition, {
  18920. operator: "&&",
  18921. left: self.condition,
  18922. right: self.body.condition
  18923. }).transform(compressor);
  18924. self.body = self.body.body;
  18925. }
  18926. if (aborts(self.body)) {
  18927. if (self.alternative) {
  18928. var alt = self.alternative;
  18929. self.alternative = null;
  18930. return make_node(AST_BlockStatement, self, {
  18931. body: [ self, alt ]
  18932. }).transform(compressor);
  18933. }
  18934. }
  18935. if (aborts(self.alternative)) {
  18936. var body = self.body;
  18937. self.body = self.alternative;
  18938. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  18939. self.alternative = null;
  18940. return make_node(AST_BlockStatement, self, {
  18941. body: [ self, body ]
  18942. }).transform(compressor);
  18943. }
  18944. return self;
  18945. });
  18946. OPT(AST_Switch, function(self, compressor){
  18947. if (self.body.length == 0 && compressor.option("conditionals")) {
  18948. return make_node(AST_SimpleStatement, self, {
  18949. body: self.expression
  18950. }).transform(compressor);
  18951. }
  18952. for(;;) {
  18953. var last_branch = self.body[self.body.length - 1];
  18954. if (last_branch) {
  18955. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  18956. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  18957. last_branch.body.pop();
  18958. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  18959. self.body.pop();
  18960. continue;
  18961. }
  18962. }
  18963. break;
  18964. }
  18965. var exp = self.expression.evaluate(compressor);
  18966. out: if (exp.length == 2) try {
  18967. // constant expression
  18968. self.expression = exp[0];
  18969. if (!compressor.option("dead_code")) break out;
  18970. var value = exp[1];
  18971. var in_if = false;
  18972. var in_block = false;
  18973. var started = false;
  18974. var stopped = false;
  18975. var ruined = false;
  18976. var tt = new TreeTransformer(function(node, descend, in_list){
  18977. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  18978. // no need to descend these node types
  18979. return node;
  18980. }
  18981. else if (node instanceof AST_Switch && node === self) {
  18982. node = node.clone();
  18983. descend(node, this);
  18984. return ruined ? node : make_node(AST_BlockStatement, node, {
  18985. body: node.body.reduce(function(a, branch){
  18986. return a.concat(branch.body);
  18987. }, [])
  18988. }).transform(compressor);
  18989. }
  18990. else if (node instanceof AST_If || node instanceof AST_Try) {
  18991. var save = in_if;
  18992. in_if = !in_block;
  18993. descend(node, this);
  18994. in_if = save;
  18995. return node;
  18996. }
  18997. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  18998. var save = in_block;
  18999. in_block = true;
  19000. descend(node, this);
  19001. in_block = save;
  19002. return node;
  19003. }
  19004. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  19005. if (in_if) {
  19006. ruined = true;
  19007. return node;
  19008. }
  19009. if (in_block) return node;
  19010. stopped = true;
  19011. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  19012. }
  19013. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  19014. if (stopped) return MAP.skip;
  19015. if (node instanceof AST_Case) {
  19016. var exp = node.expression.evaluate(compressor);
  19017. if (exp.length < 2) {
  19018. // got a case with non-constant expression, baling out
  19019. throw self;
  19020. }
  19021. if (exp[1] === value || started) {
  19022. started = true;
  19023. if (aborts(node)) stopped = true;
  19024. descend(node, this);
  19025. return node;
  19026. }
  19027. return MAP.skip;
  19028. }
  19029. descend(node, this);
  19030. return node;
  19031. }
  19032. });
  19033. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  19034. self = self.transform(tt);
  19035. } catch(ex) {
  19036. if (ex !== self) throw ex;
  19037. }
  19038. return self;
  19039. });
  19040. OPT(AST_Case, function(self, compressor){
  19041. self.body = tighten_body(self.body, compressor);
  19042. return self;
  19043. });
  19044. OPT(AST_Try, function(self, compressor){
  19045. self.body = tighten_body(self.body, compressor);
  19046. return self;
  19047. });
  19048. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  19049. this.definitions.forEach(function(def){ def.value = null });
  19050. });
  19051. AST_Definitions.DEFMETHOD("to_assignments", function(){
  19052. var assignments = this.definitions.reduce(function(a, def){
  19053. if (def.value) {
  19054. var name = make_node(AST_SymbolRef, def.name, def.name);
  19055. a.push(make_node(AST_Assign, def, {
  19056. operator : "=",
  19057. left : name,
  19058. right : def.value
  19059. }));
  19060. }
  19061. return a;
  19062. }, []);
  19063. if (assignments.length == 0) return null;
  19064. return AST_Seq.from_array(assignments);
  19065. });
  19066. OPT(AST_Definitions, function(self, compressor){
  19067. if (self.definitions.length == 0)
  19068. return make_node(AST_EmptyStatement, self);
  19069. return self;
  19070. });
  19071. OPT(AST_Function, function(self, compressor){
  19072. self = AST_Lambda.prototype.optimize.call(self, compressor);
  19073. if (compressor.option("unused")) {
  19074. if (self.name && self.name.unreferenced()) {
  19075. self.name = null;
  19076. }
  19077. }
  19078. return self;
  19079. });
  19080. OPT(AST_Call, function(self, compressor){
  19081. if (compressor.option("unsafe")) {
  19082. var exp = self.expression;
  19083. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  19084. switch (exp.name) {
  19085. case "Array":
  19086. if (self.args.length != 1) {
  19087. return make_node(AST_Array, self, {
  19088. elements: self.args
  19089. }).transform(compressor);
  19090. }
  19091. break;
  19092. case "Object":
  19093. if (self.args.length == 0) {
  19094. return make_node(AST_Object, self, {
  19095. properties: []
  19096. });
  19097. }
  19098. break;
  19099. case "String":
  19100. if (self.args.length == 0) return make_node(AST_String, self, {
  19101. value: ""
  19102. });
  19103. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  19104. left: self.args[0],
  19105. operator: "+",
  19106. right: make_node(AST_String, self, { value: "" })
  19107. }).transform(compressor);
  19108. break;
  19109. case "Number":
  19110. if (self.args.length == 0) return make_node(AST_Number, self, {
  19111. value: 0
  19112. });
  19113. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  19114. expression: self.args[0],
  19115. operator: "+"
  19116. }).transform(compressor);
  19117. case "Boolean":
  19118. if (self.args.length == 0) return make_node(AST_False, self);
  19119. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  19120. expression: make_node(AST_UnaryPrefix, null, {
  19121. expression: self.args[0],
  19122. operator: "!"
  19123. }),
  19124. operator: "!"
  19125. }).transform(compressor);
  19126. break;
  19127. case "Function":
  19128. if (all(self.args, function(x){ return x instanceof AST_String })) {
  19129. // quite a corner-case, but we can handle it:
  19130. // https://github.com/mishoo/UglifyJS2/issues/203
  19131. // if the code argument is a constant, then we can minify it.
  19132. try {
  19133. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  19134. return arg.value;
  19135. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  19136. var ast = parse(code);
  19137. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  19138. var comp = new Compressor(compressor.options);
  19139. ast = ast.transform(comp);
  19140. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  19141. ast.mangle_names();
  19142. var fun;
  19143. try {
  19144. ast.walk(new TreeWalker(function(node){
  19145. if (node instanceof AST_Lambda) {
  19146. fun = node;
  19147. throw ast;
  19148. }
  19149. }));
  19150. } catch(ex) {
  19151. if (ex !== ast) throw ex;
  19152. };
  19153. var args = fun.argnames.map(function(arg, i){
  19154. return make_node(AST_String, self.args[i], {
  19155. value: arg.print_to_string()
  19156. });
  19157. });
  19158. var code = OutputStream();
  19159. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  19160. code = code.toString().replace(/^\{|\}$/g, "");
  19161. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  19162. value: code
  19163. }));
  19164. self.args = args;
  19165. return self;
  19166. } catch(ex) {
  19167. if (ex instanceof JS_Parse_Error) {
  19168. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  19169. compressor.warn(ex.toString());
  19170. } else {
  19171. console.log(ex);
  19172. throw ex;
  19173. }
  19174. }
  19175. }
  19176. break;
  19177. }
  19178. }
  19179. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  19180. return make_node(AST_Binary, self, {
  19181. left: make_node(AST_String, self, { value: "" }),
  19182. operator: "+",
  19183. right: exp.expression
  19184. }).transform(compressor);
  19185. }
  19186. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  19187. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  19188. if (separator == null) break EXIT; // not a constant
  19189. var elements = exp.expression.elements.reduce(function(a, el){
  19190. el = el.evaluate(compressor);
  19191. if (a.length == 0 || el.length == 1) {
  19192. a.push(el);
  19193. } else {
  19194. var last = a[a.length - 1];
  19195. if (last.length == 2) {
  19196. // it's a constant
  19197. var val = "" + last[1] + separator + el[1];
  19198. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  19199. } else {
  19200. a.push(el);
  19201. }
  19202. }
  19203. return a;
  19204. }, []);
  19205. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  19206. if (elements.length == 1) return elements[0][0];
  19207. if (separator == "") {
  19208. var first;
  19209. if (elements[0][0] instanceof AST_String
  19210. || elements[1][0] instanceof AST_String) {
  19211. first = elements.shift()[0];
  19212. } else {
  19213. first = make_node(AST_String, self, { value: "" });
  19214. }
  19215. return elements.reduce(function(prev, el){
  19216. return make_node(AST_Binary, el[0], {
  19217. operator : "+",
  19218. left : prev,
  19219. right : el[0],
  19220. });
  19221. }, first).transform(compressor);
  19222. }
  19223. // need this awkward cloning to not affect original element
  19224. // best_of will decide which one to get through.
  19225. var node = self.clone();
  19226. node.expression = node.expression.clone();
  19227. node.expression.expression = node.expression.expression.clone();
  19228. node.expression.expression.elements = elements.map(function(el){
  19229. return el[0];
  19230. });
  19231. return best_of(self, node);
  19232. }
  19233. }
  19234. if (compressor.option("side_effects")) {
  19235. if (self.expression instanceof AST_Function
  19236. && self.args.length == 0
  19237. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  19238. return make_node(AST_Undefined, self).transform(compressor);
  19239. }
  19240. }
  19241. if (compressor.option("drop_console")) {
  19242. if (self.expression instanceof AST_PropAccess &&
  19243. self.expression.expression instanceof AST_SymbolRef &&
  19244. self.expression.expression.name == "console" &&
  19245. self.expression.expression.undeclared()) {
  19246. return make_node(AST_Undefined, self).transform(compressor);
  19247. }
  19248. }
  19249. return self.evaluate(compressor)[0];
  19250. });
  19251. OPT(AST_New, function(self, compressor){
  19252. if (compressor.option("unsafe")) {
  19253. var exp = self.expression;
  19254. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  19255. switch (exp.name) {
  19256. case "Object":
  19257. case "RegExp":
  19258. case "Function":
  19259. case "Error":
  19260. case "Array":
  19261. return make_node(AST_Call, self, self).transform(compressor);
  19262. }
  19263. }
  19264. }
  19265. return self;
  19266. });
  19267. OPT(AST_Seq, function(self, compressor){
  19268. if (!compressor.option("side_effects"))
  19269. return self;
  19270. if (!self.car.has_side_effects(compressor)) {
  19271. // we shouldn't compress (1,eval)(something) to
  19272. // eval(something) because that changes the meaning of
  19273. // eval (becomes lexical instead of global).
  19274. var p;
  19275. if (!(self.cdr instanceof AST_SymbolRef
  19276. && self.cdr.name == "eval"
  19277. && self.cdr.undeclared()
  19278. && (p = compressor.parent()) instanceof AST_Call
  19279. && p.expression === self)) {
  19280. return self.cdr;
  19281. }
  19282. }
  19283. if (compressor.option("cascade")) {
  19284. if (self.car instanceof AST_Assign
  19285. && !self.car.left.has_side_effects(compressor)) {
  19286. if (self.car.left.equivalent_to(self.cdr)) {
  19287. return self.car;
  19288. }
  19289. if (self.cdr instanceof AST_Call
  19290. && self.cdr.expression.equivalent_to(self.car.left)) {
  19291. self.cdr.expression = self.car;
  19292. return self.cdr;
  19293. }
  19294. }
  19295. if (!self.car.has_side_effects(compressor)
  19296. && !self.cdr.has_side_effects(compressor)
  19297. && self.car.equivalent_to(self.cdr)) {
  19298. return self.car;
  19299. }
  19300. }
  19301. if (self.cdr instanceof AST_UnaryPrefix
  19302. && self.cdr.operator == "void"
  19303. && !self.cdr.expression.has_side_effects(compressor)) {
  19304. self.cdr.operator = self.car;
  19305. return self.cdr;
  19306. }
  19307. if (self.cdr instanceof AST_Undefined) {
  19308. return make_node(AST_UnaryPrefix, self, {
  19309. operator : "void",
  19310. expression : self.car
  19311. });
  19312. }
  19313. return self;
  19314. });
  19315. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  19316. if (compressor.option("sequences")) {
  19317. if (this.expression instanceof AST_Seq) {
  19318. var seq = this.expression;
  19319. var x = seq.to_array();
  19320. this.expression = x.pop();
  19321. x.push(this);
  19322. seq = AST_Seq.from_array(x).transform(compressor);
  19323. return seq;
  19324. }
  19325. }
  19326. return this;
  19327. });
  19328. OPT(AST_UnaryPostfix, function(self, compressor){
  19329. return self.lift_sequences(compressor);
  19330. });
  19331. OPT(AST_UnaryPrefix, function(self, compressor){
  19332. self = self.lift_sequences(compressor);
  19333. var e = self.expression;
  19334. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  19335. switch (self.operator) {
  19336. case "!":
  19337. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  19338. // !!foo ==> foo, if we're in boolean context
  19339. return e.expression;
  19340. }
  19341. break;
  19342. case "typeof":
  19343. // typeof always returns a non-empty string, thus it's
  19344. // always true in booleans
  19345. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  19346. return make_node(AST_True, self);
  19347. }
  19348. if (e instanceof AST_Binary && self.operator == "!") {
  19349. self = best_of(self, e.negate(compressor));
  19350. }
  19351. }
  19352. return self.evaluate(compressor)[0];
  19353. });
  19354. function has_side_effects_or_prop_access(node, compressor) {
  19355. var save_pure_getters = compressor.option("pure_getters");
  19356. compressor.options.pure_getters = false;
  19357. var ret = node.has_side_effects(compressor);
  19358. compressor.options.pure_getters = save_pure_getters;
  19359. return ret;
  19360. }
  19361. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  19362. if (compressor.option("sequences")) {
  19363. if (this.left instanceof AST_Seq) {
  19364. var seq = this.left;
  19365. var x = seq.to_array();
  19366. this.left = x.pop();
  19367. x.push(this);
  19368. seq = AST_Seq.from_array(x).transform(compressor);
  19369. return seq;
  19370. }
  19371. if (this.right instanceof AST_Seq
  19372. && this instanceof AST_Assign
  19373. && !has_side_effects_or_prop_access(this.left, compressor)) {
  19374. var seq = this.right;
  19375. var x = seq.to_array();
  19376. this.right = x.pop();
  19377. x.push(this);
  19378. seq = AST_Seq.from_array(x).transform(compressor);
  19379. return seq;
  19380. }
  19381. }
  19382. return this;
  19383. });
  19384. var commutativeOperators = makePredicate("== === != !== * & | ^");
  19385. OPT(AST_Binary, function(self, compressor){
  19386. var reverse = compressor.has_directive("use asm") ? noop
  19387. : function(op, force) {
  19388. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  19389. if (op) self.operator = op;
  19390. var tmp = self.left;
  19391. self.left = self.right;
  19392. self.right = tmp;
  19393. }
  19394. };
  19395. if (commutativeOperators(self.operator)) {
  19396. if (self.right instanceof AST_Constant
  19397. && !(self.left instanceof AST_Constant)) {
  19398. // if right is a constant, whatever side effects the
  19399. // left side might have could not influence the
  19400. // result. hence, force switch.
  19401. if (!(self.left instanceof AST_Binary
  19402. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  19403. reverse(null, true);
  19404. }
  19405. }
  19406. if (/^[!=]==?$/.test(self.operator)) {
  19407. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  19408. if (self.right.consequent instanceof AST_SymbolRef
  19409. && self.right.consequent.definition() === self.left.definition()) {
  19410. if (/^==/.test(self.operator)) return self.right.condition;
  19411. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  19412. }
  19413. if (self.right.alternative instanceof AST_SymbolRef
  19414. && self.right.alternative.definition() === self.left.definition()) {
  19415. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  19416. if (/^!=/.test(self.operator)) return self.right.condition;
  19417. }
  19418. }
  19419. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  19420. if (self.left.consequent instanceof AST_SymbolRef
  19421. && self.left.consequent.definition() === self.right.definition()) {
  19422. if (/^==/.test(self.operator)) return self.left.condition;
  19423. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  19424. }
  19425. if (self.left.alternative instanceof AST_SymbolRef
  19426. && self.left.alternative.definition() === self.right.definition()) {
  19427. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  19428. if (/^!=/.test(self.operator)) return self.left.condition;
  19429. }
  19430. }
  19431. }
  19432. }
  19433. self = self.lift_sequences(compressor);
  19434. if (compressor.option("comparisons")) switch (self.operator) {
  19435. case "===":
  19436. case "!==":
  19437. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  19438. (self.left.is_boolean() && self.right.is_boolean())) {
  19439. self.operator = self.operator.substr(0, 2);
  19440. }
  19441. // XXX: intentionally falling down to the next case
  19442. case "==":
  19443. case "!=":
  19444. if (self.left instanceof AST_String
  19445. && self.left.value == "undefined"
  19446. && self.right instanceof AST_UnaryPrefix
  19447. && self.right.operator == "typeof"
  19448. && compressor.option("unsafe")) {
  19449. if (!(self.right.expression instanceof AST_SymbolRef)
  19450. || !self.right.expression.undeclared()) {
  19451. self.right = self.right.expression;
  19452. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  19453. if (self.operator.length == 2) self.operator += "=";
  19454. }
  19455. }
  19456. break;
  19457. }
  19458. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  19459. case "&&":
  19460. var ll = self.left.evaluate(compressor);
  19461. var rr = self.right.evaluate(compressor);
  19462. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  19463. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  19464. return make_node(AST_False, self);
  19465. }
  19466. if (ll.length > 1 && ll[1]) {
  19467. return rr[0];
  19468. }
  19469. if (rr.length > 1 && rr[1]) {
  19470. return ll[0];
  19471. }
  19472. break;
  19473. case "||":
  19474. var ll = self.left.evaluate(compressor);
  19475. var rr = self.right.evaluate(compressor);
  19476. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  19477. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  19478. return make_node(AST_True, self);
  19479. }
  19480. if (ll.length > 1 && !ll[1]) {
  19481. return rr[0];
  19482. }
  19483. if (rr.length > 1 && !rr[1]) {
  19484. return ll[0];
  19485. }
  19486. break;
  19487. case "+":
  19488. var ll = self.left.evaluate(compressor);
  19489. var rr = self.right.evaluate(compressor);
  19490. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  19491. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  19492. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  19493. return make_node(AST_True, self);
  19494. }
  19495. break;
  19496. }
  19497. if (compressor.option("comparisons")) {
  19498. if (!(compressor.parent() instanceof AST_Binary)
  19499. || compressor.parent() instanceof AST_Assign) {
  19500. var negated = make_node(AST_UnaryPrefix, self, {
  19501. operator: "!",
  19502. expression: self.negate(compressor)
  19503. });
  19504. self = best_of(self, negated);
  19505. }
  19506. switch (self.operator) {
  19507. case "<": reverse(">"); break;
  19508. case "<=": reverse(">="); break;
  19509. }
  19510. }
  19511. if (self.operator == "+" && self.right instanceof AST_String
  19512. && self.right.getValue() === "" && self.left instanceof AST_Binary
  19513. && self.left.operator == "+" && self.left.is_string(compressor)) {
  19514. return self.left;
  19515. }
  19516. if (compressor.option("evaluate")) {
  19517. if (self.operator == "+") {
  19518. if (self.left instanceof AST_Constant
  19519. && self.right instanceof AST_Binary
  19520. && self.right.operator == "+"
  19521. && self.right.left instanceof AST_Constant
  19522. && self.right.is_string(compressor)) {
  19523. self = make_node(AST_Binary, self, {
  19524. operator: "+",
  19525. left: make_node(AST_String, null, {
  19526. value: "" + self.left.getValue() + self.right.left.getValue(),
  19527. start: self.left.start,
  19528. end: self.right.left.end
  19529. }),
  19530. right: self.right.right
  19531. });
  19532. }
  19533. if (self.right instanceof AST_Constant
  19534. && self.left instanceof AST_Binary
  19535. && self.left.operator == "+"
  19536. && self.left.right instanceof AST_Constant
  19537. && self.left.is_string(compressor)) {
  19538. self = make_node(AST_Binary, self, {
  19539. operator: "+",
  19540. left: self.left.left,
  19541. right: make_node(AST_String, null, {
  19542. value: "" + self.left.right.getValue() + self.right.getValue(),
  19543. start: self.left.right.start,
  19544. end: self.right.end
  19545. })
  19546. });
  19547. }
  19548. if (self.left instanceof AST_Binary
  19549. && self.left.operator == "+"
  19550. && self.left.is_string(compressor)
  19551. && self.left.right instanceof AST_Constant
  19552. && self.right instanceof AST_Binary
  19553. && self.right.operator == "+"
  19554. && self.right.left instanceof AST_Constant
  19555. && self.right.is_string(compressor)) {
  19556. self = make_node(AST_Binary, self, {
  19557. operator: "+",
  19558. left: make_node(AST_Binary, self.left, {
  19559. operator: "+",
  19560. left: self.left.left,
  19561. right: make_node(AST_String, null, {
  19562. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  19563. start: self.left.right.start,
  19564. end: self.right.left.end
  19565. })
  19566. }),
  19567. right: self.right.right
  19568. });
  19569. }
  19570. }
  19571. }
  19572. // x * (y * z) ==> x * y * z
  19573. if (self.right instanceof AST_Binary
  19574. && self.right.operator == self.operator
  19575. && (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
  19576. {
  19577. self.left = make_node(AST_Binary, self.left, {
  19578. operator : self.operator,
  19579. left : self.left,
  19580. right : self.right.left
  19581. });
  19582. self.right = self.right.right;
  19583. return self.transform(compressor);
  19584. }
  19585. return self.evaluate(compressor)[0];
  19586. });
  19587. OPT(AST_SymbolRef, function(self, compressor){
  19588. if (self.undeclared()) {
  19589. var defines = compressor.option("global_defs");
  19590. if (defines && defines.hasOwnProperty(self.name)) {
  19591. return make_node_from_constant(compressor, defines[self.name], self);
  19592. }
  19593. switch (self.name) {
  19594. case "undefined":
  19595. return make_node(AST_Undefined, self);
  19596. case "NaN":
  19597. return make_node(AST_NaN, self);
  19598. case "Infinity":
  19599. return make_node(AST_Infinity, self);
  19600. }
  19601. }
  19602. return self;
  19603. });
  19604. OPT(AST_Undefined, function(self, compressor){
  19605. if (compressor.option("unsafe")) {
  19606. var scope = compressor.find_parent(AST_Scope);
  19607. var undef = scope.find_variable("undefined");
  19608. if (undef) {
  19609. var ref = make_node(AST_SymbolRef, self, {
  19610. name : "undefined",
  19611. scope : scope,
  19612. thedef : undef
  19613. });
  19614. ref.reference();
  19615. return ref;
  19616. }
  19617. }
  19618. return self;
  19619. });
  19620. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  19621. OPT(AST_Assign, function(self, compressor){
  19622. self = self.lift_sequences(compressor);
  19623. if (self.operator == "="
  19624. && self.left instanceof AST_SymbolRef
  19625. && self.right instanceof AST_Binary
  19626. && self.right.left instanceof AST_SymbolRef
  19627. && self.right.left.name == self.left.name
  19628. && member(self.right.operator, ASSIGN_OPS)) {
  19629. self.operator = self.right.operator + "=";
  19630. self.right = self.right.right;
  19631. }
  19632. return self;
  19633. });
  19634. OPT(AST_Conditional, function(self, compressor){
  19635. if (!compressor.option("conditionals")) return self;
  19636. if (self.condition instanceof AST_Seq) {
  19637. var car = self.condition.car;
  19638. self.condition = self.condition.cdr;
  19639. return AST_Seq.cons(car, self);
  19640. }
  19641. var cond = self.condition.evaluate(compressor);
  19642. if (cond.length > 1) {
  19643. if (cond[1]) {
  19644. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  19645. return self.consequent;
  19646. } else {
  19647. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  19648. return self.alternative;
  19649. }
  19650. }
  19651. var negated = cond[0].negate(compressor);
  19652. if (best_of(cond[0], negated) === negated) {
  19653. self = make_node(AST_Conditional, self, {
  19654. condition: negated,
  19655. consequent: self.alternative,
  19656. alternative: self.consequent
  19657. });
  19658. }
  19659. var consequent = self.consequent;
  19660. var alternative = self.alternative;
  19661. if (consequent instanceof AST_Assign
  19662. && alternative instanceof AST_Assign
  19663. && consequent.operator == alternative.operator
  19664. && consequent.left.equivalent_to(alternative.left)
  19665. ) {
  19666. /*
  19667. * Stuff like this:
  19668. * if (foo) exp = something; else exp = something_else;
  19669. * ==>
  19670. * exp = foo ? something : something_else;
  19671. */
  19672. return make_node(AST_Assign, self, {
  19673. operator: consequent.operator,
  19674. left: consequent.left,
  19675. right: make_node(AST_Conditional, self, {
  19676. condition: self.condition,
  19677. consequent: consequent.right,
  19678. alternative: alternative.right
  19679. })
  19680. });
  19681. }
  19682. if (consequent instanceof AST_Call
  19683. && alternative.TYPE === consequent.TYPE
  19684. && consequent.args.length == alternative.args.length
  19685. && consequent.expression.equivalent_to(alternative.expression)) {
  19686. if (consequent.args.length == 0) {
  19687. return make_node(AST_Seq, self, {
  19688. car: self.condition,
  19689. cdr: consequent
  19690. });
  19691. }
  19692. if (consequent.args.length == 1) {
  19693. consequent.args[0] = make_node(AST_Conditional, self, {
  19694. condition: self.condition,
  19695. consequent: consequent.args[0],
  19696. alternative: alternative.args[0]
  19697. });
  19698. return consequent;
  19699. }
  19700. }
  19701. // x?y?z:a:a --> x&&y?z:a
  19702. if (consequent instanceof AST_Conditional
  19703. && consequent.alternative.equivalent_to(alternative)) {
  19704. return make_node(AST_Conditional, self, {
  19705. condition: make_node(AST_Binary, self, {
  19706. left: self.condition,
  19707. operator: "&&",
  19708. right: consequent.condition
  19709. }),
  19710. consequent: consequent.consequent,
  19711. alternative: alternative
  19712. });
  19713. }
  19714. return self;
  19715. });
  19716. OPT(AST_Boolean, function(self, compressor){
  19717. if (compressor.option("booleans")) {
  19718. var p = compressor.parent();
  19719. if (p instanceof AST_Binary && (p.operator == "=="
  19720. || p.operator == "!=")) {
  19721. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  19722. operator : p.operator,
  19723. value : self.value,
  19724. file : p.start.file,
  19725. line : p.start.line,
  19726. col : p.start.col,
  19727. });
  19728. return make_node(AST_Number, self, {
  19729. value: +self.value
  19730. });
  19731. }
  19732. return make_node(AST_UnaryPrefix, self, {
  19733. operator: "!",
  19734. expression: make_node(AST_Number, self, {
  19735. value: 1 - self.value
  19736. })
  19737. });
  19738. }
  19739. return self;
  19740. });
  19741. OPT(AST_Sub, function(self, compressor){
  19742. var prop = self.property;
  19743. if (prop instanceof AST_String && compressor.option("properties")) {
  19744. prop = prop.getValue();
  19745. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  19746. return make_node(AST_Dot, self, {
  19747. expression : self.expression,
  19748. property : prop
  19749. });
  19750. }
  19751. var v = parseFloat(prop);
  19752. if (!isNaN(v) && v.toString() == prop) {
  19753. self.property = make_node(AST_Number, self.property, {
  19754. value: v
  19755. });
  19756. }
  19757. }
  19758. return self;
  19759. });
  19760. function literals_in_boolean_context(self, compressor) {
  19761. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  19762. return make_node(AST_True, self);
  19763. }
  19764. return self;
  19765. };
  19766. OPT(AST_Array, literals_in_boolean_context);
  19767. OPT(AST_Object, literals_in_boolean_context);
  19768. OPT(AST_RegExp, literals_in_boolean_context);
  19769. })();
  19770. /***********************************************************************
  19771. A JavaScript tokenizer / parser / beautifier / compressor.
  19772. https://github.com/mishoo/UglifyJS2
  19773. -------------------------------- (C) ---------------------------------
  19774. Author: Mihai Bazon
  19775. <mihai.bazon@gmail.com>
  19776. http://mihai.bazon.net/blog
  19777. Distributed under the BSD license:
  19778. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  19779. Redistribution and use in source and binary forms, with or without
  19780. modification, are permitted provided that the following conditions
  19781. are met:
  19782. * Redistributions of source code must retain the above
  19783. copyright notice, this list of conditions and the following
  19784. disclaimer.
  19785. * Redistributions in binary form must reproduce the above
  19786. copyright notice, this list of conditions and the following
  19787. disclaimer in the documentation and/or other materials
  19788. provided with the distribution.
  19789. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  19790. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19791. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19792. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  19793. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  19794. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  19795. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19796. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  19797. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  19798. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  19799. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  19800. SUCH DAMAGE.
  19801. ***********************************************************************/
  19802. "use strict";
  19803. // a small wrapper around fitzgen's source-map library
  19804. function SourceMap(options) {
  19805. options = defaults(options, {
  19806. file : null,
  19807. root : null,
  19808. orig : null,
  19809. orig_line_diff : 0,
  19810. dest_line_diff : 0,
  19811. });
  19812. var generator = new MOZ_SourceMap.SourceMapGenerator({
  19813. file : options.file,
  19814. sourceRoot : options.root
  19815. });
  19816. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  19817. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  19818. if (orig_map) {
  19819. var info = orig_map.originalPositionFor({
  19820. line: orig_line,
  19821. column: orig_col
  19822. });
  19823. if (info.source === null) {
  19824. return;
  19825. }
  19826. source = info.source;
  19827. orig_line = info.line;
  19828. orig_col = info.column;
  19829. name = info.name;
  19830. }
  19831. generator.addMapping({
  19832. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  19833. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  19834. source : source,
  19835. name : name
  19836. });
  19837. };
  19838. return {
  19839. add : add,
  19840. get : function() { return generator },
  19841. toString : function() { return generator.toString() }
  19842. };
  19843. };
  19844. /***********************************************************************
  19845. A JavaScript tokenizer / parser / beautifier / compressor.
  19846. https://github.com/mishoo/UglifyJS2
  19847. -------------------------------- (C) ---------------------------------
  19848. Author: Mihai Bazon
  19849. <mihai.bazon@gmail.com>
  19850. http://mihai.bazon.net/blog
  19851. Distributed under the BSD license:
  19852. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  19853. Redistribution and use in source and binary forms, with or without
  19854. modification, are permitted provided that the following conditions
  19855. are met:
  19856. * Redistributions of source code must retain the above
  19857. copyright notice, this list of conditions and the following
  19858. disclaimer.
  19859. * Redistributions in binary form must reproduce the above
  19860. copyright notice, this list of conditions and the following
  19861. disclaimer in the documentation and/or other materials
  19862. provided with the distribution.
  19863. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  19864. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19865. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19866. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  19867. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  19868. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  19869. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19870. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  19871. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  19872. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  19873. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  19874. SUCH DAMAGE.
  19875. ***********************************************************************/
  19876. "use strict";
  19877. (function(){
  19878. var MOZ_TO_ME = {
  19879. TryStatement : function(M) {
  19880. return new AST_Try({
  19881. start : my_start_token(M),
  19882. end : my_end_token(M),
  19883. body : from_moz(M.block).body,
  19884. bcatch : from_moz(M.handlers[0]),
  19885. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  19886. });
  19887. },
  19888. CatchClause : function(M) {
  19889. return new AST_Catch({
  19890. start : my_start_token(M),
  19891. end : my_end_token(M),
  19892. argname : from_moz(M.param),
  19893. body : from_moz(M.body).body
  19894. });
  19895. },
  19896. ObjectExpression : function(M) {
  19897. return new AST_Object({
  19898. start : my_start_token(M),
  19899. end : my_end_token(M),
  19900. properties : M.properties.map(function(prop){
  19901. var key = prop.key;
  19902. var name = key.type == "Identifier" ? key.name : key.value;
  19903. var args = {
  19904. start : my_start_token(key),
  19905. end : my_end_token(prop.value),
  19906. key : name,
  19907. value : from_moz(prop.value)
  19908. };
  19909. switch (prop.kind) {
  19910. case "init":
  19911. return new AST_ObjectKeyVal(args);
  19912. case "set":
  19913. args.value.name = from_moz(key);
  19914. return new AST_ObjectSetter(args);
  19915. case "get":
  19916. args.value.name = from_moz(key);
  19917. return new AST_ObjectGetter(args);
  19918. }
  19919. })
  19920. });
  19921. },
  19922. SequenceExpression : function(M) {
  19923. return AST_Seq.from_array(M.expressions.map(from_moz));
  19924. },
  19925. MemberExpression : function(M) {
  19926. return new (M.computed ? AST_Sub : AST_Dot)({
  19927. start : my_start_token(M),
  19928. end : my_end_token(M),
  19929. property : M.computed ? from_moz(M.property) : M.property.name,
  19930. expression : from_moz(M.object)
  19931. });
  19932. },
  19933. SwitchCase : function(M) {
  19934. return new (M.test ? AST_Case : AST_Default)({
  19935. start : my_start_token(M),
  19936. end : my_end_token(M),
  19937. expression : from_moz(M.test),
  19938. body : M.consequent.map(from_moz)
  19939. });
  19940. },
  19941. Literal : function(M) {
  19942. var val = M.value, args = {
  19943. start : my_start_token(M),
  19944. end : my_end_token(M)
  19945. };
  19946. if (val === null) return new AST_Null(args);
  19947. switch (typeof val) {
  19948. case "string":
  19949. args.value = val;
  19950. return new AST_String(args);
  19951. case "number":
  19952. args.value = val;
  19953. return new AST_Number(args);
  19954. case "boolean":
  19955. return new (val ? AST_True : AST_False)(args);
  19956. default:
  19957. args.value = val;
  19958. return new AST_RegExp(args);
  19959. }
  19960. },
  19961. UnaryExpression: From_Moz_Unary,
  19962. UpdateExpression: From_Moz_Unary,
  19963. Identifier: function(M) {
  19964. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  19965. return new (M.name == "this" ? AST_This
  19966. : p.type == "LabeledStatement" ? AST_Label
  19967. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  19968. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  19969. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  19970. : p.type == "CatchClause" ? AST_SymbolCatch
  19971. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  19972. : AST_SymbolRef)({
  19973. start : my_start_token(M),
  19974. end : my_end_token(M),
  19975. name : M.name
  19976. });
  19977. }
  19978. };
  19979. function From_Moz_Unary(M) {
  19980. var prefix = "prefix" in M ? M.prefix
  19981. : M.type == "UnaryExpression" ? true : false;
  19982. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  19983. start : my_start_token(M),
  19984. end : my_end_token(M),
  19985. operator : M.operator,
  19986. expression : from_moz(M.argument)
  19987. });
  19988. };
  19989. var ME_TO_MOZ = {};
  19990. map("Node", AST_Node);
  19991. map("Program", AST_Toplevel, "body@body");
  19992. map("Function", AST_Function, "id>name, params@argnames, body%body");
  19993. map("EmptyStatement", AST_EmptyStatement);
  19994. map("BlockStatement", AST_BlockStatement, "body@body");
  19995. map("ExpressionStatement", AST_SimpleStatement, "expression>body");
  19996. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  19997. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  19998. map("BreakStatement", AST_Break, "label>label");
  19999. map("ContinueStatement", AST_Continue, "label>label");
  20000. map("WithStatement", AST_With, "object>expression, body>body");
  20001. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  20002. map("ReturnStatement", AST_Return, "argument>value");
  20003. map("ThrowStatement", AST_Throw, "argument>value");
  20004. map("WhileStatement", AST_While, "test>condition, body>body");
  20005. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  20006. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  20007. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  20008. map("DebuggerStatement", AST_Debugger);
  20009. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  20010. map("VariableDeclaration", AST_Var, "declarations@definitions");
  20011. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  20012. map("ThisExpression", AST_This);
  20013. map("ArrayExpression", AST_Array, "elements@elements");
  20014. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  20015. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  20016. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  20017. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  20018. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  20019. map("NewExpression", AST_New, "callee>expression, arguments@args");
  20020. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  20021. /* -----[ tools ]----- */
  20022. function my_start_token(moznode) {
  20023. return new AST_Token({
  20024. file : moznode.loc && moznode.loc.source,
  20025. line : moznode.loc && moznode.loc.start.line,
  20026. col : moznode.loc && moznode.loc.start.column,
  20027. pos : moznode.start,
  20028. endpos : moznode.start
  20029. });
  20030. };
  20031. function my_end_token(moznode) {
  20032. return new AST_Token({
  20033. file : moznode.loc && moznode.loc.source,
  20034. line : moznode.loc && moznode.loc.end.line,
  20035. col : moznode.loc && moznode.loc.end.column,
  20036. pos : moznode.end,
  20037. endpos : moznode.end
  20038. });
  20039. };
  20040. function map(moztype, mytype, propmap) {
  20041. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  20042. moz_to_me += "return new mytype({\n" +
  20043. "start: my_start_token(M),\n" +
  20044. "end: my_end_token(M)";
  20045. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  20046. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  20047. if (!m) throw new Error("Can't understand property map: " + prop);
  20048. var moz = "M." + m[1], how = m[2], my = m[3];
  20049. moz_to_me += ",\n" + my + ": ";
  20050. if (how == "@") {
  20051. moz_to_me += moz + ".map(from_moz)";
  20052. } else if (how == ">") {
  20053. moz_to_me += "from_moz(" + moz + ")";
  20054. } else if (how == "=") {
  20055. moz_to_me += moz;
  20056. } else if (how == "%") {
  20057. moz_to_me += "from_moz(" + moz + ").body";
  20058. } else throw new Error("Can't understand operator in propmap: " + prop);
  20059. });
  20060. moz_to_me += "\n})}";
  20061. // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  20062. // console.log(moz_to_me);
  20063. moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  20064. mytype, my_start_token, my_end_token, from_moz
  20065. );
  20066. return MOZ_TO_ME[moztype] = moz_to_me;
  20067. };
  20068. var FROM_MOZ_STACK = null;
  20069. function from_moz(node) {
  20070. FROM_MOZ_STACK.push(node);
  20071. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  20072. FROM_MOZ_STACK.pop();
  20073. return ret;
  20074. };
  20075. AST_Node.from_mozilla_ast = function(node){
  20076. var save_stack = FROM_MOZ_STACK;
  20077. FROM_MOZ_STACK = [];
  20078. var ast = from_moz(node);
  20079. FROM_MOZ_STACK = save_stack;
  20080. return ast;
  20081. };
  20082. })();
  20083. AST_Node.warn_function = function(txt) { logger.error("uglifyjs2 WARN: " + txt); };
  20084. exports.minify = function(files, options, name) {
  20085. options = defaults(options, {
  20086. spidermonkey : false,
  20087. outSourceMap : null,
  20088. sourceRoot : null,
  20089. inSourceMap : null,
  20090. fromString : false,
  20091. warnings : false,
  20092. mangle : {},
  20093. output : null,
  20094. compress : {}
  20095. });
  20096. base54.reset();
  20097. // 1. parse
  20098. var toplevel = null,
  20099. sourcesContent = {};
  20100. if (options.spidermonkey) {
  20101. toplevel = AST_Node.from_mozilla_ast(files);
  20102. } else {
  20103. if (typeof files == "string")
  20104. files = [ files ];
  20105. files.forEach(function(file){
  20106. var code = options.fromString
  20107. ? file
  20108. : rjsFile.readFile(file, "utf8");
  20109. sourcesContent[file] = code;
  20110. toplevel = parse(code, {
  20111. filename: options.fromString ? name : file,
  20112. toplevel: toplevel
  20113. });
  20114. });
  20115. }
  20116. // 2. compress
  20117. if (options.compress) {
  20118. var compress = { warnings: options.warnings };
  20119. merge(compress, options.compress);
  20120. toplevel.figure_out_scope();
  20121. var sq = Compressor(compress);
  20122. toplevel = toplevel.transform(sq);
  20123. }
  20124. // 3. mangle
  20125. if (options.mangle) {
  20126. toplevel.figure_out_scope();
  20127. toplevel.compute_char_frequency();
  20128. toplevel.mangle_names(options.mangle);
  20129. }
  20130. // 4. output
  20131. var inMap = options.inSourceMap;
  20132. var output = {};
  20133. if (typeof options.inSourceMap == "string") {
  20134. inMap = rjsFile.readFile(options.inSourceMap, "utf8");
  20135. }
  20136. if (options.outSourceMap) {
  20137. output.source_map = SourceMap({
  20138. file: options.outSourceMap,
  20139. orig: inMap,
  20140. root: options.sourceRoot
  20141. });
  20142. if (options.sourceMapIncludeSources) {
  20143. for (var file in sourcesContent) {
  20144. if (sourcesContent.hasOwnProperty(file)) {
  20145. options.source_map.get().setSourceContent(file, sourcesContent[file]);
  20146. }
  20147. }
  20148. }
  20149. }
  20150. if (options.output) {
  20151. merge(output, options.output);
  20152. }
  20153. var stream = OutputStream(output);
  20154. toplevel.print(stream);
  20155. return {
  20156. code : stream + "",
  20157. map : output.source_map + ""
  20158. };
  20159. };
  20160. // exports.describe_ast = function() {
  20161. // function doitem(ctor) {
  20162. // var sub = {};
  20163. // ctor.SUBCLASSES.forEach(function(ctor){
  20164. // sub[ctor.TYPE] = doitem(ctor);
  20165. // });
  20166. // var ret = {};
  20167. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  20168. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  20169. // return ret;
  20170. // }
  20171. // return doitem(AST_Node).sub;
  20172. // }
  20173. exports.describe_ast = function() {
  20174. var out = OutputStream({ beautify: true });
  20175. function doitem(ctor) {
  20176. out.print("AST_" + ctor.TYPE);
  20177. var props = ctor.SELF_PROPS.filter(function(prop){
  20178. return !/^\$/.test(prop);
  20179. });
  20180. if (props.length > 0) {
  20181. out.space();
  20182. out.with_parens(function(){
  20183. props.forEach(function(prop, i){
  20184. if (i) out.space();
  20185. out.print(prop);
  20186. });
  20187. });
  20188. }
  20189. if (ctor.documentation) {
  20190. out.space();
  20191. out.print_string(ctor.documentation);
  20192. }
  20193. if (ctor.SUBCLASSES.length > 0) {
  20194. out.space();
  20195. out.with_block(function(){
  20196. ctor.SUBCLASSES.forEach(function(ctor, i){
  20197. out.indent();
  20198. doitem(ctor);
  20199. out.newline();
  20200. });
  20201. });
  20202. }
  20203. };
  20204. doitem(AST_Node);
  20205. return out + "";
  20206. };
  20207. });
  20208. /**
  20209. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  20210. * Available via the MIT or new BSD license.
  20211. * see: http://github.com/jrburke/requirejs for details
  20212. */
  20213. /*jslint plusplus: true */
  20214. /*global define: false */
  20215. define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
  20216. 'use strict';
  20217. function arrayToString(ary) {
  20218. var output = '[';
  20219. if (ary) {
  20220. ary.forEach(function (item, i) {
  20221. output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
  20222. });
  20223. }
  20224. output += ']';
  20225. return output;
  20226. }
  20227. //This string is saved off because JSLint complains
  20228. //about obj.arguments use, as 'reserved word'
  20229. var argPropName = 'arguments',
  20230. //Default object to use for "scope" checking for UMD identifiers.
  20231. emptyScope = {},
  20232. mixin = lang.mixin,
  20233. hasProp = lang.hasProp;
  20234. //From an esprima example for traversing its ast.
  20235. function traverse(object, visitor) {
  20236. var key, child;
  20237. if (!object) {
  20238. return;
  20239. }
  20240. if (visitor.call(null, object) === false) {
  20241. return false;
  20242. }
  20243. for (key in object) {
  20244. if (object.hasOwnProperty(key)) {
  20245. child = object[key];
  20246. if (typeof child === 'object' && child !== null) {
  20247. if (traverse(child, visitor) === false) {
  20248. return false;
  20249. }
  20250. }
  20251. }
  20252. }
  20253. }
  20254. //Like traverse, but visitor returning false just
  20255. //stops that subtree analysis, not the rest of tree
  20256. //visiting.
  20257. function traverseBroad(object, visitor) {
  20258. var key, child;
  20259. if (!object) {
  20260. return;
  20261. }
  20262. if (visitor.call(null, object) === false) {
  20263. return false;
  20264. }
  20265. for (key in object) {
  20266. if (object.hasOwnProperty(key)) {
  20267. child = object[key];
  20268. if (typeof child === 'object' && child !== null) {
  20269. traverseBroad(child, visitor);
  20270. }
  20271. }
  20272. }
  20273. }
  20274. /**
  20275. * Pulls out dependencies from an array literal with just string members.
  20276. * If string literals, will just return those string values in an array,
  20277. * skipping other items in the array.
  20278. *
  20279. * @param {Node} node an AST node.
  20280. *
  20281. * @returns {Array} an array of strings.
  20282. * If null is returned, then it means the input node was not a valid
  20283. * dependency.
  20284. */
  20285. function getValidDeps(node) {
  20286. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  20287. return;
  20288. }
  20289. var deps = [];
  20290. node.elements.some(function (elem) {
  20291. if (elem.type === 'Literal') {
  20292. deps.push(elem.value);
  20293. }
  20294. });
  20295. return deps.length ? deps : undefined;
  20296. }
  20297. /**
  20298. * Main parse function. Returns a string of any valid require or
  20299. * define/require.def calls as part of one JavaScript source string.
  20300. * @param {String} moduleName the module name that represents this file.
  20301. * It is used to create a default define if there is not one already for the
  20302. * file. This allows properly tracing dependencies for builds. Otherwise, if
  20303. * the file just has a require() call, the file dependencies will not be
  20304. * properly reflected: the file will come before its dependencies.
  20305. * @param {String} moduleName
  20306. * @param {String} fileName
  20307. * @param {String} fileContents
  20308. * @param {Object} options optional options. insertNeedsDefine: true will
  20309. * add calls to require.needsDefine() if appropriate.
  20310. * @returns {String} JS source string or null, if no require or
  20311. * define/require.def calls are found.
  20312. */
  20313. function parse(moduleName, fileName, fileContents, options) {
  20314. options = options || {};
  20315. //Set up source input
  20316. var i, moduleCall, depString,
  20317. moduleDeps = [],
  20318. result = '',
  20319. moduleList = [],
  20320. needsDefine = true,
  20321. astRoot = esprima.parse(fileContents);
  20322. parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  20323. if (!deps) {
  20324. deps = [];
  20325. }
  20326. if (callName === 'define' && (!name || name === moduleName)) {
  20327. needsDefine = false;
  20328. }
  20329. if (!name) {
  20330. //If there is no module name, the dependencies are for
  20331. //this file/default module name.
  20332. moduleDeps = moduleDeps.concat(deps);
  20333. } else {
  20334. moduleList.push({
  20335. name: name,
  20336. deps: deps
  20337. });
  20338. }
  20339. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  20340. return factoryIdentifier;
  20341. }
  20342. //If define was found, no need to dive deeper, unless
  20343. //the config explicitly wants to dig deeper.
  20344. return !!options.findNestedDependencies;
  20345. }, options);
  20346. if (options.insertNeedsDefine && needsDefine) {
  20347. result += 'require.needsDefine("' + moduleName + '");';
  20348. }
  20349. if (moduleDeps.length || moduleList.length) {
  20350. for (i = 0; i < moduleList.length; i++) {
  20351. moduleCall = moduleList[i];
  20352. if (result) {
  20353. result += '\n';
  20354. }
  20355. //If this is the main module for this file, combine any
  20356. //"anonymous" dependencies (could come from a nested require
  20357. //call) with this module.
  20358. if (moduleCall.name === moduleName) {
  20359. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  20360. moduleDeps = [];
  20361. }
  20362. depString = arrayToString(moduleCall.deps);
  20363. result += 'define("' + moduleCall.name + '",' +
  20364. depString + ');';
  20365. }
  20366. if (moduleDeps.length) {
  20367. if (result) {
  20368. result += '\n';
  20369. }
  20370. depString = arrayToString(moduleDeps);
  20371. result += 'define("' + moduleName + '",' + depString + ');';
  20372. }
  20373. }
  20374. return result || null;
  20375. }
  20376. parse.traverse = traverse;
  20377. parse.traverseBroad = traverseBroad;
  20378. /**
  20379. * Handles parsing a file recursively for require calls.
  20380. * @param {Array} parentNode the AST node to start with.
  20381. * @param {Function} onMatch function to call on a parse match.
  20382. * @param {Object} [options] This is normally the build config options if
  20383. * it is passed.
  20384. * @param {Object} [fnExpScope] holds list of function expresssion
  20385. * argument identifiers, set up internally, not passed in
  20386. */
  20387. parse.recurse = function (object, onMatch, options, fnExpScope) {
  20388. //Like traverse, but skips if branches that would not be processed
  20389. //after has application that results in tests of true or false boolean
  20390. //literal values.
  20391. var key, child, result, i, params, param, tempObject,
  20392. hasHas = options && options.has;
  20393. fnExpScope = fnExpScope || emptyScope;
  20394. if (!object) {
  20395. return;
  20396. }
  20397. //If has replacement has resulted in if(true){} or if(false){}, take
  20398. //the appropriate branch and skip the other one.
  20399. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  20400. object.test.type === 'Literal') {
  20401. if (object.test.value) {
  20402. //Take the if branch
  20403. this.recurse(object.consequent, onMatch, options, fnExpScope);
  20404. } else {
  20405. //Take the else branch
  20406. this.recurse(object.alternate, onMatch, options, fnExpScope);
  20407. }
  20408. } else {
  20409. result = this.parseNode(object, onMatch, fnExpScope);
  20410. if (result === false) {
  20411. return;
  20412. } else if (typeof result === 'string') {
  20413. return result;
  20414. }
  20415. //Build up a "scope" object that informs nested recurse calls if
  20416. //the define call references an identifier that is likely a UMD
  20417. //wrapped function expression argument.
  20418. if (object.type === 'ExpressionStatement' && object.expression &&
  20419. object.expression.type === 'CallExpression' && object.expression.callee &&
  20420. object.expression.callee.type === 'FunctionExpression') {
  20421. tempObject = object.expression.callee;
  20422. if (tempObject.params && tempObject.params.length) {
  20423. params = tempObject.params;
  20424. fnExpScope = mixin({}, fnExpScope, true);
  20425. for (i = 0; i < params.length; i++) {
  20426. param = params[i];
  20427. if (param.type === 'Identifier') {
  20428. fnExpScope[param.name] = true;
  20429. }
  20430. }
  20431. }
  20432. }
  20433. for (key in object) {
  20434. if (object.hasOwnProperty(key)) {
  20435. child = object[key];
  20436. if (typeof child === 'object' && child !== null) {
  20437. result = this.recurse(child, onMatch, options, fnExpScope);
  20438. if (typeof result === 'string') {
  20439. break;
  20440. }
  20441. }
  20442. }
  20443. }
  20444. //Check for an identifier for a factory function identifier being
  20445. //passed in as a function expression, indicating a UMD-type of
  20446. //wrapping.
  20447. if (typeof result === 'string') {
  20448. if (hasProp(fnExpScope, result)) {
  20449. //result still in scope, keep jumping out indicating the
  20450. //identifier still in use.
  20451. return result;
  20452. }
  20453. return;
  20454. }
  20455. }
  20456. };
  20457. /**
  20458. * Determines if the file defines the require/define module API.
  20459. * Specifically, it looks for the `define.amd = ` expression.
  20460. * @param {String} fileName
  20461. * @param {String} fileContents
  20462. * @returns {Boolean}
  20463. */
  20464. parse.definesRequire = function (fileName, fileContents) {
  20465. var found = false;
  20466. traverse(esprima.parse(fileContents), function (node) {
  20467. if (parse.hasDefineAmd(node)) {
  20468. found = true;
  20469. //Stop traversal
  20470. return false;
  20471. }
  20472. });
  20473. return found;
  20474. };
  20475. /**
  20476. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  20477. * define(function(require, exports, module){}) wrapper. These dependencies
  20478. * will be added to a modified define() call that lists the dependencies
  20479. * on the outside of the function.
  20480. * @param {String} fileName
  20481. * @param {String|Object} fileContents: a string of contents, or an already
  20482. * parsed AST tree.
  20483. * @returns {Array} an array of module names that are dependencies. Always
  20484. * returns an array, but could be of length zero.
  20485. */
  20486. parse.getAnonDeps = function (fileName, fileContents) {
  20487. var astRoot = typeof fileContents === 'string' ?
  20488. esprima.parse(fileContents) : fileContents,
  20489. defFunc = this.findAnonDefineFactory(astRoot);
  20490. return parse.getAnonDepsFromNode(defFunc);
  20491. };
  20492. /**
  20493. * Finds require("") calls inside a CommonJS anonymous module wrapped
  20494. * in a define function, given an AST node for the definition function.
  20495. * @param {Node} node the AST node for the definition function.
  20496. * @returns {Array} and array of dependency names. Can be of zero length.
  20497. */
  20498. parse.getAnonDepsFromNode = function (node) {
  20499. var deps = [],
  20500. funcArgLength;
  20501. if (node) {
  20502. this.findRequireDepNames(node, deps);
  20503. //If no deps, still add the standard CommonJS require, exports,
  20504. //module, in that order, to the deps, but only if specified as
  20505. //function args. In particular, if exports is used, it is favored
  20506. //over the return value of the function, so only add it if asked.
  20507. funcArgLength = node.params && node.params.length;
  20508. if (funcArgLength) {
  20509. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  20510. ["require"]).concat(deps);
  20511. }
  20512. }
  20513. return deps;
  20514. };
  20515. parse.isDefineNodeWithArgs = function (node) {
  20516. return node && node.type === 'CallExpression' &&
  20517. node.callee && node.callee.type === 'Identifier' &&
  20518. node.callee.name === 'define' && node[argPropName];
  20519. };
  20520. /**
  20521. * Finds the function in define(function (require, exports, module){});
  20522. * @param {Array} node
  20523. * @returns {Boolean}
  20524. */
  20525. parse.findAnonDefineFactory = function (node) {
  20526. var match;
  20527. traverse(node, function (node) {
  20528. var arg0, arg1;
  20529. if (parse.isDefineNodeWithArgs(node)) {
  20530. //Just the factory function passed to define
  20531. arg0 = node[argPropName][0];
  20532. if (arg0 && arg0.type === 'FunctionExpression') {
  20533. match = arg0;
  20534. return false;
  20535. }
  20536. //A string literal module ID followed by the factory function.
  20537. arg1 = node[argPropName][1];
  20538. if (arg0.type === 'Literal' &&
  20539. arg1 && arg1.type === 'FunctionExpression') {
  20540. match = arg1;
  20541. return false;
  20542. }
  20543. }
  20544. });
  20545. return match;
  20546. };
  20547. /**
  20548. * Finds any config that is passed to requirejs. That includes calls to
  20549. * require/requirejs.config(), as well as require({}, ...) and
  20550. * requirejs({}, ...)
  20551. * @param {String} fileContents
  20552. *
  20553. * @returns {Object} a config details object with the following properties:
  20554. * - config: {Object} the config object found. Can be undefined if no
  20555. * config found.
  20556. * - range: {Array} the start index and end index in the contents where
  20557. * the config was found. Can be undefined if no config found.
  20558. * Can throw an error if the config in the file cannot be evaluated in
  20559. * a build context to valid JavaScript.
  20560. */
  20561. parse.findConfig = function (fileContents) {
  20562. /*jslint evil: true */
  20563. var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
  20564. quoteRegExp = /(:\s|\[\s*)(['"])/,
  20565. astRoot = esprima.parse(fileContents, {
  20566. loc: true
  20567. });
  20568. traverse(astRoot, function (node) {
  20569. var arg,
  20570. requireType = parse.hasRequire(node);
  20571. if (requireType && (requireType === 'require' ||
  20572. requireType === 'requirejs' ||
  20573. requireType === 'requireConfig' ||
  20574. requireType === 'requirejsConfig')) {
  20575. arg = node[argPropName] && node[argPropName][0];
  20576. if (arg && arg.type === 'ObjectExpression') {
  20577. stringData = parse.nodeToString(fileContents, arg);
  20578. jsConfig = stringData.value;
  20579. foundRange = stringData.range;
  20580. return false;
  20581. }
  20582. } else {
  20583. arg = parse.getRequireObjectLiteral(node);
  20584. if (arg) {
  20585. stringData = parse.nodeToString(fileContents, arg);
  20586. jsConfig = stringData.value;
  20587. foundRange = stringData.range;
  20588. return false;
  20589. }
  20590. }
  20591. });
  20592. if (jsConfig) {
  20593. // Eval the config
  20594. quoteMatch = quoteRegExp.exec(jsConfig);
  20595. quote = (quoteMatch && quoteMatch[2]) || '"';
  20596. foundConfig = eval('(' + jsConfig + ')');
  20597. }
  20598. return {
  20599. config: foundConfig,
  20600. range: foundRange,
  20601. quote: quote
  20602. };
  20603. };
  20604. /** Returns the node for the object literal assigned to require/requirejs,
  20605. * for holding a declarative config.
  20606. */
  20607. parse.getRequireObjectLiteral = function (node) {
  20608. if (node.id && node.id.type === 'Identifier' &&
  20609. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  20610. node.init && node.init.type === 'ObjectExpression') {
  20611. return node.init;
  20612. }
  20613. };
  20614. /**
  20615. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  20616. * Does *not* do .config calls though. See pragma.namespace for the complete
  20617. * set of namespace transforms. This function is used because require calls
  20618. * inside a define() call should not be renamed, so a simple regexp is not
  20619. * good enough.
  20620. * @param {String} fileContents the contents to transform.
  20621. * @param {String} ns the namespace, *not* including trailing dot.
  20622. * @return {String} the fileContents with the namespace applied
  20623. */
  20624. parse.renameNamespace = function (fileContents, ns) {
  20625. var lines,
  20626. locs = [],
  20627. astRoot = esprima.parse(fileContents, {
  20628. loc: true
  20629. });
  20630. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  20631. locs.push(node.loc);
  20632. //Do not recurse into define functions, they should be using
  20633. //local defines.
  20634. return callName !== 'define';
  20635. }, {});
  20636. if (locs.length) {
  20637. lines = fileContents.split('\n');
  20638. //Go backwards through the found locs, adding in the namespace name
  20639. //in front.
  20640. locs.reverse();
  20641. locs.forEach(function (loc) {
  20642. var startIndex = loc.start.column,
  20643. //start.line is 1-based, not 0 based.
  20644. lineIndex = loc.start.line - 1,
  20645. line = lines[lineIndex];
  20646. lines[lineIndex] = line.substring(0, startIndex) +
  20647. ns + '.' +
  20648. line.substring(startIndex,
  20649. line.length);
  20650. });
  20651. fileContents = lines.join('\n');
  20652. }
  20653. return fileContents;
  20654. };
  20655. /**
  20656. * Finds all dependencies specified in dependency arrays and inside
  20657. * simplified commonjs wrappers.
  20658. * @param {String} fileName
  20659. * @param {String} fileContents
  20660. *
  20661. * @returns {Array} an array of dependency strings. The dependencies
  20662. * have not been normalized, they may be relative IDs.
  20663. */
  20664. parse.findDependencies = function (fileName, fileContents, options) {
  20665. var dependencies = [],
  20666. astRoot = esprima.parse(fileContents);
  20667. parse.recurse(astRoot, function (callName, config, name, deps) {
  20668. if (deps) {
  20669. dependencies = dependencies.concat(deps);
  20670. }
  20671. }, options);
  20672. return dependencies;
  20673. };
  20674. /**
  20675. * Finds only CJS dependencies, ones that are the form
  20676. * require('stringLiteral')
  20677. */
  20678. parse.findCjsDependencies = function (fileName, fileContents) {
  20679. var dependencies = [];
  20680. traverse(esprima.parse(fileContents), function (node) {
  20681. var arg;
  20682. if (node && node.type === 'CallExpression' && node.callee &&
  20683. node.callee.type === 'Identifier' &&
  20684. node.callee.name === 'require' && node[argPropName] &&
  20685. node[argPropName].length === 1) {
  20686. arg = node[argPropName][0];
  20687. if (arg.type === 'Literal') {
  20688. dependencies.push(arg.value);
  20689. }
  20690. }
  20691. });
  20692. return dependencies;
  20693. };
  20694. //function define() {}
  20695. parse.hasDefDefine = function (node) {
  20696. return node.type === 'FunctionDeclaration' && node.id &&
  20697. node.id.type === 'Identifier' && node.id.name === 'define';
  20698. };
  20699. //define.amd = ...
  20700. parse.hasDefineAmd = function (node) {
  20701. return node && node.type === 'AssignmentExpression' &&
  20702. node.left && node.left.type === 'MemberExpression' &&
  20703. node.left.object && node.left.object.name === 'define' &&
  20704. node.left.property && node.left.property.name === 'amd';
  20705. };
  20706. //define.amd reference, as in: if (define.amd)
  20707. parse.refsDefineAmd = function (node) {
  20708. return node && node.type === 'MemberExpression' &&
  20709. node.object && node.object.name === 'define' &&
  20710. node.object.type === 'Identifier' &&
  20711. node.property && node.property.name === 'amd' &&
  20712. node.property.type === 'Identifier';
  20713. };
  20714. //require(), requirejs(), require.config() and requirejs.config()
  20715. parse.hasRequire = function (node) {
  20716. var callName,
  20717. c = node && node.callee;
  20718. if (node && node.type === 'CallExpression' && c) {
  20719. if (c.type === 'Identifier' &&
  20720. (c.name === 'require' ||
  20721. c.name === 'requirejs')) {
  20722. //A require/requirejs({}, ...) call
  20723. callName = c.name;
  20724. } else if (c.type === 'MemberExpression' &&
  20725. c.object &&
  20726. c.object.type === 'Identifier' &&
  20727. (c.object.name === 'require' ||
  20728. c.object.name === 'requirejs') &&
  20729. c.property && c.property.name === 'config') {
  20730. // require/requirejs.config({}) call
  20731. callName = c.object.name + 'Config';
  20732. }
  20733. }
  20734. return callName;
  20735. };
  20736. //define()
  20737. parse.hasDefine = function (node) {
  20738. return node && node.type === 'CallExpression' && node.callee &&
  20739. node.callee.type === 'Identifier' &&
  20740. node.callee.name === 'define';
  20741. };
  20742. /**
  20743. * If there is a named define in the file, returns the name. Does not
  20744. * scan for mulitple names, just the first one.
  20745. */
  20746. parse.getNamedDefine = function (fileContents) {
  20747. var name;
  20748. traverse(esprima.parse(fileContents), function (node) {
  20749. if (node && node.type === 'CallExpression' && node.callee &&
  20750. node.callee.type === 'Identifier' &&
  20751. node.callee.name === 'define' &&
  20752. node[argPropName] && node[argPropName][0] &&
  20753. node[argPropName][0].type === 'Literal') {
  20754. name = node[argPropName][0].value;
  20755. return false;
  20756. }
  20757. });
  20758. return name;
  20759. };
  20760. /**
  20761. * Determines if define(), require({}|[]) or requirejs was called in the
  20762. * file. Also finds out if define() is declared and if define.amd is called.
  20763. */
  20764. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  20765. var uses;
  20766. traverse(esprima.parse(fileContents), function (node) {
  20767. var type, callName, arg;
  20768. if (parse.hasDefDefine(node)) {
  20769. //function define() {}
  20770. type = 'declaresDefine';
  20771. } else if (parse.hasDefineAmd(node)) {
  20772. type = 'defineAmd';
  20773. } else {
  20774. callName = parse.hasRequire(node);
  20775. if (callName) {
  20776. arg = node[argPropName] && node[argPropName][0];
  20777. if (arg && (arg.type === 'ObjectExpression' ||
  20778. arg.type === 'ArrayExpression')) {
  20779. type = callName;
  20780. }
  20781. } else if (parse.hasDefine(node)) {
  20782. type = 'define';
  20783. }
  20784. }
  20785. if (type) {
  20786. if (!uses) {
  20787. uses = {};
  20788. }
  20789. uses[type] = true;
  20790. }
  20791. });
  20792. return uses;
  20793. };
  20794. /**
  20795. * Determines if require(''), exports.x =, module.exports =,
  20796. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  20797. * also checks for Node variants.
  20798. */
  20799. parse.usesCommonJs = function (fileName, fileContents) {
  20800. var uses = null,
  20801. assignsExports = false;
  20802. traverse(esprima.parse(fileContents), function (node) {
  20803. var type,
  20804. exp = node.expression || node.init;
  20805. if (node.type === 'Identifier' &&
  20806. (node.name === '__dirname' || node.name === '__filename')) {
  20807. type = node.name.substring(2);
  20808. } else if (node.type === 'VariableDeclarator' && node.id &&
  20809. node.id.type === 'Identifier' &&
  20810. node.id.name === 'exports') {
  20811. //Hmm, a variable assignment for exports, so does not use cjs
  20812. //exports.
  20813. type = 'varExports';
  20814. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  20815. exp.left.type === 'MemberExpression' && exp.left.object) {
  20816. if (exp.left.object.name === 'module' && exp.left.property &&
  20817. exp.left.property.name === 'exports') {
  20818. type = 'moduleExports';
  20819. } else if (exp.left.object.name === 'exports' &&
  20820. exp.left.property) {
  20821. type = 'exports';
  20822. }
  20823. } else if (node && node.type === 'CallExpression' && node.callee &&
  20824. node.callee.type === 'Identifier' &&
  20825. node.callee.name === 'require' && node[argPropName] &&
  20826. node[argPropName].length === 1 &&
  20827. node[argPropName][0].type === 'Literal') {
  20828. type = 'require';
  20829. }
  20830. if (type) {
  20831. if (type === 'varExports') {
  20832. assignsExports = true;
  20833. } else if (type !== 'exports' || !assignsExports) {
  20834. if (!uses) {
  20835. uses = {};
  20836. }
  20837. uses[type] = true;
  20838. }
  20839. }
  20840. });
  20841. return uses;
  20842. };
  20843. parse.findRequireDepNames = function (node, deps) {
  20844. traverse(node, function (node) {
  20845. var arg;
  20846. if (node && node.type === 'CallExpression' && node.callee &&
  20847. node.callee.type === 'Identifier' &&
  20848. node.callee.name === 'require' &&
  20849. node[argPropName] && node[argPropName].length === 1) {
  20850. arg = node[argPropName][0];
  20851. if (arg.type === 'Literal') {
  20852. deps.push(arg.value);
  20853. }
  20854. }
  20855. });
  20856. };
  20857. /**
  20858. * Determines if a specific node is a valid require or define/require.def
  20859. * call.
  20860. * @param {Array} node
  20861. * @param {Function} onMatch a function to call when a match is found.
  20862. * It is passed the match name, and the config, name, deps possible args.
  20863. * The config, name and deps args are not normalized.
  20864. * @param {Object} fnExpScope an object whose keys are all function
  20865. * expression identifiers that should be in scope. Useful for UMD wrapper
  20866. * detection to avoid parsing more into the wrapped UMD code.
  20867. *
  20868. * @returns {String} a JS source string with the valid require/define call.
  20869. * Otherwise null.
  20870. */
  20871. parse.parseNode = function (node, onMatch, fnExpScope) {
  20872. var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
  20873. args = node && node[argPropName],
  20874. callName = parse.hasRequire(node);
  20875. if (callName === 'require' || callName === 'requirejs') {
  20876. //A plain require/requirejs call
  20877. arg = node[argPropName] && node[argPropName][0];
  20878. if (arg.type !== 'ArrayExpression') {
  20879. if (arg.type === 'ObjectExpression') {
  20880. //A config call, try the second arg.
  20881. arg = node[argPropName][1];
  20882. }
  20883. }
  20884. deps = getValidDeps(arg);
  20885. if (!deps) {
  20886. return;
  20887. }
  20888. return onMatch("require", null, null, deps, node);
  20889. } else if (parse.hasDefine(node) && args && args.length) {
  20890. name = args[0];
  20891. deps = args[1];
  20892. factory = args[2];
  20893. if (name.type === 'ArrayExpression') {
  20894. //No name, adjust args
  20895. factory = deps;
  20896. deps = name;
  20897. name = null;
  20898. } else if (name.type === 'FunctionExpression') {
  20899. //Just the factory, no name or deps
  20900. factory = name;
  20901. name = deps = null;
  20902. } else if (name.type !== 'Literal') {
  20903. //An object literal, just null out
  20904. name = deps = factory = null;
  20905. }
  20906. if (name && name.type === 'Literal' && deps) {
  20907. if (deps.type === 'FunctionExpression') {
  20908. //deps is the factory
  20909. factory = deps;
  20910. deps = null;
  20911. } else if (deps.type === 'ObjectExpression') {
  20912. //deps is object literal, null out
  20913. deps = factory = null;
  20914. } else if (deps.type === 'Identifier' && args.length === 2) {
  20915. // define('id', factory)
  20916. deps = factory = null;
  20917. }
  20918. }
  20919. if (deps && deps.type === 'ArrayExpression') {
  20920. deps = getValidDeps(deps);
  20921. } else if (factory && factory.type === 'FunctionExpression') {
  20922. //If no deps and a factory function, could be a commonjs sugar
  20923. //wrapper, scan the function for dependencies.
  20924. cjsDeps = parse.getAnonDepsFromNode(factory);
  20925. if (cjsDeps.length) {
  20926. deps = cjsDeps;
  20927. }
  20928. } else if (deps || factory) {
  20929. //Does not match the shape of an AMD call.
  20930. return;
  20931. }
  20932. //Just save off the name as a string instead of an AST object.
  20933. if (name && name.type === 'Literal') {
  20934. name = name.value;
  20935. }
  20936. return onMatch("define", null, name, deps, node,
  20937. (factory && factory.type === 'Identifier' ? factory.name : undefined),
  20938. fnExpScope);
  20939. } else if (node.type === 'CallExpression' && node.callee &&
  20940. node.callee.type === 'FunctionExpression' &&
  20941. node.callee.body && node.callee.body.body &&
  20942. node.callee.body.body.length === 1 &&
  20943. node.callee.body.body[0].type === 'IfStatement') {
  20944. bodyNode = node.callee.body.body[0];
  20945. //Look for a define(Identifier) case, but only if inside an
  20946. //if that has a define.amd test
  20947. if (bodyNode.consequent && bodyNode.consequent.body) {
  20948. exp = bodyNode.consequent.body[0];
  20949. if (exp.type === 'ExpressionStatement' && exp.expression &&
  20950. parse.hasDefine(exp.expression) &&
  20951. exp.expression.arguments &&
  20952. exp.expression.arguments.length === 1 &&
  20953. exp.expression.arguments[0].type === 'Identifier') {
  20954. //Calls define(Identifier) as first statement in body.
  20955. //Confirm the if test references define.amd
  20956. traverse(bodyNode.test, function (node) {
  20957. if (parse.refsDefineAmd(node)) {
  20958. refsDefine = true;
  20959. return false;
  20960. }
  20961. });
  20962. if (refsDefine) {
  20963. return onMatch("define", null, null, null, exp.expression,
  20964. exp.expression.arguments[0].name, fnExpScope);
  20965. }
  20966. }
  20967. }
  20968. }
  20969. };
  20970. /**
  20971. * Converts an AST node into a JS source string by extracting
  20972. * the node's location from the given contents string. Assumes
  20973. * esprima.parse() with loc was done.
  20974. * @param {String} contents
  20975. * @param {Object} node
  20976. * @returns {String} a JS source string.
  20977. */
  20978. parse.nodeToString = function (contents, node) {
  20979. var extracted,
  20980. loc = node.loc,
  20981. lines = contents.split('\n'),
  20982. firstLine = loc.start.line > 1 ?
  20983. lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
  20984. '',
  20985. preamble = firstLine +
  20986. lines[loc.start.line - 1].substring(0, loc.start.column);
  20987. if (loc.start.line === loc.end.line) {
  20988. extracted = lines[loc.start.line - 1].substring(loc.start.column,
  20989. loc.end.column);
  20990. } else {
  20991. extracted = lines[loc.start.line - 1].substring(loc.start.column) +
  20992. '\n' +
  20993. lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
  20994. '\n' +
  20995. lines[loc.end.line - 1].substring(0, loc.end.column);
  20996. }
  20997. return {
  20998. value: extracted,
  20999. range: [
  21000. preamble.length,
  21001. preamble.length + extracted.length
  21002. ]
  21003. };
  21004. };
  21005. /**
  21006. * Extracts license comments from JS text.
  21007. * @param {String} fileName
  21008. * @param {String} contents
  21009. * @returns {String} a string of license comments.
  21010. */
  21011. parse.getLicenseComments = function (fileName, contents) {
  21012. var commentNode, refNode, subNode, value, i, j,
  21013. //xpconnect's Reflect does not support comment or range, but
  21014. //prefer continued operation vs strict parity of operation,
  21015. //as license comments can be expressed in other ways, like
  21016. //via wrap args, or linked via sourcemaps.
  21017. ast = esprima.parse(contents, {
  21018. comment: true,
  21019. range: true
  21020. }),
  21021. result = '',
  21022. existsMap = {},
  21023. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  21024. if (ast.comments) {
  21025. for (i = 0; i < ast.comments.length; i++) {
  21026. commentNode = ast.comments[i];
  21027. if (commentNode.type === 'Line') {
  21028. value = '//' + commentNode.value + lineEnd;
  21029. refNode = commentNode;
  21030. if (i + 1 >= ast.comments.length) {
  21031. value += lineEnd;
  21032. } else {
  21033. //Look for immediately adjacent single line comments
  21034. //since it could from a multiple line comment made out
  21035. //of single line comments. Like this comment.
  21036. for (j = i + 1; j < ast.comments.length; j++) {
  21037. subNode = ast.comments[j];
  21038. if (subNode.type === 'Line' &&
  21039. subNode.range[0] === refNode.range[1] + 1) {
  21040. //Adjacent single line comment. Collect it.
  21041. value += '//' + subNode.value + lineEnd;
  21042. refNode = subNode;
  21043. } else {
  21044. //No more single line comment blocks. Break out
  21045. //and continue outer looping.
  21046. break;
  21047. }
  21048. }
  21049. value += lineEnd;
  21050. i = j - 1;
  21051. }
  21052. } else {
  21053. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  21054. }
  21055. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  21056. (commentNode.type === 'Block' &&
  21057. value.indexOf('/*!') === 0) ||
  21058. value.indexOf('opyright') !== -1 ||
  21059. value.indexOf('(c)') !== -1)) {
  21060. result += value;
  21061. existsMap[value] = true;
  21062. }
  21063. }
  21064. }
  21065. return result;
  21066. };
  21067. return parse;
  21068. });
  21069. /**
  21070. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  21071. * Available via the MIT or new BSD license.
  21072. * see: http://github.com/jrburke/requirejs for details
  21073. */
  21074. /*global define */
  21075. define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
  21076. function (esprima, parse, logger, lang) {
  21077. 'use strict';
  21078. var transform,
  21079. baseIndentRegExp = /^([ \t]+)/,
  21080. indentRegExp = /\{[\r\n]+([ \t]+)/,
  21081. keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
  21082. bulkIndentRegExps = {
  21083. '\n': /\n/g,
  21084. '\r\n': /\r\n/g
  21085. };
  21086. function applyIndent(str, indent, lineReturn) {
  21087. var regExp = bulkIndentRegExps[lineReturn];
  21088. return str.replace(regExp, '$&' + indent);
  21089. }
  21090. transform = {
  21091. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  21092. options = options || {};
  21093. var astRoot, contentLines, modLine,
  21094. foundAnon,
  21095. scanCount = 0,
  21096. scanReset = false,
  21097. defineInfos = [],
  21098. applySourceUrl = function (contents) {
  21099. if (options.useSourceUrl) {
  21100. contents = 'eval("' + lang.jsEscape(contents) +
  21101. '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  21102. path +
  21103. '");\n';
  21104. }
  21105. return contents;
  21106. };
  21107. try {
  21108. astRoot = esprima.parse(contents, {
  21109. loc: true
  21110. });
  21111. } catch (e) {
  21112. logger.trace('toTransport skipping ' + path + ': ' +
  21113. e.toString());
  21114. return contents;
  21115. }
  21116. //Find the define calls and their position in the files.
  21117. parse.traverse(astRoot, function (node) {
  21118. var args, firstArg, firstArgLoc, factoryNode,
  21119. needsId, depAction, foundId, init,
  21120. sourceUrlData, range,
  21121. namespaceExists = false;
  21122. // If a bundle script with a define declaration, do not
  21123. // parse any further at this level. Likely a built layer
  21124. // by some other tool.
  21125. if (node.type === 'VariableDeclarator' &&
  21126. node.id && node.id.name === 'define' &&
  21127. node.id.type === 'Identifier') {
  21128. init = node.init;
  21129. if (init && init.callee &&
  21130. init.callee.type === 'CallExpression' &&
  21131. init.callee.callee &&
  21132. init.callee.callee.type === 'Identifier' &&
  21133. init.callee.callee.name === 'require' &&
  21134. init.callee.arguments && init.callee.arguments.length === 1 &&
  21135. init.callee.arguments[0].type === 'Literal' &&
  21136. init.callee.arguments[0].value &&
  21137. init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
  21138. // the var define = require('amdefine')(module) case,
  21139. // keep going in that case.
  21140. } else {
  21141. return false;
  21142. }
  21143. }
  21144. namespaceExists = namespace &&
  21145. node.type === 'CallExpression' &&
  21146. node.callee && node.callee.object &&
  21147. node.callee.object.type === 'Identifier' &&
  21148. node.callee.object.name === namespace &&
  21149. node.callee.property.type === 'Identifier' &&
  21150. node.callee.property.name === 'define';
  21151. if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
  21152. //The arguments are where its at.
  21153. args = node.arguments;
  21154. if (!args || !args.length) {
  21155. return;
  21156. }
  21157. firstArg = args[0];
  21158. firstArgLoc = firstArg.loc;
  21159. if (args.length === 1) {
  21160. if (firstArg.type === 'Identifier') {
  21161. //The define(factory) case, but
  21162. //only allow it if one Identifier arg,
  21163. //to limit impact of false positives.
  21164. needsId = true;
  21165. depAction = 'empty';
  21166. } else if (firstArg.type === 'FunctionExpression') {
  21167. //define(function(){})
  21168. factoryNode = firstArg;
  21169. needsId = true;
  21170. depAction = 'scan';
  21171. } else if (firstArg.type === 'ObjectExpression') {
  21172. //define({});
  21173. needsId = true;
  21174. depAction = 'skip';
  21175. } else if (firstArg.type === 'Literal' &&
  21176. typeof firstArg.value === 'number') {
  21177. //define('12345');
  21178. needsId = true;
  21179. depAction = 'skip';
  21180. } else if (firstArg.type === 'UnaryExpression' &&
  21181. firstArg.operator === '-' &&
  21182. firstArg.argument &&
  21183. firstArg.argument.type === 'Literal' &&
  21184. typeof firstArg.argument.value === 'number') {
  21185. //define('-12345');
  21186. needsId = true;
  21187. depAction = 'skip';
  21188. } else if (firstArg.type === 'MemberExpression' &&
  21189. firstArg.object &&
  21190. firstArg.property &&
  21191. firstArg.property.type === 'Identifier') {
  21192. //define(this.key);
  21193. needsId = true;
  21194. depAction = 'empty';
  21195. }
  21196. } else if (firstArg.type === 'ArrayExpression') {
  21197. //define([], ...);
  21198. needsId = true;
  21199. depAction = 'skip';
  21200. } else if (firstArg.type === 'Literal' &&
  21201. typeof firstArg.value === 'string') {
  21202. //define('string', ....)
  21203. //Already has an ID.
  21204. needsId = false;
  21205. if (args.length === 2 &&
  21206. args[1].type === 'FunctionExpression') {
  21207. //Needs dependency scanning.
  21208. factoryNode = args[1];
  21209. depAction = 'scan';
  21210. } else {
  21211. depAction = 'skip';
  21212. }
  21213. } else {
  21214. //Unknown define entity, keep looking, even
  21215. //in the subtree for this node.
  21216. return;
  21217. }
  21218. range = {
  21219. foundId: foundId,
  21220. needsId: needsId,
  21221. depAction: depAction,
  21222. namespaceExists: namespaceExists,
  21223. node: node,
  21224. defineLoc: node.loc,
  21225. firstArgLoc: firstArgLoc,
  21226. factoryNode: factoryNode,
  21227. sourceUrlData: sourceUrlData
  21228. };
  21229. //Only transform ones that do not have IDs. If it has an
  21230. //ID but no dependency array, assume it is something like
  21231. //a phonegap implementation, that has its own internal
  21232. //define that cannot handle dependency array constructs,
  21233. //and if it is a named module, then it means it has been
  21234. //set for transport form.
  21235. if (range.needsId) {
  21236. if (foundAnon) {
  21237. logger.trace(path + ' has more than one anonymous ' +
  21238. 'define. May be a built file from another ' +
  21239. 'build system like, Ender. Skipping normalization.');
  21240. defineInfos = [];
  21241. return false;
  21242. } else {
  21243. foundAnon = range;
  21244. defineInfos.push(range);
  21245. }
  21246. } else if (depAction === 'scan') {
  21247. scanCount += 1;
  21248. if (scanCount > 1) {
  21249. //Just go back to an array that just has the
  21250. //anon one, since this is an already optimized
  21251. //file like the phonegap one.
  21252. if (!scanReset) {
  21253. defineInfos = foundAnon ? [foundAnon] : [];
  21254. scanReset = true;
  21255. }
  21256. } else {
  21257. defineInfos.push(range);
  21258. }
  21259. }
  21260. }
  21261. });
  21262. if (!defineInfos.length) {
  21263. return applySourceUrl(contents);
  21264. }
  21265. //Reverse the matches, need to start from the bottom of
  21266. //the file to modify it, so that the ranges are still true
  21267. //further up.
  21268. defineInfos.reverse();
  21269. contentLines = contents.split('\n');
  21270. modLine = function (loc, contentInsertion) {
  21271. var startIndex = loc.start.column,
  21272. //start.line is 1-based, not 0 based.
  21273. lineIndex = loc.start.line - 1,
  21274. line = contentLines[lineIndex];
  21275. contentLines[lineIndex] = line.substring(0, startIndex) +
  21276. contentInsertion +
  21277. line.substring(startIndex,
  21278. line.length);
  21279. };
  21280. defineInfos.forEach(function (info) {
  21281. var deps,
  21282. contentInsertion = '',
  21283. depString = '';
  21284. //Do the modifications "backwards", in other words, start with the
  21285. //one that is farthest down and work up, so that the ranges in the
  21286. //defineInfos still apply. So that means deps, id, then namespace.
  21287. if (info.needsId && moduleName) {
  21288. contentInsertion += "'" + moduleName + "',";
  21289. }
  21290. if (info.depAction === 'scan') {
  21291. deps = parse.getAnonDepsFromNode(info.factoryNode);
  21292. if (deps.length) {
  21293. depString = '[' + deps.map(function (dep) {
  21294. return "'" + dep + "'";
  21295. }) + ']';
  21296. } else {
  21297. depString = '[]';
  21298. }
  21299. depString += ',';
  21300. if (info.factoryNode) {
  21301. //Already have a named module, need to insert the
  21302. //dependencies after the name.
  21303. modLine(info.factoryNode.loc, depString);
  21304. } else {
  21305. contentInsertion += depString;
  21306. }
  21307. }
  21308. if (contentInsertion) {
  21309. modLine(info.firstArgLoc, contentInsertion);
  21310. }
  21311. //Do namespace last so that ui does not mess upthe parenRange
  21312. //used above.
  21313. if (namespace && !info.namespaceExists) {
  21314. modLine(info.defineLoc, namespace + '.');
  21315. }
  21316. //Notify any listener for the found info
  21317. if (onFound) {
  21318. onFound(info);
  21319. }
  21320. });
  21321. contents = contentLines.join('\n');
  21322. return applySourceUrl(contents);
  21323. },
  21324. /**
  21325. * Modify the contents of a require.config/requirejs.config call. This
  21326. * call will LOSE any existing comments that are in the config string.
  21327. *
  21328. * @param {String} fileContents String that may contain a config call
  21329. * @param {Function} onConfig Function called when the first config
  21330. * call is found. It will be passed an Object which is the current
  21331. * config, and the onConfig function should return an Object to use
  21332. * as the config.
  21333. * @return {String} the fileContents with the config changes applied.
  21334. */
  21335. modifyConfig: function (fileContents, onConfig) {
  21336. var details = parse.findConfig(fileContents),
  21337. config = details.config;
  21338. if (config) {
  21339. config = onConfig(config);
  21340. if (config) {
  21341. return transform.serializeConfig(config,
  21342. fileContents,
  21343. details.range[0],
  21344. details.range[1],
  21345. {
  21346. quote: details.quote
  21347. });
  21348. }
  21349. }
  21350. return fileContents;
  21351. },
  21352. serializeConfig: function (config, fileContents, start, end, options) {
  21353. //Calculate base level of indent
  21354. var indent, match, configString, outDentRegExp,
  21355. baseIndent = '',
  21356. startString = fileContents.substring(0, start),
  21357. existingConfigString = fileContents.substring(start, end),
  21358. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  21359. lastReturnIndex = startString.lastIndexOf('\n');
  21360. //Get the basic amount of indent for the require config call.
  21361. if (lastReturnIndex === -1) {
  21362. lastReturnIndex = 0;
  21363. }
  21364. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  21365. if (match && match[1]) {
  21366. baseIndent = match[1];
  21367. }
  21368. //Calculate internal indentation for config
  21369. match = indentRegExp.exec(existingConfigString);
  21370. if (match && match[1]) {
  21371. indent = match[1];
  21372. }
  21373. if (!indent || indent.length < baseIndent) {
  21374. indent = ' ';
  21375. } else {
  21376. indent = indent.substring(baseIndent.length);
  21377. }
  21378. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  21379. configString = transform.objectToString(config, {
  21380. indent: indent,
  21381. lineReturn: lineReturn,
  21382. outDentRegExp: outDentRegExp,
  21383. quote: options && options.quote
  21384. });
  21385. //Add in the base indenting level.
  21386. configString = applyIndent(configString, baseIndent, lineReturn);
  21387. return startString + configString + fileContents.substring(end);
  21388. },
  21389. /**
  21390. * Tries converting a JS object to a string. This will likely suck, and
  21391. * is tailored to the type of config expected in a loader config call.
  21392. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  21393. * no weird recursively referenced stuff.
  21394. * @param {Object} obj the object to convert
  21395. * @param {Object} options options object with the following values:
  21396. * {String} indent the indentation to use for each level
  21397. * {String} lineReturn the type of line return to use
  21398. * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  21399. * {String} quote the quote type to use, ' or ". Optional. Default is "
  21400. * @param {String} totalIndent the total indent to print for this level
  21401. * @return {String} a string representation of the object.
  21402. */
  21403. objectToString: function (obj, options, totalIndent) {
  21404. var startBrace, endBrace, nextIndent,
  21405. first = true,
  21406. value = '',
  21407. lineReturn = options.lineReturn,
  21408. indent = options.indent,
  21409. outDentRegExp = options.outDentRegExp,
  21410. quote = options.quote || '"';
  21411. totalIndent = totalIndent || '';
  21412. nextIndent = totalIndent + indent;
  21413. if (obj === null) {
  21414. value = 'null';
  21415. } else if (obj === undefined) {
  21416. value = 'undefined';
  21417. } else if (typeof obj === 'number' || typeof obj === 'boolean') {
  21418. value = obj;
  21419. } else if (typeof obj === 'string') {
  21420. //Use double quotes in case the config may also work as JSON.
  21421. value = quote + lang.jsEscape(obj) + quote;
  21422. } else if (lang.isArray(obj)) {
  21423. lang.each(obj, function (item, i) {
  21424. value += (i !== 0 ? ',' + lineReturn : '' ) +
  21425. nextIndent +
  21426. transform.objectToString(item,
  21427. options,
  21428. nextIndent);
  21429. });
  21430. startBrace = '[';
  21431. endBrace = ']';
  21432. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  21433. //The outdent regexp just helps pretty up the conversion
  21434. //just in node. Rhino strips comments and does a different
  21435. //indent scheme for Function toString, so not really helpful
  21436. //there.
  21437. value = obj.toString().replace(outDentRegExp, '$1');
  21438. } else {
  21439. //An object
  21440. lang.eachProp(obj, function (v, prop) {
  21441. value += (first ? '': ',' + lineReturn) +
  21442. nextIndent +
  21443. (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
  21444. ': ' +
  21445. transform.objectToString(v,
  21446. options,
  21447. nextIndent);
  21448. first = false;
  21449. });
  21450. startBrace = '{';
  21451. endBrace = '}';
  21452. }
  21453. if (startBrace) {
  21454. value = startBrace +
  21455. lineReturn +
  21456. value +
  21457. lineReturn + totalIndent +
  21458. endBrace;
  21459. }
  21460. return value;
  21461. }
  21462. };
  21463. return transform;
  21464. });
  21465. /**
  21466. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21467. * Available via the MIT or new BSD license.
  21468. * see: http://github.com/jrburke/requirejs for details
  21469. */
  21470. /*jslint regexp: true, plusplus: true */
  21471. /*global define: false */
  21472. define('pragma', ['parse', 'logger'], function (parse, logger) {
  21473. 'use strict';
  21474. function Temp() {}
  21475. function create(obj, mixin) {
  21476. Temp.prototype = obj;
  21477. var temp = new Temp(), prop;
  21478. //Avoid any extra memory hanging around
  21479. Temp.prototype = null;
  21480. if (mixin) {
  21481. for (prop in mixin) {
  21482. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  21483. temp[prop] = mixin[prop];
  21484. }
  21485. }
  21486. }
  21487. return temp; // Object
  21488. }
  21489. var pragma = {
  21490. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  21491. useStrictRegExp: /['"]use strict['"];/g,
  21492. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  21493. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  21494. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  21495. apiDefRegExp: /var requirejs,\s*require,\s*define;/,
  21496. defineCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  21497. defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  21498. defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  21499. defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  21500. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  21501. defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  21502. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*'function'\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  21503. removeStrict: function (contents, config) {
  21504. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '');
  21505. },
  21506. namespace: function (fileContents, ns, onLifecycleName) {
  21507. if (ns) {
  21508. //Namespace require/define calls
  21509. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  21510. fileContents = parse.renameNamespace(fileContents, ns);
  21511. //Namespace define ternary use:
  21512. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  21513. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  21514. //Namespace define jquery use:
  21515. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  21516. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  21517. //Namespace has.js define use:
  21518. fileContents = fileContents.replace(pragma.defineHasRegExp,
  21519. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  21520. //Namespace define checks.
  21521. //Do these ones last, since they are a subset of the more specific
  21522. //checks above.
  21523. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  21524. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  21525. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  21526. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  21527. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  21528. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  21529. //Check for require.js with the require/define definitions
  21530. if (pragma.apiDefRegExp.test(fileContents) &&
  21531. fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
  21532. //Wrap the file contents in a typeof check, and a function
  21533. //to contain the API globals.
  21534. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
  21535. "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
  21536. fileContents +
  21537. "\n" +
  21538. ns + ".requirejs = requirejs;" +
  21539. ns + ".require = require;" +
  21540. ns + ".define = define;\n" +
  21541. "}\n}());";
  21542. }
  21543. //Finally, if the file wants a special wrapper because it ties
  21544. //in to the requirejs internals in a way that would not fit
  21545. //the above matches, do that. Look for /*requirejs namespace: true*/
  21546. if (pragma.nsWrapRegExp.test(fileContents)) {
  21547. //Remove the pragma.
  21548. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  21549. //Alter the contents.
  21550. fileContents = '(function () {\n' +
  21551. 'var require = ' + ns + '.require,' +
  21552. 'requirejs = ' + ns + '.requirejs,' +
  21553. 'define = ' + ns + '.define;\n' +
  21554. fileContents +
  21555. '\n}());';
  21556. }
  21557. }
  21558. return fileContents;
  21559. },
  21560. /**
  21561. * processes the fileContents for some //>> conditional statements
  21562. */
  21563. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  21564. /*jslint evil: true */
  21565. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  21566. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  21567. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  21568. i, dep, moduleName, collectorMod,
  21569. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  21570. //Legacy arg defined to help in dojo conversion script. Remove later
  21571. //when dojo no longer needs conversion:
  21572. kwArgs = pragmas;
  21573. //Mix in a specific lifecycle scoped object, to allow targeting
  21574. //some pragmas/has tests to only when files are saved, or at different
  21575. //lifecycle events. Do not bother with kwArgs in this section, since
  21576. //the old dojo kwArgs were for all points in the build lifecycle.
  21577. if (onLifecycleName) {
  21578. lifecyclePragmas = config['pragmas' + onLifecycleName];
  21579. lifecycleHas = config['has' + onLifecycleName];
  21580. if (lifecyclePragmas) {
  21581. pragmas = create(pragmas || {}, lifecyclePragmas);
  21582. }
  21583. if (lifecycleHas) {
  21584. hasConfig = create(hasConfig || {}, lifecycleHas);
  21585. }
  21586. }
  21587. //Replace has references if desired
  21588. if (hasConfig) {
  21589. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  21590. if (hasConfig.hasOwnProperty(test)) {
  21591. return !!hasConfig[test];
  21592. }
  21593. return match;
  21594. });
  21595. }
  21596. if (!config.skipPragmas) {
  21597. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  21598. //Found a conditional. Get the conditional line.
  21599. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  21600. if (lineEndIndex === -1) {
  21601. lineEndIndex = fileContents.length - 1;
  21602. }
  21603. //Increment startIndex past the line so the next conditional search can be done.
  21604. startIndex = lineEndIndex + 1;
  21605. //Break apart the conditional.
  21606. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  21607. matches = conditionLine.match(pragma.conditionalRegExp);
  21608. if (matches) {
  21609. type = matches[1];
  21610. marker = matches[2];
  21611. condition = matches[3];
  21612. isTrue = false;
  21613. //See if the condition is true.
  21614. try {
  21615. isTrue = !!eval("(" + condition + ")");
  21616. } catch (e) {
  21617. throw "Error in file: " +
  21618. fileName +
  21619. ". Conditional comment: " +
  21620. conditionLine +
  21621. " failed with this error: " + e;
  21622. }
  21623. //Find the endpoint marker.
  21624. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  21625. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  21626. if (endMatches) {
  21627. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  21628. //Find the next line return based on the match position.
  21629. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  21630. if (lineEndIndex === -1) {
  21631. lineEndIndex = fileContents.length - 1;
  21632. }
  21633. //Should we include the segment?
  21634. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  21635. //Remove the conditional comments, and optionally remove the content inside
  21636. //the conditional comments.
  21637. startLength = startIndex - foundIndex;
  21638. fileContents = fileContents.substring(0, foundIndex) +
  21639. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  21640. fileContents.substring(lineEndIndex + 1, fileContents.length);
  21641. //Move startIndex to foundIndex, since that is the new position in the file
  21642. //where we need to look for more conditionals in the next while loop pass.
  21643. startIndex = foundIndex;
  21644. } else {
  21645. throw "Error in file: " +
  21646. fileName +
  21647. ". Cannot find end marker for conditional comment: " +
  21648. conditionLine;
  21649. }
  21650. }
  21651. }
  21652. }
  21653. //If need to find all plugin resources to optimize, do that now,
  21654. //before namespacing, since the namespacing will change the API
  21655. //names.
  21656. //If there is a plugin collector, scan the file for plugin resources.
  21657. if (config.optimizeAllPluginResources && pluginCollector) {
  21658. try {
  21659. deps = parse.findDependencies(fileName, fileContents);
  21660. if (deps.length) {
  21661. for (i = 0; i < deps.length; i++) {
  21662. dep = deps[i];
  21663. if (dep.indexOf('!') !== -1) {
  21664. moduleName = dep.split('!')[0];
  21665. collectorMod = pluginCollector[moduleName];
  21666. if (!collectorMod) {
  21667. collectorMod = pluginCollector[moduleName] = [];
  21668. }
  21669. collectorMod.push(dep);
  21670. }
  21671. }
  21672. }
  21673. } catch (eDep) {
  21674. logger.error('Parse error looking for plugin resources in ' +
  21675. fileName + ', skipping.');
  21676. }
  21677. }
  21678. //Strip amdefine use for node-shared modules.
  21679. if (!config.keepAmdefine) {
  21680. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  21681. }
  21682. //Do namespacing
  21683. if (onLifecycleName === 'OnSave' && config.namespace) {
  21684. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  21685. }
  21686. return pragma.removeStrict(fileContents, config);
  21687. }
  21688. };
  21689. return pragma;
  21690. });
  21691. if(env === 'browser') {
  21692. /**
  21693. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21694. * Available via the MIT or new BSD license.
  21695. * see: http://github.com/jrburke/requirejs for details
  21696. */
  21697. /*jslint strict: false */
  21698. /*global define: false */
  21699. define('browser/optimize', {});
  21700. }
  21701. if(env === 'node') {
  21702. /**
  21703. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21704. * Available via the MIT or new BSD license.
  21705. * see: http://github.com/jrburke/requirejs for details
  21706. */
  21707. /*jslint strict: false */
  21708. /*global define: false */
  21709. define('node/optimize', {});
  21710. }
  21711. if(env === 'rhino') {
  21712. /**
  21713. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21714. * Available via the MIT or new BSD license.
  21715. * see: http://github.com/jrburke/requirejs for details
  21716. */
  21717. /*jslint sloppy: true, plusplus: true */
  21718. /*global define, java, Packages, com */
  21719. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  21720. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  21721. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  21722. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  21723. if (!Array.prototype.reduce) {
  21724. Array.prototype.reduce = function (fn /*, initialValue */) {
  21725. var i = 0,
  21726. length = this.length,
  21727. accumulator;
  21728. if (arguments.length >= 2) {
  21729. accumulator = arguments[1];
  21730. } else {
  21731. if (length) {
  21732. while (!(i in this)) {
  21733. i++;
  21734. }
  21735. accumulator = this[i++];
  21736. }
  21737. }
  21738. for (; i < length; i++) {
  21739. if (i in this) {
  21740. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  21741. }
  21742. }
  21743. return accumulator;
  21744. };
  21745. }
  21746. var JSSourceFilefromCode, optimize,
  21747. mapRegExp = /"file":"[^"]+"/;
  21748. //Bind to Closure compiler, but if it is not available, do not sweat it.
  21749. try {
  21750. // Try older closure compiler that worked on Java 6
  21751. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  21752. } catch (e) {
  21753. try {
  21754. // Try for newer closure compiler that needs Java 7+
  21755. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  21756. } catch (e) {}
  21757. }
  21758. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  21759. function closurefromCode(filename, content) {
  21760. return JSSourceFilefromCode.invoke(null, [filename, content]);
  21761. }
  21762. function getFileWriter(fileName, encoding) {
  21763. var outFile = new java.io.File(fileName), outWriter, parentDir;
  21764. parentDir = outFile.getAbsoluteFile().getParentFile();
  21765. if (!parentDir.exists()) {
  21766. if (!parentDir.mkdirs()) {
  21767. throw "Could not create directory: " + parentDir.getAbsolutePath();
  21768. }
  21769. }
  21770. if (encoding) {
  21771. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  21772. } else {
  21773. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  21774. }
  21775. return new java.io.BufferedWriter(outWriter);
  21776. }
  21777. optimize = {
  21778. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  21779. config = config || {};
  21780. var result, mappings, optimized, compressed, baseName, writer,
  21781. outBaseName, outFileNameMap, outFileNameMapContent,
  21782. srcOutFileName, concatNameMap,
  21783. jscomp = Packages.com.google.javascript.jscomp,
  21784. flags = Packages.com.google.common.flags,
  21785. //Set up source input
  21786. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  21787. sourceListArray = new java.util.ArrayList(),
  21788. options, option, FLAG_compilation_level, compiler,
  21789. Compiler = Packages.com.google.javascript.jscomp.Compiler,
  21790. CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
  21791. logger.trace("Minifying file: " + fileName);
  21792. baseName = (new java.io.File(fileName)).getName();
  21793. //Set up options
  21794. options = new jscomp.CompilerOptions();
  21795. for (option in config.CompilerOptions) {
  21796. // options are false by default and jslint wanted an if statement in this for loop
  21797. if (config.CompilerOptions[option]) {
  21798. options[option] = config.CompilerOptions[option];
  21799. }
  21800. }
  21801. options.prettyPrint = keepLines || options.prettyPrint;
  21802. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  21803. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  21804. if (config.generateSourceMaps) {
  21805. mappings = new java.util.ArrayList();
  21806. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
  21807. options.setSourceMapLocationMappings(mappings);
  21808. options.setSourceMapOutputPath(fileName + ".map");
  21809. }
  21810. //Trigger the compiler
  21811. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  21812. compiler = new Compiler();
  21813. //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
  21814. //accepting the getDefaultExterns return value (a List) also wants the sources as a List
  21815. sourceListArray.add(jsSourceFile);
  21816. result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);
  21817. if (result.success) {
  21818. optimized = String(compiler.toSource());
  21819. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  21820. outBaseName = (new java.io.File(outFileName)).getName();
  21821. srcOutFileName = outFileName + ".src.js";
  21822. outFileNameMap = outFileName + ".map";
  21823. //If previous .map file exists, move it to the ".src.js"
  21824. //location. Need to update the sourceMappingURL part in the
  21825. //src.js file too.
  21826. if (file.exists(outFileNameMap)) {
  21827. concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
  21828. file.saveFile(concatNameMap, file.readFile(outFileNameMap));
  21829. file.saveFile(srcOutFileName,
  21830. fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
  21831. '/# sourceMappingURL=$1.src.js.map'));
  21832. } else {
  21833. file.saveUtf8File(srcOutFileName, fileContents);
  21834. }
  21835. writer = getFileWriter(outFileNameMap, "utf-8");
  21836. result.sourceMap.appendTo(writer, outFileName);
  21837. writer.close();
  21838. //Not sure how better to do this, but right now the .map file
  21839. //leaks the full OS path in the "file" property. Manually
  21840. //modify it to not do that.
  21841. file.saveFile(outFileNameMap,
  21842. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  21843. fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
  21844. } else {
  21845. fileContents = optimized;
  21846. }
  21847. return fileContents;
  21848. } else {
  21849. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  21850. }
  21851. return fileContents;
  21852. }
  21853. };
  21854. return optimize;
  21855. });
  21856. }
  21857. if(env === 'xpconnect') {
  21858. define('xpconnect/optimize', {});
  21859. }
  21860. /**
  21861. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21862. * Available via the MIT or new BSD license.
  21863. * see: http://github.com/jrburke/requirejs for details
  21864. */
  21865. /*jslint plusplus: true, nomen: true, regexp: true */
  21866. /*global define: false */
  21867. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  21868. 'pragma', 'uglifyjs/index', 'uglifyjs2',
  21869. 'source-map'],
  21870. function (lang, logger, envOptimize, file, parse,
  21871. pragma, uglify, uglify2,
  21872. sourceMap) {
  21873. 'use strict';
  21874. var optimize,
  21875. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  21876. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  21877. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
  21878. protocolRegExp = /^\w+:/,
  21879. SourceMapGenerator = sourceMap.SourceMapGenerator,
  21880. SourceMapConsumer =sourceMap.SourceMapConsumer;
  21881. /**
  21882. * If an URL from a CSS url value contains start/end quotes, remove them.
  21883. * This is not done in the regexp, since my regexp fu is not that strong,
  21884. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  21885. * @param {String} url
  21886. */
  21887. function cleanCssUrlQuotes(url) {
  21888. //Make sure we are not ending in whitespace.
  21889. //Not very confident of the css regexps above that there will not be ending
  21890. //whitespace.
  21891. url = url.replace(/\s+$/, "");
  21892. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  21893. url = url.substring(1, url.length - 1);
  21894. }
  21895. return url;
  21896. }
  21897. function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
  21898. return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  21899. var firstChar, hasProtocol, parts, i,
  21900. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  21901. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  21902. //Only do the work for relative URLs. Skip things that start with / or #, or have
  21903. //a protocol.
  21904. firstChar = fixedUrlMatch.charAt(0);
  21905. hasProtocol = protocolRegExp.test(fixedUrlMatch);
  21906. if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {
  21907. //It is a relative URL, tack on the cssPrefix and path prefix
  21908. urlMatch = cssPrefix + path + fixedUrlMatch;
  21909. } else if (!hasProtocol) {
  21910. logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
  21911. }
  21912. //Collapse .. and .
  21913. parts = urlMatch.split("/");
  21914. for (i = parts.length - 1; i > 0; i--) {
  21915. if (parts[i] === ".") {
  21916. parts.splice(i, 1);
  21917. } else if (parts[i] === "..") {
  21918. if (i !== 0 && parts[i - 1] !== "..") {
  21919. parts.splice(i - 1, 2);
  21920. i -= 1;
  21921. }
  21922. }
  21923. }
  21924. return "url(" + parts.join("/") + ")";
  21925. });
  21926. }
  21927. /**
  21928. * Inlines nested stylesheets that have @import calls in them.
  21929. * @param {String} fileName the file name
  21930. * @param {String} fileContents the file contents
  21931. * @param {String} cssImportIgnore comma delimited string of files to ignore
  21932. * @param {String} cssPrefix string to be prefixed before relative URLs
  21933. * @param {Object} included an object used to track the files already imported
  21934. */
  21935. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
  21936. //Find the last slash in the name.
  21937. fileName = fileName.replace(lang.backSlashRegExp, "/");
  21938. var endIndex = fileName.lastIndexOf("/"),
  21939. //Make a file path based on the last slash.
  21940. //If no slash, so must be just a file name. Use empty string then.
  21941. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  21942. //store a list of merged files
  21943. importList = [],
  21944. skippedList = [];
  21945. //First make a pass by removing any commented out @import calls.
  21946. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  21947. //Make sure we have a delimited ignore list to make matching faster
  21948. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  21949. cssImportIgnore += ",";
  21950. }
  21951. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  21952. //Only process media type "all" or empty media type rules.
  21953. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  21954. skippedList.push(fileName);
  21955. return fullMatch;
  21956. }
  21957. importFileName = cleanCssUrlQuotes(importFileName);
  21958. //Ignore the file import if it is part of an ignore list.
  21959. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  21960. return fullMatch;
  21961. }
  21962. //Make sure we have a unix path for the rest of the operation.
  21963. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  21964. try {
  21965. //if a relative path, then tack on the filePath.
  21966. //If it is not a relative path, then the readFile below will fail,
  21967. //and we will just skip that import.
  21968. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  21969. importContents = file.readFile(fullImportFileName),
  21970. importEndIndex, importPath, flat;
  21971. //Skip the file if it has already been included.
  21972. if (included[fullImportFileName]) {
  21973. return '';
  21974. }
  21975. included[fullImportFileName] = true;
  21976. //Make sure to flatten any nested imports.
  21977. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  21978. importContents = flat.fileContents;
  21979. if (flat.importList.length) {
  21980. importList.push.apply(importList, flat.importList);
  21981. }
  21982. if (flat.skippedList.length) {
  21983. skippedList.push.apply(skippedList, flat.skippedList);
  21984. }
  21985. //Make the full import path
  21986. importEndIndex = importFileName.lastIndexOf("/");
  21987. //Make a file path based on the last slash.
  21988. //If no slash, so must be just a file name. Use empty string then.
  21989. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  21990. //fix url() on relative import (#5)
  21991. importPath = importPath.replace(/^\.\//, '');
  21992. //Modify URL paths to match the path represented by this file.
  21993. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
  21994. importList.push(fullImportFileName);
  21995. return importContents;
  21996. } catch (e) {
  21997. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  21998. return fullMatch;
  21999. }
  22000. });
  22001. if (cssPrefix && topLevel) {
  22002. //Modify URL paths to match the path represented by this file.
  22003. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
  22004. }
  22005. return {
  22006. importList : importList,
  22007. skippedList: skippedList,
  22008. fileContents : fileContents
  22009. };
  22010. }
  22011. optimize = {
  22012. /**
  22013. * Optimizes a file that contains JavaScript content. Optionally collects
  22014. * plugin resources mentioned in a file, and then passes the content
  22015. * through an minifier if one is specified via config.optimize.
  22016. *
  22017. * @param {String} fileName the name of the file to optimize
  22018. * @param {String} fileContents the contents to optimize. If this is
  22019. * a null value, then fileName will be used to read the fileContents.
  22020. * @param {String} outFileName the name of the file to use for the
  22021. * saved optimized content.
  22022. * @param {Object} config the build config object.
  22023. * @param {Array} [pluginCollector] storage for any plugin resources
  22024. * found.
  22025. */
  22026. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  22027. if (!fileContents) {
  22028. fileContents = file.readFile(fileName);
  22029. }
  22030. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  22031. file.saveUtf8File(outFileName, fileContents);
  22032. },
  22033. /**
  22034. * Optimizes a file that contains JavaScript content. Optionally collects
  22035. * plugin resources mentioned in a file, and then passes the content
  22036. * through an minifier if one is specified via config.optimize.
  22037. *
  22038. * @param {String} fileName the name of the file that matches the
  22039. * fileContents.
  22040. * @param {String} fileContents the string of JS to optimize.
  22041. * @param {Object} [config] the build config object.
  22042. * @param {Array} [pluginCollector] storage for any plugin resources
  22043. * found.
  22044. */
  22045. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  22046. var optFunc, optConfig,
  22047. parts = (String(config.optimize)).split('.'),
  22048. optimizerName = parts[0],
  22049. keepLines = parts[1] === 'keepLines',
  22050. licenseContents = '';
  22051. config = config || {};
  22052. //Apply pragmas/namespace renaming
  22053. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  22054. //Optimize the JS files if asked.
  22055. if (optimizerName && optimizerName !== 'none') {
  22056. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  22057. if (!optFunc) {
  22058. throw new Error('optimizer with name of "' +
  22059. optimizerName +
  22060. '" not found for this environment');
  22061. }
  22062. optConfig = config[optimizerName] || {};
  22063. if (config.generateSourceMaps) {
  22064. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  22065. optConfig._buildSourceMap = config._buildSourceMap;
  22066. }
  22067. try {
  22068. if (config.preserveLicenseComments) {
  22069. //Pull out any license comments for prepending after optimization.
  22070. try {
  22071. licenseContents = parse.getLicenseComments(fileName, fileContents);
  22072. } catch (e) {
  22073. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  22074. }
  22075. }
  22076. fileContents = licenseContents + optFunc(fileName,
  22077. fileContents,
  22078. outFileName,
  22079. keepLines,
  22080. optConfig);
  22081. if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
  22082. config._buildSourceMap = optConfig._buildSourceMap;
  22083. }
  22084. } catch (e) {
  22085. if (config.throwWhen && config.throwWhen.optimize) {
  22086. throw e;
  22087. } else {
  22088. logger.error(e);
  22089. }
  22090. }
  22091. } else {
  22092. if (config._buildSourceMap) {
  22093. config._buildSourceMap = null;
  22094. }
  22095. }
  22096. return fileContents;
  22097. },
  22098. /**
  22099. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  22100. * optionally removes line returns.
  22101. * @param {String} fileName the path to the CSS file to optimize
  22102. * @param {String} outFileName the path to save the optimized file.
  22103. * @param {Object} config the config object with the optimizeCss and
  22104. * cssImportIgnore options.
  22105. */
  22106. cssFile: function (fileName, outFileName, config) {
  22107. //Read in the file. Make sure we have a JS string.
  22108. var originalFileContents = file.readFile(fileName),
  22109. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
  22110. //Do not use the flattened CSS if there was one that was skipped.
  22111. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  22112. startIndex, endIndex, buildText, comment;
  22113. if (flat.skippedList.length) {
  22114. logger.warn('Cannot inline @imports for ' + fileName +
  22115. ',\nthe following files had media queries in them:\n' +
  22116. flat.skippedList.join('\n'));
  22117. }
  22118. //Do comment removal.
  22119. try {
  22120. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  22121. startIndex = 0;
  22122. //Get rid of comments.
  22123. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  22124. endIndex = fileContents.indexOf("*/", startIndex + 2);
  22125. if (endIndex === -1) {
  22126. throw "Improper comment in CSS file: " + fileName;
  22127. }
  22128. comment = fileContents.substring(startIndex, endIndex);
  22129. if (config.preserveLicenseComments &&
  22130. (comment.indexOf('license') !== -1 ||
  22131. comment.indexOf('opyright') !== -1 ||
  22132. comment.indexOf('(c)') !== -1)) {
  22133. //Keep the comment, just increment the startIndex
  22134. startIndex = endIndex;
  22135. } else {
  22136. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  22137. startIndex = 0;
  22138. }
  22139. }
  22140. }
  22141. //Get rid of newlines.
  22142. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  22143. fileContents = fileContents.replace(/[\r\n]/g, " ");
  22144. fileContents = fileContents.replace(/\s+/g, " ");
  22145. fileContents = fileContents.replace(/\{\s/g, "{");
  22146. fileContents = fileContents.replace(/\s\}/g, "}");
  22147. } else {
  22148. //Remove multiple empty lines.
  22149. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  22150. fileContents = fileContents.replace(/(\n)+/g, "\n");
  22151. }
  22152. //Remove unnecessary whitespace
  22153. if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
  22154. //Remove leading and trailing whitespace from lines
  22155. fileContents = fileContents.replace(/^[ \t]+/gm, "");
  22156. fileContents = fileContents.replace(/[ \t]+$/gm, "");
  22157. //Remove whitespace after semicolon, colon, curly brackets and commas
  22158. fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
  22159. //Remove whitespace before opening curly brackets
  22160. fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
  22161. //Truncate double whitespace
  22162. fileContents = fileContents.replace(/([ \t])+/g, "$1");
  22163. //Remove empty lines
  22164. fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
  22165. }
  22166. } catch (e) {
  22167. fileContents = originalFileContents;
  22168. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  22169. }
  22170. file.saveUtf8File(outFileName, fileContents);
  22171. //text output to stdout and/or written to build.txt file
  22172. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  22173. flat.importList.push(fileName);
  22174. buildText += flat.importList.map(function(path){
  22175. return path.replace(config.dir, "");
  22176. }).join("\n");
  22177. return {
  22178. importList: flat.importList,
  22179. buildText: buildText +"\n"
  22180. };
  22181. },
  22182. /**
  22183. * Optimizes CSS files, inlining @import calls, stripping comments, and
  22184. * optionally removes line returns.
  22185. * @param {String} startDir the path to the top level directory
  22186. * @param {Object} config the config object with the optimizeCss and
  22187. * cssImportIgnore options.
  22188. */
  22189. css: function (startDir, config) {
  22190. var buildText = "",
  22191. importList = [],
  22192. shouldRemove = config.dir && config.removeCombined,
  22193. i, fileName, result, fileList;
  22194. if (config.optimizeCss.indexOf("standard") !== -1) {
  22195. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  22196. if (fileList) {
  22197. for (i = 0; i < fileList.length; i++) {
  22198. fileName = fileList[i];
  22199. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  22200. result = optimize.cssFile(fileName, fileName, config);
  22201. buildText += result.buildText;
  22202. if (shouldRemove) {
  22203. result.importList.pop();
  22204. importList = importList.concat(result.importList);
  22205. }
  22206. }
  22207. }
  22208. if (shouldRemove) {
  22209. importList.forEach(function (path) {
  22210. if (file.exists(path)) {
  22211. file.deleteFile(path);
  22212. }
  22213. });
  22214. }
  22215. }
  22216. return buildText;
  22217. },
  22218. optimizers: {
  22219. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  22220. var parser = uglify.parser,
  22221. processor = uglify.uglify,
  22222. ast, errMessage, errMatch;
  22223. config = config || {};
  22224. logger.trace("Uglifying file: " + fileName);
  22225. try {
  22226. ast = parser.parse(fileContents, config.strict_semicolons);
  22227. if (config.no_mangle !== true) {
  22228. ast = processor.ast_mangle(ast, config);
  22229. }
  22230. ast = processor.ast_squeeze(ast, config);
  22231. fileContents = processor.gen_code(ast, config);
  22232. if (config.max_line_length) {
  22233. fileContents = processor.split_lines(fileContents, config.max_line_length);
  22234. }
  22235. //Add trailing semicolon to match uglifyjs command line version
  22236. fileContents += ';';
  22237. } catch (e) {
  22238. errMessage = e.toString();
  22239. errMatch = /\nError(\r)?\n/.exec(errMessage);
  22240. if (errMatch) {
  22241. errMessage = errMessage.substring(0, errMatch.index);
  22242. }
  22243. throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
  22244. }
  22245. return fileContents;
  22246. },
  22247. uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
  22248. var result, existingMap, resultMap, finalMap, sourceIndex,
  22249. uconfig = {},
  22250. existingMapPath = outFileName + '.map',
  22251. baseName = fileName && fileName.split('/').pop();
  22252. config = config || {};
  22253. lang.mixin(uconfig, config, true);
  22254. uconfig.fromString = true;
  22255. if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
  22256. uconfig.outSourceMap = baseName;
  22257. if (config._buildSourceMap) {
  22258. existingMap = JSON.parse(config._buildSourceMap);
  22259. uconfig.inSourceMap = existingMap;
  22260. } else if (file.exists(existingMapPath)) {
  22261. uconfig.inSourceMap = existingMapPath;
  22262. existingMap = JSON.parse(file.readFile(existingMapPath));
  22263. }
  22264. }
  22265. logger.trace("Uglify2 file: " + fileName);
  22266. try {
  22267. //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
  22268. result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');
  22269. if (uconfig.outSourceMap && result.map) {
  22270. resultMap = result.map;
  22271. if (existingMap) {
  22272. resultMap = JSON.parse(resultMap);
  22273. finalMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(resultMap));
  22274. finalMap.applySourceMap(new SourceMapConsumer(existingMap));
  22275. resultMap = finalMap.toString();
  22276. } else if (!config._buildSourceMap) {
  22277. file.saveFile(outFileName + '.src.js', fileContents);
  22278. }
  22279. fileContents = result.code;
  22280. if (config._buildSourceMap) {
  22281. config._buildSourceMap = resultMap;
  22282. } else {
  22283. file.saveFile(outFileName + '.map', resultMap);
  22284. fileContents += "\n//# sourceMappingURL=" + baseName + ".map";
  22285. }
  22286. } else {
  22287. fileContents = result.code;
  22288. }
  22289. } catch (e) {
  22290. throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
  22291. }
  22292. return fileContents;
  22293. }
  22294. }
  22295. };
  22296. return optimize;
  22297. });
  22298. /**
  22299. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22300. * Available via the MIT or new BSD license.
  22301. * see: http://github.com/jrburke/requirejs for details
  22302. */
  22303. /*
  22304. * This file patches require.js to communicate with the build system.
  22305. */
  22306. //Using sloppy since this uses eval for some code like plugins,
  22307. //which may not be strict mode compliant. So if use strict is used
  22308. //below they will have strict rules applied and may cause an error.
  22309. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  22310. /*global require, define: true */
  22311. //NOT asking for require as a dependency since the goal is to modify the
  22312. //global require below
  22313. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  22314. file,
  22315. pragma,
  22316. parse,
  22317. lang,
  22318. logger,
  22319. commonJs,
  22320. prim
  22321. ) {
  22322. var allowRun = true,
  22323. hasProp = lang.hasProp,
  22324. falseProp = lang.falseProp,
  22325. getOwn = lang.getOwn;
  22326. //Turn off throwing on resolution conflict, that was just an older prim
  22327. //idea about finding errors early, but does not comply with how promises
  22328. //should operate.
  22329. prim.hideResolutionConflict = true;
  22330. //This method should be called when the patches to require should take hold.
  22331. return function () {
  22332. if (!allowRun) {
  22333. return;
  22334. }
  22335. allowRun = false;
  22336. var layer,
  22337. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  22338. oldNewContext = require.s.newContext,
  22339. oldDef,
  22340. //create local undefined values for module and exports,
  22341. //so that when files are evaled in this function they do not
  22342. //see the node values used for r.js
  22343. exports,
  22344. module;
  22345. /**
  22346. * Reset "global" build caches that are kept around between
  22347. * build layer builds. Useful to do when there are multiple
  22348. * top level requirejs.optimize() calls.
  22349. */
  22350. require._cacheReset = function () {
  22351. //Stored raw text caches, used by browser use.
  22352. require._cachedRawText = {};
  22353. //Stored cached file contents for reuse in other layers.
  22354. require._cachedFileContents = {};
  22355. //Store which cached files contain a require definition.
  22356. require._cachedDefinesRequireUrls = {};
  22357. };
  22358. require._cacheReset();
  22359. /**
  22360. * Makes sure the URL is something that can be supported by the
  22361. * optimization tool.
  22362. * @param {String} url
  22363. * @returns {Boolean}
  22364. */
  22365. require._isSupportedBuildUrl = function (url) {
  22366. //Ignore URLs with protocols, hosts or question marks, means either network
  22367. //access is needed to fetch it or it is too dynamic. Note that
  22368. //on Windows, full paths are used for some urls, which include
  22369. //the drive, like c:/something, so need to test for something other
  22370. //than just a colon.
  22371. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  22372. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  22373. return true;
  22374. } else {
  22375. if (!layer.ignoredUrls[url]) {
  22376. if (url.indexOf('empty:') === -1) {
  22377. logger.info('Cannot optimize network URL, skipping: ' + url);
  22378. }
  22379. layer.ignoredUrls[url] = true;
  22380. }
  22381. return false;
  22382. }
  22383. };
  22384. function normalizeUrlWithBase(context, moduleName, url) {
  22385. //Adjust the URL if it was not transformed to use baseUrl.
  22386. if (require.jsExtRegExp.test(moduleName)) {
  22387. url = (context.config.dir || context.config.dirBaseUrl) + url;
  22388. }
  22389. return url;
  22390. }
  22391. //Overrides the new context call to add existing tracking features.
  22392. require.s.newContext = function (name) {
  22393. var context = oldNewContext(name),
  22394. oldEnable = context.enable,
  22395. moduleProto = context.Module.prototype,
  22396. oldInit = moduleProto.init,
  22397. oldCallPlugin = moduleProto.callPlugin;
  22398. //Only do this for the context used for building.
  22399. if (name === '_') {
  22400. //For build contexts, do everything sync
  22401. context.nextTick = function (fn) {
  22402. fn();
  22403. };
  22404. context.needFullExec = {};
  22405. context.fullExec = {};
  22406. context.plugins = {};
  22407. context.buildShimExports = {};
  22408. //Override the shim exports function generator to just
  22409. //spit out strings that can be used in the stringified
  22410. //build output.
  22411. context.makeShimExports = function (value) {
  22412. var fn;
  22413. if (context.config.wrapShim) {
  22414. fn = function () {
  22415. var str = 'return ';
  22416. // If specifies an export that is just a global
  22417. // name, no dot for a `this.` and such, then also
  22418. // attach to the global, for `var a = {}` files
  22419. // where the function closure would hide that from
  22420. // the global object.
  22421. if (value.exports && value.exports.indexOf('.') === -1) {
  22422. str += 'root.' + value.exports + ' = ';
  22423. }
  22424. if (value.init) {
  22425. str += '(' + value.init.toString() + '.apply(this, arguments))';
  22426. }
  22427. if (value.init && value.exports) {
  22428. str += ' || ';
  22429. }
  22430. if (value.exports) {
  22431. str += value.exports;
  22432. }
  22433. str += ';';
  22434. return str;
  22435. };
  22436. } else {
  22437. fn = function () {
  22438. return '(function (global) {\n' +
  22439. ' return function () {\n' +
  22440. ' var ret, fn;\n' +
  22441. (value.init ?
  22442. (' fn = ' + value.init.toString() + ';\n' +
  22443. ' ret = fn.apply(global, arguments);\n') : '') +
  22444. (value.exports ?
  22445. ' return ret || global.' + value.exports + ';\n' :
  22446. ' return ret;\n') +
  22447. ' };\n' +
  22448. '}(this))';
  22449. };
  22450. }
  22451. return fn;
  22452. };
  22453. context.enable = function (depMap, parent) {
  22454. var id = depMap.id,
  22455. parentId = parent && parent.map.id,
  22456. needFullExec = context.needFullExec,
  22457. fullExec = context.fullExec,
  22458. mod = getOwn(context.registry, id);
  22459. if (mod && !mod.defined) {
  22460. if (parentId && getOwn(needFullExec, parentId)) {
  22461. needFullExec[id] = depMap;
  22462. }
  22463. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  22464. (parentId && getOwn(needFullExec, parentId) &&
  22465. falseProp(fullExec, id))) {
  22466. context.require.undef(id);
  22467. }
  22468. return oldEnable.apply(context, arguments);
  22469. };
  22470. //Override load so that the file paths can be collected.
  22471. context.load = function (moduleName, url) {
  22472. /*jslint evil: true */
  22473. var contents, pluginBuilderMatch, builderName,
  22474. shim, shimExports;
  22475. //Do not mark the url as fetched if it is
  22476. //not an empty: URL, used by the optimizer.
  22477. //In that case we need to be sure to call
  22478. //load() for each module that is mapped to
  22479. //empty: so that dependencies are satisfied
  22480. //correctly.
  22481. if (url.indexOf('empty:') === 0) {
  22482. delete context.urlFetched[url];
  22483. }
  22484. //Only handle urls that can be inlined, so that means avoiding some
  22485. //URLs like ones that require network access or may be too dynamic,
  22486. //like JSONP
  22487. if (require._isSupportedBuildUrl(url)) {
  22488. //Adjust the URL if it was not transformed to use baseUrl.
  22489. url = normalizeUrlWithBase(context, moduleName, url);
  22490. //Save the module name to path and path to module name mappings.
  22491. layer.buildPathMap[moduleName] = url;
  22492. layer.buildFileToModule[url] = moduleName;
  22493. if (hasProp(context.plugins, moduleName)) {
  22494. //plugins need to have their source evaled as-is.
  22495. context.needFullExec[moduleName] = true;
  22496. }
  22497. prim().start(function () {
  22498. if (hasProp(require._cachedFileContents, url) &&
  22499. (falseProp(context.needFullExec, moduleName) ||
  22500. getOwn(context.fullExec, moduleName))) {
  22501. contents = require._cachedFileContents[url];
  22502. //If it defines require, mark it so it can be hoisted.
  22503. //Done here and in the else below, before the
  22504. //else block removes code from the contents.
  22505. //Related to #263
  22506. if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  22507. layer.existingRequireUrl = url;
  22508. }
  22509. } else {
  22510. //Load the file contents, process for conditionals, then
  22511. //evaluate it.
  22512. return require._cacheReadAsync(url).then(function (text) {
  22513. contents = text;
  22514. if (context.config.cjsTranslate &&
  22515. (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
  22516. contents = commonJs.convert(url, contents);
  22517. }
  22518. //If there is a read filter, run it now.
  22519. if (context.config.onBuildRead) {
  22520. contents = context.config.onBuildRead(moduleName, url, contents);
  22521. }
  22522. contents = pragma.process(url, contents, context.config, 'OnExecute');
  22523. //Find out if the file contains a require() definition. Need to know
  22524. //this so we can inject plugins right after it, but before they are needed,
  22525. //and to make sure this file is first, so that define calls work.
  22526. try {
  22527. if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
  22528. layer.existingRequireUrl = url;
  22529. require._cachedDefinesRequireUrls[url] = true;
  22530. }
  22531. } catch (e1) {
  22532. throw new Error('Parse error using esprima ' +
  22533. 'for file: ' + url + '\n' + e1);
  22534. }
  22535. }).then(function () {
  22536. if (hasProp(context.plugins, moduleName)) {
  22537. //This is a loader plugin, check to see if it has a build extension,
  22538. //otherwise the plugin will act as the plugin builder too.
  22539. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  22540. if (pluginBuilderMatch) {
  22541. //Load the plugin builder for the plugin contents.
  22542. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  22543. context.makeModuleMap(moduleName),
  22544. null,
  22545. true).id;
  22546. return require._cacheReadAsync(context.nameToUrl(builderName));
  22547. }
  22548. }
  22549. return contents;
  22550. }).then(function (text) {
  22551. contents = text;
  22552. //Parse out the require and define calls.
  22553. //Do this even for plugins in case they have their own
  22554. //dependencies that may be separate to how the pluginBuilder works.
  22555. try {
  22556. if (falseProp(context.needFullExec, moduleName)) {
  22557. contents = parse(moduleName, url, contents, {
  22558. insertNeedsDefine: true,
  22559. has: context.config.has,
  22560. findNestedDependencies: context.config.findNestedDependencies
  22561. });
  22562. }
  22563. } catch (e2) {
  22564. throw new Error('Parse error using esprima ' +
  22565. 'for file: ' + url + '\n' + e2);
  22566. }
  22567. require._cachedFileContents[url] = contents;
  22568. });
  22569. }
  22570. }).then(function () {
  22571. if (contents) {
  22572. eval(contents);
  22573. }
  22574. try {
  22575. //If have a string shim config, and this is
  22576. //a fully executed module, try to see if
  22577. //it created a variable in this eval scope
  22578. if (getOwn(context.needFullExec, moduleName)) {
  22579. shim = getOwn(context.config.shim, moduleName);
  22580. if (shim && shim.exports) {
  22581. shimExports = eval(shim.exports);
  22582. if (typeof shimExports !== 'undefined') {
  22583. context.buildShimExports[moduleName] = shimExports;
  22584. }
  22585. }
  22586. }
  22587. //Need to close out completion of this module
  22588. //so that listeners will get notified that it is available.
  22589. context.completeLoad(moduleName);
  22590. } catch (e) {
  22591. //Track which module could not complete loading.
  22592. if (!e.moduleTree) {
  22593. e.moduleTree = [];
  22594. }
  22595. e.moduleTree.push(moduleName);
  22596. throw e;
  22597. }
  22598. }).then(null, function (eOuter) {
  22599. if (!eOuter.fileName) {
  22600. eOuter.fileName = url;
  22601. }
  22602. throw eOuter;
  22603. }).end();
  22604. } else {
  22605. //With unsupported URLs still need to call completeLoad to
  22606. //finish loading.
  22607. context.completeLoad(moduleName);
  22608. }
  22609. };
  22610. //Marks module has having a name, and optionally executes the
  22611. //callback, but only if it meets certain criteria.
  22612. context.execCb = function (name, cb, args, exports) {
  22613. var buildShimExports = getOwn(layer.context.buildShimExports, name);
  22614. if (buildShimExports) {
  22615. return buildShimExports;
  22616. } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
  22617. return cb.apply(exports, args);
  22618. }
  22619. return undefined;
  22620. };
  22621. moduleProto.init = function (depMaps) {
  22622. if (context.needFullExec[this.map.id]) {
  22623. lang.each(depMaps, lang.bind(this, function (depMap) {
  22624. if (typeof depMap === 'string') {
  22625. depMap = context.makeModuleMap(depMap,
  22626. (this.map.isDefine ? this.map : this.map.parentMap));
  22627. }
  22628. if (!context.fullExec[depMap.id]) {
  22629. context.require.undef(depMap.id);
  22630. }
  22631. }));
  22632. }
  22633. return oldInit.apply(this, arguments);
  22634. };
  22635. moduleProto.callPlugin = function () {
  22636. var map = this.map,
  22637. pluginMap = context.makeModuleMap(map.prefix),
  22638. pluginId = pluginMap.id,
  22639. pluginMod = getOwn(context.registry, pluginId);
  22640. context.plugins[pluginId] = true;
  22641. context.needFullExec[pluginId] = map;
  22642. //If the module is not waiting to finish being defined,
  22643. //undef it and start over, to get full execution.
  22644. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  22645. context.require.undef(pluginMap.id);
  22646. }
  22647. return oldCallPlugin.apply(this, arguments);
  22648. };
  22649. }
  22650. return context;
  22651. };
  22652. //Clear up the existing context so that the newContext modifications
  22653. //above will be active.
  22654. delete require.s.contexts._;
  22655. /** Reset state for each build layer pass. */
  22656. require._buildReset = function () {
  22657. var oldContext = require.s.contexts._;
  22658. //Clear up the existing context.
  22659. delete require.s.contexts._;
  22660. //Set up new context, so the layer object can hold onto it.
  22661. require({});
  22662. layer = require._layer = {
  22663. buildPathMap: {},
  22664. buildFileToModule: {},
  22665. buildFilePaths: [],
  22666. pathAdded: {},
  22667. modulesWithNames: {},
  22668. needsDefine: {},
  22669. existingRequireUrl: "",
  22670. ignoredUrls: {},
  22671. context: require.s.contexts._
  22672. };
  22673. //Return the previous context in case it is needed, like for
  22674. //the basic config object.
  22675. return oldContext;
  22676. };
  22677. require._buildReset();
  22678. //Override define() to catch modules that just define an object, so that
  22679. //a dummy define call is not put in the build file for them. They do
  22680. //not end up getting defined via context.execCb, so we need to catch them
  22681. //at the define call.
  22682. oldDef = define;
  22683. //This function signature does not have to be exact, just match what we
  22684. //are looking for.
  22685. define = function (name) {
  22686. if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
  22687. layer.modulesWithNames[name] = true;
  22688. }
  22689. return oldDef.apply(require, arguments);
  22690. };
  22691. define.amd = oldDef.amd;
  22692. //Add some utilities for plugins
  22693. require._readFile = file.readFile;
  22694. require._fileExists = function (path) {
  22695. return file.exists(path);
  22696. };
  22697. //Called when execManager runs for a dependency. Used to figure out
  22698. //what order of execution.
  22699. require.onResourceLoad = function (context, map) {
  22700. var id = map.id,
  22701. url;
  22702. // Fix up any maps that need to be normalized as part of the fullExec
  22703. // plumbing for plugins to participate in the build.
  22704. if (context.plugins && lang.hasProp(context.plugins, id)) {
  22705. lang.eachProp(context.needFullExec, function(value, prop) {
  22706. // For plugin entries themselves, they do not have a map
  22707. // value in needFullExec, just a "true" entry.
  22708. if (value !== true && value.prefix === id && value.unnormalized) {
  22709. var map = context.makeModuleMap(value.originalName, value.parentMap);
  22710. context.needFullExec[map.id] = map;
  22711. }
  22712. });
  22713. }
  22714. //If build needed a full execution, indicate it
  22715. //has been done now. But only do it if the context is tracking
  22716. //that. Only valid for the context used in a build, not for
  22717. //other contexts being run, like for useLib, plain requirejs
  22718. //use in node/rhino.
  22719. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  22720. context.fullExec[id] = map;
  22721. }
  22722. //A plugin.
  22723. if (map.prefix) {
  22724. if (falseProp(layer.pathAdded, id)) {
  22725. layer.buildFilePaths.push(id);
  22726. //For plugins the real path is not knowable, use the name
  22727. //for both module to file and file to module mappings.
  22728. layer.buildPathMap[id] = id;
  22729. layer.buildFileToModule[id] = id;
  22730. layer.modulesWithNames[id] = true;
  22731. layer.pathAdded[id] = true;
  22732. }
  22733. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  22734. //If the url has not been added to the layer yet, and it
  22735. //is from an actual file that was loaded, add it now.
  22736. url = normalizeUrlWithBase(context, id, map.url);
  22737. if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
  22738. //Remember the list of dependencies for this layer.
  22739. layer.buildFilePaths.push(url);
  22740. layer.pathAdded[url] = true;
  22741. }
  22742. }
  22743. };
  22744. //Called by output of the parse() function, when a file does not
  22745. //explicitly call define, probably just require, but the parse()
  22746. //function normalizes on define() for dependency mapping and file
  22747. //ordering works correctly.
  22748. require.needsDefine = function (moduleName) {
  22749. layer.needsDefine[moduleName] = true;
  22750. };
  22751. };
  22752. });
  22753. /**
  22754. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22755. * Available via the MIT or new BSD license.
  22756. * see: http://github.com/jrburke/requirejs for details
  22757. */
  22758. /*jslint */
  22759. /*global define: false, console: false */
  22760. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  22761. 'use strict';
  22762. var commonJs = {
  22763. //Set to false if you do not want this file to log. Useful in environments
  22764. //like node where you want the work to happen without noise.
  22765. useLog: true,
  22766. convertDir: function (commonJsPath, savePath) {
  22767. var fileList, i,
  22768. jsFileRegExp = /\.js$/,
  22769. fileName, convertedFileName, fileContents;
  22770. //Get list of files to convert.
  22771. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  22772. //Normalize on front slashes and make sure the paths do not end in a slash.
  22773. commonJsPath = commonJsPath.replace(/\\/g, "/");
  22774. savePath = savePath.replace(/\\/g, "/");
  22775. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  22776. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  22777. }
  22778. if (savePath.charAt(savePath.length - 1) === "/") {
  22779. savePath = savePath.substring(0, savePath.length - 1);
  22780. }
  22781. //Cycle through all the JS files and convert them.
  22782. if (!fileList || !fileList.length) {
  22783. if (commonJs.useLog) {
  22784. if (commonJsPath === "convert") {
  22785. //A request just to convert one file.
  22786. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  22787. } else {
  22788. console.log("No files to convert in directory: " + commonJsPath);
  22789. }
  22790. }
  22791. } else {
  22792. for (i = 0; i < fileList.length; i++) {
  22793. fileName = fileList[i];
  22794. convertedFileName = fileName.replace(commonJsPath, savePath);
  22795. //Handle JS files.
  22796. if (jsFileRegExp.test(fileName)) {
  22797. fileContents = file.readFile(fileName);
  22798. fileContents = commonJs.convert(fileName, fileContents);
  22799. file.saveUtf8File(convertedFileName, fileContents);
  22800. } else {
  22801. //Just copy the file over.
  22802. file.copyFile(fileName, convertedFileName, true);
  22803. }
  22804. }
  22805. }
  22806. },
  22807. /**
  22808. * Does the actual file conversion.
  22809. *
  22810. * @param {String} fileName the name of the file.
  22811. *
  22812. * @param {String} fileContents the contents of a file :)
  22813. *
  22814. * @returns {String} the converted contents
  22815. */
  22816. convert: function (fileName, fileContents) {
  22817. //Strip out comments.
  22818. try {
  22819. var preamble = '',
  22820. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  22821. //First see if the module is not already RequireJS-formatted.
  22822. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  22823. return fileContents;
  22824. }
  22825. if (commonJsProps.dirname || commonJsProps.filename) {
  22826. preamble = 'var __filename = module.uri || "", ' +
  22827. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  22828. }
  22829. //Construct the wrapper boilerplate.
  22830. fileContents = 'define(function (require, exports, module) {' +
  22831. preamble +
  22832. fileContents +
  22833. '\n});\n';
  22834. } catch (e) {
  22835. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  22836. return fileContents;
  22837. }
  22838. return fileContents;
  22839. }
  22840. };
  22841. return commonJs;
  22842. });
  22843. /**
  22844. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22845. * Available via the MIT or new BSD license.
  22846. * see: http://github.com/jrburke/requirejs for details
  22847. */
  22848. /*jslint plusplus: true, nomen: true, regexp: true */
  22849. /*global define, requirejs, java, process, console */
  22850. define('build', function (require) {
  22851. 'use strict';
  22852. var build,
  22853. lang = require('lang'),
  22854. prim = require('prim'),
  22855. logger = require('logger'),
  22856. file = require('env!env/file'),
  22857. parse = require('parse'),
  22858. optimize = require('optimize'),
  22859. pragma = require('pragma'),
  22860. transform = require('transform'),
  22861. requirePatch = require('requirePatch'),
  22862. env = require('env'),
  22863. commonJs = require('commonJs'),
  22864. SourceMapGenerator = require('source-map/source-map-generator'),
  22865. hasProp = lang.hasProp,
  22866. getOwn = lang.getOwn,
  22867. falseProp = lang.falseProp,
  22868. endsWithSemiColonRegExp = /;\s*$/,
  22869. endsWithSlashRegExp = /[\/\\]$/,
  22870. resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/;
  22871. prim.nextTick = function (fn) {
  22872. fn();
  22873. };
  22874. //Now map require to the outermost requirejs, now that we have
  22875. //local dependencies for this module. The rest of the require use is
  22876. //manipulating the requirejs loader.
  22877. require = requirejs;
  22878. //Caching function for performance. Attached to
  22879. //require so it can be reused in requirePatch.js. _cachedRawText
  22880. //set up by requirePatch.js
  22881. require._cacheReadAsync = function (path, encoding) {
  22882. var d;
  22883. if (lang.hasProp(require._cachedRawText, path)) {
  22884. d = prim();
  22885. d.resolve(require._cachedRawText[path]);
  22886. return d.promise;
  22887. } else {
  22888. return file.readFileAsync(path, encoding).then(function (text) {
  22889. require._cachedRawText[path] = text;
  22890. return text;
  22891. });
  22892. }
  22893. };
  22894. function makeBuildBaseConfig() {
  22895. return {
  22896. appDir: "",
  22897. pragmas: {},
  22898. paths: {},
  22899. optimize: "uglify",
  22900. optimizeCss: "standard.keepLines.keepWhitespace",
  22901. inlineText: true,
  22902. isBuild: true,
  22903. optimizeAllPluginResources: false,
  22904. findNestedDependencies: false,
  22905. preserveLicenseComments: true,
  22906. //By default, all files/directories are copied, unless
  22907. //they match this regexp, by default just excludes .folders
  22908. dirExclusionRegExp: file.dirExclusionRegExp,
  22909. _buildPathToModuleIndex: {}
  22910. };
  22911. }
  22912. /**
  22913. * Some JS may not be valid if concatenated with other JS, in particular
  22914. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  22915. * those cases.
  22916. */
  22917. function addSemiColon(text, config) {
  22918. if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
  22919. return text;
  22920. } else {
  22921. return text + ";";
  22922. }
  22923. }
  22924. function endsWithSlash(dirName) {
  22925. if (dirName.charAt(dirName.length - 1) !== "/") {
  22926. dirName += "/";
  22927. }
  22928. return dirName;
  22929. }
  22930. //Method used by plugin writeFile calls, defined up here to avoid
  22931. //jslint warning about "making a function in a loop".
  22932. function makeWriteFile(namespace, layer) {
  22933. function writeFile(name, contents) {
  22934. logger.trace('Saving plugin-optimized file: ' + name);
  22935. file.saveUtf8File(name, contents);
  22936. }
  22937. writeFile.asModule = function (moduleName, fileName, contents) {
  22938. writeFile(fileName,
  22939. build.toTransport(namespace, moduleName, fileName, contents, layer));
  22940. };
  22941. return writeFile;
  22942. }
  22943. /**
  22944. * Main API entry point into the build. The args argument can either be
  22945. * an array of arguments (like the onese passed on a command-line),
  22946. * or it can be a JavaScript object that has the format of a build profile
  22947. * file.
  22948. *
  22949. * If it is an object, then in addition to the normal properties allowed in
  22950. * a build profile file, the object should contain one other property:
  22951. *
  22952. * The object could also contain a "buildFile" property, which is a string
  22953. * that is the file path to a build profile that contains the rest
  22954. * of the build profile directives.
  22955. *
  22956. * This function does not return a status, it should throw an error if
  22957. * there is a problem completing the build.
  22958. */
  22959. build = function (args) {
  22960. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  22961. i, j, errorMod,
  22962. stackRegExp = /( {4}at[^\n]+)\n/,
  22963. standardIndent = ' ';
  22964. return prim().start(function () {
  22965. if (!args || lang.isArray(args)) {
  22966. if (!args || args.length < 1) {
  22967. logger.error("build.js buildProfile.js\n" +
  22968. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  22969. return undefined;
  22970. }
  22971. //Next args can include a build file path as well as other build args.
  22972. //build file path comes first. If it does not contain an = then it is
  22973. //a build file path. Otherwise, just all build args.
  22974. if (args[0].indexOf("=") === -1) {
  22975. buildFile = args[0];
  22976. args.splice(0, 1);
  22977. }
  22978. //Remaining args are options to the build
  22979. cmdConfig = build.convertArrayToObject(args);
  22980. cmdConfig.buildFile = buildFile;
  22981. } else {
  22982. cmdConfig = args;
  22983. }
  22984. return build._run(cmdConfig);
  22985. }).then(null, function (e) {
  22986. var err;
  22987. errorMsg = e.toString();
  22988. errorTree = e.moduleTree;
  22989. stackMatch = stackRegExp.exec(errorMsg);
  22990. if (stackMatch) {
  22991. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  22992. }
  22993. //If a module tree that shows what module triggered the error,
  22994. //print it out.
  22995. if (errorTree && errorTree.length > 0) {
  22996. errorMsg += '\nIn module tree:\n';
  22997. for (i = errorTree.length - 1; i > -1; i--) {
  22998. errorMod = errorTree[i];
  22999. if (errorMod) {
  23000. for (j = errorTree.length - i; j > -1; j--) {
  23001. errorMsg += standardIndent;
  23002. }
  23003. errorMsg += errorMod + '\n';
  23004. }
  23005. }
  23006. logger.error(errorMsg);
  23007. }
  23008. errorStack = e.stack;
  23009. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  23010. errorMsg += '\n' + errorStack;
  23011. } else {
  23012. if (!stackMatch && errorStack) {
  23013. //Just trim out the first "at" in the stack.
  23014. stackMatch = stackRegExp.exec(errorStack);
  23015. if (stackMatch) {
  23016. errorMsg += '\n' + stackMatch[0] || '';
  23017. }
  23018. }
  23019. }
  23020. err = new Error(errorMsg);
  23021. err.originalError = e;
  23022. throw err;
  23023. });
  23024. };
  23025. build._run = function (cmdConfig) {
  23026. var buildPaths, fileName, fileNames,
  23027. paths, i,
  23028. baseConfig, config,
  23029. modules, srcPath, buildContext,
  23030. destPath, moduleMap, parentModuleMap, context,
  23031. resources, resource, plugin, fileContents,
  23032. pluginProcessed = {},
  23033. buildFileContents = "",
  23034. pluginCollector = {};
  23035. return prim().start(function () {
  23036. var prop;
  23037. //Can now run the patches to require.js to allow it to be used for
  23038. //build generation. Do it here instead of at the top of the module
  23039. //because we want normal require behavior to load the build tool
  23040. //then want to switch to build mode.
  23041. requirePatch();
  23042. config = build.createConfig(cmdConfig);
  23043. paths = config.paths;
  23044. //Remove the previous build dir, in case it contains source transforms,
  23045. //like the ones done with onBuildRead and onBuildWrite.
  23046. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  23047. file.deleteFile(config.dir);
  23048. }
  23049. if (!config.out && !config.cssIn) {
  23050. //This is not just a one-off file build but a full build profile, with
  23051. //lots of files to process.
  23052. //First copy all the baseUrl content
  23053. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  23054. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  23055. buildPaths = {};
  23056. if (config.appDir) {
  23057. //All the paths should be inside the appDir, so just adjust
  23058. //the paths to use the dirBaseUrl
  23059. for (prop in paths) {
  23060. if (hasProp(paths, prop)) {
  23061. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  23062. }
  23063. }
  23064. } else {
  23065. //If no appDir, then make sure to copy the other paths to this directory.
  23066. for (prop in paths) {
  23067. if (hasProp(paths, prop)) {
  23068. //Set up build path for each path prefix, but only do so
  23069. //if the path falls out of the current baseUrl
  23070. if (paths[prop].indexOf(config.baseUrl) === 0) {
  23071. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  23072. } else {
  23073. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop.replace(/\./g, "/");
  23074. //Make sure source path is fully formed with baseUrl,
  23075. //if it is a relative URL.
  23076. srcPath = paths[prop];
  23077. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  23078. srcPath = config.baseUrl + srcPath;
  23079. }
  23080. destPath = config.dirBaseUrl + buildPaths[prop];
  23081. //Skip empty: paths
  23082. if (srcPath !== 'empty:') {
  23083. //If the srcPath is a directory, copy the whole directory.
  23084. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  23085. //Copy files to build area. Copy all files (the /\w/ regexp)
  23086. file.copyDir(srcPath, destPath, /\w/, true);
  23087. } else {
  23088. //Try a .js extension
  23089. srcPath += '.js';
  23090. destPath += '.js';
  23091. file.copyFile(srcPath, destPath);
  23092. }
  23093. }
  23094. }
  23095. }
  23096. }
  23097. }
  23098. }
  23099. //Figure out source file location for each module layer. Do this by seeding require
  23100. //with source area configuration. This is needed so that later the module layers
  23101. //can be manually copied over to the source area, since the build may be
  23102. //require multiple times and the above copyDir call only copies newer files.
  23103. require({
  23104. baseUrl: config.baseUrl,
  23105. paths: paths,
  23106. packagePaths: config.packagePaths,
  23107. packages: config.packages
  23108. });
  23109. buildContext = require.s.contexts._;
  23110. modules = config.modules;
  23111. if (modules) {
  23112. modules.forEach(function (module) {
  23113. if (module.name) {
  23114. module._sourcePath = buildContext.nameToUrl(module.name);
  23115. //If the module does not exist, and this is not a "new" module layer,
  23116. //as indicated by a true "create" property on the module, and
  23117. //it is not a plugin-loaded resource, and there is no
  23118. //'rawText' containing the module's source then throw an error.
  23119. if (!file.exists(module._sourcePath) && !module.create &&
  23120. module.name.indexOf('!') === -1 &&
  23121. (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  23122. throw new Error("ERROR: module path does not exist: " +
  23123. module._sourcePath + " for module named: " + module.name +
  23124. ". Path is relative to: " + file.absPath('.'));
  23125. }
  23126. }
  23127. });
  23128. }
  23129. if (config.out) {
  23130. //Just set up the _buildPath for the module layer.
  23131. require(config);
  23132. if (!config.cssIn) {
  23133. config.modules[0]._buildPath = typeof config.out === 'function' ?
  23134. 'FUNCTION' : config.out;
  23135. }
  23136. } else if (!config.cssIn) {
  23137. //Now set up the config for require to use the build area, and calculate the
  23138. //build file locations. Pass along any config info too.
  23139. baseConfig = {
  23140. baseUrl: config.dirBaseUrl,
  23141. paths: buildPaths
  23142. };
  23143. lang.mixin(baseConfig, config);
  23144. require(baseConfig);
  23145. if (modules) {
  23146. modules.forEach(function (module) {
  23147. if (module.name) {
  23148. module._buildPath = buildContext.nameToUrl(module.name, null);
  23149. //If buildPath and sourcePath are the same, throw since this
  23150. //would result in modifying source. This condition can happen
  23151. //with some more tricky paths: config and appDir/baseUrl
  23152. //setting, which is a sign of incorrect config.
  23153. if (module._buildPath === module._sourcePath) {
  23154. throw new Error('Module ID \'' + module.name +
  23155. '\' has a source path that is same as output path: ' +
  23156. module._sourcePath +
  23157. '. Stopping, config is malformed.');
  23158. }
  23159. if (!module.create) {
  23160. file.copyFile(module._sourcePath, module._buildPath);
  23161. }
  23162. }
  23163. });
  23164. }
  23165. }
  23166. //Run CSS optimizations before doing JS module tracing, to allow
  23167. //things like text loader plugins loading CSS to get the optimized
  23168. //CSS.
  23169. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  23170. buildFileContents += optimize.css(config.dir, config);
  23171. }
  23172. }).then(function() {
  23173. baseConfig = lang.deeplikeCopy(require.s.contexts._.config);
  23174. }).then(function () {
  23175. var actions = [];
  23176. if (modules) {
  23177. actions = modules.map(function (module, i) {
  23178. return function () {
  23179. //Save off buildPath to module index in a hash for quicker
  23180. //lookup later.
  23181. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
  23182. //Call require to calculate dependencies.
  23183. return build.traceDependencies(module, config, baseConfig)
  23184. .then(function (layer) {
  23185. module.layer = layer;
  23186. });
  23187. };
  23188. });
  23189. return prim.serial(actions);
  23190. }
  23191. }).then(function () {
  23192. var actions;
  23193. if (modules) {
  23194. //Now build up shadow layers for anything that should be excluded.
  23195. //Do this after tracing dependencies for each module, in case one
  23196. //of those modules end up being one of the excluded values.
  23197. actions = modules.map(function (module) {
  23198. return function () {
  23199. if (module.exclude) {
  23200. module.excludeLayers = [];
  23201. return prim.serial(module.exclude.map(function (exclude, i) {
  23202. return function () {
  23203. //See if it is already in the list of modules.
  23204. //If not trace dependencies for it.
  23205. var found = build.findBuildModule(exclude, modules);
  23206. if (found) {
  23207. module.excludeLayers[i] = found;
  23208. } else {
  23209. return build.traceDependencies({name: exclude}, config, baseConfig)
  23210. .then(function (layer) {
  23211. module.excludeLayers[i] = { layer: layer };
  23212. });
  23213. }
  23214. };
  23215. }));
  23216. }
  23217. };
  23218. });
  23219. return prim.serial(actions);
  23220. }
  23221. }).then(function () {
  23222. if (modules) {
  23223. return prim.serial(modules.map(function (module) {
  23224. return function () {
  23225. if (module.exclude) {
  23226. //module.exclude is an array of module names. For each one,
  23227. //get the nested dependencies for it via a matching entry
  23228. //in the module.excludeLayers array.
  23229. module.exclude.forEach(function (excludeModule, i) {
  23230. var excludeLayer = module.excludeLayers[i].layer,
  23231. map = excludeLayer.buildFileToModule;
  23232. excludeLayer.buildFilePaths.forEach(function(filePath){
  23233. build.removeModulePath(map[filePath], filePath, module.layer);
  23234. });
  23235. });
  23236. }
  23237. if (module.excludeShallow) {
  23238. //module.excludeShallow is an array of module names.
  23239. //shallow exclusions are just that module itself, and not
  23240. //its nested dependencies.
  23241. module.excludeShallow.forEach(function (excludeShallowModule) {
  23242. var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
  23243. if (path) {
  23244. build.removeModulePath(excludeShallowModule, path, module.layer);
  23245. }
  23246. });
  23247. }
  23248. //Flatten them and collect the build output for each module.
  23249. return build.flattenModule(module, module.layer, config).then(function (builtModule) {
  23250. var finalText, baseName;
  23251. //Save it to a temp file for now, in case there are other layers that
  23252. //contain optimized content that should not be included in later
  23253. //layer optimizations. See issue #56.
  23254. if (module._buildPath === 'FUNCTION') {
  23255. module._buildText = builtModule.text;
  23256. module._buildSourceMap = builtModule.sourceMap;
  23257. } else {
  23258. finalText = builtModule.text;
  23259. if (builtModule.sourceMap) {
  23260. baseName = module._buildPath.split('/');
  23261. baseName = baseName.pop();
  23262. finalText += '\n//# sourceMappingURL=' + baseName + '.map';
  23263. file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
  23264. }
  23265. file.saveUtf8File(module._buildPath + '-temp', finalText);
  23266. }
  23267. buildFileContents += builtModule.buildText;
  23268. });
  23269. };
  23270. }));
  23271. }
  23272. }).then(function () {
  23273. var moduleName, outOrigSourceMap;
  23274. if (modules) {
  23275. //Now move the build layers to their final position.
  23276. modules.forEach(function (module) {
  23277. var finalPath = module._buildPath;
  23278. if (finalPath !== 'FUNCTION') {
  23279. if (file.exists(finalPath)) {
  23280. file.deleteFile(finalPath);
  23281. }
  23282. file.renameFile(finalPath + '-temp', finalPath);
  23283. //And finally, if removeCombined is specified, remove
  23284. //any of the files that were used in this layer.
  23285. //Be sure not to remove other build layers.
  23286. if (config.removeCombined && !config.out) {
  23287. module.layer.buildFilePaths.forEach(function (path) {
  23288. var isLayer = modules.some(function (mod) {
  23289. return mod._buildPath === path;
  23290. }),
  23291. relPath = build.makeRelativeFilePath(config.dir, path);
  23292. if (file.exists(path) &&
  23293. // not a build layer target
  23294. !isLayer &&
  23295. // not outside the build directory
  23296. relPath.indexOf('..') !== 0) {
  23297. file.deleteFile(path);
  23298. }
  23299. });
  23300. }
  23301. }
  23302. //Signal layer is done
  23303. if (config.onModuleBundleComplete) {
  23304. config.onModuleBundleComplete(module.onCompleteData);
  23305. }
  23306. });
  23307. }
  23308. //If removeCombined in play, remove any empty directories that
  23309. //may now exist because of its use
  23310. if (config.removeCombined && !config.out && config.dir) {
  23311. file.deleteEmptyDirs(config.dir);
  23312. }
  23313. //Do other optimizations.
  23314. if (config.out && !config.cssIn) {
  23315. //Just need to worry about one JS file.
  23316. fileName = config.modules[0]._buildPath;
  23317. if (fileName === 'FUNCTION') {
  23318. outOrigSourceMap = config.modules[0]._buildSourceMap;
  23319. config._buildSourceMap = outOrigSourceMap;
  23320. config.modules[0]._buildText = optimize.js((config.modules[0].name ||
  23321. config.modules[0].include[0] ||
  23322. fileName) + '.build.js',
  23323. config.modules[0]._buildText,
  23324. null,
  23325. config);
  23326. if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
  23327. config.modules[0]._buildSourceMap = config._buildSourceMap;
  23328. config._buildSourceMap = null;
  23329. }
  23330. } else {
  23331. optimize.jsFile(fileName, null, fileName, config);
  23332. }
  23333. } else if (!config.cssIn) {
  23334. //Normal optimizations across modules.
  23335. //JS optimizations.
  23336. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  23337. fileNames.forEach(function (fileName) {
  23338. var cfg, override, moduleIndex;
  23339. //Generate the module name from the config.dir root.
  23340. moduleName = fileName.replace(config.dir, '');
  23341. //Get rid of the extension
  23342. moduleName = moduleName.substring(0, moduleName.length - 3);
  23343. //If there is an override for a specific layer build module,
  23344. //and this file is that module, mix in the override for use
  23345. //by optimize.jsFile.
  23346. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  23347. //Normalize, since getOwn could have returned undefined
  23348. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  23349. //Try to avoid extra work if the other files do not need to
  23350. //be read. Build layers should be processed at the very
  23351. //least for optimization.
  23352. if (moduleIndex > -1 || !config.skipDirOptimize ||
  23353. config.normalizeDirDefines === "all" ||
  23354. config.cjsTranslate) {
  23355. //Convert the file to transport format, but without a name
  23356. //inserted (by passing null for moduleName) since the files are
  23357. //standalone, one module per file.
  23358. fileContents = file.readFile(fileName);
  23359. //For builds, if wanting cjs translation, do it now, so that
  23360. //the individual modules can be loaded cross domain via
  23361. //plain script tags.
  23362. if (config.cjsTranslate &&
  23363. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  23364. fileContents = commonJs.convert(fileName, fileContents);
  23365. }
  23366. if (moduleIndex === -1) {
  23367. if (config.onBuildRead) {
  23368. fileContents = config.onBuildRead(moduleName,
  23369. fileName,
  23370. fileContents);
  23371. }
  23372. //Only do transport normalization if this is not a build
  23373. //layer (since it was already normalized) and if
  23374. //normalizeDirDefines indicated all should be done.
  23375. if (config.normalizeDirDefines === "all") {
  23376. fileContents = build.toTransport(config.namespace,
  23377. null,
  23378. fileName,
  23379. fileContents);
  23380. }
  23381. if (config.onBuildWrite) {
  23382. fileContents = config.onBuildWrite(moduleName,
  23383. fileName,
  23384. fileContents);
  23385. }
  23386. }
  23387. override = moduleIndex > -1 ?
  23388. config.modules[moduleIndex].override : null;
  23389. if (override) {
  23390. cfg = build.createOverrideConfig(config, override);
  23391. } else {
  23392. cfg = config;
  23393. }
  23394. if (moduleIndex > -1 || !config.skipDirOptimize) {
  23395. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  23396. }
  23397. }
  23398. });
  23399. //Normalize all the plugin resources.
  23400. context = require.s.contexts._;
  23401. for (moduleName in pluginCollector) {
  23402. if (hasProp(pluginCollector, moduleName)) {
  23403. parentModuleMap = context.makeModuleMap(moduleName);
  23404. resources = pluginCollector[moduleName];
  23405. for (i = 0; i < resources.length; i++) {
  23406. resource = resources[i];
  23407. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  23408. if (falseProp(context.plugins, moduleMap.prefix)) {
  23409. //Set the value in context.plugins so it
  23410. //will be evaluated as a full plugin.
  23411. context.plugins[moduleMap.prefix] = true;
  23412. //Do not bother if the plugin is not available.
  23413. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  23414. continue;
  23415. }
  23416. //Rely on the require in the build environment
  23417. //to be synchronous
  23418. context.require([moduleMap.prefix]);
  23419. //Now that the plugin is loaded, redo the moduleMap
  23420. //since the plugin will need to normalize part of the path.
  23421. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  23422. }
  23423. //Only bother with plugin resources that can be handled
  23424. //processed by the plugin, via support of the writeFile
  23425. //method.
  23426. if (falseProp(pluginProcessed, moduleMap.id)) {
  23427. //Only do the work if the plugin was really loaded.
  23428. //Using an internal access because the file may
  23429. //not really be loaded.
  23430. plugin = getOwn(context.defined, moduleMap.prefix);
  23431. if (plugin && plugin.writeFile) {
  23432. plugin.writeFile(
  23433. moduleMap.prefix,
  23434. moduleMap.name,
  23435. require,
  23436. makeWriteFile(
  23437. config.namespace
  23438. ),
  23439. context.config
  23440. );
  23441. }
  23442. pluginProcessed[moduleMap.id] = true;
  23443. }
  23444. }
  23445. }
  23446. }
  23447. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  23448. //All module layers are done, write out the build.txt file.
  23449. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  23450. }
  23451. //If just have one CSS file to optimize, do that here.
  23452. if (config.cssIn) {
  23453. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  23454. }
  23455. if (typeof config.out === 'function') {
  23456. config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
  23457. }
  23458. //Print out what was built into which layers.
  23459. if (buildFileContents) {
  23460. logger.info(buildFileContents);
  23461. return buildFileContents;
  23462. }
  23463. return '';
  23464. });
  23465. };
  23466. /**
  23467. * Converts command line args like "paths.foo=../some/path"
  23468. * result.paths = { foo: '../some/path' } where prop = paths,
  23469. * name = paths.foo and value = ../some/path, so it assumes the
  23470. * name=value splitting has already happened.
  23471. */
  23472. function stringDotToObj(result, name, value) {
  23473. var parts = name.split('.');
  23474. parts.forEach(function (prop, i) {
  23475. if (i === parts.length - 1) {
  23476. result[prop] = value;
  23477. } else {
  23478. if (falseProp(result, prop)) {
  23479. result[prop] = {};
  23480. }
  23481. result = result[prop];
  23482. }
  23483. });
  23484. }
  23485. build.objProps = {
  23486. paths: true,
  23487. wrap: true,
  23488. pragmas: true,
  23489. pragmasOnSave: true,
  23490. has: true,
  23491. hasOnSave: true,
  23492. uglify: true,
  23493. uglify2: true,
  23494. closure: true,
  23495. map: true,
  23496. throwWhen: true
  23497. };
  23498. build.hasDotPropMatch = function (prop) {
  23499. var dotProp,
  23500. index = prop.indexOf('.');
  23501. if (index !== -1) {
  23502. dotProp = prop.substring(0, index);
  23503. return hasProp(build.objProps, dotProp);
  23504. }
  23505. return false;
  23506. };
  23507. /**
  23508. * Converts an array that has String members of "name=value"
  23509. * into an object, where the properties on the object are the names in the array.
  23510. * Also converts the strings "true" and "false" to booleans for the values.
  23511. * member name/value pairs, and converts some comma-separated lists into
  23512. * arrays.
  23513. * @param {Array} ary
  23514. */
  23515. build.convertArrayToObject = function (ary) {
  23516. var result = {}, i, separatorIndex, prop, value,
  23517. needArray = {
  23518. "include": true,
  23519. "exclude": true,
  23520. "excludeShallow": true,
  23521. "insertRequire": true,
  23522. "stubModules": true,
  23523. "deps": true,
  23524. "mainConfigFile": true
  23525. };
  23526. for (i = 0; i < ary.length; i++) {
  23527. separatorIndex = ary[i].indexOf("=");
  23528. if (separatorIndex === -1) {
  23529. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  23530. }
  23531. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  23532. if (value === "true") {
  23533. value = true;
  23534. } else if (value === "false") {
  23535. value = false;
  23536. }
  23537. prop = ary[i].substring(0, separatorIndex);
  23538. //Convert to array if necessary
  23539. if (getOwn(needArray, prop)) {
  23540. value = value.split(",");
  23541. }
  23542. if (build.hasDotPropMatch(prop)) {
  23543. stringDotToObj(result, prop, value);
  23544. } else {
  23545. result[prop] = value;
  23546. }
  23547. }
  23548. return result; //Object
  23549. };
  23550. build.makeAbsPath = function (path, absFilePath) {
  23551. if (!absFilePath) {
  23552. return path;
  23553. }
  23554. //Add abspath if necessary. If path starts with a slash or has a colon,
  23555. //then already is an abolute path.
  23556. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  23557. path = absFilePath +
  23558. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  23559. path;
  23560. path = file.normalize(path);
  23561. }
  23562. return path.replace(lang.backSlashRegExp, '/');
  23563. };
  23564. build.makeAbsObject = function (props, obj, absFilePath) {
  23565. var i, prop;
  23566. if (obj) {
  23567. for (i = 0; i < props.length; i++) {
  23568. prop = props[i];
  23569. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  23570. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  23571. }
  23572. }
  23573. }
  23574. };
  23575. /**
  23576. * For any path in a possible config, make it absolute relative
  23577. * to the absFilePath passed in.
  23578. */
  23579. build.makeAbsConfig = function (config, absFilePath) {
  23580. var props, prop, i;
  23581. props = ["appDir", "dir", "baseUrl"];
  23582. for (i = 0; i < props.length; i++) {
  23583. prop = props[i];
  23584. if (getOwn(config, prop)) {
  23585. //Add abspath if necessary, make sure these paths end in
  23586. //slashes
  23587. if (prop === "baseUrl") {
  23588. config.originalBaseUrl = config.baseUrl;
  23589. if (config.appDir) {
  23590. //If baseUrl with an appDir, the baseUrl is relative to
  23591. //the appDir, *not* the absFilePath. appDir and dir are
  23592. //made absolute before baseUrl, so this will work.
  23593. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  23594. } else {
  23595. //The dir output baseUrl is same as regular baseUrl, both
  23596. //relative to the absFilePath.
  23597. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  23598. }
  23599. } else {
  23600. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  23601. }
  23602. config[prop] = endsWithSlash(config[prop]);
  23603. }
  23604. }
  23605. build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]),
  23606. config, absFilePath);
  23607. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  23608. };
  23609. /**
  23610. * Creates a relative path to targetPath from refPath.
  23611. * Only deals with file paths, not folders. If folders,
  23612. * make sure paths end in a trailing '/'.
  23613. */
  23614. build.makeRelativeFilePath = function (refPath, targetPath) {
  23615. var i, dotLength, finalParts, length, targetParts, targetName,
  23616. refParts = refPath.split('/'),
  23617. hasEndSlash = endsWithSlashRegExp.test(targetPath),
  23618. dotParts = [];
  23619. targetPath = file.normalize(targetPath);
  23620. if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
  23621. targetPath += '/';
  23622. }
  23623. targetParts = targetPath.split('/');
  23624. //Pull off file name
  23625. targetName = targetParts.pop();
  23626. //Also pop off the ref file name to make the matches against
  23627. //targetParts equivalent.
  23628. refParts.pop();
  23629. length = refParts.length;
  23630. for (i = 0; i < length; i += 1) {
  23631. if (refParts[i] !== targetParts[i]) {
  23632. break;
  23633. }
  23634. }
  23635. //Now i is the index in which they diverge.
  23636. finalParts = targetParts.slice(i);
  23637. dotLength = length - i;
  23638. for (i = 0; i > -1 && i < dotLength; i += 1) {
  23639. dotParts.push('..');
  23640. }
  23641. return dotParts.join('/') + (dotParts.length ? '/' : '') +
  23642. finalParts.join('/') + (finalParts.length ? '/' : '') +
  23643. targetName;
  23644. };
  23645. build.nestedMix = {
  23646. paths: true,
  23647. has: true,
  23648. hasOnSave: true,
  23649. pragmas: true,
  23650. pragmasOnSave: true
  23651. };
  23652. /**
  23653. * Mixes additional source config into target config, and merges some
  23654. * nested config, like paths, correctly.
  23655. */
  23656. function mixConfig(target, source, skipArrays) {
  23657. var prop, value, isArray, targetValue;
  23658. for (prop in source) {
  23659. if (hasProp(source, prop)) {
  23660. //If the value of the property is a plain object, then
  23661. //allow a one-level-deep mixing of it.
  23662. value = source[prop];
  23663. isArray = lang.isArray(value);
  23664. if (typeof value === 'object' && value &&
  23665. !isArray && !lang.isFunction(value) &&
  23666. !lang.isRegExp(value)) {
  23667. // TODO: need to generalize this work, maybe also reuse
  23668. // the work done in requirejs configure, perhaps move to
  23669. // just a deep copy/merge overall. However, given the
  23670. // amount of observable change, wait for a dot release.
  23671. // This change is in relation to #645
  23672. if (prop === 'map') {
  23673. if (!target.map) {
  23674. target.map = {};
  23675. }
  23676. lang.deepMix(target.map, source.map);
  23677. } else {
  23678. target[prop] = lang.mixin({}, target[prop], value, true);
  23679. }
  23680. } else if (isArray) {
  23681. if (!skipArrays) {
  23682. // Some config, like packages, are arrays. For those,
  23683. // just merge the results.
  23684. targetValue = target[prop];
  23685. if (lang.isArray(targetValue)) {
  23686. target[prop] = targetValue.concat(value);
  23687. } else {
  23688. target[prop] = value;
  23689. }
  23690. }
  23691. } else {
  23692. target[prop] = value;
  23693. }
  23694. }
  23695. }
  23696. //Set up log level since it can affect if errors are thrown
  23697. //or caught and passed to errbacks while doing config setup.
  23698. if (lang.hasProp(target, 'logLevel')) {
  23699. logger.logLevel(target.logLevel);
  23700. }
  23701. }
  23702. /**
  23703. * Converts a wrap.startFile or endFile to be start/end as a string.
  23704. * the startFile/endFile values can be arrays.
  23705. */
  23706. function flattenWrapFile(wrap, keyName, absFilePath) {
  23707. var keyFileName = keyName + 'File';
  23708. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  23709. wrap[keyName] = '';
  23710. if (typeof wrap[keyFileName] === 'string') {
  23711. wrap[keyFileName] = [wrap[keyFileName]];
  23712. }
  23713. wrap[keyFileName].forEach(function (fileName) {
  23714. wrap[keyName] += (wrap[keyName] ? '\n' : '') +
  23715. file.readFile(build.makeAbsPath(fileName, absFilePath));
  23716. });
  23717. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  23718. //Allow missing one, just set to empty string.
  23719. wrap[keyName] = '';
  23720. } else if (typeof wrap[keyName] !== 'string') {
  23721. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  23722. }
  23723. }
  23724. function normalizeWrapConfig(config, absFilePath) {
  23725. //Get any wrap text.
  23726. try {
  23727. if (config.wrap) {
  23728. if (config.wrap === true) {
  23729. //Use default values.
  23730. config.wrap = {
  23731. start: '(function () {',
  23732. end: '}());'
  23733. };
  23734. } else {
  23735. flattenWrapFile(config.wrap, 'start', absFilePath);
  23736. flattenWrapFile(config.wrap, 'end', absFilePath);
  23737. }
  23738. }
  23739. } catch (wrapError) {
  23740. throw new Error('Malformed wrap config: ' + wrapError.toString());
  23741. }
  23742. }
  23743. /**
  23744. * Creates a config object for an optimization build.
  23745. * It will also read the build profile if it is available, to create
  23746. * the configuration.
  23747. *
  23748. * @param {Object} cfg config options that take priority
  23749. * over defaults and ones in the build file. These options could
  23750. * be from a command line, for instance.
  23751. *
  23752. * @param {Object} the created config object.
  23753. */
  23754. build.createConfig = function (cfg) {
  23755. /*jslint evil: true */
  23756. var buildFileContents, buildFileConfig, mainConfig,
  23757. mainConfigFile, mainConfigPath, buildFile, absFilePath,
  23758. config = {},
  23759. buildBaseConfig = makeBuildBaseConfig();
  23760. //Make sure all paths are relative to current directory.
  23761. absFilePath = file.absPath('.');
  23762. build.makeAbsConfig(cfg, absFilePath);
  23763. build.makeAbsConfig(buildBaseConfig, absFilePath);
  23764. lang.mixin(config, buildBaseConfig);
  23765. lang.mixin(config, cfg, true);
  23766. //Set up log level early since it can affect if errors are thrown
  23767. //or caught and passed to errbacks, even while constructing config.
  23768. if (lang.hasProp(config, 'logLevel')) {
  23769. logger.logLevel(config.logLevel);
  23770. }
  23771. if (config.buildFile) {
  23772. //A build file exists, load it to get more config.
  23773. buildFile = file.absPath(config.buildFile);
  23774. //Find the build file, and make sure it exists, if this is a build
  23775. //that has a build profile, and not just command line args with an in=path
  23776. if (!file.exists(buildFile)) {
  23777. throw new Error("ERROR: build file does not exist: " + buildFile);
  23778. }
  23779. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  23780. //Load build file options.
  23781. buildFileContents = file.readFile(buildFile);
  23782. try {
  23783. buildFileConfig = eval("(" + buildFileContents + ")");
  23784. build.makeAbsConfig(buildFileConfig, absFilePath);
  23785. //Mix in the config now so that items in mainConfigFile can
  23786. //be resolved relative to them if necessary, like if appDir
  23787. //is set here, but the baseUrl is in mainConfigFile. Will
  23788. //re-mix in the same build config later after mainConfigFile
  23789. //is processed, since build config should take priority.
  23790. mixConfig(config, buildFileConfig);
  23791. } catch (e) {
  23792. throw new Error("Build file " + buildFile + " is malformed: " + e);
  23793. }
  23794. }
  23795. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  23796. if (mainConfigFile) {
  23797. if (typeof mainConfigFile === 'string') {
  23798. mainConfigFile = [mainConfigFile];
  23799. }
  23800. mainConfigFile.forEach(function (configFile) {
  23801. configFile = build.makeAbsPath(configFile, absFilePath);
  23802. if (!file.exists(configFile)) {
  23803. throw new Error(configFile + ' does not exist.');
  23804. }
  23805. try {
  23806. mainConfig = parse.findConfig(file.readFile(configFile)).config;
  23807. } catch (configError) {
  23808. throw new Error('The config in mainConfigFile ' +
  23809. configFile +
  23810. ' cannot be used because it cannot be evaluated' +
  23811. ' correctly while running in the optimizer. Try only' +
  23812. ' using a config that is also valid JSON, or do not use' +
  23813. ' mainConfigFile and instead copy the config values needed' +
  23814. ' into a build file or command line arguments given to the optimizer.\n' +
  23815. 'Source error from parsing: ' + configFile + ': ' + configError);
  23816. }
  23817. if (mainConfig) {
  23818. mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
  23819. //Add in some existing config, like appDir, since they can be
  23820. //used inside the configFile -- paths and baseUrl are
  23821. //relative to them.
  23822. if (config.appDir && !mainConfig.appDir) {
  23823. mainConfig.appDir = config.appDir;
  23824. }
  23825. //If no baseUrl, then use the directory holding the main config.
  23826. if (!mainConfig.baseUrl) {
  23827. mainConfig.baseUrl = mainConfigPath;
  23828. }
  23829. build.makeAbsConfig(mainConfig, mainConfigPath);
  23830. mixConfig(config, mainConfig);
  23831. }
  23832. });
  23833. }
  23834. //Mix in build file config, but only after mainConfig has been mixed in.
  23835. //Since this is a re-application, skip array merging.
  23836. if (buildFileConfig) {
  23837. mixConfig(config, buildFileConfig, true);
  23838. }
  23839. //Re-apply the override config values. Command line
  23840. //args should take precedence over build file values.
  23841. //Since this is a re-application, skip array merging.
  23842. mixConfig(config, cfg, true);
  23843. //Fix paths to full paths so that they can be adjusted consistently
  23844. //lately to be in the output area.
  23845. lang.eachProp(config.paths, function (value, prop) {
  23846. if (lang.isArray(value)) {
  23847. throw new Error('paths fallback not supported in optimizer. ' +
  23848. 'Please provide a build config path override ' +
  23849. 'for ' + prop);
  23850. }
  23851. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  23852. });
  23853. //Set final output dir
  23854. if (hasProp(config, "baseUrl")) {
  23855. if (config.appDir) {
  23856. if (!config.originalBaseUrl) {
  23857. throw new Error('Please set a baseUrl in the build config');
  23858. }
  23859. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  23860. } else {
  23861. config.dirBaseUrl = config.dir || config.baseUrl;
  23862. }
  23863. //Make sure dirBaseUrl ends in a slash, since it is
  23864. //concatenated with other strings.
  23865. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  23866. }
  23867. //If out=stdout, write output to STDOUT instead of a file.
  23868. if (config.out && config.out === 'stdout') {
  23869. config.out = function (content) {
  23870. var e = env.get();
  23871. if (e === 'rhino') {
  23872. var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');
  23873. out.println(content);
  23874. } else if (e === 'node') {
  23875. process.stdout.setEncoding('utf8');
  23876. process.stdout.write(content);
  23877. } else {
  23878. console.log(content);
  23879. }
  23880. };
  23881. }
  23882. //Check for errors in config
  23883. if (config.main) {
  23884. throw new Error('"main" passed as an option, but the ' +
  23885. 'supported option is called "name".');
  23886. }
  23887. if (config.out && !config.name && !config.modules && !config.include &&
  23888. !config.cssIn) {
  23889. throw new Error('Missing either a "name", "include" or "modules" ' +
  23890. 'option');
  23891. }
  23892. if (config.cssIn) {
  23893. if (config.dir || config.appDir) {
  23894. throw new Error('cssIn is only for the output of single file ' +
  23895. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  23896. }
  23897. if (!config.out) {
  23898. throw new Error('"out" option missing.');
  23899. }
  23900. }
  23901. if (!config.cssIn && !config.baseUrl) {
  23902. //Just use the current directory as the baseUrl
  23903. config.baseUrl = './';
  23904. }
  23905. if (!config.out && !config.dir) {
  23906. throw new Error('Missing either an "out" or "dir" config value. ' +
  23907. 'If using "appDir" for a full project optimization, ' +
  23908. 'use "dir". If you want to optimize to one file, ' +
  23909. 'use "out".');
  23910. }
  23911. if (config.appDir && config.out) {
  23912. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  23913. 'instead. appDir is used to copy whole projects, ' +
  23914. 'where "out" with "baseUrl" is used to just ' +
  23915. 'optimize to one file.');
  23916. }
  23917. if (config.out && config.dir) {
  23918. throw new Error('The "out" and "dir" options are incompatible.' +
  23919. ' Use "out" if you are targeting a single file' +
  23920. ' for optimization, and "dir" if you want the appDir' +
  23921. ' or baseUrl directories optimized.');
  23922. }
  23923. if (config.dir) {
  23924. // Make sure the output dir is not set to a parent of the
  23925. // source dir or the same dir, as it will result in source
  23926. // code deletion.
  23927. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
  23928. config.dir === config.appDir ||
  23929. (config.baseUrl && build.makeRelativeFilePath(config.dir,
  23930. config.baseUrl).indexOf('..') !== 0) ||
  23931. (config.appDir &&
  23932. build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
  23933. throw new Error('"dir" is set to a parent or same directory as' +
  23934. ' "appDir" or "baseUrl". This can result in' +
  23935. ' the deletion of source code. Stopping. If' +
  23936. ' you want to allow possible overwriting of' +
  23937. ' source code, set "allowSourceOverwrites"' +
  23938. ' to true in the build config, but do so at' +
  23939. ' your own risk. In that case, you may want' +
  23940. ' to also set "keepBuildDir" to true.');
  23941. }
  23942. }
  23943. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  23944. throw new Error('insertRequire should be a list of module IDs' +
  23945. ' to insert in to a require([]) call.');
  23946. }
  23947. if (config.generateSourceMaps) {
  23948. if (config.preserveLicenseComments && config.optimize !== 'none') {
  23949. throw new Error('Cannot use preserveLicenseComments and ' +
  23950. 'generateSourceMaps together. Either explcitly set ' +
  23951. 'preserveLicenseComments to false (default is true) or ' +
  23952. 'turn off generateSourceMaps. If you want source maps with ' +
  23953. 'license comments, see: ' +
  23954. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  23955. } else if (config.optimize !== 'none' &&
  23956. config.optimize !== 'closure' &&
  23957. config.optimize !== 'uglify2') {
  23958. //Allow optimize: none to pass, since it is useful when toggling
  23959. //minification on and off to debug something, and it implicitly
  23960. //works, since it does not need a source map.
  23961. throw new Error('optimize: "' + config.optimize +
  23962. '" does not support generateSourceMaps.');
  23963. }
  23964. }
  23965. if ((config.name || config.include) && !config.modules) {
  23966. //Just need to build one file, but may be part of a whole appDir/
  23967. //baseUrl copy, but specified on the command line, so cannot do
  23968. //the modules array setup. So create a modules section in that
  23969. //case.
  23970. config.modules = [
  23971. {
  23972. name: config.name,
  23973. out: config.out,
  23974. create: config.create,
  23975. include: config.include,
  23976. exclude: config.exclude,
  23977. excludeShallow: config.excludeShallow,
  23978. insertRequire: config.insertRequire,
  23979. stubModules: config.stubModules
  23980. }
  23981. ];
  23982. delete config.stubModules;
  23983. } else if (config.modules && config.out) {
  23984. throw new Error('If the "modules" option is used, then there ' +
  23985. 'should be a "dir" option set and "out" should ' +
  23986. 'not be used since "out" is only for single file ' +
  23987. 'optimization output.');
  23988. } else if (config.modules && config.name) {
  23989. throw new Error('"name" and "modules" options are incompatible. ' +
  23990. 'Either use "name" if doing a single file ' +
  23991. 'optimization, or "modules" if you want to target ' +
  23992. 'more than one file for optimization.');
  23993. }
  23994. if (config.out && !config.cssIn) {
  23995. //Just one file to optimize.
  23996. //Does not have a build file, so set up some defaults.
  23997. //Optimizing CSS should not be allowed, unless explicitly
  23998. //asked for on command line. In that case the only task is
  23999. //to optimize a CSS file.
  24000. if (!cfg.optimizeCss) {
  24001. config.optimizeCss = "none";
  24002. }
  24003. }
  24004. //Normalize cssPrefix
  24005. if (config.cssPrefix) {
  24006. //Make sure cssPrefix ends in a slash
  24007. config.cssPrefix = endsWithSlash(config.cssPrefix);
  24008. } else {
  24009. config.cssPrefix = '';
  24010. }
  24011. //Cycle through modules and normalize
  24012. if (config.modules && config.modules.length) {
  24013. config.modules.forEach(function (mod) {
  24014. //Combine any local stubModules with global values.
  24015. if (config.stubModules) {
  24016. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  24017. }
  24018. //Create a hash lookup for the stubModules config to make lookup
  24019. //cheaper later.
  24020. if (mod.stubModules) {
  24021. mod.stubModules._byName = {};
  24022. mod.stubModules.forEach(function (id) {
  24023. mod.stubModules._byName[id] = true;
  24024. });
  24025. }
  24026. // Legacy command support, which allowed a single string ID
  24027. // for include.
  24028. if (typeof mod.include === 'string') {
  24029. mod.include = [mod.include];
  24030. }
  24031. //Allow wrap config in overrides, but normalize it.
  24032. if (mod.override) {
  24033. normalizeWrapConfig(mod.override, absFilePath);
  24034. }
  24035. });
  24036. }
  24037. normalizeWrapConfig(config, absFilePath);
  24038. //Do final input verification
  24039. if (config.context) {
  24040. throw new Error('The build argument "context" is not supported' +
  24041. ' in a build. It should only be used in web' +
  24042. ' pages.');
  24043. }
  24044. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  24045. //set to "skip" otherwise set to "all".
  24046. if (!hasProp(config, 'normalizeDirDefines')) {
  24047. if (config.optimize === 'none' || config.skipDirOptimize) {
  24048. config.normalizeDirDefines = 'skip';
  24049. } else {
  24050. config.normalizeDirDefines = 'all';
  24051. }
  24052. }
  24053. //Set file.fileExclusionRegExp if desired
  24054. if (hasProp(config, 'fileExclusionRegExp')) {
  24055. if (typeof config.fileExclusionRegExp === "string") {
  24056. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  24057. } else {
  24058. file.exclusionRegExp = config.fileExclusionRegExp;
  24059. }
  24060. } else if (hasProp(config, 'dirExclusionRegExp')) {
  24061. //Set file.dirExclusionRegExp if desired, this is the old
  24062. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  24063. //compatibility
  24064. file.exclusionRegExp = config.dirExclusionRegExp;
  24065. }
  24066. //Track the deps, but in a different key, so that they are not loaded
  24067. //as part of config seeding before all config is in play (#648). Was
  24068. //going to merge this in with "include", but include is added after
  24069. //the "name" target. To preserve what r.js has done previously, make
  24070. //sure "deps" comes before the "name".
  24071. if (config.deps) {
  24072. config._depsInclude = config.deps;
  24073. }
  24074. //Remove things that may cause problems in the build.
  24075. //deps already merged above
  24076. delete config.deps;
  24077. delete config.jQuery;
  24078. delete config.enforceDefine;
  24079. delete config.urlArgs;
  24080. return config;
  24081. };
  24082. /**
  24083. * finds the module being built/optimized with the given moduleName,
  24084. * or returns null.
  24085. * @param {String} moduleName
  24086. * @param {Array} modules
  24087. * @returns {Object} the module object from the build profile, or null.
  24088. */
  24089. build.findBuildModule = function (moduleName, modules) {
  24090. var i, module;
  24091. for (i = 0; i < modules.length; i++) {
  24092. module = modules[i];
  24093. if (module.name === moduleName) {
  24094. return module;
  24095. }
  24096. }
  24097. return null;
  24098. };
  24099. /**
  24100. * Removes a module name and path from a layer, if it is supposed to be
  24101. * excluded from the layer.
  24102. * @param {String} moduleName the name of the module
  24103. * @param {String} path the file path for the module
  24104. * @param {Object} layer the layer to remove the module/path from
  24105. */
  24106. build.removeModulePath = function (module, path, layer) {
  24107. var index = layer.buildFilePaths.indexOf(path);
  24108. if (index !== -1) {
  24109. layer.buildFilePaths.splice(index, 1);
  24110. }
  24111. };
  24112. /**
  24113. * Uses the module build config object to trace the dependencies for the
  24114. * given module.
  24115. *
  24116. * @param {Object} module the module object from the build config info.
  24117. * @param {Object} config the build config object.
  24118. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
  24119. *
  24120. * @returns {Object} layer information about what paths and modules should
  24121. * be in the flattened module.
  24122. */
  24123. build.traceDependencies = function (module, config, baseLoaderConfig) {
  24124. var include, override, layer, context, oldContext,
  24125. rawTextByIds,
  24126. syncChecks = {
  24127. rhino: true,
  24128. node: true,
  24129. xpconnect: true
  24130. },
  24131. deferred = prim();
  24132. //Reset some state set up in requirePatch.js, and clean up require's
  24133. //current context.
  24134. oldContext = require._buildReset();
  24135. //Grab the reset layer and context after the reset, but keep the
  24136. //old config to reuse in the new context.
  24137. layer = require._layer;
  24138. context = layer.context;
  24139. //Put back basic config, use a fresh object for it.
  24140. if (baseLoaderConfig) {
  24141. require(lang.deeplikeCopy(baseLoaderConfig));
  24142. }
  24143. logger.trace("\nTracing dependencies for: " + (module.name ||
  24144. (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
  24145. include = config._depsInclude || [];
  24146. include = include.concat(module.name && !module.create ? [module.name] : []);
  24147. if (module.include) {
  24148. include = include.concat(module.include);
  24149. }
  24150. //If there are overrides to basic config, set that up now.;
  24151. if (module.override) {
  24152. if (baseLoaderConfig) {
  24153. override = build.createOverrideConfig(baseLoaderConfig, module.override);
  24154. } else {
  24155. override = lang.deeplikeCopy(module.override);
  24156. }
  24157. require(override);
  24158. }
  24159. //Now, populate the rawText cache with any values explicitly passed in
  24160. //via config.
  24161. rawTextByIds = require.s.contexts._.config.rawText;
  24162. if (rawTextByIds) {
  24163. lang.eachProp(rawTextByIds, function (contents, id) {
  24164. var url = require.toUrl(id) + '.js';
  24165. require._cachedRawText[url] = contents;
  24166. });
  24167. }
  24168. //Configure the callbacks to be called.
  24169. deferred.reject.__requireJsBuild = true;
  24170. //Use a wrapping function so can check for errors.
  24171. function includeFinished(value) {
  24172. //If a sync build environment, check for errors here, instead of
  24173. //in the then callback below, since some errors, like two IDs pointed
  24174. //to same URL but only one anon ID will leave the loader in an
  24175. //unresolved state since a setTimeout cannot be used to check for
  24176. //timeout.
  24177. var hasError = false;
  24178. if (syncChecks[env.get()]) {
  24179. try {
  24180. build.checkForErrors(context);
  24181. } catch (e) {
  24182. hasError = true;
  24183. deferred.reject(e);
  24184. }
  24185. }
  24186. if (!hasError) {
  24187. deferred.resolve(value);
  24188. }
  24189. }
  24190. includeFinished.__requireJsBuild = true;
  24191. //Figure out module layer dependencies by calling require to do the work.
  24192. require(include, includeFinished, deferred.reject);
  24193. // If a sync env, then with the "two IDs to same anon module path"
  24194. // issue, the require never completes, need to check for errors
  24195. // here.
  24196. if (syncChecks[env.get()]) {
  24197. build.checkForErrors(context);
  24198. }
  24199. return deferred.promise.then(function () {
  24200. //Reset config
  24201. if (module.override && baseLoaderConfig) {
  24202. require(lang.deeplikeCopy(baseLoaderConfig));
  24203. }
  24204. build.checkForErrors(context);
  24205. return layer;
  24206. });
  24207. };
  24208. build.checkForErrors = function (context) {
  24209. //Check to see if it all loaded. If not, then throw, and give
  24210. //a message on what is left.
  24211. var id, prop, mod, idParts, pluginId, pluginResources,
  24212. errMessage = '',
  24213. failedPluginMap = {},
  24214. failedPluginIds = [],
  24215. errIds = [],
  24216. errUrlMap = {},
  24217. errUrlConflicts = {},
  24218. hasErrUrl = false,
  24219. hasUndefined = false,
  24220. defined = context.defined,
  24221. registry = context.registry;
  24222. function populateErrUrlMap(id, errUrl, skipNew) {
  24223. // Loader plugins do not have an errUrl, so skip them.
  24224. if (!errUrl) {
  24225. return;
  24226. }
  24227. if (!skipNew) {
  24228. errIds.push(id);
  24229. }
  24230. if (errUrlMap[errUrl]) {
  24231. hasErrUrl = true;
  24232. //This error module has the same URL as another
  24233. //error module, could be misconfiguration.
  24234. if (!errUrlConflicts[errUrl]) {
  24235. errUrlConflicts[errUrl] = [];
  24236. //Store the original module that had the same URL.
  24237. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  24238. }
  24239. errUrlConflicts[errUrl].push(id);
  24240. } else if (!skipNew) {
  24241. errUrlMap[errUrl] = id;
  24242. }
  24243. }
  24244. for (id in registry) {
  24245. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  24246. hasUndefined = true;
  24247. mod = getOwn(registry, id);
  24248. idParts = id.split('!');
  24249. pluginId = idParts[0];
  24250. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  24251. populateErrUrlMap(id, mod.map.url);
  24252. }
  24253. //Look for plugins that did not call load()
  24254. if (idParts.length > 1) {
  24255. if (falseProp(failedPluginMap, pluginId)) {
  24256. failedPluginIds.push(pluginId);
  24257. }
  24258. pluginResources = failedPluginMap[pluginId];
  24259. if (!pluginResources) {
  24260. pluginResources = failedPluginMap[pluginId] = [];
  24261. }
  24262. pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
  24263. }
  24264. }
  24265. }
  24266. // If have some modules that are not defined/stuck in the registry,
  24267. // then check defined modules for URL overlap.
  24268. if (hasUndefined) {
  24269. for (id in defined) {
  24270. if (hasProp(defined, id) && id.indexOf('!') === -1) {
  24271. populateErrUrlMap(id, require.toUrl(id) + '.js', true);
  24272. }
  24273. }
  24274. }
  24275. if (errIds.length || failedPluginIds.length) {
  24276. if (failedPluginIds.length) {
  24277. errMessage += 'Loader plugin' +
  24278. (failedPluginIds.length === 1 ? '' : 's') +
  24279. ' did not call ' +
  24280. 'the load callback in the build:\n' +
  24281. failedPluginIds.map(function (pluginId) {
  24282. var pluginResources = failedPluginMap[pluginId];
  24283. return pluginId + ':\n ' + pluginResources.join('\n ');
  24284. }).join('\n') + '\n';
  24285. }
  24286. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  24287. if (hasErrUrl) {
  24288. errMessage += '\nThe following modules share the same URL. This ' +
  24289. 'could be a misconfiguration if that URL only has ' +
  24290. 'one anonymous module in it:';
  24291. for (prop in errUrlConflicts) {
  24292. if (hasProp(errUrlConflicts, prop)) {
  24293. errMessage += '\n' + prop + ': ' +
  24294. errUrlConflicts[prop].join(', ');
  24295. }
  24296. }
  24297. }
  24298. throw new Error(errMessage);
  24299. }
  24300. };
  24301. build.createOverrideConfig = function (config, override) {
  24302. var cfg = lang.deeplikeCopy(config),
  24303. oride = lang.deeplikeCopy(override);
  24304. lang.eachProp(oride, function (value, prop) {
  24305. if (hasProp(build.objProps, prop)) {
  24306. //An object property, merge keys. Start a new object
  24307. //so that source object in config does not get modified.
  24308. cfg[prop] = {};
  24309. lang.mixin(cfg[prop], config[prop], true);
  24310. lang.mixin(cfg[prop], override[prop], true);
  24311. } else {
  24312. cfg[prop] = override[prop];
  24313. }
  24314. });
  24315. return cfg;
  24316. };
  24317. /**
  24318. * Uses the module build config object to create an flattened version
  24319. * of the module, with deep dependencies included.
  24320. *
  24321. * @param {Object} module the module object from the build config info.
  24322. *
  24323. * @param {Object} layer the layer object returned from build.traceDependencies.
  24324. *
  24325. * @param {Object} the build config object.
  24326. *
  24327. * @returns {Object} with two properties: "text", the text of the flattened
  24328. * module, and "buildText", a string of text representing which files were
  24329. * included in the flattened module text.
  24330. */
  24331. build.flattenModule = function (module, layer, config) {
  24332. var fileContents, sourceMapGenerator,
  24333. sourceMapBase,
  24334. buildFileContents = '';
  24335. return prim().start(function () {
  24336. var reqIndex, currContents, fileForSourceMap,
  24337. moduleName, shim, packageMain, packageName,
  24338. parts, builder, writeApi,
  24339. namespace, namespaceWithDot, stubModulesByName,
  24340. context = layer.context,
  24341. onLayerEnds = [],
  24342. onLayerEndAdded = {};
  24343. //Use override settings, particularly for pragmas
  24344. //Do this before the var readings since it reads config values.
  24345. if (module.override) {
  24346. config = build.createOverrideConfig(config, module.override);
  24347. }
  24348. namespace = config.namespace || '';
  24349. namespaceWithDot = namespace ? namespace + '.' : '';
  24350. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  24351. //Start build output for the module.
  24352. module.onCompleteData = {
  24353. name: module.name,
  24354. path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
  24355. included: []
  24356. };
  24357. buildFileContents += "\n" +
  24358. module.onCompleteData.path +
  24359. "\n----------------\n";
  24360. //If there was an existing file with require in it, hoist to the top.
  24361. if (layer.existingRequireUrl) {
  24362. reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
  24363. if (reqIndex !== -1) {
  24364. layer.buildFilePaths.splice(reqIndex, 1);
  24365. layer.buildFilePaths.unshift(layer.existingRequireUrl);
  24366. }
  24367. }
  24368. if (config.generateSourceMaps) {
  24369. sourceMapBase = config.dir || config.baseUrl;
  24370. fileForSourceMap = module._buildPath === 'FUNCTION' ?
  24371. (module.name || module.include[0] || 'FUNCTION') + '.build.js' :
  24372. module._buildPath.replace(sourceMapBase, '');
  24373. sourceMapGenerator = new SourceMapGenerator.SourceMapGenerator({
  24374. file: fileForSourceMap
  24375. });
  24376. }
  24377. //Write the built module to disk, and build up the build output.
  24378. fileContents = "";
  24379. return prim.serial(layer.buildFilePaths.map(function (path) {
  24380. return function () {
  24381. var lineCount,
  24382. singleContents = '';
  24383. moduleName = layer.buildFileToModule[path];
  24384. packageName = moduleName.split('/').shift();
  24385. //If the moduleName is for a package main, then update it to the
  24386. //real main value.
  24387. packageMain = layer.context.config.pkgs &&
  24388. getOwn(layer.context.config.pkgs, packageName);
  24389. if (packageMain !== moduleName) {
  24390. // Not a match, clear packageMain
  24391. packageMain = undefined;
  24392. }
  24393. return prim().start(function () {
  24394. //Figure out if the module is a result of a build plugin, and if so,
  24395. //then delegate to that plugin.
  24396. parts = context.makeModuleMap(moduleName);
  24397. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  24398. if (builder) {
  24399. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  24400. onLayerEnds.push(builder);
  24401. onLayerEndAdded[parts.prefix] = true;
  24402. }
  24403. if (builder.write) {
  24404. writeApi = function (input) {
  24405. singleContents += "\n" + addSemiColon(input, config);
  24406. if (config.onBuildWrite) {
  24407. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  24408. }
  24409. };
  24410. writeApi.asModule = function (moduleName, input) {
  24411. singleContents += "\n" +
  24412. addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
  24413. useSourceUrl: layer.context.config.useSourceUrl
  24414. }), config);
  24415. if (config.onBuildWrite) {
  24416. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  24417. }
  24418. };
  24419. builder.write(parts.prefix, parts.name, writeApi);
  24420. }
  24421. return;
  24422. } else {
  24423. return prim().start(function () {
  24424. if (hasProp(stubModulesByName, moduleName)) {
  24425. //Just want to insert a simple module definition instead
  24426. //of the source module. Useful for plugins that inline
  24427. //all their resources.
  24428. if (hasProp(layer.context.plugins, moduleName)) {
  24429. //Slightly different content for plugins, to indicate
  24430. //that dynamic loading will not work.
  24431. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  24432. } else {
  24433. return 'define({});';
  24434. }
  24435. } else {
  24436. return require._cacheReadAsync(path);
  24437. }
  24438. }).then(function (text) {
  24439. var hasPackageName;
  24440. currContents = text;
  24441. if (config.cjsTranslate &&
  24442. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  24443. currContents = commonJs.convert(path, currContents);
  24444. }
  24445. if (config.onBuildRead) {
  24446. currContents = config.onBuildRead(moduleName, path, currContents);
  24447. }
  24448. if (packageMain) {
  24449. hasPackageName = (packageName === parse.getNamedDefine(currContents));
  24450. }
  24451. if (namespace) {
  24452. currContents = pragma.namespace(currContents, namespace);
  24453. }
  24454. currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
  24455. useSourceUrl: config.useSourceUrl
  24456. });
  24457. if (packageMain && !hasPackageName) {
  24458. currContents = addSemiColon(currContents, config) + '\n';
  24459. currContents += namespaceWithDot + "define('" +
  24460. packageName + "', ['" + moduleName +
  24461. "'], function (main) { return main; });\n";
  24462. }
  24463. if (config.onBuildWrite) {
  24464. currContents = config.onBuildWrite(moduleName, path, currContents);
  24465. }
  24466. //Semicolon is for files that are not well formed when
  24467. //concatenated with other content.
  24468. singleContents += addSemiColon(currContents, config);
  24469. });
  24470. }
  24471. }).then(function () {
  24472. var refPath, pluginId, resourcePath,
  24473. sourceMapPath, sourceMapLineNumber,
  24474. shortPath = path.replace(config.dir, "");
  24475. module.onCompleteData.included.push(shortPath);
  24476. buildFileContents += shortPath + "\n";
  24477. //Some files may not have declared a require module, and if so,
  24478. //put in a placeholder call so the require does not try to load them
  24479. //after the module is processed.
  24480. //If we have a name, but no defined module, then add in the placeholder.
  24481. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  24482. shim = config.shim && (getOwn(config.shim, moduleName) || (packageMain && getOwn(config.shim, moduleName) || getOwn(config.shim, packageName)));
  24483. if (shim) {
  24484. if (config.wrapShim) {
  24485. singleContents = '(function(root) {\n' +
  24486. namespaceWithDot + 'define("' + moduleName + '", ' +
  24487. (shim.deps && shim.deps.length ?
  24488. build.makeJsArrayString(shim.deps) + ', ' : '[], ') +
  24489. 'function() {\n' +
  24490. ' return (function() {\n' +
  24491. singleContents +
  24492. // Start with a \n in case last line is a comment
  24493. // in the singleContents, like a sourceURL comment.
  24494. '\n' + (shim.exportsFn ? shim.exportsFn() : '') +
  24495. '\n' +
  24496. ' }).apply(root, arguments);\n' +
  24497. '});\n' +
  24498. '}(this));\n';
  24499. } else {
  24500. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  24501. (shim.deps && shim.deps.length ?
  24502. build.makeJsArrayString(shim.deps) + ', ' : '') +
  24503. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  24504. ');\n';
  24505. }
  24506. } else {
  24507. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  24508. }
  24509. }
  24510. //Add line break at end of file, instead of at beginning,
  24511. //so source map line numbers stay correct, but still allow
  24512. //for some space separation between files in case ASI issues
  24513. //for concatenation would cause an error otherwise.
  24514. singleContents += '\n';
  24515. //Add to the source map
  24516. if (sourceMapGenerator) {
  24517. refPath = config.out ? config.baseUrl : module._buildPath;
  24518. parts = path.split('!');
  24519. if (parts.length === 1) {
  24520. //Not a plugin resource, fix the path
  24521. sourceMapPath = build.makeRelativeFilePath(refPath, path);
  24522. } else {
  24523. //Plugin resource. If it looks like just a plugin
  24524. //followed by a module ID, pull off the plugin
  24525. //and put it at the end of the name, otherwise
  24526. //just leave it alone.
  24527. pluginId = parts.shift();
  24528. resourcePath = parts.join('!');
  24529. if (resourceIsModuleIdRegExp.test(resourcePath)) {
  24530. sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
  24531. '!' + pluginId;
  24532. } else {
  24533. sourceMapPath = path;
  24534. }
  24535. }
  24536. sourceMapLineNumber = fileContents.split('\n').length - 1;
  24537. lineCount = singleContents.split('\n').length;
  24538. for (var i = 1; i <= lineCount; i += 1) {
  24539. sourceMapGenerator.addMapping({
  24540. generated: {
  24541. line: sourceMapLineNumber + i,
  24542. column: 0
  24543. },
  24544. original: {
  24545. line: i,
  24546. column: 0
  24547. },
  24548. source: sourceMapPath
  24549. });
  24550. }
  24551. //Store the content of the original in the source
  24552. //map since other transforms later like minification
  24553. //can mess up translating back to the original
  24554. //source.
  24555. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
  24556. }
  24557. //Add the file to the final contents
  24558. fileContents += singleContents;
  24559. });
  24560. };
  24561. })).then(function () {
  24562. if (onLayerEnds.length) {
  24563. onLayerEnds.forEach(function (builder) {
  24564. var path;
  24565. if (typeof module.out === 'string') {
  24566. path = module.out;
  24567. } else if (typeof module._buildPath === 'string') {
  24568. path = module._buildPath;
  24569. }
  24570. builder.onLayerEnd(function (input) {
  24571. fileContents += "\n" + addSemiColon(input, config);
  24572. }, {
  24573. name: module.name,
  24574. path: path
  24575. });
  24576. });
  24577. }
  24578. if (module.create) {
  24579. //The ID is for a created layer. Write out
  24580. //a module definition for it in case the
  24581. //built file is used with enforceDefine
  24582. //(#432)
  24583. fileContents += '\n' + namespaceWithDot + 'define("' + module.name + '", function(){});\n';
  24584. }
  24585. //Add a require at the end to kick start module execution, if that
  24586. //was desired. Usually this is only specified when using small shim
  24587. //loaders like almond.
  24588. if (module.insertRequire) {
  24589. fileContents += '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n';
  24590. }
  24591. });
  24592. }).then(function () {
  24593. return {
  24594. text: config.wrap ?
  24595. config.wrap.start + fileContents + config.wrap.end :
  24596. fileContents,
  24597. buildText: buildFileContents,
  24598. sourceMap: sourceMapGenerator ?
  24599. JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
  24600. undefined
  24601. };
  24602. });
  24603. };
  24604. //Converts an JS array of strings to a string representation.
  24605. //Not using JSON.stringify() for Rhino's sake.
  24606. build.makeJsArrayString = function (ary) {
  24607. return '["' + ary.map(function (item) {
  24608. //Escape any double quotes, backslashes
  24609. return lang.jsEscape(item);
  24610. }).join('","') + '"]';
  24611. };
  24612. build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
  24613. var baseUrl = layer && layer.context.config.baseUrl;
  24614. function onFound(info) {
  24615. //Only mark this module as having a name if not a named module,
  24616. //or if a named module and the name matches expectations.
  24617. if (layer && (info.needsId || info.foundId === moduleName)) {
  24618. layer.modulesWithNames[moduleName] = true;
  24619. }
  24620. }
  24621. //Convert path to be a local one to the baseUrl, useful for
  24622. //useSourceUrl.
  24623. if (baseUrl) {
  24624. path = path.replace(baseUrl, '');
  24625. }
  24626. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  24627. };
  24628. return build;
  24629. });
  24630. }
  24631. /**
  24632. * Sets the default baseUrl for requirejs to be directory of top level
  24633. * script.
  24634. */
  24635. function setBaseUrl(fileName) {
  24636. //Use the file name's directory as the baseUrl if available.
  24637. dir = fileName.replace(/\\/g, '/');
  24638. if (dir.indexOf('/') !== -1) {
  24639. dir = dir.split('/');
  24640. dir.pop();
  24641. dir = dir.join('/');
  24642. //Make sure dir is JS-escaped, since it will be part of a JS string.
  24643. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
  24644. }
  24645. }
  24646. function createRjsApi() {
  24647. //Create a method that will run the optimzer given an object
  24648. //config.
  24649. requirejs.optimize = function (config, callback, errback) {
  24650. if (!loadedOptimizedLib) {
  24651. loadLib();
  24652. loadedOptimizedLib = true;
  24653. }
  24654. //Create the function that will be called once build modules
  24655. //have been loaded.
  24656. var runBuild = function (build, logger, quit) {
  24657. //Make sure config has a log level, and if not,
  24658. //make it "silent" by default.
  24659. config.logLevel = config.hasOwnProperty('logLevel') ?
  24660. config.logLevel : logger.SILENT;
  24661. //Reset build internals first in case this is part
  24662. //of a long-running server process that could have
  24663. //exceptioned out in a bad state. It is only defined
  24664. //after the first call though.
  24665. if (requirejs._buildReset) {
  24666. requirejs._buildReset();
  24667. requirejs._cacheReset();
  24668. }
  24669. function done(result) {
  24670. //And clean up, in case something else triggers
  24671. //a build in another pathway.
  24672. if (requirejs._buildReset) {
  24673. requirejs._buildReset();
  24674. requirejs._cacheReset();
  24675. }
  24676. // Ensure errors get propagated to the errback
  24677. if (result instanceof Error) {
  24678. throw result;
  24679. }
  24680. return result;
  24681. }
  24682. errback = errback || function (err) {
  24683. // Using console here since logger may have
  24684. // turned off error logging. Since quit is
  24685. // called want to be sure a message is printed.
  24686. console.log(err);
  24687. quit(1);
  24688. };
  24689. build(config).then(done, done).then(callback, errback);
  24690. };
  24691. requirejs({
  24692. context: 'build'
  24693. }, ['build', 'logger', 'env!env/quit'], runBuild);
  24694. };
  24695. requirejs.tools = {
  24696. useLib: function (contextName, callback) {
  24697. if (!callback) {
  24698. callback = contextName;
  24699. contextName = 'uselib';
  24700. }
  24701. if (!useLibLoaded[contextName]) {
  24702. loadLib();
  24703. useLibLoaded[contextName] = true;
  24704. }
  24705. var req = requirejs({
  24706. context: contextName
  24707. });
  24708. req(['build'], function () {
  24709. callback(req);
  24710. });
  24711. }
  24712. };
  24713. requirejs.define = define;
  24714. }
  24715. //If in Node, and included via a require('requirejs'), just export and
  24716. //THROW IT ON THE GROUND!
  24717. if (env === 'node' && reqMain !== module) {
  24718. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  24719. createRjsApi();
  24720. module.exports = requirejs;
  24721. return;
  24722. } else if (env === 'browser') {
  24723. //Only option is to use the API.
  24724. setBaseUrl(location.href);
  24725. createRjsApi();
  24726. return;
  24727. } else if ((env === 'rhino' || env === 'xpconnect') &&
  24728. //User sets up requirejsAsLib variable to indicate it is loaded
  24729. //via load() to be used as a library.
  24730. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  24731. //This script is loaded via rhino's load() method, expose the
  24732. //API and get out.
  24733. setBaseUrl(fileName);
  24734. createRjsApi();
  24735. return;
  24736. }
  24737. if (commandOption === 'o') {
  24738. //Do the optimizer work.
  24739. loadLib();
  24740. /**
  24741. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  24742. * Available via the MIT or new BSD license.
  24743. * see: http://github.com/jrburke/requirejs for details
  24744. */
  24745. /*
  24746. * Create a build.js file that has the build options you want and pass that
  24747. * build file to this file to do the build. See example.build.js for more information.
  24748. */
  24749. /*jslint strict: false, nomen: false */
  24750. /*global require: false */
  24751. require({
  24752. baseUrl: require.s.contexts._.config.baseUrl,
  24753. //Use a separate context than the default context so that the
  24754. //build can use the default context.
  24755. context: 'build',
  24756. catchError: {
  24757. define: true
  24758. }
  24759. }, ['env!env/args', 'env!env/quit', 'logger', 'build'],
  24760. function (args, quit, logger, build) {
  24761. build(args).then(function () {}, function (err) {
  24762. logger.error(err);
  24763. quit(1);
  24764. });
  24765. });
  24766. } else if (commandOption === 'v') {
  24767. console.log('r.js: ' + version +
  24768. ', RequireJS: ' + this.requirejsVars.require.version +
  24769. ', UglifyJS2: 2.4.13, UglifyJS: 1.3.4');
  24770. } else if (commandOption === 'convert') {
  24771. loadLib();
  24772. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  24773. function (args, commonJs, print) {
  24774. var srcDir, outDir;
  24775. srcDir = args[0];
  24776. outDir = args[1];
  24777. if (!srcDir || !outDir) {
  24778. print('Usage: path/to/commonjs/modules output/dir');
  24779. return;
  24780. }
  24781. commonJs.convertDir(args[0], args[1]);
  24782. });
  24783. } else {
  24784. //Just run an app
  24785. //Load the bundled libraries for use in the app.
  24786. if (commandOption === 'lib') {
  24787. loadLib();
  24788. }
  24789. setBaseUrl(fileName);
  24790. if (exists(fileName)) {
  24791. exec(readFile(fileName), fileName);
  24792. } else {
  24793. showHelp();
  24794. }
  24795. }
  24796. }((typeof console !== 'undefined' ? console : undefined),
  24797. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  24798. typeof Components !== 'undefined' && Components.interfaces) ?
  24799. Array.prototype.slice.call(arguments, 0) : []),
  24800. (typeof readFile !== 'undefined' ? readFile : undefined)));