r.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140
  1. /**
  2. * @license r.js 2.1.22 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/requirejs for details
  5. */
  6. /*
  7. * This is a bootstrap script to allow running RequireJS in the command line
  8. * in either a Java/Rhino or Node environment. It is modified by the top-level
  9. * dist.js file to inject other files to completely enable this file. It is
  10. * the shell of the r.js file.
  11. */
  12. /*jslint evil: true, nomen: true, sloppy: true */
  13. /*global readFile: true, process: false, Packages: false, print: false,
  14. console: false, java: false, module: false, requirejsVars, navigator,
  15. document, importScripts, self, location, Components, FileUtils */
  16. var requirejs, require, define, xpcUtil;
  17. (function (console, args, readFileFunc) {
  18. var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
  19. nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci,
  20. version = '2.1.22',
  21. jsSuffixRegExp = /\.js$/,
  22. commandOption = '',
  23. useLibLoaded = {},
  24. //Used by jslib/rhino/args.js
  25. rhinoArgs = args,
  26. //Used by jslib/xpconnect/args.js
  27. xpconnectArgs = args,
  28. readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
  29. function showHelp() {
  30. console.log('See https://github.com/jrburke/r.js for usage.');
  31. }
  32. if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  33. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  34. env = 'browser';
  35. readFile = function (path) {
  36. return fs.readFileSync(path, 'utf8');
  37. };
  38. exec = function (string) {
  39. return eval(string);
  40. };
  41. exists = function () {
  42. console.log('x.js exists not applicable in browser env');
  43. return false;
  44. };
  45. } else if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  46. env = 'node';
  47. //Get the fs module via Node's require before it
  48. //gets replaced. Used in require/node.js
  49. fs = require('fs');
  50. vm = require('vm');
  51. path = require('path');
  52. //In Node 0.7+ existsSync is on fs.
  53. existsForNode = fs.existsSync || path.existsSync;
  54. nodeRequire = require;
  55. nodeDefine = define;
  56. reqMain = require.main;
  57. //Temporarily hide require and define to allow require.js to define
  58. //them.
  59. require = undefined;
  60. define = undefined;
  61. readFile = function (path) {
  62. return fs.readFileSync(path, 'utf8');
  63. };
  64. exec = function (string, name) {
  65. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  66. name ? fs.realpathSync(name) : '');
  67. };
  68. exists = function (fileName) {
  69. return existsForNode(fileName);
  70. };
  71. fileName = process.argv[2];
  72. if (fileName && fileName.indexOf('-') === 0) {
  73. commandOption = fileName.substring(1);
  74. fileName = process.argv[3];
  75. }
  76. } else if (typeof Packages !== 'undefined') {
  77. env = 'rhino';
  78. fileName = args[0];
  79. if (fileName && fileName.indexOf('-') === 0) {
  80. commandOption = fileName.substring(1);
  81. fileName = args[1];
  82. }
  83. //Exec/readFile differs between Rhino and Nashorn. Rhino has an
  84. //importPackage where Nashorn does not, so branch on that. This is a
  85. //coarser check -- detecting readFile existence might also be enough for
  86. //this spot. However, sticking with importPackage to keep it the same
  87. //as other Rhino/Nashorn detection branches.
  88. if (typeof importPackage !== 'undefined') {
  89. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  90. exec = function (string, name) {
  91. return rhinoContext.evaluateString(this, string, name, 0, null);
  92. };
  93. } else {
  94. exec = function (string, name) {
  95. load({ script: string, name: name});
  96. };
  97. readFile = readFully;
  98. }
  99. exists = function (fileName) {
  100. return (new java.io.File(fileName)).exists();
  101. };
  102. //Define a console.log for easier logging. Don't
  103. //get fancy though.
  104. if (typeof console === 'undefined') {
  105. console = {
  106. log: function () {
  107. print.apply(undefined, arguments);
  108. }
  109. };
  110. }
  111. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  112. env = 'xpconnect';
  113. Components.utils['import']('resource://gre/modules/FileUtils.jsm');
  114. Cc = Components.classes;
  115. Ci = Components.interfaces;
  116. fileName = args[0];
  117. if (fileName && fileName.indexOf('-') === 0) {
  118. commandOption = fileName.substring(1);
  119. fileName = args[1];
  120. }
  121. xpcUtil = {
  122. isWindows: ('@mozilla.org/windows-registry-key;1' in Cc),
  123. cwd: function () {
  124. return FileUtils.getFile("CurWorkD", []).path;
  125. },
  126. //Remove . and .. from paths, normalize on front slashes
  127. normalize: function (path) {
  128. //There has to be an easier way to do this.
  129. var i, part, ary,
  130. firstChar = path.charAt(0);
  131. if (firstChar !== '/' &&
  132. firstChar !== '\\' &&
  133. path.indexOf(':') === -1) {
  134. //A relative path. Use the current working directory.
  135. path = xpcUtil.cwd() + '/' + path;
  136. }
  137. ary = path.replace(/\\/g, '/').split('/');
  138. for (i = 0; i < ary.length; i += 1) {
  139. part = ary[i];
  140. if (part === '.') {
  141. ary.splice(i, 1);
  142. i -= 1;
  143. } else if (part === '..') {
  144. ary.splice(i - 1, 2);
  145. i -= 2;
  146. }
  147. }
  148. return ary.join('/');
  149. },
  150. xpfile: function (path) {
  151. var fullPath;
  152. try {
  153. fullPath = xpcUtil.normalize(path);
  154. if (xpcUtil.isWindows) {
  155. fullPath = fullPath.replace(/\//g, '\\');
  156. }
  157. return new FileUtils.File(fullPath);
  158. } catch (e) {
  159. throw new Error((fullPath || path) + ' failed: ' + e);
  160. }
  161. },
  162. readFile: function (/*String*/path, /*String?*/encoding) {
  163. //A file read function that can deal with BOMs
  164. encoding = encoding || "utf-8";
  165. var inStream, convertStream,
  166. readData = {},
  167. fileObj = xpcUtil.xpfile(path);
  168. //XPCOM, you so crazy
  169. try {
  170. inStream = Cc['@mozilla.org/network/file-input-stream;1']
  171. .createInstance(Ci.nsIFileInputStream);
  172. inStream.init(fileObj, 1, 0, false);
  173. convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
  174. .createInstance(Ci.nsIConverterInputStream);
  175. convertStream.init(inStream, encoding, inStream.available(),
  176. Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  177. convertStream.readString(inStream.available(), readData);
  178. return readData.value;
  179. } catch (e) {
  180. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  181. } finally {
  182. if (convertStream) {
  183. convertStream.close();
  184. }
  185. if (inStream) {
  186. inStream.close();
  187. }
  188. }
  189. }
  190. };
  191. readFile = xpcUtil.readFile;
  192. exec = function (string) {
  193. return eval(string);
  194. };
  195. exists = function (fileName) {
  196. return xpcUtil.xpfile(fileName).exists();
  197. };
  198. //Define a console.log for easier logging. Don't
  199. //get fancy though.
  200. if (typeof console === 'undefined') {
  201. console = {
  202. log: function () {
  203. print.apply(undefined, arguments);
  204. }
  205. };
  206. }
  207. }
  208. /** vim: et:ts=4:sw=4:sts=4
  209. * @license RequireJS 2.1.22 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
  210. * Available via the MIT or new BSD license.
  211. * see: http://github.com/jrburke/requirejs for details
  212. */
  213. //Not using strict: uneven strict support in browsers, #392, and causes
  214. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  215. /*jslint regexp: true, nomen: true, sloppy: true */
  216. /*global window, navigator, document, importScripts, setTimeout, opera */
  217. (function (global) {
  218. var req, s, head, baseElement, dataMain, src,
  219. interactiveScript, currentlyAddingScript, mainScript, subPath,
  220. version = '2.1.22',
  221. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  222. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  223. jsSuffixRegExp = /\.js$/,
  224. currDirRegExp = /^\.\//,
  225. op = Object.prototype,
  226. ostring = op.toString,
  227. hasOwn = op.hasOwnProperty,
  228. ap = Array.prototype,
  229. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  230. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  231. //PS3 indicates loaded and complete, but need to wait for complete
  232. //specifically. Sequence is 'loading', 'loaded', execution,
  233. // then 'complete'. The UA check is unfortunate, but not sure how
  234. //to feature test w/o causing perf issues.
  235. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  236. /^complete$/ : /^(complete|loaded)$/,
  237. defContextName = '_',
  238. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  239. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  240. contexts = {},
  241. cfg = {},
  242. globalDefQueue = [],
  243. useInteractive = false;
  244. function isFunction(it) {
  245. return ostring.call(it) === '[object Function]';
  246. }
  247. function isArray(it) {
  248. return ostring.call(it) === '[object Array]';
  249. }
  250. /**
  251. * Helper function for iterating over an array. If the func returns
  252. * a true value, it will break out of the loop.
  253. */
  254. function each(ary, func) {
  255. if (ary) {
  256. var i;
  257. for (i = 0; i < ary.length; i += 1) {
  258. if (ary[i] && func(ary[i], i, ary)) {
  259. break;
  260. }
  261. }
  262. }
  263. }
  264. /**
  265. * Helper function for iterating over an array backwards. If the func
  266. * returns a true value, it will break out of the loop.
  267. */
  268. function eachReverse(ary, func) {
  269. if (ary) {
  270. var i;
  271. for (i = ary.length - 1; i > -1; i -= 1) {
  272. if (ary[i] && func(ary[i], i, ary)) {
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. function hasProp(obj, prop) {
  279. return hasOwn.call(obj, prop);
  280. }
  281. function getOwn(obj, prop) {
  282. return hasProp(obj, prop) && obj[prop];
  283. }
  284. /**
  285. * Cycles over properties in an object and calls a function for each
  286. * property value. If the function returns a truthy value, then the
  287. * iteration is stopped.
  288. */
  289. function eachProp(obj, func) {
  290. var prop;
  291. for (prop in obj) {
  292. if (hasProp(obj, prop)) {
  293. if (func(obj[prop], prop)) {
  294. break;
  295. }
  296. }
  297. }
  298. }
  299. /**
  300. * Simple function to mix in properties from source into target,
  301. * but only if target does not already have a property of the same name.
  302. */
  303. function mixin(target, source, force, deepStringMixin) {
  304. if (source) {
  305. eachProp(source, function (value, prop) {
  306. if (force || !hasProp(target, prop)) {
  307. if (deepStringMixin && typeof value === 'object' && value &&
  308. !isArray(value) && !isFunction(value) &&
  309. !(value instanceof RegExp)) {
  310. if (!target[prop]) {
  311. target[prop] = {};
  312. }
  313. mixin(target[prop], value, force, deepStringMixin);
  314. } else {
  315. target[prop] = value;
  316. }
  317. }
  318. });
  319. }
  320. return target;
  321. }
  322. //Similar to Function.prototype.bind, but the 'this' object is specified
  323. //first, since it is easier to read/figure out what 'this' will be.
  324. function bind(obj, fn) {
  325. return function () {
  326. return fn.apply(obj, arguments);
  327. };
  328. }
  329. function scripts() {
  330. return document.getElementsByTagName('script');
  331. }
  332. function defaultOnError(err) {
  333. throw err;
  334. }
  335. //Allow getting a global that is expressed in
  336. //dot notation, like 'a.b.c'.
  337. function getGlobal(value) {
  338. if (!value) {
  339. return value;
  340. }
  341. var g = global;
  342. each(value.split('.'), function (part) {
  343. g = g[part];
  344. });
  345. return g;
  346. }
  347. /**
  348. * Constructs an error with a pointer to an URL with more information.
  349. * @param {String} id the error ID that maps to an ID on a web page.
  350. * @param {String} message human readable error.
  351. * @param {Error} [err] the original error, if there is one.
  352. *
  353. * @returns {Error}
  354. */
  355. function makeError(id, msg, err, requireModules) {
  356. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  357. e.requireType = id;
  358. e.requireModules = requireModules;
  359. if (err) {
  360. e.originalError = err;
  361. }
  362. return e;
  363. }
  364. if (typeof define !== 'undefined') {
  365. //If a define is already in play via another AMD loader,
  366. //do not overwrite.
  367. return;
  368. }
  369. if (typeof requirejs !== 'undefined') {
  370. if (isFunction(requirejs)) {
  371. //Do not overwrite an existing requirejs instance.
  372. return;
  373. }
  374. cfg = requirejs;
  375. requirejs = undefined;
  376. }
  377. //Allow for a require config object
  378. if (typeof require !== 'undefined' && !isFunction(require)) {
  379. //assume it is a config object.
  380. cfg = require;
  381. require = undefined;
  382. }
  383. function newContext(contextName) {
  384. var inCheckLoaded, Module, context, handlers,
  385. checkLoadedTimeoutId,
  386. config = {
  387. //Defaults. Do not set a default for map
  388. //config to speed up normalize(), which
  389. //will run faster if there is no default.
  390. waitSeconds: 7,
  391. baseUrl: './',
  392. paths: {},
  393. bundles: {},
  394. pkgs: {},
  395. shim: {},
  396. config: {}
  397. },
  398. registry = {},
  399. //registry of just enabled modules, to speed
  400. //cycle breaking code when lots of modules
  401. //are registered, but not activated.
  402. enabledRegistry = {},
  403. undefEvents = {},
  404. defQueue = [],
  405. defined = {},
  406. urlFetched = {},
  407. bundlesMap = {},
  408. requireCounter = 1,
  409. unnormalizedCounter = 1;
  410. /**
  411. * Trims the . and .. from an array of path segments.
  412. * It will keep a leading path segment if a .. will become
  413. * the first path segment, to help with module name lookups,
  414. * which act like paths, but can be remapped. But the end result,
  415. * all paths that use this function should look normalized.
  416. * NOTE: this method MODIFIES the input array.
  417. * @param {Array} ary the array of path segments.
  418. */
  419. function trimDots(ary) {
  420. var i, part;
  421. for (i = 0; i < ary.length; i++) {
  422. part = ary[i];
  423. if (part === '.') {
  424. ary.splice(i, 1);
  425. i -= 1;
  426. } else if (part === '..') {
  427. // If at the start, or previous value is still ..,
  428. // keep them so that when converted to a path it may
  429. // still work when converted to a path, even though
  430. // as an ID it is less than ideal. In larger point
  431. // releases, may be better to just kick out an error.
  432. if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
  433. continue;
  434. } else if (i > 0) {
  435. ary.splice(i - 1, 2);
  436. i -= 2;
  437. }
  438. }
  439. }
  440. }
  441. /**
  442. * Given a relative module name, like ./something, normalize it to
  443. * a real name that can be mapped to a path.
  444. * @param {String} name the relative name
  445. * @param {String} baseName a real name that the name arg is relative
  446. * to.
  447. * @param {Boolean} applyMap apply the map config to the value. Should
  448. * only be done if this normalization is for a dependency ID.
  449. * @returns {String} normalized name
  450. */
  451. function normalize(name, baseName, applyMap) {
  452. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  453. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  454. baseParts = (baseName && baseName.split('/')),
  455. map = config.map,
  456. starMap = map && map['*'];
  457. //Adjust any relative paths.
  458. if (name) {
  459. name = name.split('/');
  460. lastIndex = name.length - 1;
  461. // If wanting node ID compatibility, strip .js from end
  462. // of IDs. Have to do this here, and not in nameToUrl
  463. // because node allows either .js or non .js to map
  464. // to same file.
  465. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  466. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  467. }
  468. // Starts with a '.' so need the baseName
  469. if (name[0].charAt(0) === '.' && baseParts) {
  470. //Convert baseName to array, and lop off the last part,
  471. //so that . matches that 'directory' and not name of the baseName's
  472. //module. For instance, baseName of 'one/two/three', maps to
  473. //'one/two/three.js', but we want the directory, 'one/two' for
  474. //this normalization.
  475. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  476. name = normalizedBaseParts.concat(name);
  477. }
  478. trimDots(name);
  479. name = name.join('/');
  480. }
  481. //Apply map config if available.
  482. if (applyMap && map && (baseParts || starMap)) {
  483. nameParts = name.split('/');
  484. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  485. nameSegment = nameParts.slice(0, i).join('/');
  486. if (baseParts) {
  487. //Find the longest baseName segment match in the config.
  488. //So, do joins on the biggest to smallest lengths of baseParts.
  489. for (j = baseParts.length; j > 0; j -= 1) {
  490. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  491. //baseName segment has config, find if it has one for
  492. //this name.
  493. if (mapValue) {
  494. mapValue = getOwn(mapValue, nameSegment);
  495. if (mapValue) {
  496. //Match, update name to the new value.
  497. foundMap = mapValue;
  498. foundI = i;
  499. break outerLoop;
  500. }
  501. }
  502. }
  503. }
  504. //Check for a star map match, but just hold on to it,
  505. //if there is a shorter segment match later in a matching
  506. //config, then favor over this star map.
  507. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  508. foundStarMap = getOwn(starMap, nameSegment);
  509. starI = i;
  510. }
  511. }
  512. if (!foundMap && foundStarMap) {
  513. foundMap = foundStarMap;
  514. foundI = starI;
  515. }
  516. if (foundMap) {
  517. nameParts.splice(0, foundI, foundMap);
  518. name = nameParts.join('/');
  519. }
  520. }
  521. // If the name points to a package's name, use
  522. // the package main instead.
  523. pkgMain = getOwn(config.pkgs, name);
  524. return pkgMain ? pkgMain : name;
  525. }
  526. function removeScript(name) {
  527. if (isBrowser) {
  528. each(scripts(), function (scriptNode) {
  529. if (scriptNode.getAttribute('data-requiremodule') === name &&
  530. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  531. scriptNode.parentNode.removeChild(scriptNode);
  532. return true;
  533. }
  534. });
  535. }
  536. }
  537. function hasPathFallback(id) {
  538. var pathConfig = getOwn(config.paths, id);
  539. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  540. //Pop off the first array value, since it failed, and
  541. //retry
  542. pathConfig.shift();
  543. context.require.undef(id);
  544. //Custom require that does not do map translation, since
  545. //ID is "absolute", already mapped/resolved.
  546. context.makeRequire(null, {
  547. skipMap: true
  548. })([id]);
  549. return true;
  550. }
  551. }
  552. //Turns a plugin!resource to [plugin, resource]
  553. //with the plugin being undefined if the name
  554. //did not have a plugin prefix.
  555. function splitPrefix(name) {
  556. var prefix,
  557. index = name ? name.indexOf('!') : -1;
  558. if (index > -1) {
  559. prefix = name.substring(0, index);
  560. name = name.substring(index + 1, name.length);
  561. }
  562. return [prefix, name];
  563. }
  564. /**
  565. * Creates a module mapping that includes plugin prefix, module
  566. * name, and path. If parentModuleMap is provided it will
  567. * also normalize the name via require.normalize()
  568. *
  569. * @param {String} name the module name
  570. * @param {String} [parentModuleMap] parent module map
  571. * for the module name, used to resolve relative names.
  572. * @param {Boolean} isNormalized: is the ID already normalized.
  573. * This is true if this call is done for a define() module ID.
  574. * @param {Boolean} applyMap: apply the map config to the ID.
  575. * Should only be true if this map is for a dependency.
  576. *
  577. * @returns {Object}
  578. */
  579. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  580. var url, pluginModule, suffix, nameParts,
  581. prefix = null,
  582. parentName = parentModuleMap ? parentModuleMap.name : null,
  583. originalName = name,
  584. isDefine = true,
  585. normalizedName = '';
  586. //If no name, then it means it is a require call, generate an
  587. //internal name.
  588. if (!name) {
  589. isDefine = false;
  590. name = '_@r' + (requireCounter += 1);
  591. }
  592. nameParts = splitPrefix(name);
  593. prefix = nameParts[0];
  594. name = nameParts[1];
  595. if (prefix) {
  596. prefix = normalize(prefix, parentName, applyMap);
  597. pluginModule = getOwn(defined, prefix);
  598. }
  599. //Account for relative paths if there is a base name.
  600. if (name) {
  601. if (prefix) {
  602. if (pluginModule && pluginModule.normalize) {
  603. //Plugin is loaded, use its normalize method.
  604. normalizedName = pluginModule.normalize(name, function (name) {
  605. return normalize(name, parentName, applyMap);
  606. });
  607. } else {
  608. // If nested plugin references, then do not try to
  609. // normalize, as it will not normalize correctly. This
  610. // places a restriction on resourceIds, and the longer
  611. // term solution is not to normalize until plugins are
  612. // loaded and all normalizations to allow for async
  613. // loading of a loader plugin. But for now, fixes the
  614. // common uses. Details in #1131
  615. normalizedName = name.indexOf('!') === -1 ?
  616. normalize(name, parentName, applyMap) :
  617. name;
  618. }
  619. } else {
  620. //A regular module.
  621. normalizedName = normalize(name, parentName, applyMap);
  622. //Normalized name may be a plugin ID due to map config
  623. //application in normalize. The map config values must
  624. //already be normalized, so do not need to redo that part.
  625. nameParts = splitPrefix(normalizedName);
  626. prefix = nameParts[0];
  627. normalizedName = nameParts[1];
  628. isNormalized = true;
  629. url = context.nameToUrl(normalizedName);
  630. }
  631. }
  632. //If the id is a plugin id that cannot be determined if it needs
  633. //normalization, stamp it with a unique ID so two matching relative
  634. //ids that may conflict can be separate.
  635. suffix = prefix && !pluginModule && !isNormalized ?
  636. '_unnormalized' + (unnormalizedCounter += 1) :
  637. '';
  638. return {
  639. prefix: prefix,
  640. name: normalizedName,
  641. parentMap: parentModuleMap,
  642. unnormalized: !!suffix,
  643. url: url,
  644. originalName: originalName,
  645. isDefine: isDefine,
  646. id: (prefix ?
  647. prefix + '!' + normalizedName :
  648. normalizedName) + suffix
  649. };
  650. }
  651. function getModule(depMap) {
  652. var id = depMap.id,
  653. mod = getOwn(registry, id);
  654. if (!mod) {
  655. mod = registry[id] = new context.Module(depMap);
  656. }
  657. return mod;
  658. }
  659. function on(depMap, name, fn) {
  660. var id = depMap.id,
  661. mod = getOwn(registry, id);
  662. if (hasProp(defined, id) &&
  663. (!mod || mod.defineEmitComplete)) {
  664. if (name === 'defined') {
  665. fn(defined[id]);
  666. }
  667. } else {
  668. mod = getModule(depMap);
  669. if (mod.error && name === 'error') {
  670. fn(mod.error);
  671. } else {
  672. mod.on(name, fn);
  673. }
  674. }
  675. }
  676. function onError(err, errback) {
  677. var ids = err.requireModules,
  678. notified = false;
  679. if (errback) {
  680. errback(err);
  681. } else {
  682. each(ids, function (id) {
  683. var mod = getOwn(registry, id);
  684. if (mod) {
  685. //Set error on module, so it skips timeout checks.
  686. mod.error = err;
  687. if (mod.events.error) {
  688. notified = true;
  689. mod.emit('error', err);
  690. }
  691. }
  692. });
  693. if (!notified) {
  694. req.onError(err);
  695. }
  696. }
  697. }
  698. /**
  699. * Internal method to transfer globalQueue items to this context's
  700. * defQueue.
  701. */
  702. function takeGlobalQueue() {
  703. //Push all the globalDefQueue items into the context's defQueue
  704. if (globalDefQueue.length) {
  705. each(globalDefQueue, function(queueItem) {
  706. var id = queueItem[0];
  707. if (typeof id === 'string') {
  708. context.defQueueMap[id] = true;
  709. }
  710. defQueue.push(queueItem);
  711. });
  712. globalDefQueue = [];
  713. }
  714. }
  715. handlers = {
  716. 'require': function (mod) {
  717. if (mod.require) {
  718. return mod.require;
  719. } else {
  720. return (mod.require = context.makeRequire(mod.map));
  721. }
  722. },
  723. 'exports': function (mod) {
  724. mod.usingExports = true;
  725. if (mod.map.isDefine) {
  726. if (mod.exports) {
  727. return (defined[mod.map.id] = mod.exports);
  728. } else {
  729. return (mod.exports = defined[mod.map.id] = {});
  730. }
  731. }
  732. },
  733. 'module': function (mod) {
  734. if (mod.module) {
  735. return mod.module;
  736. } else {
  737. return (mod.module = {
  738. id: mod.map.id,
  739. uri: mod.map.url,
  740. config: function () {
  741. return getOwn(config.config, mod.map.id) || {};
  742. },
  743. exports: mod.exports || (mod.exports = {})
  744. });
  745. }
  746. }
  747. };
  748. function cleanRegistry(id) {
  749. //Clean up machinery used for waiting modules.
  750. delete registry[id];
  751. delete enabledRegistry[id];
  752. }
  753. function breakCycle(mod, traced, processed) {
  754. var id = mod.map.id;
  755. if (mod.error) {
  756. mod.emit('error', mod.error);
  757. } else {
  758. traced[id] = true;
  759. each(mod.depMaps, function (depMap, i) {
  760. var depId = depMap.id,
  761. dep = getOwn(registry, depId);
  762. //Only force things that have not completed
  763. //being defined, so still in the registry,
  764. //and only if it has not been matched up
  765. //in the module already.
  766. if (dep && !mod.depMatched[i] && !processed[depId]) {
  767. if (getOwn(traced, depId)) {
  768. mod.defineDep(i, defined[depId]);
  769. mod.check(); //pass false?
  770. } else {
  771. breakCycle(dep, traced, processed);
  772. }
  773. }
  774. });
  775. processed[id] = true;
  776. }
  777. }
  778. function checkLoaded() {
  779. var err, usingPathFallback,
  780. waitInterval = config.waitSeconds * 1000,
  781. //It is possible to disable the wait interval by using waitSeconds of 0.
  782. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  783. noLoads = [],
  784. reqCalls = [],
  785. stillLoading = false,
  786. needCycleCheck = true;
  787. //Do not bother if this call was a result of a cycle break.
  788. if (inCheckLoaded) {
  789. return;
  790. }
  791. inCheckLoaded = true;
  792. //Figure out the state of all the modules.
  793. eachProp(enabledRegistry, function (mod) {
  794. var map = mod.map,
  795. modId = map.id;
  796. //Skip things that are not enabled or in error state.
  797. if (!mod.enabled) {
  798. return;
  799. }
  800. if (!map.isDefine) {
  801. reqCalls.push(mod);
  802. }
  803. if (!mod.error) {
  804. //If the module should be executed, and it has not
  805. //been inited and time is up, remember it.
  806. if (!mod.inited && expired) {
  807. if (hasPathFallback(modId)) {
  808. usingPathFallback = true;
  809. stillLoading = true;
  810. } else {
  811. noLoads.push(modId);
  812. removeScript(modId);
  813. }
  814. } else if (!mod.inited && mod.fetched && map.isDefine) {
  815. stillLoading = true;
  816. if (!map.prefix) {
  817. //No reason to keep looking for unfinished
  818. //loading. If the only stillLoading is a
  819. //plugin resource though, keep going,
  820. //because it may be that a plugin resource
  821. //is waiting on a non-plugin cycle.
  822. return (needCycleCheck = false);
  823. }
  824. }
  825. }
  826. });
  827. if (expired && noLoads.length) {
  828. //If wait time expired, throw error of unloaded modules.
  829. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  830. err.contextName = context.contextName;
  831. return onError(err);
  832. }
  833. //Not expired, check for a cycle.
  834. if (needCycleCheck) {
  835. each(reqCalls, function (mod) {
  836. breakCycle(mod, {}, {});
  837. });
  838. }
  839. //If still waiting on loads, and the waiting load is something
  840. //other than a plugin resource, or there are still outstanding
  841. //scripts, then just try back later.
  842. if ((!expired || usingPathFallback) && stillLoading) {
  843. //Something is still waiting to load. Wait for it, but only
  844. //if a timeout is not already in effect.
  845. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  846. checkLoadedTimeoutId = setTimeout(function () {
  847. checkLoadedTimeoutId = 0;
  848. checkLoaded();
  849. }, 50);
  850. }
  851. }
  852. inCheckLoaded = false;
  853. }
  854. Module = function (map) {
  855. this.events = getOwn(undefEvents, map.id) || {};
  856. this.map = map;
  857. this.shim = getOwn(config.shim, map.id);
  858. this.depExports = [];
  859. this.depMaps = [];
  860. this.depMatched = [];
  861. this.pluginMaps = {};
  862. this.depCount = 0;
  863. /* this.exports this.factory
  864. this.depMaps = [],
  865. this.enabled, this.fetched
  866. */
  867. };
  868. Module.prototype = {
  869. init: function (depMaps, factory, errback, options) {
  870. options = options || {};
  871. //Do not do more inits if already done. Can happen if there
  872. //are multiple define calls for the same module. That is not
  873. //a normal, common case, but it is also not unexpected.
  874. if (this.inited) {
  875. return;
  876. }
  877. this.factory = factory;
  878. if (errback) {
  879. //Register for errors on this module.
  880. this.on('error', errback);
  881. } else if (this.events.error) {
  882. //If no errback already, but there are error listeners
  883. //on this module, set up an errback to pass to the deps.
  884. errback = bind(this, function (err) {
  885. this.emit('error', err);
  886. });
  887. }
  888. //Do a copy of the dependency array, so that
  889. //source inputs are not modified. For example
  890. //"shim" deps are passed in here directly, and
  891. //doing a direct modification of the depMaps array
  892. //would affect that config.
  893. this.depMaps = depMaps && depMaps.slice(0);
  894. this.errback = errback;
  895. //Indicate this module has be initialized
  896. this.inited = true;
  897. this.ignore = options.ignore;
  898. //Could have option to init this module in enabled mode,
  899. //or could have been previously marked as enabled. However,
  900. //the dependencies are not known until init is called. So
  901. //if enabled previously, now trigger dependencies as enabled.
  902. if (options.enabled || this.enabled) {
  903. //Enable this module and dependencies.
  904. //Will call this.check()
  905. this.enable();
  906. } else {
  907. this.check();
  908. }
  909. },
  910. defineDep: function (i, depExports) {
  911. //Because of cycles, defined callback for a given
  912. //export can be called more than once.
  913. if (!this.depMatched[i]) {
  914. this.depMatched[i] = true;
  915. this.depCount -= 1;
  916. this.depExports[i] = depExports;
  917. }
  918. },
  919. fetch: function () {
  920. if (this.fetched) {
  921. return;
  922. }
  923. this.fetched = true;
  924. context.startTime = (new Date()).getTime();
  925. var map = this.map;
  926. //If the manager is for a plugin managed resource,
  927. //ask the plugin to load it now.
  928. if (this.shim) {
  929. context.makeRequire(this.map, {
  930. enableBuildCallback: true
  931. })(this.shim.deps || [], bind(this, function () {
  932. return map.prefix ? this.callPlugin() : this.load();
  933. }));
  934. } else {
  935. //Regular dependency.
  936. return map.prefix ? this.callPlugin() : this.load();
  937. }
  938. },
  939. load: function () {
  940. var url = this.map.url;
  941. //Regular dependency.
  942. if (!urlFetched[url]) {
  943. urlFetched[url] = true;
  944. context.load(this.map.id, url);
  945. }
  946. },
  947. /**
  948. * Checks if the module is ready to define itself, and if so,
  949. * define it.
  950. */
  951. check: function () {
  952. if (!this.enabled || this.enabling) {
  953. return;
  954. }
  955. var err, cjsModule,
  956. id = this.map.id,
  957. depExports = this.depExports,
  958. exports = this.exports,
  959. factory = this.factory;
  960. if (!this.inited) {
  961. // Only fetch if not already in the defQueue.
  962. if (!hasProp(context.defQueueMap, id)) {
  963. this.fetch();
  964. }
  965. } else if (this.error) {
  966. this.emit('error', this.error);
  967. } else if (!this.defining) {
  968. //The factory could trigger another require call
  969. //that would result in checking this module to
  970. //define itself again. If already in the process
  971. //of doing that, skip this work.
  972. this.defining = true;
  973. if (this.depCount < 1 && !this.defined) {
  974. if (isFunction(factory)) {
  975. try {
  976. exports = context.execCb(id, factory, depExports, exports);
  977. } catch (e) {
  978. err = e;
  979. }
  980. // Favor return value over exports. If node/cjs in play,
  981. // then will not have a return value anyway. Favor
  982. // module.exports assignment over exports object.
  983. if (this.map.isDefine && exports === undefined) {
  984. cjsModule = this.module;
  985. if (cjsModule) {
  986. exports = cjsModule.exports;
  987. } else if (this.usingExports) {
  988. //exports already set the defined value.
  989. exports = this.exports;
  990. }
  991. }
  992. if (err) {
  993. // If there is an error listener, favor passing
  994. // to that instead of throwing an error. However,
  995. // only do it for define()'d modules. require
  996. // errbacks should not be called for failures in
  997. // their callbacks (#699). However if a global
  998. // onError is set, use that.
  999. if ((this.events.error && this.map.isDefine) ||
  1000. req.onError !== defaultOnError) {
  1001. err.requireMap = this.map;
  1002. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  1003. err.requireType = this.map.isDefine ? 'define' : 'require';
  1004. return onError((this.error = err));
  1005. } else if (typeof console !== 'undefined' &&
  1006. console.error) {
  1007. // Log the error for debugging. If promises could be
  1008. // used, this would be different, but making do.
  1009. console.error(err);
  1010. } else {
  1011. // Do not want to completely lose the error. While this
  1012. // will mess up processing and lead to similar results
  1013. // as bug 1440, it at least surfaces the error.
  1014. req.onError(err);
  1015. }
  1016. }
  1017. } else {
  1018. //Just a literal value
  1019. exports = factory;
  1020. }
  1021. this.exports = exports;
  1022. if (this.map.isDefine && !this.ignore) {
  1023. defined[id] = exports;
  1024. if (req.onResourceLoad) {
  1025. var resLoadMaps = [];
  1026. each(this.depMaps, function (depMap) {
  1027. resLoadMaps.push(depMap.normalizedMap || depMap);
  1028. });
  1029. req.onResourceLoad(context, this.map, resLoadMaps);
  1030. }
  1031. }
  1032. //Clean up
  1033. cleanRegistry(id);
  1034. this.defined = true;
  1035. }
  1036. //Finished the define stage. Allow calling check again
  1037. //to allow define notifications below in the case of a
  1038. //cycle.
  1039. this.defining = false;
  1040. if (this.defined && !this.defineEmitted) {
  1041. this.defineEmitted = true;
  1042. this.emit('defined', this.exports);
  1043. this.defineEmitComplete = true;
  1044. }
  1045. }
  1046. },
  1047. callPlugin: function () {
  1048. var map = this.map,
  1049. id = map.id,
  1050. //Map already normalized the prefix.
  1051. pluginMap = makeModuleMap(map.prefix);
  1052. //Mark this as a dependency for this plugin, so it
  1053. //can be traced for cycles.
  1054. this.depMaps.push(pluginMap);
  1055. on(pluginMap, 'defined', bind(this, function (plugin) {
  1056. var load, normalizedMap, normalizedMod,
  1057. bundleId = getOwn(bundlesMap, this.map.id),
  1058. name = this.map.name,
  1059. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1060. localRequire = context.makeRequire(map.parentMap, {
  1061. enableBuildCallback: true
  1062. });
  1063. //If current map is not normalized, wait for that
  1064. //normalized name to load instead of continuing.
  1065. if (this.map.unnormalized) {
  1066. //Normalize the ID if the plugin allows it.
  1067. if (plugin.normalize) {
  1068. name = plugin.normalize(name, function (name) {
  1069. return normalize(name, parentName, true);
  1070. }) || '';
  1071. }
  1072. //prefix and name should already be normalized, no need
  1073. //for applying map config again either.
  1074. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1075. this.map.parentMap);
  1076. on(normalizedMap,
  1077. 'defined', bind(this, function (value) {
  1078. this.map.normalizedMap = normalizedMap;
  1079. this.init([], function () { return value; }, null, {
  1080. enabled: true,
  1081. ignore: true
  1082. });
  1083. }));
  1084. normalizedMod = getOwn(registry, normalizedMap.id);
  1085. if (normalizedMod) {
  1086. //Mark this as a dependency for this plugin, so it
  1087. //can be traced for cycles.
  1088. this.depMaps.push(normalizedMap);
  1089. if (this.events.error) {
  1090. normalizedMod.on('error', bind(this, function (err) {
  1091. this.emit('error', err);
  1092. }));
  1093. }
  1094. normalizedMod.enable();
  1095. }
  1096. return;
  1097. }
  1098. //If a paths config, then just load that file instead to
  1099. //resolve the plugin, as it is built into that paths layer.
  1100. if (bundleId) {
  1101. this.map.url = context.nameToUrl(bundleId);
  1102. this.load();
  1103. return;
  1104. }
  1105. load = bind(this, function (value) {
  1106. this.init([], function () { return value; }, null, {
  1107. enabled: true
  1108. });
  1109. });
  1110. load.error = bind(this, function (err) {
  1111. this.inited = true;
  1112. this.error = err;
  1113. err.requireModules = [id];
  1114. //Remove temp unnormalized modules for this module,
  1115. //since they will never be resolved otherwise now.
  1116. eachProp(registry, function (mod) {
  1117. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1118. cleanRegistry(mod.map.id);
  1119. }
  1120. });
  1121. onError(err);
  1122. });
  1123. //Allow plugins to load other code without having to know the
  1124. //context or how to 'complete' the load.
  1125. load.fromText = bind(this, function (text, textAlt) {
  1126. /*jslint evil: true */
  1127. var moduleName = map.name,
  1128. moduleMap = makeModuleMap(moduleName),
  1129. hasInteractive = useInteractive;
  1130. //As of 2.1.0, support just passing the text, to reinforce
  1131. //fromText only being called once per resource. Still
  1132. //support old style of passing moduleName but discard
  1133. //that moduleName in favor of the internal ref.
  1134. if (textAlt) {
  1135. text = textAlt;
  1136. }
  1137. //Turn off interactive script matching for IE for any define
  1138. //calls in the text, then turn it back on at the end.
  1139. if (hasInteractive) {
  1140. useInteractive = false;
  1141. }
  1142. //Prime the system by creating a module instance for
  1143. //it.
  1144. getModule(moduleMap);
  1145. //Transfer any config to this other module.
  1146. if (hasProp(config.config, id)) {
  1147. config.config[moduleName] = config.config[id];
  1148. }
  1149. try {
  1150. req.exec(text);
  1151. } catch (e) {
  1152. return onError(makeError('fromtexteval',
  1153. 'fromText eval for ' + id +
  1154. ' failed: ' + e,
  1155. e,
  1156. [id]));
  1157. }
  1158. if (hasInteractive) {
  1159. useInteractive = true;
  1160. }
  1161. //Mark this as a dependency for the plugin
  1162. //resource
  1163. this.depMaps.push(moduleMap);
  1164. //Support anonymous modules.
  1165. context.completeLoad(moduleName);
  1166. //Bind the value of that module to the value for this
  1167. //resource ID.
  1168. localRequire([moduleName], load);
  1169. });
  1170. //Use parentName here since the plugin's name is not reliable,
  1171. //could be some weird string with no path that actually wants to
  1172. //reference the parentName's path.
  1173. plugin.load(map.name, localRequire, load, config);
  1174. }));
  1175. context.enable(pluginMap, this);
  1176. this.pluginMaps[pluginMap.id] = pluginMap;
  1177. },
  1178. enable: function () {
  1179. enabledRegistry[this.map.id] = this;
  1180. this.enabled = true;
  1181. //Set flag mentioning that the module is enabling,
  1182. //so that immediate calls to the defined callbacks
  1183. //for dependencies do not trigger inadvertent load
  1184. //with the depCount still being zero.
  1185. this.enabling = true;
  1186. //Enable each dependency
  1187. each(this.depMaps, bind(this, function (depMap, i) {
  1188. var id, mod, handler;
  1189. if (typeof depMap === 'string') {
  1190. //Dependency needs to be converted to a depMap
  1191. //and wired up to this module.
  1192. depMap = makeModuleMap(depMap,
  1193. (this.map.isDefine ? this.map : this.map.parentMap),
  1194. false,
  1195. !this.skipMap);
  1196. this.depMaps[i] = depMap;
  1197. handler = getOwn(handlers, depMap.id);
  1198. if (handler) {
  1199. this.depExports[i] = handler(this);
  1200. return;
  1201. }
  1202. this.depCount += 1;
  1203. on(depMap, 'defined', bind(this, function (depExports) {
  1204. if (this.undefed) {
  1205. return;
  1206. }
  1207. this.defineDep(i, depExports);
  1208. this.check();
  1209. }));
  1210. if (this.errback) {
  1211. on(depMap, 'error', bind(this, this.errback));
  1212. } else if (this.events.error) {
  1213. // No direct errback on this module, but something
  1214. // else is listening for errors, so be sure to
  1215. // propagate the error correctly.
  1216. on(depMap, 'error', bind(this, function(err) {
  1217. this.emit('error', err);
  1218. }));
  1219. }
  1220. }
  1221. id = depMap.id;
  1222. mod = registry[id];
  1223. //Skip special modules like 'require', 'exports', 'module'
  1224. //Also, don't call enable if it is already enabled,
  1225. //important in circular dependency cases.
  1226. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1227. context.enable(depMap, this);
  1228. }
  1229. }));
  1230. //Enable each plugin that is used in
  1231. //a dependency
  1232. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1233. var mod = getOwn(registry, pluginMap.id);
  1234. if (mod && !mod.enabled) {
  1235. context.enable(pluginMap, this);
  1236. }
  1237. }));
  1238. this.enabling = false;
  1239. this.check();
  1240. },
  1241. on: function (name, cb) {
  1242. var cbs = this.events[name];
  1243. if (!cbs) {
  1244. cbs = this.events[name] = [];
  1245. }
  1246. cbs.push(cb);
  1247. },
  1248. emit: function (name, evt) {
  1249. each(this.events[name], function (cb) {
  1250. cb(evt);
  1251. });
  1252. if (name === 'error') {
  1253. //Now that the error handler was triggered, remove
  1254. //the listeners, since this broken Module instance
  1255. //can stay around for a while in the registry.
  1256. delete this.events[name];
  1257. }
  1258. }
  1259. };
  1260. function callGetModule(args) {
  1261. //Skip modules already defined.
  1262. if (!hasProp(defined, args[0])) {
  1263. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1264. }
  1265. }
  1266. function removeListener(node, func, name, ieName) {
  1267. //Favor detachEvent because of IE9
  1268. //issue, see attachEvent/addEventListener comment elsewhere
  1269. //in this file.
  1270. if (node.detachEvent && !isOpera) {
  1271. //Probably IE. If not it will throw an error, which will be
  1272. //useful to know.
  1273. if (ieName) {
  1274. node.detachEvent(ieName, func);
  1275. }
  1276. } else {
  1277. node.removeEventListener(name, func, false);
  1278. }
  1279. }
  1280. /**
  1281. * Given an event from a script node, get the requirejs info from it,
  1282. * and then removes the event listeners on the node.
  1283. * @param {Event} evt
  1284. * @returns {Object}
  1285. */
  1286. function getScriptData(evt) {
  1287. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1288. //all old browsers will be supported, but this one was easy enough
  1289. //to support and still makes sense.
  1290. var node = evt.currentTarget || evt.srcElement;
  1291. //Remove the listeners once here.
  1292. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1293. removeListener(node, context.onScriptError, 'error');
  1294. return {
  1295. node: node,
  1296. id: node && node.getAttribute('data-requiremodule')
  1297. };
  1298. }
  1299. function intakeDefines() {
  1300. var args;
  1301. //Any defined modules in the global queue, intake them now.
  1302. takeGlobalQueue();
  1303. //Make sure any remaining defQueue items get properly processed.
  1304. while (defQueue.length) {
  1305. args = defQueue.shift();
  1306. if (args[0] === null) {
  1307. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
  1308. args[args.length - 1]));
  1309. } else {
  1310. //args are id, deps, factory. Should be normalized by the
  1311. //define() function.
  1312. callGetModule(args);
  1313. }
  1314. }
  1315. context.defQueueMap = {};
  1316. }
  1317. context = {
  1318. config: config,
  1319. contextName: contextName,
  1320. registry: registry,
  1321. defined: defined,
  1322. urlFetched: urlFetched,
  1323. defQueue: defQueue,
  1324. defQueueMap: {},
  1325. Module: Module,
  1326. makeModuleMap: makeModuleMap,
  1327. nextTick: req.nextTick,
  1328. onError: onError,
  1329. /**
  1330. * Set a configuration for the context.
  1331. * @param {Object} cfg config object to integrate.
  1332. */
  1333. configure: function (cfg) {
  1334. //Make sure the baseUrl ends in a slash.
  1335. if (cfg.baseUrl) {
  1336. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1337. cfg.baseUrl += '/';
  1338. }
  1339. }
  1340. //Save off the paths since they require special processing,
  1341. //they are additive.
  1342. var shim = config.shim,
  1343. objs = {
  1344. paths: true,
  1345. bundles: true,
  1346. config: true,
  1347. map: true
  1348. };
  1349. eachProp(cfg, function (value, prop) {
  1350. if (objs[prop]) {
  1351. if (!config[prop]) {
  1352. config[prop] = {};
  1353. }
  1354. mixin(config[prop], value, true, true);
  1355. } else {
  1356. config[prop] = value;
  1357. }
  1358. });
  1359. //Reverse map the bundles
  1360. if (cfg.bundles) {
  1361. eachProp(cfg.bundles, function (value, prop) {
  1362. each(value, function (v) {
  1363. if (v !== prop) {
  1364. bundlesMap[v] = prop;
  1365. }
  1366. });
  1367. });
  1368. }
  1369. //Merge shim
  1370. if (cfg.shim) {
  1371. eachProp(cfg.shim, function (value, id) {
  1372. //Normalize the structure
  1373. if (isArray(value)) {
  1374. value = {
  1375. deps: value
  1376. };
  1377. }
  1378. if ((value.exports || value.init) && !value.exportsFn) {
  1379. value.exportsFn = context.makeShimExports(value);
  1380. }
  1381. shim[id] = value;
  1382. });
  1383. config.shim = shim;
  1384. }
  1385. //Adjust packages if necessary.
  1386. if (cfg.packages) {
  1387. each(cfg.packages, function (pkgObj) {
  1388. var location, name;
  1389. pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
  1390. name = pkgObj.name;
  1391. location = pkgObj.location;
  1392. if (location) {
  1393. config.paths[name] = pkgObj.location;
  1394. }
  1395. //Save pointer to main module ID for pkg name.
  1396. //Remove leading dot in main, so main paths are normalized,
  1397. //and remove any trailing .js, since different package
  1398. //envs have different conventions: some use a module name,
  1399. //some use a file name.
  1400. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1401. .replace(currDirRegExp, '')
  1402. .replace(jsSuffixRegExp, '');
  1403. });
  1404. }
  1405. //If there are any "waiting to execute" modules in the registry,
  1406. //update the maps for them, since their info, like URLs to load,
  1407. //may have changed.
  1408. eachProp(registry, function (mod, id) {
  1409. //If module already has init called, since it is too
  1410. //late to modify them, and ignore unnormalized ones
  1411. //since they are transient.
  1412. if (!mod.inited && !mod.map.unnormalized) {
  1413. mod.map = makeModuleMap(id, null, true);
  1414. }
  1415. });
  1416. //If a deps array or a config callback is specified, then call
  1417. //require with those args. This is useful when require is defined as a
  1418. //config object before require.js is loaded.
  1419. if (cfg.deps || cfg.callback) {
  1420. context.require(cfg.deps || [], cfg.callback);
  1421. }
  1422. },
  1423. makeShimExports: function (value) {
  1424. function fn() {
  1425. var ret;
  1426. if (value.init) {
  1427. ret = value.init.apply(global, arguments);
  1428. }
  1429. return ret || (value.exports && getGlobal(value.exports));
  1430. }
  1431. return fn;
  1432. },
  1433. makeRequire: function (relMap, options) {
  1434. options = options || {};
  1435. function localRequire(deps, callback, errback) {
  1436. var id, map, requireMod;
  1437. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1438. callback.__requireJsBuild = true;
  1439. }
  1440. if (typeof deps === 'string') {
  1441. if (isFunction(callback)) {
  1442. //Invalid call
  1443. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1444. }
  1445. //If require|exports|module are requested, get the
  1446. //value for them from the special handlers. Caveat:
  1447. //this only works while module is being defined.
  1448. if (relMap && hasProp(handlers, deps)) {
  1449. return handlers[deps](registry[relMap.id]);
  1450. }
  1451. //Synchronous access to one module. If require.get is
  1452. //available (as in the Node adapter), prefer that.
  1453. if (req.get) {
  1454. return req.get(context, deps, relMap, localRequire);
  1455. }
  1456. //Normalize module name, if it contains . or ..
  1457. map = makeModuleMap(deps, relMap, false, true);
  1458. id = map.id;
  1459. if (!hasProp(defined, id)) {
  1460. return onError(makeError('notloaded', 'Module name "' +
  1461. id +
  1462. '" has not been loaded yet for context: ' +
  1463. contextName +
  1464. (relMap ? '' : '. Use require([])')));
  1465. }
  1466. return defined[id];
  1467. }
  1468. //Grab defines waiting in the global queue.
  1469. intakeDefines();
  1470. //Mark all the dependencies as needing to be loaded.
  1471. context.nextTick(function () {
  1472. //Some defines could have been added since the
  1473. //require call, collect them.
  1474. intakeDefines();
  1475. requireMod = getModule(makeModuleMap(null, relMap));
  1476. //Store if map config should be applied to this require
  1477. //call for dependencies.
  1478. requireMod.skipMap = options.skipMap;
  1479. requireMod.init(deps, callback, errback, {
  1480. enabled: true
  1481. });
  1482. checkLoaded();
  1483. });
  1484. return localRequire;
  1485. }
  1486. mixin(localRequire, {
  1487. isBrowser: isBrowser,
  1488. /**
  1489. * Converts a module name + .extension into an URL path.
  1490. * *Requires* the use of a module name. It does not support using
  1491. * plain URLs like nameToUrl.
  1492. */
  1493. toUrl: function (moduleNamePlusExt) {
  1494. var ext,
  1495. index = moduleNamePlusExt.lastIndexOf('.'),
  1496. segment = moduleNamePlusExt.split('/')[0],
  1497. isRelative = segment === '.' || segment === '..';
  1498. //Have a file extension alias, and it is not the
  1499. //dots from a relative path.
  1500. if (index !== -1 && (!isRelative || index > 1)) {
  1501. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1502. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1503. }
  1504. return context.nameToUrl(normalize(moduleNamePlusExt,
  1505. relMap && relMap.id, true), ext, true);
  1506. },
  1507. defined: function (id) {
  1508. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1509. },
  1510. specified: function (id) {
  1511. id = makeModuleMap(id, relMap, false, true).id;
  1512. return hasProp(defined, id) || hasProp(registry, id);
  1513. }
  1514. });
  1515. //Only allow undef on top level require calls
  1516. if (!relMap) {
  1517. localRequire.undef = function (id) {
  1518. //Bind any waiting define() calls to this context,
  1519. //fix for #408
  1520. takeGlobalQueue();
  1521. var map = makeModuleMap(id, relMap, true),
  1522. mod = getOwn(registry, id);
  1523. mod.undefed = true;
  1524. removeScript(id);
  1525. delete defined[id];
  1526. delete urlFetched[map.url];
  1527. delete undefEvents[id];
  1528. //Clean queued defines too. Go backwards
  1529. //in array so that the splices do not
  1530. //mess up the iteration.
  1531. eachReverse(defQueue, function(args, i) {
  1532. if (args[0] === id) {
  1533. defQueue.splice(i, 1);
  1534. }
  1535. });
  1536. delete context.defQueueMap[id];
  1537. if (mod) {
  1538. //Hold on to listeners in case the
  1539. //module will be attempted to be reloaded
  1540. //using a different config.
  1541. if (mod.events.defined) {
  1542. undefEvents[id] = mod.events;
  1543. }
  1544. cleanRegistry(id);
  1545. }
  1546. };
  1547. }
  1548. return localRequire;
  1549. },
  1550. /**
  1551. * Called to enable a module if it is still in the registry
  1552. * awaiting enablement. A second arg, parent, the parent module,
  1553. * is passed in for context, when this method is overridden by
  1554. * the optimizer. Not shown here to keep code compact.
  1555. */
  1556. enable: function (depMap) {
  1557. var mod = getOwn(registry, depMap.id);
  1558. if (mod) {
  1559. getModule(depMap).enable();
  1560. }
  1561. },
  1562. /**
  1563. * Internal method used by environment adapters to complete a load event.
  1564. * A load event could be a script load or just a load pass from a synchronous
  1565. * load call.
  1566. * @param {String} moduleName the name of the module to potentially complete.
  1567. */
  1568. completeLoad: function (moduleName) {
  1569. var found, args, mod,
  1570. shim = getOwn(config.shim, moduleName) || {},
  1571. shExports = shim.exports;
  1572. takeGlobalQueue();
  1573. while (defQueue.length) {
  1574. args = defQueue.shift();
  1575. if (args[0] === null) {
  1576. args[0] = moduleName;
  1577. //If already found an anonymous module and bound it
  1578. //to this name, then this is some other anon module
  1579. //waiting for its completeLoad to fire.
  1580. if (found) {
  1581. break;
  1582. }
  1583. found = true;
  1584. } else if (args[0] === moduleName) {
  1585. //Found matching define call for this script!
  1586. found = true;
  1587. }
  1588. callGetModule(args);
  1589. }
  1590. context.defQueueMap = {};
  1591. //Do this after the cycle of callGetModule in case the result
  1592. //of those calls/init calls changes the registry.
  1593. mod = getOwn(registry, moduleName);
  1594. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1595. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1596. if (hasPathFallback(moduleName)) {
  1597. return;
  1598. } else {
  1599. return onError(makeError('nodefine',
  1600. 'No define call for ' + moduleName,
  1601. null,
  1602. [moduleName]));
  1603. }
  1604. } else {
  1605. //A script that does not call define(), so just simulate
  1606. //the call for it.
  1607. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1608. }
  1609. }
  1610. checkLoaded();
  1611. },
  1612. /**
  1613. * Converts a module name to a file path. Supports cases where
  1614. * moduleName may actually be just an URL.
  1615. * Note that it **does not** call normalize on the moduleName,
  1616. * it is assumed to have already been normalized. This is an
  1617. * internal API, not a public one. Use toUrl for the public API.
  1618. */
  1619. nameToUrl: function (moduleName, ext, skipExt) {
  1620. var paths, syms, i, parentModule, url,
  1621. parentPath, bundleId,
  1622. pkgMain = getOwn(config.pkgs, moduleName);
  1623. if (pkgMain) {
  1624. moduleName = pkgMain;
  1625. }
  1626. bundleId = getOwn(bundlesMap, moduleName);
  1627. if (bundleId) {
  1628. return context.nameToUrl(bundleId, ext, skipExt);
  1629. }
  1630. //If a colon is in the URL, it indicates a protocol is used and it is just
  1631. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1632. //or ends with .js, then assume the user meant to use an url and not a module id.
  1633. //The slash is important for protocol-less URLs as well as full paths.
  1634. if (req.jsExtRegExp.test(moduleName)) {
  1635. //Just a plain path, not module name lookup, so just return it.
  1636. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1637. //an extension, this method probably needs to be reworked.
  1638. url = moduleName + (ext || '');
  1639. } else {
  1640. //A module that needs to be converted to a path.
  1641. paths = config.paths;
  1642. syms = moduleName.split('/');
  1643. //For each module name segment, see if there is a path
  1644. //registered for it. Start with most specific name
  1645. //and work up from it.
  1646. for (i = syms.length; i > 0; i -= 1) {
  1647. parentModule = syms.slice(0, i).join('/');
  1648. parentPath = getOwn(paths, parentModule);
  1649. if (parentPath) {
  1650. //If an array, it means there are a few choices,
  1651. //Choose the one that is desired
  1652. if (isArray(parentPath)) {
  1653. parentPath = parentPath[0];
  1654. }
  1655. syms.splice(0, i, parentPath);
  1656. break;
  1657. }
  1658. }
  1659. //Join the path parts together, then figure out if baseUrl is needed.
  1660. url = syms.join('/');
  1661. url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
  1662. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1663. }
  1664. return config.urlArgs ? url +
  1665. ((url.indexOf('?') === -1 ? '?' : '&') +
  1666. config.urlArgs) : url;
  1667. },
  1668. //Delegates to req.load. Broken out as a separate function to
  1669. //allow overriding in the optimizer.
  1670. load: function (id, url) {
  1671. req.load(context, id, url);
  1672. },
  1673. /**
  1674. * Executes a module callback function. Broken out as a separate function
  1675. * solely to allow the build system to sequence the files in the built
  1676. * layer in the right sequence.
  1677. *
  1678. * @private
  1679. */
  1680. execCb: function (name, callback, args, exports) {
  1681. return callback.apply(exports, args);
  1682. },
  1683. /**
  1684. * callback for script loads, used to check status of loading.
  1685. *
  1686. * @param {Event} evt the event from the browser for the script
  1687. * that was loaded.
  1688. */
  1689. onScriptLoad: function (evt) {
  1690. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1691. //all old browsers will be supported, but this one was easy enough
  1692. //to support and still makes sense.
  1693. if (evt.type === 'load' ||
  1694. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1695. //Reset interactive script so a script node is not held onto for
  1696. //to long.
  1697. interactiveScript = null;
  1698. //Pull out the name of the module and the context.
  1699. var data = getScriptData(evt);
  1700. context.completeLoad(data.id);
  1701. }
  1702. },
  1703. /**
  1704. * Callback for script errors.
  1705. */
  1706. onScriptError: function (evt) {
  1707. var data = getScriptData(evt);
  1708. if (!hasPathFallback(data.id)) {
  1709. var parents = [];
  1710. eachProp(registry, function(value, key) {
  1711. if (key.indexOf('_@r') !== 0) {
  1712. each(value.depMaps, function(depMap) {
  1713. if (depMap.id === data.id) {
  1714. parents.push(key);
  1715. }
  1716. return true;
  1717. });
  1718. }
  1719. });
  1720. return onError(makeError('scripterror', 'Script error for "' + data.id +
  1721. (parents.length ?
  1722. '", needed by: ' + parents.join(', ') :
  1723. '"'), evt, [data.id]));
  1724. }
  1725. }
  1726. };
  1727. context.require = context.makeRequire();
  1728. return context;
  1729. }
  1730. /**
  1731. * Main entry point.
  1732. *
  1733. * If the only argument to require is a string, then the module that
  1734. * is represented by that string is fetched for the appropriate context.
  1735. *
  1736. * If the first argument is an array, then it will be treated as an array
  1737. * of dependency string names to fetch. An optional function callback can
  1738. * be specified to execute when all of those dependencies are available.
  1739. *
  1740. * Make a local req variable to help Caja compliance (it assumes things
  1741. * on a require that are not standardized), and to give a short
  1742. * name for minification/local scope use.
  1743. */
  1744. req = requirejs = function (deps, callback, errback, optional) {
  1745. //Find the right context, use default
  1746. var context, config,
  1747. contextName = defContextName;
  1748. // Determine if have config object in the call.
  1749. if (!isArray(deps) && typeof deps !== 'string') {
  1750. // deps is a config object
  1751. config = deps;
  1752. if (isArray(callback)) {
  1753. // Adjust args if there are dependencies
  1754. deps = callback;
  1755. callback = errback;
  1756. errback = optional;
  1757. } else {
  1758. deps = [];
  1759. }
  1760. }
  1761. if (config && config.context) {
  1762. contextName = config.context;
  1763. }
  1764. context = getOwn(contexts, contextName);
  1765. if (!context) {
  1766. context = contexts[contextName] = req.s.newContext(contextName);
  1767. }
  1768. if (config) {
  1769. context.configure(config);
  1770. }
  1771. return context.require(deps, callback, errback);
  1772. };
  1773. /**
  1774. * Support require.config() to make it easier to cooperate with other
  1775. * AMD loaders on globally agreed names.
  1776. */
  1777. req.config = function (config) {
  1778. return req(config);
  1779. };
  1780. /**
  1781. * Execute something after the current tick
  1782. * of the event loop. Override for other envs
  1783. * that have a better solution than setTimeout.
  1784. * @param {Function} fn function to execute later.
  1785. */
  1786. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1787. setTimeout(fn, 4);
  1788. } : function (fn) { fn(); };
  1789. /**
  1790. * Export require as a global, but only if it does not already exist.
  1791. */
  1792. if (!require) {
  1793. require = req;
  1794. }
  1795. req.version = version;
  1796. //Used to filter out dependencies that are already paths.
  1797. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1798. req.isBrowser = isBrowser;
  1799. s = req.s = {
  1800. contexts: contexts,
  1801. newContext: newContext
  1802. };
  1803. //Create default context.
  1804. req({});
  1805. //Exports some context-sensitive methods on global require.
  1806. each([
  1807. 'toUrl',
  1808. 'undef',
  1809. 'defined',
  1810. 'specified'
  1811. ], function (prop) {
  1812. //Reference from contexts instead of early binding to default context,
  1813. //so that during builds, the latest instance of the default context
  1814. //with its config gets used.
  1815. req[prop] = function () {
  1816. var ctx = contexts[defContextName];
  1817. return ctx.require[prop].apply(ctx, arguments);
  1818. };
  1819. });
  1820. if (isBrowser) {
  1821. head = s.head = document.getElementsByTagName('head')[0];
  1822. //If BASE tag is in play, using appendChild is a problem for IE6.
  1823. //When that browser dies, this can be removed. Details in this jQuery bug:
  1824. //http://dev.jquery.com/ticket/2709
  1825. baseElement = document.getElementsByTagName('base')[0];
  1826. if (baseElement) {
  1827. head = s.head = baseElement.parentNode;
  1828. }
  1829. }
  1830. /**
  1831. * Any errors that require explicitly generates will be passed to this
  1832. * function. Intercept/override it if you want custom error handling.
  1833. * @param {Error} err the error object.
  1834. */
  1835. req.onError = defaultOnError;
  1836. /**
  1837. * Creates the node for the load command. Only used in browser envs.
  1838. */
  1839. req.createNode = function (config, moduleName, url) {
  1840. var node = config.xhtml ?
  1841. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1842. document.createElement('script');
  1843. node.type = config.scriptType || 'text/javascript';
  1844. node.charset = 'utf-8';
  1845. node.async = true;
  1846. return node;
  1847. };
  1848. /**
  1849. * Does the request to load a module for the browser case.
  1850. * Make this a separate function to allow other environments
  1851. * to override it.
  1852. *
  1853. * @param {Object} context the require context to find state.
  1854. * @param {String} moduleName the name of the module.
  1855. * @param {Object} url the URL to the module.
  1856. */
  1857. req.load = function (context, moduleName, url) {
  1858. var config = (context && context.config) || {},
  1859. node;
  1860. if (isBrowser) {
  1861. //In the browser so use a script tag
  1862. node = req.createNode(config, moduleName, url);
  1863. if (config.onNodeCreated) {
  1864. config.onNodeCreated(node, config, moduleName, url);
  1865. }
  1866. node.setAttribute('data-requirecontext', context.contextName);
  1867. node.setAttribute('data-requiremodule', moduleName);
  1868. //Set up load listener. Test attachEvent first because IE9 has
  1869. //a subtle issue in its addEventListener and script onload firings
  1870. //that do not match the behavior of all other browsers with
  1871. //addEventListener support, which fire the onload event for a
  1872. //script right after the script execution. See:
  1873. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1874. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1875. //script execution mode.
  1876. if (node.attachEvent &&
  1877. //Check if node.attachEvent is artificially added by custom script or
  1878. //natively supported by browser
  1879. //read https://github.com/jrburke/requirejs/issues/187
  1880. //if we can NOT find [native code] then it must NOT natively supported.
  1881. //in IE8, node.attachEvent does not have toString()
  1882. //Note the test for "[native code" with no closing brace, see:
  1883. //https://github.com/jrburke/requirejs/issues/273
  1884. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1885. !isOpera) {
  1886. //Probably IE. IE (at least 6-8) do not fire
  1887. //script onload right after executing the script, so
  1888. //we cannot tie the anonymous define call to a name.
  1889. //However, IE reports the script as being in 'interactive'
  1890. //readyState at the time of the define call.
  1891. useInteractive = true;
  1892. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1893. //It would be great to add an error handler here to catch
  1894. //404s in IE9+. However, onreadystatechange will fire before
  1895. //the error handler, so that does not help. If addEventListener
  1896. //is used, then IE will fire error before load, but we cannot
  1897. //use that pathway given the connect.microsoft.com issue
  1898. //mentioned above about not doing the 'script execute,
  1899. //then fire the script load event listener before execute
  1900. //next script' that other browsers do.
  1901. //Best hope: IE10 fixes the issues,
  1902. //and then destroys all installs of IE 6-9.
  1903. //node.attachEvent('onerror', context.onScriptError);
  1904. } else {
  1905. node.addEventListener('load', context.onScriptLoad, false);
  1906. node.addEventListener('error', context.onScriptError, false);
  1907. }
  1908. node.src = url;
  1909. //For some cache cases in IE 6-8, the script executes before the end
  1910. //of the appendChild execution, so to tie an anonymous define
  1911. //call to the module name (which is stored on the node), hold on
  1912. //to a reference to this node, but clear after the DOM insertion.
  1913. currentlyAddingScript = node;
  1914. if (baseElement) {
  1915. head.insertBefore(node, baseElement);
  1916. } else {
  1917. head.appendChild(node);
  1918. }
  1919. currentlyAddingScript = null;
  1920. return node;
  1921. } else if (isWebWorker) {
  1922. try {
  1923. //In a web worker, use importScripts. This is not a very
  1924. //efficient use of importScripts, importScripts will block until
  1925. //its script is downloaded and evaluated. However, if web workers
  1926. //are in play, the expectation is that a build has been done so
  1927. //that only one script needs to be loaded anyway. This may need
  1928. //to be reevaluated if other use cases become common.
  1929. importScripts(url);
  1930. //Account for anonymous modules
  1931. context.completeLoad(moduleName);
  1932. } catch (e) {
  1933. context.onError(makeError('importscripts',
  1934. 'importScripts failed for ' +
  1935. moduleName + ' at ' + url,
  1936. e,
  1937. [moduleName]));
  1938. }
  1939. }
  1940. };
  1941. function getInteractiveScript() {
  1942. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1943. return interactiveScript;
  1944. }
  1945. eachReverse(scripts(), function (script) {
  1946. if (script.readyState === 'interactive') {
  1947. return (interactiveScript = script);
  1948. }
  1949. });
  1950. return interactiveScript;
  1951. }
  1952. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1953. if (isBrowser && !cfg.skipDataMain) {
  1954. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1955. eachReverse(scripts(), function (script) {
  1956. //Set the 'head' where we can append children by
  1957. //using the script's parent.
  1958. if (!head) {
  1959. head = script.parentNode;
  1960. }
  1961. //Look for a data-main attribute to set main script for the page
  1962. //to load. If it is there, the path to data main becomes the
  1963. //baseUrl, if it is not already set.
  1964. dataMain = script.getAttribute('data-main');
  1965. if (dataMain) {
  1966. //Preserve dataMain in case it is a path (i.e. contains '?')
  1967. mainScript = dataMain;
  1968. //Set final baseUrl if there is not already an explicit one.
  1969. if (!cfg.baseUrl) {
  1970. //Pull off the directory of data-main for use as the
  1971. //baseUrl.
  1972. src = mainScript.split('/');
  1973. mainScript = src.pop();
  1974. subPath = src.length ? src.join('/') + '/' : './';
  1975. cfg.baseUrl = subPath;
  1976. }
  1977. //Strip off any trailing .js since mainScript is now
  1978. //like a module name.
  1979. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1980. //If mainScript is still a path, fall back to dataMain
  1981. if (req.jsExtRegExp.test(mainScript)) {
  1982. mainScript = dataMain;
  1983. }
  1984. //Put the data-main script in the files to load.
  1985. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1986. return true;
  1987. }
  1988. });
  1989. }
  1990. /**
  1991. * The function that handles definitions of modules. Differs from
  1992. * require() in that a string for the module should be the first argument,
  1993. * and the function to execute after dependencies are loaded should
  1994. * return a value to define the module corresponding to the first argument's
  1995. * name.
  1996. */
  1997. define = function (name, deps, callback) {
  1998. var node, context;
  1999. //Allow for anonymous modules
  2000. if (typeof name !== 'string') {
  2001. //Adjust args appropriately
  2002. callback = deps;
  2003. deps = name;
  2004. name = null;
  2005. }
  2006. //This module may not have dependencies
  2007. if (!isArray(deps)) {
  2008. callback = deps;
  2009. deps = null;
  2010. }
  2011. //If no name, and callback is a function, then figure out if it a
  2012. //CommonJS thing with dependencies.
  2013. if (!deps && isFunction(callback)) {
  2014. deps = [];
  2015. //Remove comments from the callback string,
  2016. //look for require calls, and pull them into the dependencies,
  2017. //but only if there are function args.
  2018. if (callback.length) {
  2019. callback
  2020. .toString()
  2021. .replace(commentRegExp, '')
  2022. .replace(cjsRequireRegExp, function (match, dep) {
  2023. deps.push(dep);
  2024. });
  2025. //May be a CommonJS thing even without require calls, but still
  2026. //could use exports, and module. Avoid doing exports and module
  2027. //work though if it just needs require.
  2028. //REQUIRES the function to expect the CommonJS variables in the
  2029. //order listed below.
  2030. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  2031. }
  2032. }
  2033. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  2034. //work.
  2035. if (useInteractive) {
  2036. node = currentlyAddingScript || getInteractiveScript();
  2037. if (node) {
  2038. if (!name) {
  2039. name = node.getAttribute('data-requiremodule');
  2040. }
  2041. context = contexts[node.getAttribute('data-requirecontext')];
  2042. }
  2043. }
  2044. //Always save off evaluating the def call until the script onload handler.
  2045. //This allows multiple modules to be in a file without prematurely
  2046. //tracing dependencies, and allows for anonymous module support,
  2047. //where the module name is not known until the script onload event
  2048. //occurs. If no context, use the global queue, and get it processed
  2049. //in the onscript load callback.
  2050. if (context) {
  2051. context.defQueue.push([name, deps, callback]);
  2052. context.defQueueMap[name] = true;
  2053. } else {
  2054. globalDefQueue.push([name, deps, callback]);
  2055. }
  2056. };
  2057. define.amd = {
  2058. jQuery: true
  2059. };
  2060. /**
  2061. * Executes the text. Normally just uses eval, but can be modified
  2062. * to use a better, environment-specific call. Only used for transpiling
  2063. * loader plugins, not for plain JS modules.
  2064. * @param {String} text the text to execute/evaluate.
  2065. */
  2066. req.exec = function (text) {
  2067. /*jslint evil: true */
  2068. return eval(text);
  2069. };
  2070. //Set up with config info.
  2071. req(cfg);
  2072. }(this));
  2073. this.requirejsVars = {
  2074. require: require,
  2075. requirejs: require,
  2076. define: define
  2077. };
  2078. if (env === 'browser') {
  2079. /**
  2080. * @license RequireJS rhino Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2081. * Available via the MIT or new BSD license.
  2082. * see: http://github.com/jrburke/requirejs for details
  2083. */
  2084. //sloppy since eval enclosed with use strict causes problems if the source
  2085. //text is not strict-compliant.
  2086. /*jslint sloppy: true, evil: true */
  2087. /*global require, XMLHttpRequest */
  2088. (function () {
  2089. // Separate function to avoid eval pollution, same with arguments use.
  2090. function exec() {
  2091. eval(arguments[0]);
  2092. }
  2093. require.load = function (context, moduleName, url) {
  2094. var xhr = new XMLHttpRequest();
  2095. xhr.open('GET', url, true);
  2096. xhr.send();
  2097. xhr.onreadystatechange = function () {
  2098. if (xhr.readyState === 4) {
  2099. exec(xhr.responseText);
  2100. //Support anonymous modules.
  2101. context.completeLoad(moduleName);
  2102. }
  2103. };
  2104. };
  2105. }());
  2106. } else if (env === 'rhino') {
  2107. /**
  2108. * @license RequireJS rhino Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2109. * Available via the MIT or new BSD license.
  2110. * see: http://github.com/jrburke/requirejs for details
  2111. */
  2112. /*jslint */
  2113. /*global require: false, java: false, load: false */
  2114. (function () {
  2115. 'use strict';
  2116. require.load = function (context, moduleName, url) {
  2117. load(url);
  2118. //Support anonymous modules.
  2119. context.completeLoad(moduleName);
  2120. };
  2121. }());
  2122. } else if (env === 'node') {
  2123. this.requirejsVars.nodeRequire = nodeRequire;
  2124. require.nodeRequire = nodeRequire;
  2125. /**
  2126. * @license RequireJS node Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2127. * Available via the MIT or new BSD license.
  2128. * see: http://github.com/jrburke/requirejs for details
  2129. */
  2130. //Explicity not strict since this file contains an eval call, and do not want
  2131. //to enforce strict on code evaluated that way. See
  2132. //https://github.com/jrburke/r.js/issues/774
  2133. /*jslint regexp: false, sloppy: true*/
  2134. /*global require: false, define: false, requirejsVars: false, process: false */
  2135. /**
  2136. * This adapter assumes that x.js has loaded it and set up
  2137. * some variables. This adapter just allows limited RequireJS
  2138. * usage from within the requirejs directory. The general
  2139. * node adapater is r.js.
  2140. */
  2141. (function () {
  2142. var nodeReq = requirejsVars.nodeRequire,
  2143. req = requirejsVars.require,
  2144. def = requirejsVars.define,
  2145. fs = nodeReq('fs'),
  2146. path = nodeReq('path'),
  2147. vm = nodeReq('vm'),
  2148. //In Node 0.7+ existsSync is on fs.
  2149. exists = fs.existsSync || path.existsSync,
  2150. hasOwn = Object.prototype.hasOwnProperty;
  2151. function hasProp(obj, prop) {
  2152. return hasOwn.call(obj, prop);
  2153. }
  2154. function syncTick(fn) {
  2155. fn();
  2156. }
  2157. function makeError(message, moduleName) {
  2158. var err = new Error(message);
  2159. err.requireModules = [moduleName];
  2160. return err;
  2161. }
  2162. //Supply an implementation that allows synchronous get of a module.
  2163. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2164. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2165. context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
  2166. }
  2167. var ret, oldTick,
  2168. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2169. //Normalize module name, if it contains . or ..
  2170. moduleName = moduleMap.id;
  2171. if (hasProp(context.defined, moduleName)) {
  2172. ret = context.defined[moduleName];
  2173. } else {
  2174. if (ret === undefined) {
  2175. //Make sure nextTick for this type of call is sync-based.
  2176. oldTick = context.nextTick;
  2177. context.nextTick = syncTick;
  2178. try {
  2179. if (moduleMap.prefix) {
  2180. //A plugin, call requirejs to handle it. Now that
  2181. //nextTick is syncTick, the require will complete
  2182. //synchronously.
  2183. localRequire([moduleMap.originalName]);
  2184. //Now that plugin is loaded, can regenerate the moduleMap
  2185. //to get the final, normalized ID.
  2186. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2187. moduleName = moduleMap.id;
  2188. } else {
  2189. //Try to dynamically fetch it.
  2190. req.load(context, moduleName, moduleMap.url);
  2191. //Enable the module
  2192. context.enable(moduleMap, relModuleMap);
  2193. }
  2194. //Break any cycles by requiring it normally, but this will
  2195. //finish synchronously
  2196. context.require([moduleName]);
  2197. //The above calls are sync, so can do the next thing safely.
  2198. ret = context.defined[moduleName];
  2199. } finally {
  2200. context.nextTick = oldTick;
  2201. }
  2202. }
  2203. }
  2204. return ret;
  2205. };
  2206. req.nextTick = function (fn) {
  2207. process.nextTick(fn);
  2208. };
  2209. //Add wrapper around the code so that it gets the requirejs
  2210. //API instead of the Node API, and it is done lexically so
  2211. //that it survives later execution.
  2212. req.makeNodeWrapper = function (contents) {
  2213. return '(function (require, requirejs, define) { ' +
  2214. contents +
  2215. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2216. };
  2217. req.load = function (context, moduleName, url) {
  2218. var contents, err,
  2219. config = context.config;
  2220. if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
  2221. console.warn('Shim config not supported in Node, may or may not work. Detected ' +
  2222. 'for module: ' + moduleName);
  2223. }
  2224. if (exists(url)) {
  2225. contents = fs.readFileSync(url, 'utf8');
  2226. contents = req.makeNodeWrapper(contents);
  2227. try {
  2228. vm.runInThisContext(contents, fs.realpathSync(url));
  2229. } catch (e) {
  2230. err = new Error('Evaluating ' + url + ' as module "' +
  2231. moduleName + '" failed with error: ' + e);
  2232. err.originalError = e;
  2233. err.moduleName = moduleName;
  2234. err.requireModules = [moduleName];
  2235. err.fileName = url;
  2236. return context.onError(err);
  2237. }
  2238. } else {
  2239. def(moduleName, function () {
  2240. //Get the original name, since relative requires may be
  2241. //resolved differently in node (issue #202). Also, if relative,
  2242. //make it relative to the URL of the item requesting it
  2243. //(issue #393)
  2244. var dirName,
  2245. map = hasProp(context.registry, moduleName) &&
  2246. context.registry[moduleName].map,
  2247. parentMap = map && map.parentMap,
  2248. originalName = map && map.originalName;
  2249. if (originalName.charAt(0) === '.' && parentMap) {
  2250. dirName = parentMap.url.split('/');
  2251. dirName.pop();
  2252. originalName = dirName.join('/') + '/' + originalName;
  2253. }
  2254. try {
  2255. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2256. } catch (e) {
  2257. err = new Error('Tried loading "' + moduleName + '" at ' +
  2258. url + ' then tried node\'s require("' +
  2259. originalName + '") and it failed ' +
  2260. 'with error: ' + e);
  2261. err.originalError = e;
  2262. err.moduleName = originalName;
  2263. err.requireModules = [moduleName];
  2264. throw err;
  2265. }
  2266. });
  2267. }
  2268. //Support anonymous modules.
  2269. context.completeLoad(moduleName);
  2270. };
  2271. //Override to provide the function wrapper for define/require.
  2272. req.exec = function (text) {
  2273. /*jslint evil: true */
  2274. text = req.makeNodeWrapper(text);
  2275. return eval(text);
  2276. };
  2277. }());
  2278. } else if (env === 'xpconnect') {
  2279. /**
  2280. * @license RequireJS xpconnect Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2281. * Available via the MIT or new BSD license.
  2282. * see: http://github.com/jrburke/requirejs for details
  2283. */
  2284. /*jslint */
  2285. /*global require, load */
  2286. (function () {
  2287. 'use strict';
  2288. require.load = function (context, moduleName, url) {
  2289. load(url);
  2290. //Support anonymous modules.
  2291. context.completeLoad(moduleName);
  2292. };
  2293. }());
  2294. }
  2295. //Support a default file name to execute. Useful for hosted envs
  2296. //like Joyent where it defaults to a server.js as the only executed
  2297. //script. But only do it if this is not an optimization run.
  2298. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2299. fileName = 'main.js';
  2300. }
  2301. /**
  2302. * Loads the library files that can be used for the optimizer, or for other
  2303. * tasks.
  2304. */
  2305. function loadLib() {
  2306. /**
  2307. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2308. * Available via the MIT or new BSD license.
  2309. * see: http://github.com/jrburke/requirejs for details
  2310. */
  2311. /*jslint strict: false */
  2312. /*global Packages: false, process: false, window: false, navigator: false,
  2313. document: false, define: false */
  2314. /**
  2315. * A plugin that modifies any /env/ path to be the right path based on
  2316. * the host environment. Right now only works for Node, Rhino and browser.
  2317. */
  2318. (function () {
  2319. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2320. env = 'unknown';
  2321. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  2322. env = 'node';
  2323. } else if (typeof Packages !== 'undefined') {
  2324. env = 'rhino';
  2325. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2326. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2327. env = 'browser';
  2328. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2329. env = 'xpconnect';
  2330. }
  2331. define('env', {
  2332. get: function () {
  2333. return env;
  2334. },
  2335. load: function (name, req, load, config) {
  2336. //Allow override in the config.
  2337. if (config.env) {
  2338. env = config.env;
  2339. }
  2340. name = name.replace(pathRegExp, function (match, prefix) {
  2341. if (match.indexOf('{') === -1) {
  2342. return prefix + env + '/';
  2343. } else {
  2344. return env;
  2345. }
  2346. });
  2347. req([name], function (mod) {
  2348. load(mod);
  2349. });
  2350. }
  2351. });
  2352. }());
  2353. /**
  2354. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2355. * Available via the MIT or new BSD license.
  2356. * see: http://github.com/jrburke/requirejs for details
  2357. */
  2358. /*jslint plusplus: true */
  2359. /*global define, java */
  2360. define('lang', function () {
  2361. 'use strict';
  2362. var lang, isJavaObj,
  2363. hasOwn = Object.prototype.hasOwnProperty;
  2364. function hasProp(obj, prop) {
  2365. return hasOwn.call(obj, prop);
  2366. }
  2367. isJavaObj = function () {
  2368. return false;
  2369. };
  2370. //Rhino, but not Nashorn (detected by importPackage not existing)
  2371. //Can have some strange foreign objects.
  2372. if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') {
  2373. isJavaObj = function (obj) {
  2374. return obj instanceof java.lang.Object;
  2375. };
  2376. }
  2377. lang = {
  2378. backSlashRegExp: /\\/g,
  2379. ostring: Object.prototype.toString,
  2380. isArray: Array.isArray || function (it) {
  2381. return lang.ostring.call(it) === "[object Array]";
  2382. },
  2383. isFunction: function(it) {
  2384. return lang.ostring.call(it) === "[object Function]";
  2385. },
  2386. isRegExp: function(it) {
  2387. return it && it instanceof RegExp;
  2388. },
  2389. hasProp: hasProp,
  2390. //returns true if the object does not have an own property prop,
  2391. //or if it does, it is a falsy value.
  2392. falseProp: function (obj, prop) {
  2393. return !hasProp(obj, prop) || !obj[prop];
  2394. },
  2395. //gets own property value for given prop on object
  2396. getOwn: function (obj, prop) {
  2397. return hasProp(obj, prop) && obj[prop];
  2398. },
  2399. _mixin: function(dest, source, override){
  2400. var name;
  2401. for (name in source) {
  2402. if(source.hasOwnProperty(name) &&
  2403. (override || !dest.hasOwnProperty(name))) {
  2404. dest[name] = source[name];
  2405. }
  2406. }
  2407. return dest; // Object
  2408. },
  2409. /**
  2410. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2411. * then the source objects properties are force copied over to dest.
  2412. */
  2413. mixin: function(dest){
  2414. var parameters = Array.prototype.slice.call(arguments),
  2415. override, i, l;
  2416. if (!dest) { dest = {}; }
  2417. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2418. override = parameters.pop();
  2419. }
  2420. for (i = 1, l = parameters.length; i < l; i++) {
  2421. lang._mixin(dest, parameters[i], override);
  2422. }
  2423. return dest; // Object
  2424. },
  2425. /**
  2426. * Does a deep mix of source into dest, where source values override
  2427. * dest values if a winner is needed.
  2428. * @param {Object} dest destination object that receives the mixed
  2429. * values.
  2430. * @param {Object} source source object contributing properties to mix
  2431. * in.
  2432. * @return {[Object]} returns dest object with the modification.
  2433. */
  2434. deepMix: function(dest, source) {
  2435. lang.eachProp(source, function (value, prop) {
  2436. if (typeof value === 'object' && value &&
  2437. !lang.isArray(value) && !lang.isFunction(value) &&
  2438. !(value instanceof RegExp)) {
  2439. if (!dest[prop]) {
  2440. dest[prop] = {};
  2441. }
  2442. lang.deepMix(dest[prop], value);
  2443. } else {
  2444. dest[prop] = value;
  2445. }
  2446. });
  2447. return dest;
  2448. },
  2449. /**
  2450. * Does a type of deep copy. Do not give it anything fancy, best
  2451. * for basic object copies of objects that also work well as
  2452. * JSON-serialized things, or has properties pointing to functions.
  2453. * For non-array/object values, just returns the same object.
  2454. * @param {Object} obj copy properties from this object
  2455. * @param {Object} [ignoredProps] optional object whose own properties
  2456. * are keys that should be ignored.
  2457. * @return {Object}
  2458. */
  2459. deeplikeCopy: function (obj, ignoredProps) {
  2460. var type, result;
  2461. if (lang.isArray(obj)) {
  2462. result = [];
  2463. obj.forEach(function(value) {
  2464. result.push(lang.deeplikeCopy(value, ignoredProps));
  2465. });
  2466. return result;
  2467. }
  2468. type = typeof obj;
  2469. if (obj === null || obj === undefined || type === 'boolean' ||
  2470. type === 'string' || type === 'number' || lang.isFunction(obj) ||
  2471. lang.isRegExp(obj)|| isJavaObj(obj)) {
  2472. return obj;
  2473. }
  2474. //Anything else is an object, hopefully.
  2475. result = {};
  2476. lang.eachProp(obj, function(value, key) {
  2477. if (!ignoredProps || !hasProp(ignoredProps, key)) {
  2478. result[key] = lang.deeplikeCopy(value, ignoredProps);
  2479. }
  2480. });
  2481. return result;
  2482. },
  2483. delegate: (function () {
  2484. // boodman/crockford delegation w/ cornford optimization
  2485. function TMP() {}
  2486. return function (obj, props) {
  2487. TMP.prototype = obj;
  2488. var tmp = new TMP();
  2489. TMP.prototype = null;
  2490. if (props) {
  2491. lang.mixin(tmp, props);
  2492. }
  2493. return tmp; // Object
  2494. };
  2495. }()),
  2496. /**
  2497. * Helper function for iterating over an array. If the func returns
  2498. * a true value, it will break out of the loop.
  2499. */
  2500. each: function each(ary, func) {
  2501. if (ary) {
  2502. var i;
  2503. for (i = 0; i < ary.length; i += 1) {
  2504. if (func(ary[i], i, ary)) {
  2505. break;
  2506. }
  2507. }
  2508. }
  2509. },
  2510. /**
  2511. * Cycles over properties in an object and calls a function for each
  2512. * property value. If the function returns a truthy value, then the
  2513. * iteration is stopped.
  2514. */
  2515. eachProp: function eachProp(obj, func) {
  2516. var prop;
  2517. for (prop in obj) {
  2518. if (hasProp(obj, prop)) {
  2519. if (func(obj[prop], prop)) {
  2520. break;
  2521. }
  2522. }
  2523. }
  2524. },
  2525. //Similar to Function.prototype.bind, but the "this" object is specified
  2526. //first, since it is easier to read/figure out what "this" will be.
  2527. bind: function bind(obj, fn) {
  2528. return function () {
  2529. return fn.apply(obj, arguments);
  2530. };
  2531. },
  2532. //Escapes a content string to be be a string that has characters escaped
  2533. //for inclusion as part of a JS string.
  2534. jsEscape: function (content) {
  2535. return content.replace(/(["'\\])/g, '\\$1')
  2536. .replace(/[\f]/g, "\\f")
  2537. .replace(/[\b]/g, "\\b")
  2538. .replace(/[\n]/g, "\\n")
  2539. .replace(/[\t]/g, "\\t")
  2540. .replace(/[\r]/g, "\\r");
  2541. }
  2542. };
  2543. return lang;
  2544. });
  2545. /**
  2546. * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2547. * Available via the MIT or new BSD license.
  2548. * see: http://github.com/requirejs/prim for details
  2549. */
  2550. /*global setImmediate, process, setTimeout, define, module */
  2551. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2552. //in promise-tests to pass.
  2553. //Since the goal of prim is to be a small impl for trusted code, it is
  2554. //more important to normally throw in this case so that we can find
  2555. //logic errors quicker.
  2556. var prim;
  2557. (function () {
  2558. 'use strict';
  2559. var op = Object.prototype,
  2560. hasOwn = op.hasOwnProperty;
  2561. function hasProp(obj, prop) {
  2562. return hasOwn.call(obj, prop);
  2563. }
  2564. /**
  2565. * Helper function for iterating over an array. If the func returns
  2566. * a true value, it will break out of the loop.
  2567. */
  2568. function each(ary, func) {
  2569. if (ary) {
  2570. var i;
  2571. for (i = 0; i < ary.length; i += 1) {
  2572. if (ary[i]) {
  2573. func(ary[i], i, ary);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. function check(p) {
  2579. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2580. if (!prim.hideResolutionConflict) {
  2581. throw new Error('Prim promise already resolved: ' +
  2582. JSON.stringify(p));
  2583. }
  2584. return false;
  2585. }
  2586. return true;
  2587. }
  2588. function notify(ary, value) {
  2589. prim.nextTick(function () {
  2590. each(ary, function (item) {
  2591. item(value);
  2592. });
  2593. });
  2594. }
  2595. prim = function prim() {
  2596. var p,
  2597. ok = [],
  2598. fail = [];
  2599. return (p = {
  2600. callback: function (yes, no) {
  2601. if (no) {
  2602. p.errback(no);
  2603. }
  2604. if (hasProp(p, 'v')) {
  2605. prim.nextTick(function () {
  2606. yes(p.v);
  2607. });
  2608. } else {
  2609. ok.push(yes);
  2610. }
  2611. },
  2612. errback: function (no) {
  2613. if (hasProp(p, 'e')) {
  2614. prim.nextTick(function () {
  2615. no(p.e);
  2616. });
  2617. } else {
  2618. fail.push(no);
  2619. }
  2620. },
  2621. finished: function () {
  2622. return hasProp(p, 'e') || hasProp(p, 'v');
  2623. },
  2624. rejected: function () {
  2625. return hasProp(p, 'e');
  2626. },
  2627. resolve: function (v) {
  2628. if (check(p)) {
  2629. p.v = v;
  2630. notify(ok, v);
  2631. }
  2632. return p;
  2633. },
  2634. reject: function (e) {
  2635. if (check(p)) {
  2636. p.e = e;
  2637. notify(fail, e);
  2638. }
  2639. return p;
  2640. },
  2641. start: function (fn) {
  2642. p.resolve();
  2643. return p.promise.then(fn);
  2644. },
  2645. promise: {
  2646. then: function (yes, no) {
  2647. var next = prim();
  2648. p.callback(function (v) {
  2649. try {
  2650. if (yes && typeof yes === 'function') {
  2651. v = yes(v);
  2652. }
  2653. if (v && v.then) {
  2654. v.then(next.resolve, next.reject);
  2655. } else {
  2656. next.resolve(v);
  2657. }
  2658. } catch (e) {
  2659. next.reject(e);
  2660. }
  2661. }, function (e) {
  2662. var err;
  2663. try {
  2664. if (!no || typeof no !== 'function') {
  2665. next.reject(e);
  2666. } else {
  2667. err = no(e);
  2668. if (err && err.then) {
  2669. err.then(next.resolve, next.reject);
  2670. } else {
  2671. next.resolve(err);
  2672. }
  2673. }
  2674. } catch (e2) {
  2675. next.reject(e2);
  2676. }
  2677. });
  2678. return next.promise;
  2679. },
  2680. fail: function (no) {
  2681. return p.promise.then(null, no);
  2682. },
  2683. end: function () {
  2684. p.errback(function (e) {
  2685. throw e;
  2686. });
  2687. }
  2688. }
  2689. });
  2690. };
  2691. prim.serial = function (ary) {
  2692. var result = prim().resolve().promise;
  2693. each(ary, function (item) {
  2694. result = result.then(function () {
  2695. return item();
  2696. });
  2697. });
  2698. return result;
  2699. };
  2700. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2701. (typeof process !== 'undefined' && process.nextTick ?
  2702. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2703. function (fn) {
  2704. setTimeout(fn, 0);
  2705. } : function (fn) {
  2706. fn();
  2707. }));
  2708. if (typeof define === 'function' && define.amd) {
  2709. define('prim', function () { return prim; });
  2710. } else if (typeof module !== 'undefined' && module.exports) {
  2711. module.exports = prim;
  2712. }
  2713. }());
  2714. if(env === 'browser') {
  2715. /**
  2716. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2717. * Available via the MIT or new BSD license.
  2718. * see: http://github.com/jrburke/requirejs for details
  2719. */
  2720. /*jslint strict: false */
  2721. /*global define: false, load: false */
  2722. //Just a stub for use with uglify's consolidator.js
  2723. define('browser/assert', function () {
  2724. return {};
  2725. });
  2726. }
  2727. if(env === 'node') {
  2728. /**
  2729. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2730. * Available via the MIT or new BSD license.
  2731. * see: http://github.com/jrburke/requirejs for details
  2732. */
  2733. /*jslint strict: false */
  2734. /*global define: false, load: false */
  2735. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2736. define('node/assert', ['assert'], function (assert) {
  2737. return assert;
  2738. });
  2739. }
  2740. if(env === 'rhino') {
  2741. /**
  2742. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2743. * Available via the MIT or new BSD license.
  2744. * see: http://github.com/jrburke/requirejs for details
  2745. */
  2746. /*jslint strict: false */
  2747. /*global define: false, load: false */
  2748. //Just a stub for use with uglify's consolidator.js
  2749. define('rhino/assert', function () {
  2750. return {};
  2751. });
  2752. }
  2753. if(env === 'xpconnect') {
  2754. /**
  2755. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2756. * Available via the MIT or new BSD license.
  2757. * see: http://github.com/jrburke/requirejs for details
  2758. */
  2759. /*jslint strict: false */
  2760. /*global define: false, load: false */
  2761. //Just a stub for use with uglify's consolidator.js
  2762. define('xpconnect/assert', function () {
  2763. return {};
  2764. });
  2765. }
  2766. if(env === 'browser') {
  2767. /**
  2768. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2769. * Available via the MIT or new BSD license.
  2770. * see: http://github.com/jrburke/requirejs for details
  2771. */
  2772. /*jslint strict: false */
  2773. /*global define: false, process: false */
  2774. define('browser/args', function () {
  2775. //Always expect config via an API call
  2776. return [];
  2777. });
  2778. }
  2779. if(env === 'node') {
  2780. /**
  2781. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2782. * Available via the MIT or new BSD license.
  2783. * see: http://github.com/jrburke/requirejs for details
  2784. */
  2785. /*jslint strict: false */
  2786. /*global define: false, process: false */
  2787. define('node/args', function () {
  2788. //Do not return the "node" or "r.js" arguments
  2789. var args = process.argv.slice(2);
  2790. //Ignore any command option used for main x.js branching
  2791. if (args[0] && args[0].indexOf('-') === 0) {
  2792. args = args.slice(1);
  2793. }
  2794. return args;
  2795. });
  2796. }
  2797. if(env === 'rhino') {
  2798. /**
  2799. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2800. * Available via the MIT or new BSD license.
  2801. * see: http://github.com/jrburke/requirejs for details
  2802. */
  2803. /*jslint strict: false */
  2804. /*global define: false, process: false */
  2805. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2806. define('rhino/args', function () {
  2807. var args = jsLibRhinoArgs;
  2808. //Ignore any command option used for main x.js branching
  2809. if (args[0] && args[0].indexOf('-') === 0) {
  2810. args = args.slice(1);
  2811. }
  2812. return args;
  2813. });
  2814. }
  2815. if(env === 'xpconnect') {
  2816. /**
  2817. * @license Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2818. * Available via the MIT or new BSD license.
  2819. * see: http://github.com/jrburke/requirejs for details
  2820. */
  2821. /*jslint strict: false */
  2822. /*global define, xpconnectArgs */
  2823. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2824. define('xpconnect/args', function () {
  2825. var args = jsLibXpConnectArgs;
  2826. //Ignore any command option used for main x.js branching
  2827. if (args[0] && args[0].indexOf('-') === 0) {
  2828. args = args.slice(1);
  2829. }
  2830. return args;
  2831. });
  2832. }
  2833. if(env === 'browser') {
  2834. /**
  2835. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2836. * Available via the MIT or new BSD license.
  2837. * see: http://github.com/jrburke/requirejs for details
  2838. */
  2839. /*jslint strict: false */
  2840. /*global define: false, console: false */
  2841. define('browser/load', ['./file'], function (file) {
  2842. function load(fileName) {
  2843. eval(file.readFile(fileName));
  2844. }
  2845. return load;
  2846. });
  2847. }
  2848. if(env === 'node') {
  2849. /**
  2850. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2851. * Available via the MIT or new BSD license.
  2852. * see: http://github.com/jrburke/requirejs for details
  2853. */
  2854. /*jslint strict: false */
  2855. /*global define: false, console: false */
  2856. define('node/load', ['fs'], function (fs) {
  2857. function load(fileName) {
  2858. var contents = fs.readFileSync(fileName, 'utf8');
  2859. process.compile(contents, fileName);
  2860. }
  2861. return load;
  2862. });
  2863. }
  2864. if(env === 'rhino') {
  2865. /**
  2866. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2867. * Available via the MIT or new BSD license.
  2868. * see: http://github.com/jrburke/requirejs for details
  2869. */
  2870. /*jslint strict: false */
  2871. /*global define: false, load: false */
  2872. define('rhino/load', function () {
  2873. return load;
  2874. });
  2875. }
  2876. if(env === 'xpconnect') {
  2877. /**
  2878. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2879. * Available via the MIT or new BSD license.
  2880. * see: http://github.com/jrburke/requirejs for details
  2881. */
  2882. /*jslint strict: false */
  2883. /*global define: false, load: false */
  2884. define('xpconnect/load', function () {
  2885. return load;
  2886. });
  2887. }
  2888. if(env === 'browser') {
  2889. /**
  2890. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2891. * Available via the MIT or new BSD license.
  2892. * see: http://github.com/jrburke/requirejs for details
  2893. */
  2894. /*jslint sloppy: true, nomen: true */
  2895. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2896. define('browser/file', ['prim'], function (prim) {
  2897. var file,
  2898. currDirRegExp = /^\.(\/|$)/;
  2899. function frontSlash(path) {
  2900. return path.replace(/\\/g, '/');
  2901. }
  2902. function exists(path) {
  2903. var status, xhr = new XMLHttpRequest();
  2904. //Oh yeah, that is right SYNC IO. Behold its glory
  2905. //and horrible blocking behavior.
  2906. xhr.open('HEAD', path, false);
  2907. xhr.send();
  2908. status = xhr.status;
  2909. return status === 200 || status === 304;
  2910. }
  2911. function mkDir(dir) {
  2912. console.log('mkDir is no-op in browser');
  2913. }
  2914. function mkFullDir(dir) {
  2915. console.log('mkFullDir is no-op in browser');
  2916. }
  2917. file = {
  2918. backSlashRegExp: /\\/g,
  2919. exclusionRegExp: /^\./,
  2920. getLineSeparator: function () {
  2921. return '/';
  2922. },
  2923. exists: function (fileName) {
  2924. return exists(fileName);
  2925. },
  2926. parent: function (fileName) {
  2927. var parts = fileName.split('/');
  2928. parts.pop();
  2929. return parts.join('/');
  2930. },
  2931. /**
  2932. * Gets the absolute file path as a string, normalized
  2933. * to using front slashes for path separators.
  2934. * @param {String} fileName
  2935. */
  2936. absPath: function (fileName) {
  2937. var dir;
  2938. if (currDirRegExp.test(fileName)) {
  2939. dir = frontSlash(location.href);
  2940. if (dir.indexOf('/') !== -1) {
  2941. dir = dir.split('/');
  2942. //Pull off protocol and host, just want
  2943. //to allow paths (other build parts, like
  2944. //require._isSupportedBuildUrl do not support
  2945. //full URLs), but a full path from
  2946. //the root.
  2947. dir.splice(0, 3);
  2948. dir.pop();
  2949. dir = '/' + dir.join('/');
  2950. }
  2951. fileName = dir + fileName.substring(1);
  2952. }
  2953. return fileName;
  2954. },
  2955. normalize: function (fileName) {
  2956. return fileName;
  2957. },
  2958. isFile: function (path) {
  2959. return true;
  2960. },
  2961. isDirectory: function (path) {
  2962. return false;
  2963. },
  2964. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2965. console.log('file.getFilteredFileList is no-op in browser');
  2966. },
  2967. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2968. console.log('file.copyDir is no-op in browser');
  2969. },
  2970. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2971. console.log('file.copyFile is no-op in browser');
  2972. },
  2973. /**
  2974. * Renames a file. May fail if "to" already exists or is on another drive.
  2975. */
  2976. renameFile: function (from, to) {
  2977. console.log('file.renameFile is no-op in browser');
  2978. },
  2979. /**
  2980. * Reads a *text* file.
  2981. */
  2982. readFile: function (path, encoding) {
  2983. var xhr = new XMLHttpRequest();
  2984. //Oh yeah, that is right SYNC IO. Behold its glory
  2985. //and horrible blocking behavior.
  2986. xhr.open('GET', path, false);
  2987. xhr.send();
  2988. return xhr.responseText;
  2989. },
  2990. readFileAsync: function (path, encoding) {
  2991. var xhr = new XMLHttpRequest(),
  2992. d = prim();
  2993. xhr.open('GET', path, true);
  2994. xhr.send();
  2995. xhr.onreadystatechange = function () {
  2996. if (xhr.readyState === 4) {
  2997. if (xhr.status > 400) {
  2998. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2999. } else {
  3000. d.resolve(xhr.responseText);
  3001. }
  3002. }
  3003. };
  3004. return d.promise;
  3005. },
  3006. saveUtf8File: function (fileName, fileContents) {
  3007. //summary: saves a *text* file using UTF-8 encoding.
  3008. file.saveFile(fileName, fileContents, "utf8");
  3009. },
  3010. saveFile: function (fileName, fileContents, encoding) {
  3011. requirejs.browser.saveFile(fileName, fileContents, encoding);
  3012. },
  3013. deleteFile: function (fileName) {
  3014. console.log('file.deleteFile is no-op in browser');
  3015. },
  3016. /**
  3017. * Deletes any empty directories under the given directory.
  3018. */
  3019. deleteEmptyDirs: function (startDir) {
  3020. console.log('file.deleteEmptyDirs is no-op in browser');
  3021. }
  3022. };
  3023. return file;
  3024. });
  3025. }
  3026. if(env === 'node') {
  3027. /**
  3028. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3029. * Available via the MIT or new BSD license.
  3030. * see: http://github.com/jrburke/requirejs for details
  3031. */
  3032. /*jslint plusplus: false, octal:false, strict: false */
  3033. /*global define: false, process: false */
  3034. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  3035. var isWindows = process.platform === 'win32',
  3036. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  3037. file;
  3038. function frontSlash(path) {
  3039. return path.replace(/\\/g, '/');
  3040. }
  3041. function exists(path) {
  3042. if (isWindows && path.charAt(path.length - 1) === '/' &&
  3043. path.charAt(path.length - 2) !== ':') {
  3044. path = path.substring(0, path.length - 1);
  3045. }
  3046. try {
  3047. fs.statSync(path);
  3048. return true;
  3049. } catch (e) {
  3050. return false;
  3051. }
  3052. }
  3053. function mkDir(dir) {
  3054. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  3055. fs.mkdirSync(dir, 511);
  3056. }
  3057. }
  3058. function mkFullDir(dir) {
  3059. var parts = dir.split('/'),
  3060. currDir = '',
  3061. first = true;
  3062. parts.forEach(function (part) {
  3063. //First part may be empty string if path starts with a slash.
  3064. currDir += part + '/';
  3065. first = false;
  3066. if (part) {
  3067. mkDir(currDir);
  3068. }
  3069. });
  3070. }
  3071. file = {
  3072. backSlashRegExp: /\\/g,
  3073. exclusionRegExp: /^\./,
  3074. getLineSeparator: function () {
  3075. return '/';
  3076. },
  3077. exists: function (fileName) {
  3078. return exists(fileName);
  3079. },
  3080. parent: function (fileName) {
  3081. var parts = fileName.split('/');
  3082. parts.pop();
  3083. return parts.join('/');
  3084. },
  3085. /**
  3086. * Gets the absolute file path as a string, normalized
  3087. * to using front slashes for path separators.
  3088. * @param {String} fileName
  3089. */
  3090. absPath: function (fileName) {
  3091. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  3092. },
  3093. normalize: function (fileName) {
  3094. return frontSlash(path.normalize(fileName));
  3095. },
  3096. isFile: function (path) {
  3097. return fs.statSync(path).isFile();
  3098. },
  3099. isDirectory: function (path) {
  3100. return fs.statSync(path).isDirectory();
  3101. },
  3102. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  3103. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3104. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3105. //and it will be treated as the "include" case.
  3106. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3107. //is set to another value.
  3108. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3109. i, stat, filePath, ok, dirFiles, fileName;
  3110. topDir = startDir;
  3111. regExpInclude = regExpFilters.include || regExpFilters;
  3112. regExpExclude = regExpFilters.exclude || null;
  3113. if (file.exists(topDir)) {
  3114. dirFileArray = fs.readdirSync(topDir);
  3115. for (i = 0; i < dirFileArray.length; i++) {
  3116. fileName = dirFileArray[i];
  3117. filePath = path.join(topDir, fileName);
  3118. stat = fs.statSync(filePath);
  3119. if (stat.isFile()) {
  3120. if (makeUnixPaths) {
  3121. //Make sure we have a JS string.
  3122. if (filePath.indexOf("/") === -1) {
  3123. filePath = frontSlash(filePath);
  3124. }
  3125. }
  3126. ok = true;
  3127. if (regExpInclude) {
  3128. ok = filePath.match(regExpInclude);
  3129. }
  3130. if (ok && regExpExclude) {
  3131. ok = !filePath.match(regExpExclude);
  3132. }
  3133. if (ok && (!file.exclusionRegExp ||
  3134. !file.exclusionRegExp.test(fileName))) {
  3135. files.push(filePath);
  3136. }
  3137. } else if (stat.isDirectory() &&
  3138. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  3139. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  3140. files.push.apply(files, dirFiles);
  3141. }
  3142. }
  3143. }
  3144. return files; //Array
  3145. },
  3146. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3147. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3148. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3149. regExpFilter = regExpFilter || /\w/;
  3150. //Normalize th directory names, but keep front slashes.
  3151. //path module on windows now returns backslashed paths.
  3152. srcDir = frontSlash(path.normalize(srcDir));
  3153. destDir = frontSlash(path.normalize(destDir));
  3154. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3155. copiedFiles = [], i, srcFileName, destFileName;
  3156. for (i = 0; i < fileNames.length; i++) {
  3157. srcFileName = fileNames[i];
  3158. destFileName = srcFileName.replace(srcDir, destDir);
  3159. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3160. copiedFiles.push(destFileName);
  3161. }
  3162. }
  3163. return copiedFiles.length ? copiedFiles : null; //Array or null
  3164. },
  3165. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3166. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3167. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3168. var parentDir;
  3169. //logger.trace("Src filename: " + srcFileName);
  3170. //logger.trace("Dest filename: " + destFileName);
  3171. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3172. //than dest.
  3173. if (onlyCopyNew) {
  3174. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  3175. return false; //Boolean
  3176. }
  3177. }
  3178. //Make sure destination dir exists.
  3179. parentDir = path.dirname(destFileName);
  3180. if (!file.exists(parentDir)) {
  3181. mkFullDir(parentDir);
  3182. }
  3183. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  3184. return true; //Boolean
  3185. },
  3186. /**
  3187. * Renames a file. May fail if "to" already exists or is on another drive.
  3188. */
  3189. renameFile: function (from, to) {
  3190. return fs.renameSync(from, to);
  3191. },
  3192. /**
  3193. * Reads a *text* file.
  3194. */
  3195. readFile: function (/*String*/path, /*String?*/encoding) {
  3196. if (encoding === 'utf-8') {
  3197. encoding = 'utf8';
  3198. }
  3199. if (!encoding) {
  3200. encoding = 'utf8';
  3201. }
  3202. var text = fs.readFileSync(path, encoding);
  3203. //Hmm, would not expect to get A BOM, but it seems to happen,
  3204. //remove it just in case.
  3205. if (text.indexOf('\uFEFF') === 0) {
  3206. text = text.substring(1, text.length);
  3207. }
  3208. return text;
  3209. },
  3210. readFileAsync: function (path, encoding) {
  3211. var d = prim();
  3212. try {
  3213. d.resolve(file.readFile(path, encoding));
  3214. } catch (e) {
  3215. d.reject(e);
  3216. }
  3217. return d.promise;
  3218. },
  3219. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3220. //summary: saves a *text* file using UTF-8 encoding.
  3221. file.saveFile(fileName, fileContents, "utf8");
  3222. },
  3223. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3224. //summary: saves a *text* file.
  3225. var parentDir;
  3226. if (encoding === 'utf-8') {
  3227. encoding = 'utf8';
  3228. }
  3229. if (!encoding) {
  3230. encoding = 'utf8';
  3231. }
  3232. //Make sure destination directories exist.
  3233. parentDir = path.dirname(fileName);
  3234. if (!file.exists(parentDir)) {
  3235. mkFullDir(parentDir);
  3236. }
  3237. fs.writeFileSync(fileName, fileContents, encoding);
  3238. },
  3239. deleteFile: function (/*String*/fileName) {
  3240. //summary: deletes a file or directory if it exists.
  3241. var files, i, stat;
  3242. if (file.exists(fileName)) {
  3243. stat = fs.lstatSync(fileName);
  3244. if (stat.isDirectory()) {
  3245. files = fs.readdirSync(fileName);
  3246. for (i = 0; i < files.length; i++) {
  3247. this.deleteFile(path.join(fileName, files[i]));
  3248. }
  3249. fs.rmdirSync(fileName);
  3250. } else {
  3251. fs.unlinkSync(fileName);
  3252. }
  3253. }
  3254. },
  3255. /**
  3256. * Deletes any empty directories under the given directory.
  3257. */
  3258. deleteEmptyDirs: function (startDir) {
  3259. var dirFileArray, i, fileName, filePath, stat;
  3260. if (file.exists(startDir)) {
  3261. dirFileArray = fs.readdirSync(startDir);
  3262. for (i = 0; i < dirFileArray.length; i++) {
  3263. fileName = dirFileArray[i];
  3264. filePath = path.join(startDir, fileName);
  3265. stat = fs.lstatSync(filePath);
  3266. if (stat.isDirectory()) {
  3267. file.deleteEmptyDirs(filePath);
  3268. }
  3269. }
  3270. //If directory is now empty, remove it.
  3271. if (fs.readdirSync(startDir).length === 0) {
  3272. file.deleteFile(startDir);
  3273. }
  3274. }
  3275. }
  3276. };
  3277. return file;
  3278. });
  3279. }
  3280. if(env === 'rhino') {
  3281. /**
  3282. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3283. * Available via the MIT or new BSD license.
  3284. * see: http://github.com/jrburke/requirejs for details
  3285. */
  3286. //Helper functions to deal with file I/O.
  3287. /*jslint plusplus: false */
  3288. /*global java: false, define: false */
  3289. define('rhino/file', ['prim'], function (prim) {
  3290. var file = {
  3291. backSlashRegExp: /\\/g,
  3292. exclusionRegExp: /^\./,
  3293. getLineSeparator: function () {
  3294. return file.lineSeparator;
  3295. },
  3296. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3297. exists: function (fileName) {
  3298. return (new java.io.File(fileName)).exists();
  3299. },
  3300. parent: function (fileName) {
  3301. return file.absPath((new java.io.File(fileName)).getParentFile());
  3302. },
  3303. normalize: function (fileName) {
  3304. return file.absPath(fileName);
  3305. },
  3306. isFile: function (path) {
  3307. return (new java.io.File(path)).isFile();
  3308. },
  3309. isDirectory: function (path) {
  3310. return (new java.io.File(path)).isDirectory();
  3311. },
  3312. /**
  3313. * Gets the absolute file path as a string, normalized
  3314. * to using front slashes for path separators.
  3315. * @param {java.io.File||String} file
  3316. */
  3317. absPath: function (fileObj) {
  3318. if (typeof fileObj === "string") {
  3319. fileObj = new java.io.File(fileObj);
  3320. }
  3321. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3322. },
  3323. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3324. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3325. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3326. //and it will be treated as the "include" case.
  3327. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3328. //is set to another value.
  3329. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3330. i, fileObj, filePath, ok, dirFiles;
  3331. topDir = startDir;
  3332. if (!startDirIsJavaObject) {
  3333. topDir = new java.io.File(startDir);
  3334. }
  3335. regExpInclude = regExpFilters.include || regExpFilters;
  3336. regExpExclude = regExpFilters.exclude || null;
  3337. if (topDir.exists()) {
  3338. dirFileArray = topDir.listFiles();
  3339. for (i = 0; i < dirFileArray.length; i++) {
  3340. fileObj = dirFileArray[i];
  3341. if (fileObj.isFile()) {
  3342. filePath = fileObj.getPath();
  3343. if (makeUnixPaths) {
  3344. //Make sure we have a JS string.
  3345. filePath = String(filePath);
  3346. if (filePath.indexOf("/") === -1) {
  3347. filePath = filePath.replace(/\\/g, "/");
  3348. }
  3349. }
  3350. ok = true;
  3351. if (regExpInclude) {
  3352. ok = filePath.match(regExpInclude);
  3353. }
  3354. if (ok && regExpExclude) {
  3355. ok = !filePath.match(regExpExclude);
  3356. }
  3357. if (ok && (!file.exclusionRegExp ||
  3358. !file.exclusionRegExp.test(fileObj.getName()))) {
  3359. files.push(filePath);
  3360. }
  3361. } else if (fileObj.isDirectory() &&
  3362. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3363. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3364. files.push.apply(files, dirFiles);
  3365. }
  3366. }
  3367. }
  3368. return files; //Array
  3369. },
  3370. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3371. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3372. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3373. regExpFilter = regExpFilter || /\w/;
  3374. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3375. copiedFiles = [], i, srcFileName, destFileName;
  3376. for (i = 0; i < fileNames.length; i++) {
  3377. srcFileName = fileNames[i];
  3378. destFileName = srcFileName.replace(srcDir, destDir);
  3379. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3380. copiedFiles.push(destFileName);
  3381. }
  3382. }
  3383. return copiedFiles.length ? copiedFiles : null; //Array or null
  3384. },
  3385. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3386. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3387. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3388. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3389. srcChannel, destChannel;
  3390. //logger.trace("Src filename: " + srcFileName);
  3391. //logger.trace("Dest filename: " + destFileName);
  3392. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3393. //than dest.
  3394. if (onlyCopyNew) {
  3395. srcFile = new java.io.File(srcFileName);
  3396. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3397. return false; //Boolean
  3398. }
  3399. }
  3400. //Make sure destination dir exists.
  3401. parentDir = destFile.getParentFile();
  3402. if (!parentDir.exists()) {
  3403. if (!parentDir.mkdirs()) {
  3404. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3405. }
  3406. }
  3407. //Java's version of copy file.
  3408. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3409. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3410. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3411. srcChannel.close();
  3412. destChannel.close();
  3413. return true; //Boolean
  3414. },
  3415. /**
  3416. * Renames a file. May fail if "to" already exists or is on another drive.
  3417. */
  3418. renameFile: function (from, to) {
  3419. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3420. },
  3421. readFile: function (/*String*/path, /*String?*/encoding) {
  3422. //A file read function that can deal with BOMs
  3423. encoding = encoding || "utf-8";
  3424. var fileObj = new java.io.File(path),
  3425. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3426. stringBuffer, line;
  3427. try {
  3428. stringBuffer = new java.lang.StringBuffer();
  3429. line = input.readLine();
  3430. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3431. // http://www.unicode.org/faq/utf_bom.html
  3432. // 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:
  3433. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3434. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3435. // Eat the BOM, since we've already found the encoding on this file,
  3436. // and we plan to concatenating this buffer with others; the BOM should
  3437. // only appear at the top of a file.
  3438. line = line.substring(1);
  3439. }
  3440. while (line !== null) {
  3441. stringBuffer.append(line);
  3442. stringBuffer.append(file.lineSeparator);
  3443. line = input.readLine();
  3444. }
  3445. //Make sure we return a JavaScript string and not a Java string.
  3446. return String(stringBuffer.toString()); //String
  3447. } finally {
  3448. input.close();
  3449. }
  3450. },
  3451. readFileAsync: function (path, encoding) {
  3452. var d = prim();
  3453. try {
  3454. d.resolve(file.readFile(path, encoding));
  3455. } catch (e) {
  3456. d.reject(e);
  3457. }
  3458. return d.promise;
  3459. },
  3460. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3461. //summary: saves a file using UTF-8 encoding.
  3462. file.saveFile(fileName, fileContents, "utf-8");
  3463. },
  3464. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3465. //summary: saves a file.
  3466. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3467. parentDir = outFile.getAbsoluteFile().getParentFile();
  3468. if (!parentDir.exists()) {
  3469. if (!parentDir.mkdirs()) {
  3470. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3471. }
  3472. }
  3473. if (encoding) {
  3474. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3475. } else {
  3476. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3477. }
  3478. os = new java.io.BufferedWriter(outWriter);
  3479. try {
  3480. //If in Nashorn, need to coerce the JS string to a Java string so that
  3481. //writer.write method dispatch correctly detects the type.
  3482. if (typeof importPackage !== 'undefined') {
  3483. os.write(fileContents);
  3484. } else {
  3485. os.write(new java.lang.String(fileContents));
  3486. }
  3487. } finally {
  3488. os.close();
  3489. }
  3490. },
  3491. deleteFile: function (/*String*/fileName) {
  3492. //summary: deletes a file or directory if it exists.
  3493. var fileObj = new java.io.File(fileName), files, i;
  3494. if (fileObj.exists()) {
  3495. if (fileObj.isDirectory()) {
  3496. files = fileObj.listFiles();
  3497. for (i = 0; i < files.length; i++) {
  3498. this.deleteFile(files[i]);
  3499. }
  3500. }
  3501. fileObj["delete"]();
  3502. }
  3503. },
  3504. /**
  3505. * Deletes any empty directories under the given directory.
  3506. * The startDirIsJavaObject is private to this implementation's
  3507. * recursion needs.
  3508. */
  3509. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3510. var topDir = startDir,
  3511. dirFileArray, i, fileObj;
  3512. if (!startDirIsJavaObject) {
  3513. topDir = new java.io.File(startDir);
  3514. }
  3515. if (topDir.exists()) {
  3516. dirFileArray = topDir.listFiles();
  3517. for (i = 0; i < dirFileArray.length; i++) {
  3518. fileObj = dirFileArray[i];
  3519. if (fileObj.isDirectory()) {
  3520. file.deleteEmptyDirs(fileObj, true);
  3521. }
  3522. }
  3523. //If the directory is empty now, delete it.
  3524. if (topDir.listFiles().length === 0) {
  3525. file.deleteFile(String(topDir.getPath()));
  3526. }
  3527. }
  3528. }
  3529. };
  3530. return file;
  3531. });
  3532. }
  3533. if(env === 'xpconnect') {
  3534. /**
  3535. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3536. * Available via the MIT or new BSD license.
  3537. * see: http://github.com/jrburke/requirejs for details
  3538. */
  3539. //Helper functions to deal with file I/O.
  3540. /*jslint plusplus: false */
  3541. /*global define, Components, xpcUtil */
  3542. define('xpconnect/file', ['prim'], function (prim) {
  3543. var file,
  3544. Cc = Components.classes,
  3545. Ci = Components.interfaces,
  3546. //Depends on xpcUtil which is set up in x.js
  3547. xpfile = xpcUtil.xpfile;
  3548. function mkFullDir(dirObj) {
  3549. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3550. if (!dirObj.exists()) {
  3551. dirObj.create(1, 511);
  3552. }
  3553. }
  3554. file = {
  3555. backSlashRegExp: /\\/g,
  3556. exclusionRegExp: /^\./,
  3557. getLineSeparator: function () {
  3558. return file.lineSeparator;
  3559. },
  3560. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3561. '\r\n' : '\n',
  3562. exists: function (fileName) {
  3563. return xpfile(fileName).exists();
  3564. },
  3565. parent: function (fileName) {
  3566. return xpfile(fileName).parent;
  3567. },
  3568. normalize: function (fileName) {
  3569. return file.absPath(fileName);
  3570. },
  3571. isFile: function (path) {
  3572. return xpfile(path).isFile();
  3573. },
  3574. isDirectory: function (path) {
  3575. return xpfile(path).isDirectory();
  3576. },
  3577. /**
  3578. * Gets the absolute file path as a string, normalized
  3579. * to using front slashes for path separators.
  3580. * @param {java.io.File||String} file
  3581. */
  3582. absPath: function (fileObj) {
  3583. if (typeof fileObj === "string") {
  3584. fileObj = xpfile(fileObj);
  3585. }
  3586. return fileObj.path;
  3587. },
  3588. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3589. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3590. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3591. //and it will be treated as the "include" case.
  3592. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3593. //is set to another value.
  3594. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3595. fileObj, filePath, ok, dirFiles;
  3596. topDir = startDir;
  3597. if (!startDirIsObject) {
  3598. topDir = xpfile(startDir);
  3599. }
  3600. regExpInclude = regExpFilters.include || regExpFilters;
  3601. regExpExclude = regExpFilters.exclude || null;
  3602. if (topDir.exists()) {
  3603. dirFileArray = topDir.directoryEntries;
  3604. while (dirFileArray.hasMoreElements()) {
  3605. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3606. if (fileObj.isFile()) {
  3607. filePath = fileObj.path;
  3608. if (makeUnixPaths) {
  3609. if (filePath.indexOf("/") === -1) {
  3610. filePath = filePath.replace(/\\/g, "/");
  3611. }
  3612. }
  3613. ok = true;
  3614. if (regExpInclude) {
  3615. ok = filePath.match(regExpInclude);
  3616. }
  3617. if (ok && regExpExclude) {
  3618. ok = !filePath.match(regExpExclude);
  3619. }
  3620. if (ok && (!file.exclusionRegExp ||
  3621. !file.exclusionRegExp.test(fileObj.leafName))) {
  3622. files.push(filePath);
  3623. }
  3624. } else if (fileObj.isDirectory() &&
  3625. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3626. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3627. files.push.apply(files, dirFiles);
  3628. }
  3629. }
  3630. }
  3631. return files; //Array
  3632. },
  3633. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3634. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3635. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3636. regExpFilter = regExpFilter || /\w/;
  3637. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3638. copiedFiles = [], i, srcFileName, destFileName;
  3639. for (i = 0; i < fileNames.length; i += 1) {
  3640. srcFileName = fileNames[i];
  3641. destFileName = srcFileName.replace(srcDir, destDir);
  3642. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3643. copiedFiles.push(destFileName);
  3644. }
  3645. }
  3646. return copiedFiles.length ? copiedFiles : null; //Array or null
  3647. },
  3648. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3649. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3650. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3651. var destFile = xpfile(destFileName),
  3652. srcFile = xpfile(srcFileName);
  3653. //logger.trace("Src filename: " + srcFileName);
  3654. //logger.trace("Dest filename: " + destFileName);
  3655. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3656. //than dest.
  3657. if (onlyCopyNew) {
  3658. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3659. return false; //Boolean
  3660. }
  3661. }
  3662. srcFile.copyTo(destFile.parent, destFile.leafName);
  3663. return true; //Boolean
  3664. },
  3665. /**
  3666. * Renames a file. May fail if "to" already exists or is on another drive.
  3667. */
  3668. renameFile: function (from, to) {
  3669. var toFile = xpfile(to);
  3670. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3671. },
  3672. readFile: xpcUtil.readFile,
  3673. readFileAsync: function (path, encoding) {
  3674. var d = prim();
  3675. try {
  3676. d.resolve(file.readFile(path, encoding));
  3677. } catch (e) {
  3678. d.reject(e);
  3679. }
  3680. return d.promise;
  3681. },
  3682. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3683. //summary: saves a file using UTF-8 encoding.
  3684. file.saveFile(fileName, fileContents, "utf-8");
  3685. },
  3686. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3687. var outStream, convertStream,
  3688. fileObj = xpfile(fileName);
  3689. mkFullDir(fileObj.parent);
  3690. try {
  3691. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3692. .createInstance(Ci.nsIFileOutputStream);
  3693. //438 is decimal for 0777
  3694. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3695. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3696. .createInstance(Ci.nsIConverterOutputStream);
  3697. convertStream.init(outStream, encoding, 0, 0);
  3698. convertStream.writeString(fileContents);
  3699. } catch (e) {
  3700. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3701. } finally {
  3702. if (convertStream) {
  3703. convertStream.close();
  3704. }
  3705. if (outStream) {
  3706. outStream.close();
  3707. }
  3708. }
  3709. },
  3710. deleteFile: function (/*String*/fileName) {
  3711. //summary: deletes a file or directory if it exists.
  3712. var fileObj = xpfile(fileName);
  3713. if (fileObj.exists()) {
  3714. fileObj.remove(true);
  3715. }
  3716. },
  3717. /**
  3718. * Deletes any empty directories under the given directory.
  3719. * The startDirIsJavaObject is private to this implementation's
  3720. * recursion needs.
  3721. */
  3722. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3723. var topDir = startDir,
  3724. dirFileArray, fileObj;
  3725. if (!startDirIsObject) {
  3726. topDir = xpfile(startDir);
  3727. }
  3728. if (topDir.exists()) {
  3729. dirFileArray = topDir.directoryEntries;
  3730. while (dirFileArray.hasMoreElements()) {
  3731. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3732. if (fileObj.isDirectory()) {
  3733. file.deleteEmptyDirs(fileObj, true);
  3734. }
  3735. }
  3736. //If the directory is empty now, delete it.
  3737. dirFileArray = topDir.directoryEntries;
  3738. if (!dirFileArray.hasMoreElements()) {
  3739. file.deleteFile(topDir.path);
  3740. }
  3741. }
  3742. }
  3743. };
  3744. return file;
  3745. });
  3746. }
  3747. if(env === 'browser') {
  3748. /*global process */
  3749. define('browser/quit', function () {
  3750. 'use strict';
  3751. return function (code) {
  3752. };
  3753. });
  3754. }
  3755. if(env === 'node') {
  3756. /*global process */
  3757. define('node/quit', function () {
  3758. 'use strict';
  3759. return function (code) {
  3760. var draining = 0;
  3761. var exit = function () {
  3762. if (draining === 0) {
  3763. process.exit(code);
  3764. } else {
  3765. draining -= 1;
  3766. }
  3767. };
  3768. if (process.stdout.bufferSize) {
  3769. draining += 1;
  3770. process.stdout.once('drain', exit);
  3771. }
  3772. if (process.stderr.bufferSize) {
  3773. draining += 1;
  3774. process.stderr.once('drain', exit);
  3775. }
  3776. exit();
  3777. };
  3778. });
  3779. }
  3780. if(env === 'rhino') {
  3781. /*global quit */
  3782. define('rhino/quit', function () {
  3783. 'use strict';
  3784. return function (code) {
  3785. return quit(code);
  3786. };
  3787. });
  3788. }
  3789. if(env === 'xpconnect') {
  3790. /*global quit */
  3791. define('xpconnect/quit', function () {
  3792. 'use strict';
  3793. return function (code) {
  3794. return quit(code);
  3795. };
  3796. });
  3797. }
  3798. if(env === 'browser') {
  3799. /**
  3800. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3801. * Available via the MIT or new BSD license.
  3802. * see: http://github.com/jrburke/requirejs for details
  3803. */
  3804. /*jslint strict: false */
  3805. /*global define: false, console: false */
  3806. define('browser/print', function () {
  3807. function print(msg) {
  3808. console.log(msg);
  3809. }
  3810. return print;
  3811. });
  3812. }
  3813. if(env === 'node') {
  3814. /**
  3815. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3816. * Available via the MIT or new BSD license.
  3817. * see: http://github.com/jrburke/requirejs for details
  3818. */
  3819. /*jslint strict: false */
  3820. /*global define: false, console: false */
  3821. define('node/print', function () {
  3822. function print(msg) {
  3823. console.log(msg);
  3824. }
  3825. return print;
  3826. });
  3827. }
  3828. if(env === 'rhino') {
  3829. /**
  3830. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3831. * Available via the MIT or new BSD license.
  3832. * see: http://github.com/jrburke/requirejs for details
  3833. */
  3834. /*jslint strict: false */
  3835. /*global define: false, print: false */
  3836. define('rhino/print', function () {
  3837. return print;
  3838. });
  3839. }
  3840. if(env === 'xpconnect') {
  3841. /**
  3842. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3843. * Available via the MIT or new BSD license.
  3844. * see: http://github.com/jrburke/requirejs for details
  3845. */
  3846. /*jslint strict: false */
  3847. /*global define: false, print: false */
  3848. define('xpconnect/print', function () {
  3849. return print;
  3850. });
  3851. }
  3852. /**
  3853. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3854. * Available via the MIT or new BSD license.
  3855. * see: http://github.com/jrburke/requirejs for details
  3856. */
  3857. /*jslint nomen: false, strict: false */
  3858. /*global define: false */
  3859. define('logger', ['env!env/print'], function (print) {
  3860. var logger = {
  3861. TRACE: 0,
  3862. INFO: 1,
  3863. WARN: 2,
  3864. ERROR: 3,
  3865. SILENT: 4,
  3866. level: 0,
  3867. logPrefix: "",
  3868. logLevel: function( level ) {
  3869. this.level = level;
  3870. },
  3871. trace: function (message) {
  3872. if (this.level <= this.TRACE) {
  3873. this._print(message);
  3874. }
  3875. },
  3876. info: function (message) {
  3877. if (this.level <= this.INFO) {
  3878. this._print(message);
  3879. }
  3880. },
  3881. warn: function (message) {
  3882. if (this.level <= this.WARN) {
  3883. this._print(message);
  3884. }
  3885. },
  3886. error: function (message) {
  3887. if (this.level <= this.ERROR) {
  3888. this._print(message);
  3889. }
  3890. },
  3891. _print: function (message) {
  3892. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3893. },
  3894. _sysPrint: function (message) {
  3895. print(message);
  3896. }
  3897. };
  3898. return logger;
  3899. });
  3900. //Just a blank file to use when building the optimizer with the optimizer,
  3901. //so that the build does not attempt to inline some env modules,
  3902. //like Node's fs and path.
  3903. /*
  3904. Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
  3905. Redistribution and use in source and binary forms, with or without
  3906. modification, are permitted provided that the following conditions are met:
  3907. * Redistributions of source code must retain the above copyright
  3908. notice, this list of conditions and the following disclaimer.
  3909. * Redistributions in binary form must reproduce the above copyright
  3910. notice, this list of conditions and the following disclaimer in the
  3911. documentation and/or other materials provided with the distribution.
  3912. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3913. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3914. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3915. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3916. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3917. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3918. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3919. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3920. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3921. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3922. */
  3923. (function (root, factory) {
  3924. 'use strict';
  3925. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  3926. // Rhino, and plain browser loading.
  3927. /* istanbul ignore next */
  3928. if (typeof define === 'function' && define.amd) {
  3929. define('esprima', ['exports'], factory);
  3930. } else if (typeof exports !== 'undefined') {
  3931. factory(exports);
  3932. } else {
  3933. factory((root.esprima = {}));
  3934. }
  3935. }(this, function (exports) {
  3936. 'use strict';
  3937. var Token,
  3938. TokenName,
  3939. FnExprTokens,
  3940. Syntax,
  3941. PlaceHolders,
  3942. Messages,
  3943. Regex,
  3944. source,
  3945. strict,
  3946. index,
  3947. lineNumber,
  3948. lineStart,
  3949. hasLineTerminator,
  3950. lastIndex,
  3951. lastLineNumber,
  3952. lastLineStart,
  3953. startIndex,
  3954. startLineNumber,
  3955. startLineStart,
  3956. scanning,
  3957. length,
  3958. lookahead,
  3959. state,
  3960. extra,
  3961. isBindingElement,
  3962. isAssignmentTarget,
  3963. firstCoverInitializedNameError;
  3964. Token = {
  3965. BooleanLiteral: 1,
  3966. EOF: 2,
  3967. Identifier: 3,
  3968. Keyword: 4,
  3969. NullLiteral: 5,
  3970. NumericLiteral: 6,
  3971. Punctuator: 7,
  3972. StringLiteral: 8,
  3973. RegularExpression: 9,
  3974. Template: 10
  3975. };
  3976. TokenName = {};
  3977. TokenName[Token.BooleanLiteral] = 'Boolean';
  3978. TokenName[Token.EOF] = '<end>';
  3979. TokenName[Token.Identifier] = 'Identifier';
  3980. TokenName[Token.Keyword] = 'Keyword';
  3981. TokenName[Token.NullLiteral] = 'Null';
  3982. TokenName[Token.NumericLiteral] = 'Numeric';
  3983. TokenName[Token.Punctuator] = 'Punctuator';
  3984. TokenName[Token.StringLiteral] = 'String';
  3985. TokenName[Token.RegularExpression] = 'RegularExpression';
  3986. TokenName[Token.Template] = 'Template';
  3987. // A function following one of those tokens is an expression.
  3988. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  3989. 'return', 'case', 'delete', 'throw', 'void',
  3990. // assignment operators
  3991. '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
  3992. '&=', '|=', '^=', ',',
  3993. // binary/unary operators
  3994. '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  3995. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  3996. '<=', '<', '>', '!=', '!=='];
  3997. Syntax = {
  3998. AssignmentExpression: 'AssignmentExpression',
  3999. AssignmentPattern: 'AssignmentPattern',
  4000. ArrayExpression: 'ArrayExpression',
  4001. ArrayPattern: 'ArrayPattern',
  4002. ArrowFunctionExpression: 'ArrowFunctionExpression',
  4003. BlockStatement: 'BlockStatement',
  4004. BinaryExpression: 'BinaryExpression',
  4005. BreakStatement: 'BreakStatement',
  4006. CallExpression: 'CallExpression',
  4007. CatchClause: 'CatchClause',
  4008. ClassBody: 'ClassBody',
  4009. ClassDeclaration: 'ClassDeclaration',
  4010. ClassExpression: 'ClassExpression',
  4011. ConditionalExpression: 'ConditionalExpression',
  4012. ContinueStatement: 'ContinueStatement',
  4013. DoWhileStatement: 'DoWhileStatement',
  4014. DebuggerStatement: 'DebuggerStatement',
  4015. EmptyStatement: 'EmptyStatement',
  4016. ExportAllDeclaration: 'ExportAllDeclaration',
  4017. ExportDefaultDeclaration: 'ExportDefaultDeclaration',
  4018. ExportNamedDeclaration: 'ExportNamedDeclaration',
  4019. ExportSpecifier: 'ExportSpecifier',
  4020. ExpressionStatement: 'ExpressionStatement',
  4021. ForStatement: 'ForStatement',
  4022. ForOfStatement: 'ForOfStatement',
  4023. ForInStatement: 'ForInStatement',
  4024. FunctionDeclaration: 'FunctionDeclaration',
  4025. FunctionExpression: 'FunctionExpression',
  4026. Identifier: 'Identifier',
  4027. IfStatement: 'IfStatement',
  4028. ImportDeclaration: 'ImportDeclaration',
  4029. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  4030. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  4031. ImportSpecifier: 'ImportSpecifier',
  4032. Literal: 'Literal',
  4033. LabeledStatement: 'LabeledStatement',
  4034. LogicalExpression: 'LogicalExpression',
  4035. MemberExpression: 'MemberExpression',
  4036. MetaProperty: 'MetaProperty',
  4037. MethodDefinition: 'MethodDefinition',
  4038. NewExpression: 'NewExpression',
  4039. ObjectExpression: 'ObjectExpression',
  4040. ObjectPattern: 'ObjectPattern',
  4041. Program: 'Program',
  4042. Property: 'Property',
  4043. RestElement: 'RestElement',
  4044. ReturnStatement: 'ReturnStatement',
  4045. SequenceExpression: 'SequenceExpression',
  4046. SpreadElement: 'SpreadElement',
  4047. Super: 'Super',
  4048. SwitchCase: 'SwitchCase',
  4049. SwitchStatement: 'SwitchStatement',
  4050. TaggedTemplateExpression: 'TaggedTemplateExpression',
  4051. TemplateElement: 'TemplateElement',
  4052. TemplateLiteral: 'TemplateLiteral',
  4053. ThisExpression: 'ThisExpression',
  4054. ThrowStatement: 'ThrowStatement',
  4055. TryStatement: 'TryStatement',
  4056. UnaryExpression: 'UnaryExpression',
  4057. UpdateExpression: 'UpdateExpression',
  4058. VariableDeclaration: 'VariableDeclaration',
  4059. VariableDeclarator: 'VariableDeclarator',
  4060. WhileStatement: 'WhileStatement',
  4061. WithStatement: 'WithStatement',
  4062. YieldExpression: 'YieldExpression'
  4063. };
  4064. PlaceHolders = {
  4065. ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
  4066. };
  4067. // Error messages should be identical to V8.
  4068. Messages = {
  4069. UnexpectedToken: 'Unexpected token %0',
  4070. UnexpectedNumber: 'Unexpected number',
  4071. UnexpectedString: 'Unexpected string',
  4072. UnexpectedIdentifier: 'Unexpected identifier',
  4073. UnexpectedReserved: 'Unexpected reserved word',
  4074. UnexpectedTemplate: 'Unexpected quasi %0',
  4075. UnexpectedEOS: 'Unexpected end of input',
  4076. NewlineAfterThrow: 'Illegal newline after throw',
  4077. InvalidRegExp: 'Invalid regular expression',
  4078. UnterminatedRegExp: 'Invalid regular expression: missing /',
  4079. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  4080. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  4081. InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
  4082. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  4083. NoCatchOrFinally: 'Missing catch or finally after try',
  4084. UnknownLabel: 'Undefined label \'%0\'',
  4085. Redeclaration: '%0 \'%1\' has already been declared',
  4086. IllegalContinue: 'Illegal continue statement',
  4087. IllegalBreak: 'Illegal break statement',
  4088. IllegalReturn: 'Illegal return statement',
  4089. StrictModeWith: 'Strict mode code may not include a with statement',
  4090. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  4091. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  4092. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  4093. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  4094. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  4095. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  4096. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  4097. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  4098. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  4099. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  4100. StrictReservedWord: 'Use of future reserved word in strict mode',
  4101. TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
  4102. ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
  4103. DefaultRestParameter: 'Unexpected token =',
  4104. ObjectPatternAsRestParameter: 'Unexpected token {',
  4105. DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
  4106. ConstructorSpecialMethod: 'Class constructor may not be an accessor',
  4107. DuplicateConstructor: 'A class may only have one constructor',
  4108. StaticPrototype: 'Classes may not have static property named prototype',
  4109. MissingFromClause: 'Unexpected token',
  4110. NoAsAfterImportNamespace: 'Unexpected token',
  4111. InvalidModuleSpecifier: 'Unexpected token',
  4112. IllegalImportDeclaration: 'Unexpected token',
  4113. IllegalExportDeclaration: 'Unexpected token',
  4114. DuplicateBinding: 'Duplicate binding %0'
  4115. };
  4116. // See also tools/generate-unicode-regex.js.
  4117. Regex = {
  4118. // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
  4119. NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
  4120. // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
  4121. NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\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-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
  4122. };
  4123. // Ensure the condition is true, otherwise throw an error.
  4124. // This is only to have a better contract semantic, i.e. another safety net
  4125. // to catch a logic error. The condition shall be fulfilled in normal case.
  4126. // Do NOT use this to enforce a certain condition on any user input.
  4127. function assert(condition, message) {
  4128. /* istanbul ignore if */
  4129. if (!condition) {
  4130. throw new Error('ASSERT: ' + message);
  4131. }
  4132. }
  4133. function isDecimalDigit(ch) {
  4134. return (ch >= 0x30 && ch <= 0x39); // 0..9
  4135. }
  4136. function isHexDigit(ch) {
  4137. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  4138. }
  4139. function isOctalDigit(ch) {
  4140. return '01234567'.indexOf(ch) >= 0;
  4141. }
  4142. function octalToDecimal(ch) {
  4143. // \0 is not octal escape sequence
  4144. var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
  4145. if (index < length && isOctalDigit(source[index])) {
  4146. octal = true;
  4147. code = code * 8 + '01234567'.indexOf(source[index++]);
  4148. // 3 digits are only allowed when string starts
  4149. // with 0, 1, 2, 3
  4150. if ('0123'.indexOf(ch) >= 0 &&
  4151. index < length &&
  4152. isOctalDigit(source[index])) {
  4153. code = code * 8 + '01234567'.indexOf(source[index++]);
  4154. }
  4155. }
  4156. return {
  4157. code: code,
  4158. octal: octal
  4159. };
  4160. }
  4161. // ECMA-262 11.2 White Space
  4162. function isWhiteSpace(ch) {
  4163. return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
  4164. (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
  4165. }
  4166. // ECMA-262 11.3 Line Terminators
  4167. function isLineTerminator(ch) {
  4168. return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
  4169. }
  4170. // ECMA-262 11.6 Identifier Names and Identifiers
  4171. function fromCodePoint(cp) {
  4172. return (cp < 0x10000) ? String.fromCharCode(cp) :
  4173. String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
  4174. String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
  4175. }
  4176. function isIdentifierStart(ch) {
  4177. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4178. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4179. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4180. (ch === 0x5C) || // \ (backslash)
  4181. ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
  4182. }
  4183. function isIdentifierPart(ch) {
  4184. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4185. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4186. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4187. (ch >= 0x30 && ch <= 0x39) || // 0..9
  4188. (ch === 0x5C) || // \ (backslash)
  4189. ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
  4190. }
  4191. // ECMA-262 11.6.2.2 Future Reserved Words
  4192. function isFutureReservedWord(id) {
  4193. switch (id) {
  4194. case 'enum':
  4195. case 'export':
  4196. case 'import':
  4197. case 'super':
  4198. return true;
  4199. default:
  4200. return false;
  4201. }
  4202. }
  4203. function isStrictModeReservedWord(id) {
  4204. switch (id) {
  4205. case 'implements':
  4206. case 'interface':
  4207. case 'package':
  4208. case 'private':
  4209. case 'protected':
  4210. case 'public':
  4211. case 'static':
  4212. case 'yield':
  4213. case 'let':
  4214. return true;
  4215. default:
  4216. return false;
  4217. }
  4218. }
  4219. function isRestrictedWord(id) {
  4220. return id === 'eval' || id === 'arguments';
  4221. }
  4222. // ECMA-262 11.6.2.1 Keywords
  4223. function isKeyword(id) {
  4224. switch (id.length) {
  4225. case 2:
  4226. return (id === 'if') || (id === 'in') || (id === 'do');
  4227. case 3:
  4228. return (id === 'var') || (id === 'for') || (id === 'new') ||
  4229. (id === 'try') || (id === 'let');
  4230. case 4:
  4231. return (id === 'this') || (id === 'else') || (id === 'case') ||
  4232. (id === 'void') || (id === 'with') || (id === 'enum');
  4233. case 5:
  4234. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  4235. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  4236. (id === 'class') || (id === 'super');
  4237. case 6:
  4238. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  4239. (id === 'switch') || (id === 'export') || (id === 'import');
  4240. case 7:
  4241. return (id === 'default') || (id === 'finally') || (id === 'extends');
  4242. case 8:
  4243. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  4244. case 10:
  4245. return (id === 'instanceof');
  4246. default:
  4247. return false;
  4248. }
  4249. }
  4250. // ECMA-262 11.4 Comments
  4251. function addComment(type, value, start, end, loc) {
  4252. var comment;
  4253. assert(typeof start === 'number', 'Comment must have valid position');
  4254. state.lastCommentStart = start;
  4255. comment = {
  4256. type: type,
  4257. value: value
  4258. };
  4259. if (extra.range) {
  4260. comment.range = [start, end];
  4261. }
  4262. if (extra.loc) {
  4263. comment.loc = loc;
  4264. }
  4265. extra.comments.push(comment);
  4266. if (extra.attachComment) {
  4267. extra.leadingComments.push(comment);
  4268. extra.trailingComments.push(comment);
  4269. }
  4270. if (extra.tokenize) {
  4271. comment.type = comment.type + 'Comment';
  4272. if (extra.delegate) {
  4273. comment = extra.delegate(comment);
  4274. }
  4275. extra.tokens.push(comment);
  4276. }
  4277. }
  4278. function skipSingleLineComment(offset) {
  4279. var start, loc, ch, comment;
  4280. start = index - offset;
  4281. loc = {
  4282. start: {
  4283. line: lineNumber,
  4284. column: index - lineStart - offset
  4285. }
  4286. };
  4287. while (index < length) {
  4288. ch = source.charCodeAt(index);
  4289. ++index;
  4290. if (isLineTerminator(ch)) {
  4291. hasLineTerminator = true;
  4292. if (extra.comments) {
  4293. comment = source.slice(start + offset, index - 1);
  4294. loc.end = {
  4295. line: lineNumber,
  4296. column: index - lineStart - 1
  4297. };
  4298. addComment('Line', comment, start, index - 1, loc);
  4299. }
  4300. if (ch === 13 && source.charCodeAt(index) === 10) {
  4301. ++index;
  4302. }
  4303. ++lineNumber;
  4304. lineStart = index;
  4305. return;
  4306. }
  4307. }
  4308. if (extra.comments) {
  4309. comment = source.slice(start + offset, index);
  4310. loc.end = {
  4311. line: lineNumber,
  4312. column: index - lineStart
  4313. };
  4314. addComment('Line', comment, start, index, loc);
  4315. }
  4316. }
  4317. function skipMultiLineComment() {
  4318. var start, loc, ch, comment;
  4319. if (extra.comments) {
  4320. start = index - 2;
  4321. loc = {
  4322. start: {
  4323. line: lineNumber,
  4324. column: index - lineStart - 2
  4325. }
  4326. };
  4327. }
  4328. while (index < length) {
  4329. ch = source.charCodeAt(index);
  4330. if (isLineTerminator(ch)) {
  4331. if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
  4332. ++index;
  4333. }
  4334. hasLineTerminator = true;
  4335. ++lineNumber;
  4336. ++index;
  4337. lineStart = index;
  4338. } else if (ch === 0x2A) {
  4339. // Block comment ends with '*/'.
  4340. if (source.charCodeAt(index + 1) === 0x2F) {
  4341. ++index;
  4342. ++index;
  4343. if (extra.comments) {
  4344. comment = source.slice(start + 2, index - 2);
  4345. loc.end = {
  4346. line: lineNumber,
  4347. column: index - lineStart
  4348. };
  4349. addComment('Block', comment, start, index, loc);
  4350. }
  4351. return;
  4352. }
  4353. ++index;
  4354. } else {
  4355. ++index;
  4356. }
  4357. }
  4358. // Ran off the end of the file - the whole thing is a comment
  4359. if (extra.comments) {
  4360. loc.end = {
  4361. line: lineNumber,
  4362. column: index - lineStart
  4363. };
  4364. comment = source.slice(start + 2, index);
  4365. addComment('Block', comment, start, index, loc);
  4366. }
  4367. tolerateUnexpectedToken();
  4368. }
  4369. function skipComment() {
  4370. var ch, start;
  4371. hasLineTerminator = false;
  4372. start = (index === 0);
  4373. while (index < length) {
  4374. ch = source.charCodeAt(index);
  4375. if (isWhiteSpace(ch)) {
  4376. ++index;
  4377. } else if (isLineTerminator(ch)) {
  4378. hasLineTerminator = true;
  4379. ++index;
  4380. if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
  4381. ++index;
  4382. }
  4383. ++lineNumber;
  4384. lineStart = index;
  4385. start = true;
  4386. } else if (ch === 0x2F) { // U+002F is '/'
  4387. ch = source.charCodeAt(index + 1);
  4388. if (ch === 0x2F) {
  4389. ++index;
  4390. ++index;
  4391. skipSingleLineComment(2);
  4392. start = true;
  4393. } else if (ch === 0x2A) { // U+002A is '*'
  4394. ++index;
  4395. ++index;
  4396. skipMultiLineComment();
  4397. } else {
  4398. break;
  4399. }
  4400. } else if (start && ch === 0x2D) { // U+002D is '-'
  4401. // U+003E is '>'
  4402. if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
  4403. // '-->' is a single-line comment
  4404. index += 3;
  4405. skipSingleLineComment(3);
  4406. } else {
  4407. break;
  4408. }
  4409. } else if (ch === 0x3C) { // U+003C is '<'
  4410. if (source.slice(index + 1, index + 4) === '!--') {
  4411. ++index; // `<`
  4412. ++index; // `!`
  4413. ++index; // `-`
  4414. ++index; // `-`
  4415. skipSingleLineComment(4);
  4416. } else {
  4417. break;
  4418. }
  4419. } else {
  4420. break;
  4421. }
  4422. }
  4423. }
  4424. function scanHexEscape(prefix) {
  4425. var i, len, ch, code = 0;
  4426. len = (prefix === 'u') ? 4 : 2;
  4427. for (i = 0; i < len; ++i) {
  4428. if (index < length && isHexDigit(source[index])) {
  4429. ch = source[index++];
  4430. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4431. } else {
  4432. return '';
  4433. }
  4434. }
  4435. return String.fromCharCode(code);
  4436. }
  4437. function scanUnicodeCodePointEscape() {
  4438. var ch, code;
  4439. ch = source[index];
  4440. code = 0;
  4441. // At least, one hex digit is required.
  4442. if (ch === '}') {
  4443. throwUnexpectedToken();
  4444. }
  4445. while (index < length) {
  4446. ch = source[index++];
  4447. if (!isHexDigit(ch)) {
  4448. break;
  4449. }
  4450. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4451. }
  4452. if (code > 0x10FFFF || ch !== '}') {
  4453. throwUnexpectedToken();
  4454. }
  4455. return fromCodePoint(code);
  4456. }
  4457. function codePointAt(i) {
  4458. var cp, first, second;
  4459. cp = source.charCodeAt(i);
  4460. if (cp >= 0xD800 && cp <= 0xDBFF) {
  4461. second = source.charCodeAt(i + 1);
  4462. if (second >= 0xDC00 && second <= 0xDFFF) {
  4463. first = cp;
  4464. cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  4465. }
  4466. }
  4467. return cp;
  4468. }
  4469. function getComplexIdentifier() {
  4470. var cp, ch, id;
  4471. cp = codePointAt(index);
  4472. id = fromCodePoint(cp);
  4473. index += id.length;
  4474. // '\u' (U+005C, U+0075) denotes an escaped character.
  4475. if (cp === 0x5C) {
  4476. if (source.charCodeAt(index) !== 0x75) {
  4477. throwUnexpectedToken();
  4478. }
  4479. ++index;
  4480. if (source[index] === '{') {
  4481. ++index;
  4482. ch = scanUnicodeCodePointEscape();
  4483. } else {
  4484. ch = scanHexEscape('u');
  4485. cp = ch.charCodeAt(0);
  4486. if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
  4487. throwUnexpectedToken();
  4488. }
  4489. }
  4490. id = ch;
  4491. }
  4492. while (index < length) {
  4493. cp = codePointAt(index);
  4494. if (!isIdentifierPart(cp)) {
  4495. break;
  4496. }
  4497. ch = fromCodePoint(cp);
  4498. id += ch;
  4499. index += ch.length;
  4500. // '\u' (U+005C, U+0075) denotes an escaped character.
  4501. if (cp === 0x5C) {
  4502. id = id.substr(0, id.length - 1);
  4503. if (source.charCodeAt(index) !== 0x75) {
  4504. throwUnexpectedToken();
  4505. }
  4506. ++index;
  4507. if (source[index] === '{') {
  4508. ++index;
  4509. ch = scanUnicodeCodePointEscape();
  4510. } else {
  4511. ch = scanHexEscape('u');
  4512. cp = ch.charCodeAt(0);
  4513. if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
  4514. throwUnexpectedToken();
  4515. }
  4516. }
  4517. id += ch;
  4518. }
  4519. }
  4520. return id;
  4521. }
  4522. function getIdentifier() {
  4523. var start, ch;
  4524. start = index++;
  4525. while (index < length) {
  4526. ch = source.charCodeAt(index);
  4527. if (ch === 0x5C) {
  4528. // Blackslash (U+005C) marks Unicode escape sequence.
  4529. index = start;
  4530. return getComplexIdentifier();
  4531. } else if (ch >= 0xD800 && ch < 0xDFFF) {
  4532. // Need to handle surrogate pairs.
  4533. index = start;
  4534. return getComplexIdentifier();
  4535. }
  4536. if (isIdentifierPart(ch)) {
  4537. ++index;
  4538. } else {
  4539. break;
  4540. }
  4541. }
  4542. return source.slice(start, index);
  4543. }
  4544. function scanIdentifier() {
  4545. var start, id, type;
  4546. start = index;
  4547. // Backslash (U+005C) starts an escaped character.
  4548. id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();
  4549. // There is no keyword or literal with only one character.
  4550. // Thus, it must be an identifier.
  4551. if (id.length === 1) {
  4552. type = Token.Identifier;
  4553. } else if (isKeyword(id)) {
  4554. type = Token.Keyword;
  4555. } else if (id === 'null') {
  4556. type = Token.NullLiteral;
  4557. } else if (id === 'true' || id === 'false') {
  4558. type = Token.BooleanLiteral;
  4559. } else {
  4560. type = Token.Identifier;
  4561. }
  4562. return {
  4563. type: type,
  4564. value: id,
  4565. lineNumber: lineNumber,
  4566. lineStart: lineStart,
  4567. start: start,
  4568. end: index
  4569. };
  4570. }
  4571. // ECMA-262 11.7 Punctuators
  4572. function scanPunctuator() {
  4573. var token, str;
  4574. token = {
  4575. type: Token.Punctuator,
  4576. value: '',
  4577. lineNumber: lineNumber,
  4578. lineStart: lineStart,
  4579. start: index,
  4580. end: index
  4581. };
  4582. // Check for most common single-character punctuators.
  4583. str = source[index];
  4584. switch (str) {
  4585. case '(':
  4586. if (extra.tokenize) {
  4587. extra.openParenToken = extra.tokenValues.length;
  4588. }
  4589. ++index;
  4590. break;
  4591. case '{':
  4592. if (extra.tokenize) {
  4593. extra.openCurlyToken = extra.tokenValues.length;
  4594. }
  4595. state.curlyStack.push('{');
  4596. ++index;
  4597. break;
  4598. case '.':
  4599. ++index;
  4600. if (source[index] === '.' && source[index + 1] === '.') {
  4601. // Spread operator: ...
  4602. index += 2;
  4603. str = '...';
  4604. }
  4605. break;
  4606. case '}':
  4607. ++index;
  4608. state.curlyStack.pop();
  4609. break;
  4610. case ')':
  4611. case ';':
  4612. case ',':
  4613. case '[':
  4614. case ']':
  4615. case ':':
  4616. case '?':
  4617. case '~':
  4618. ++index;
  4619. break;
  4620. default:
  4621. // 4-character punctuator.
  4622. str = source.substr(index, 4);
  4623. if (str === '>>>=') {
  4624. index += 4;
  4625. } else {
  4626. // 3-character punctuators.
  4627. str = str.substr(0, 3);
  4628. if (str === '===' || str === '!==' || str === '>>>' ||
  4629. str === '<<=' || str === '>>=') {
  4630. index += 3;
  4631. } else {
  4632. // 2-character punctuators.
  4633. str = str.substr(0, 2);
  4634. if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
  4635. str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
  4636. str === '++' || str === '--' || str === '<<' || str === '>>' ||
  4637. str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
  4638. str === '<=' || str === '>=' || str === '=>') {
  4639. index += 2;
  4640. } else {
  4641. // 1-character punctuators.
  4642. str = source[index];
  4643. if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
  4644. ++index;
  4645. }
  4646. }
  4647. }
  4648. }
  4649. }
  4650. if (index === token.start) {
  4651. throwUnexpectedToken();
  4652. }
  4653. token.end = index;
  4654. token.value = str;
  4655. return token;
  4656. }
  4657. // ECMA-262 11.8.3 Numeric Literals
  4658. function scanHexLiteral(start) {
  4659. var number = '';
  4660. while (index < length) {
  4661. if (!isHexDigit(source[index])) {
  4662. break;
  4663. }
  4664. number += source[index++];
  4665. }
  4666. if (number.length === 0) {
  4667. throwUnexpectedToken();
  4668. }
  4669. if (isIdentifierStart(source.charCodeAt(index))) {
  4670. throwUnexpectedToken();
  4671. }
  4672. return {
  4673. type: Token.NumericLiteral,
  4674. value: parseInt('0x' + number, 16),
  4675. lineNumber: lineNumber,
  4676. lineStart: lineStart,
  4677. start: start,
  4678. end: index
  4679. };
  4680. }
  4681. function scanBinaryLiteral(start) {
  4682. var ch, number;
  4683. number = '';
  4684. while (index < length) {
  4685. ch = source[index];
  4686. if (ch !== '0' && ch !== '1') {
  4687. break;
  4688. }
  4689. number += source[index++];
  4690. }
  4691. if (number.length === 0) {
  4692. // only 0b or 0B
  4693. throwUnexpectedToken();
  4694. }
  4695. if (index < length) {
  4696. ch = source.charCodeAt(index);
  4697. /* istanbul ignore else */
  4698. if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  4699. throwUnexpectedToken();
  4700. }
  4701. }
  4702. return {
  4703. type: Token.NumericLiteral,
  4704. value: parseInt(number, 2),
  4705. lineNumber: lineNumber,
  4706. lineStart: lineStart,
  4707. start: start,
  4708. end: index
  4709. };
  4710. }
  4711. function scanOctalLiteral(prefix, start) {
  4712. var number, octal;
  4713. if (isOctalDigit(prefix)) {
  4714. octal = true;
  4715. number = '0' + source[index++];
  4716. } else {
  4717. octal = false;
  4718. ++index;
  4719. number = '';
  4720. }
  4721. while (index < length) {
  4722. if (!isOctalDigit(source[index])) {
  4723. break;
  4724. }
  4725. number += source[index++];
  4726. }
  4727. if (!octal && number.length === 0) {
  4728. // only 0o or 0O
  4729. throwUnexpectedToken();
  4730. }
  4731. if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
  4732. throwUnexpectedToken();
  4733. }
  4734. return {
  4735. type: Token.NumericLiteral,
  4736. value: parseInt(number, 8),
  4737. octal: octal,
  4738. lineNumber: lineNumber,
  4739. lineStart: lineStart,
  4740. start: start,
  4741. end: index
  4742. };
  4743. }
  4744. function isImplicitOctalLiteral() {
  4745. var i, ch;
  4746. // Implicit octal, unless there is a non-octal digit.
  4747. // (Annex B.1.1 on Numeric Literals)
  4748. for (i = index + 1; i < length; ++i) {
  4749. ch = source[i];
  4750. if (ch === '8' || ch === '9') {
  4751. return false;
  4752. }
  4753. if (!isOctalDigit(ch)) {
  4754. return true;
  4755. }
  4756. }
  4757. return true;
  4758. }
  4759. function scanNumericLiteral() {
  4760. var number, start, ch;
  4761. ch = source[index];
  4762. assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
  4763. 'Numeric literal must start with a decimal digit or a decimal point');
  4764. start = index;
  4765. number = '';
  4766. if (ch !== '.') {
  4767. number = source[index++];
  4768. ch = source[index];
  4769. // Hex number starts with '0x'.
  4770. // Octal number starts with '0'.
  4771. // Octal number in ES6 starts with '0o'.
  4772. // Binary number in ES6 starts with '0b'.
  4773. if (number === '0') {
  4774. if (ch === 'x' || ch === 'X') {
  4775. ++index;
  4776. return scanHexLiteral(start);
  4777. }
  4778. if (ch === 'b' || ch === 'B') {
  4779. ++index;
  4780. return scanBinaryLiteral(start);
  4781. }
  4782. if (ch === 'o' || ch === 'O') {
  4783. return scanOctalLiteral(ch, start);
  4784. }
  4785. if (isOctalDigit(ch)) {
  4786. if (isImplicitOctalLiteral()) {
  4787. return scanOctalLiteral(ch, start);
  4788. }
  4789. }
  4790. }
  4791. while (isDecimalDigit(source.charCodeAt(index))) {
  4792. number += source[index++];
  4793. }
  4794. ch = source[index];
  4795. }
  4796. if (ch === '.') {
  4797. number += source[index++];
  4798. while (isDecimalDigit(source.charCodeAt(index))) {
  4799. number += source[index++];
  4800. }
  4801. ch = source[index];
  4802. }
  4803. if (ch === 'e' || ch === 'E') {
  4804. number += source[index++];
  4805. ch = source[index];
  4806. if (ch === '+' || ch === '-') {
  4807. number += source[index++];
  4808. }
  4809. if (isDecimalDigit(source.charCodeAt(index))) {
  4810. while (isDecimalDigit(source.charCodeAt(index))) {
  4811. number += source[index++];
  4812. }
  4813. } else {
  4814. throwUnexpectedToken();
  4815. }
  4816. }
  4817. if (isIdentifierStart(source.charCodeAt(index))) {
  4818. throwUnexpectedToken();
  4819. }
  4820. return {
  4821. type: Token.NumericLiteral,
  4822. value: parseFloat(number),
  4823. lineNumber: lineNumber,
  4824. lineStart: lineStart,
  4825. start: start,
  4826. end: index
  4827. };
  4828. }
  4829. // ECMA-262 11.8.4 String Literals
  4830. function scanStringLiteral() {
  4831. var str = '', quote, start, ch, unescaped, octToDec, octal = false;
  4832. quote = source[index];
  4833. assert((quote === '\'' || quote === '"'),
  4834. 'String literal must starts with a quote');
  4835. start = index;
  4836. ++index;
  4837. while (index < length) {
  4838. ch = source[index++];
  4839. if (ch === quote) {
  4840. quote = '';
  4841. break;
  4842. } else if (ch === '\\') {
  4843. ch = source[index++];
  4844. if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
  4845. switch (ch) {
  4846. case 'u':
  4847. case 'x':
  4848. if (source[index] === '{') {
  4849. ++index;
  4850. str += scanUnicodeCodePointEscape();
  4851. } else {
  4852. unescaped = scanHexEscape(ch);
  4853. if (!unescaped) {
  4854. throw throwUnexpectedToken();
  4855. }
  4856. str += unescaped;
  4857. }
  4858. break;
  4859. case 'n':
  4860. str += '\n';
  4861. break;
  4862. case 'r':
  4863. str += '\r';
  4864. break;
  4865. case 't':
  4866. str += '\t';
  4867. break;
  4868. case 'b':
  4869. str += '\b';
  4870. break;
  4871. case 'f':
  4872. str += '\f';
  4873. break;
  4874. case 'v':
  4875. str += '\x0B';
  4876. break;
  4877. case '8':
  4878. case '9':
  4879. str += ch;
  4880. tolerateUnexpectedToken();
  4881. break;
  4882. default:
  4883. if (isOctalDigit(ch)) {
  4884. octToDec = octalToDecimal(ch);
  4885. octal = octToDec.octal || octal;
  4886. str += String.fromCharCode(octToDec.code);
  4887. } else {
  4888. str += ch;
  4889. }
  4890. break;
  4891. }
  4892. } else {
  4893. ++lineNumber;
  4894. if (ch === '\r' && source[index] === '\n') {
  4895. ++index;
  4896. }
  4897. lineStart = index;
  4898. }
  4899. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4900. break;
  4901. } else {
  4902. str += ch;
  4903. }
  4904. }
  4905. if (quote !== '') {
  4906. throwUnexpectedToken();
  4907. }
  4908. return {
  4909. type: Token.StringLiteral,
  4910. value: str,
  4911. octal: octal,
  4912. lineNumber: startLineNumber,
  4913. lineStart: startLineStart,
  4914. start: start,
  4915. end: index
  4916. };
  4917. }
  4918. // ECMA-262 11.8.6 Template Literal Lexical Components
  4919. function scanTemplate() {
  4920. var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
  4921. terminated = false;
  4922. tail = false;
  4923. start = index;
  4924. head = (source[index] === '`');
  4925. rawOffset = 2;
  4926. ++index;
  4927. while (index < length) {
  4928. ch = source[index++];
  4929. if (ch === '`') {
  4930. rawOffset = 1;
  4931. tail = true;
  4932. terminated = true;
  4933. break;
  4934. } else if (ch === '$') {
  4935. if (source[index] === '{') {
  4936. state.curlyStack.push('${');
  4937. ++index;
  4938. terminated = true;
  4939. break;
  4940. }
  4941. cooked += ch;
  4942. } else if (ch === '\\') {
  4943. ch = source[index++];
  4944. if (!isLineTerminator(ch.charCodeAt(0))) {
  4945. switch (ch) {
  4946. case 'n':
  4947. cooked += '\n';
  4948. break;
  4949. case 'r':
  4950. cooked += '\r';
  4951. break;
  4952. case 't':
  4953. cooked += '\t';
  4954. break;
  4955. case 'u':
  4956. case 'x':
  4957. if (source[index] === '{') {
  4958. ++index;
  4959. cooked += scanUnicodeCodePointEscape();
  4960. } else {
  4961. restore = index;
  4962. unescaped = scanHexEscape(ch);
  4963. if (unescaped) {
  4964. cooked += unescaped;
  4965. } else {
  4966. index = restore;
  4967. cooked += ch;
  4968. }
  4969. }
  4970. break;
  4971. case 'b':
  4972. cooked += '\b';
  4973. break;
  4974. case 'f':
  4975. cooked += '\f';
  4976. break;
  4977. case 'v':
  4978. cooked += '\v';
  4979. break;
  4980. default:
  4981. if (ch === '0') {
  4982. if (isDecimalDigit(source.charCodeAt(index))) {
  4983. // Illegal: \01 \02 and so on
  4984. throwError(Messages.TemplateOctalLiteral);
  4985. }
  4986. cooked += '\0';
  4987. } else if (isOctalDigit(ch)) {
  4988. // Illegal: \1 \2
  4989. throwError(Messages.TemplateOctalLiteral);
  4990. } else {
  4991. cooked += ch;
  4992. }
  4993. break;
  4994. }
  4995. } else {
  4996. ++lineNumber;
  4997. if (ch === '\r' && source[index] === '\n') {
  4998. ++index;
  4999. }
  5000. lineStart = index;
  5001. }
  5002. } else if (isLineTerminator(ch.charCodeAt(0))) {
  5003. ++lineNumber;
  5004. if (ch === '\r' && source[index] === '\n') {
  5005. ++index;
  5006. }
  5007. lineStart = index;
  5008. cooked += '\n';
  5009. } else {
  5010. cooked += ch;
  5011. }
  5012. }
  5013. if (!terminated) {
  5014. throwUnexpectedToken();
  5015. }
  5016. if (!head) {
  5017. state.curlyStack.pop();
  5018. }
  5019. return {
  5020. type: Token.Template,
  5021. value: {
  5022. cooked: cooked,
  5023. raw: source.slice(start + 1, index - rawOffset)
  5024. },
  5025. head: head,
  5026. tail: tail,
  5027. lineNumber: lineNumber,
  5028. lineStart: lineStart,
  5029. start: start,
  5030. end: index
  5031. };
  5032. }
  5033. // ECMA-262 11.8.5 Regular Expression Literals
  5034. function testRegExp(pattern, flags) {
  5035. // The BMP character to use as a replacement for astral symbols when
  5036. // translating an ES6 "u"-flagged pattern to an ES5-compatible
  5037. // approximation.
  5038. // Note: replacing with '\uFFFF' enables false positives in unlikely
  5039. // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
  5040. // pattern that would not be detected by this substitution.
  5041. var astralSubstitute = '\uFFFF',
  5042. tmp = pattern;
  5043. if (flags.indexOf('u') >= 0) {
  5044. tmp = tmp
  5045. // Replace every Unicode escape sequence with the equivalent
  5046. // BMP character or a constant ASCII code point in the case of
  5047. // astral symbols. (See the above note on `astralSubstitute`
  5048. // for more information.)
  5049. .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
  5050. var codePoint = parseInt($1 || $2, 16);
  5051. if (codePoint > 0x10FFFF) {
  5052. throwUnexpectedToken(null, Messages.InvalidRegExp);
  5053. }
  5054. if (codePoint <= 0xFFFF) {
  5055. return String.fromCharCode(codePoint);
  5056. }
  5057. return astralSubstitute;
  5058. })
  5059. // Replace each paired surrogate with a single ASCII symbol to
  5060. // avoid throwing on regular expressions that are only valid in
  5061. // combination with the "u" flag.
  5062. .replace(
  5063. /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  5064. astralSubstitute
  5065. );
  5066. }
  5067. // First, detect invalid regular expressions.
  5068. try {
  5069. RegExp(tmp);
  5070. } catch (e) {
  5071. throwUnexpectedToken(null, Messages.InvalidRegExp);
  5072. }
  5073. // Return a regular expression object for this pattern-flag pair, or
  5074. // `null` in case the current environment doesn't support the flags it
  5075. // uses.
  5076. try {
  5077. return new RegExp(pattern, flags);
  5078. } catch (exception) {
  5079. return null;
  5080. }
  5081. }
  5082. function scanRegExpBody() {
  5083. var ch, str, classMarker, terminated, body;
  5084. ch = source[index];
  5085. assert(ch === '/', 'Regular expression literal must start with a slash');
  5086. str = source[index++];
  5087. classMarker = false;
  5088. terminated = false;
  5089. while (index < length) {
  5090. ch = source[index++];
  5091. str += ch;
  5092. if (ch === '\\') {
  5093. ch = source[index++];
  5094. // ECMA-262 7.8.5
  5095. if (isLineTerminator(ch.charCodeAt(0))) {
  5096. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  5097. }
  5098. str += ch;
  5099. } else if (isLineTerminator(ch.charCodeAt(0))) {
  5100. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  5101. } else if (classMarker) {
  5102. if (ch === ']') {
  5103. classMarker = false;
  5104. }
  5105. } else {
  5106. if (ch === '/') {
  5107. terminated = true;
  5108. break;
  5109. } else if (ch === '[') {
  5110. classMarker = true;
  5111. }
  5112. }
  5113. }
  5114. if (!terminated) {
  5115. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  5116. }
  5117. // Exclude leading and trailing slash.
  5118. body = str.substr(1, str.length - 2);
  5119. return {
  5120. value: body,
  5121. literal: str
  5122. };
  5123. }
  5124. function scanRegExpFlags() {
  5125. var ch, str, flags, restore;
  5126. str = '';
  5127. flags = '';
  5128. while (index < length) {
  5129. ch = source[index];
  5130. if (!isIdentifierPart(ch.charCodeAt(0))) {
  5131. break;
  5132. }
  5133. ++index;
  5134. if (ch === '\\' && index < length) {
  5135. ch = source[index];
  5136. if (ch === 'u') {
  5137. ++index;
  5138. restore = index;
  5139. ch = scanHexEscape('u');
  5140. if (ch) {
  5141. flags += ch;
  5142. for (str += '\\u'; restore < index; ++restore) {
  5143. str += source[restore];
  5144. }
  5145. } else {
  5146. index = restore;
  5147. flags += 'u';
  5148. str += '\\u';
  5149. }
  5150. tolerateUnexpectedToken();
  5151. } else {
  5152. str += '\\';
  5153. tolerateUnexpectedToken();
  5154. }
  5155. } else {
  5156. flags += ch;
  5157. str += ch;
  5158. }
  5159. }
  5160. return {
  5161. value: flags,
  5162. literal: str
  5163. };
  5164. }
  5165. function scanRegExp() {
  5166. var start, body, flags, value;
  5167. scanning = true;
  5168. lookahead = null;
  5169. skipComment();
  5170. start = index;
  5171. body = scanRegExpBody();
  5172. flags = scanRegExpFlags();
  5173. value = testRegExp(body.value, flags.value);
  5174. scanning = false;
  5175. if (extra.tokenize) {
  5176. return {
  5177. type: Token.RegularExpression,
  5178. value: value,
  5179. regex: {
  5180. pattern: body.value,
  5181. flags: flags.value
  5182. },
  5183. lineNumber: lineNumber,
  5184. lineStart: lineStart,
  5185. start: start,
  5186. end: index
  5187. };
  5188. }
  5189. return {
  5190. literal: body.literal + flags.literal,
  5191. value: value,
  5192. regex: {
  5193. pattern: body.value,
  5194. flags: flags.value
  5195. },
  5196. start: start,
  5197. end: index
  5198. };
  5199. }
  5200. function collectRegex() {
  5201. var pos, loc, regex, token;
  5202. skipComment();
  5203. pos = index;
  5204. loc = {
  5205. start: {
  5206. line: lineNumber,
  5207. column: index - lineStart
  5208. }
  5209. };
  5210. regex = scanRegExp();
  5211. loc.end = {
  5212. line: lineNumber,
  5213. column: index - lineStart
  5214. };
  5215. /* istanbul ignore next */
  5216. if (!extra.tokenize) {
  5217. // Pop the previous token, which is likely '/' or '/='
  5218. if (extra.tokens.length > 0) {
  5219. token = extra.tokens[extra.tokens.length - 1];
  5220. if (token.range[0] === pos && token.type === 'Punctuator') {
  5221. if (token.value === '/' || token.value === '/=') {
  5222. extra.tokens.pop();
  5223. }
  5224. }
  5225. }
  5226. extra.tokens.push({
  5227. type: 'RegularExpression',
  5228. value: regex.literal,
  5229. regex: regex.regex,
  5230. range: [pos, index],
  5231. loc: loc
  5232. });
  5233. }
  5234. return regex;
  5235. }
  5236. function isIdentifierName(token) {
  5237. return token.type === Token.Identifier ||
  5238. token.type === Token.Keyword ||
  5239. token.type === Token.BooleanLiteral ||
  5240. token.type === Token.NullLiteral;
  5241. }
  5242. // Using the following algorithm:
  5243. // https://github.com/mozilla/sweet.js/wiki/design
  5244. function advanceSlash() {
  5245. var regex, previous, check;
  5246. function testKeyword(value) {
  5247. return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
  5248. }
  5249. previous = extra.tokenValues[extra.tokens.length - 1];
  5250. regex = (previous !== null);
  5251. switch (previous) {
  5252. case 'this':
  5253. case ']':
  5254. regex = false;
  5255. break;
  5256. case ')':
  5257. check = extra.tokenValues[extra.openParenToken - 1];
  5258. regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
  5259. break;
  5260. case '}':
  5261. // Dividing a function by anything makes little sense,
  5262. // but we have to check for that.
  5263. regex = false;
  5264. if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
  5265. // Anonymous function, e.g. function(){} /42
  5266. check = extra.tokenValues[extra.openCurlyToken - 4];
  5267. regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
  5268. } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
  5269. // Named function, e.g. function f(){} /42/
  5270. check = extra.tokenValues[extra.openCurlyToken - 5];
  5271. regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
  5272. }
  5273. }
  5274. return regex ? collectRegex() : scanPunctuator();
  5275. }
  5276. function advance() {
  5277. var cp, token;
  5278. if (index >= length) {
  5279. return {
  5280. type: Token.EOF,
  5281. lineNumber: lineNumber,
  5282. lineStart: lineStart,
  5283. start: index,
  5284. end: index
  5285. };
  5286. }
  5287. cp = source.charCodeAt(index);
  5288. if (isIdentifierStart(cp)) {
  5289. token = scanIdentifier();
  5290. if (strict && isStrictModeReservedWord(token.value)) {
  5291. token.type = Token.Keyword;
  5292. }
  5293. return token;
  5294. }
  5295. // Very common: ( and ) and ;
  5296. if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
  5297. return scanPunctuator();
  5298. }
  5299. // String literal starts with single quote (U+0027) or double quote (U+0022).
  5300. if (cp === 0x27 || cp === 0x22) {
  5301. return scanStringLiteral();
  5302. }
  5303. // Dot (.) U+002E can also start a floating-point number, hence the need
  5304. // to check the next character.
  5305. if (cp === 0x2E) {
  5306. if (isDecimalDigit(source.charCodeAt(index + 1))) {
  5307. return scanNumericLiteral();
  5308. }
  5309. return scanPunctuator();
  5310. }
  5311. if (isDecimalDigit(cp)) {
  5312. return scanNumericLiteral();
  5313. }
  5314. // Slash (/) U+002F can also start a regex.
  5315. if (extra.tokenize && cp === 0x2F) {
  5316. return advanceSlash();
  5317. }
  5318. // Template literals start with ` (U+0060) for template head
  5319. // or } (U+007D) for template middle or template tail.
  5320. if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
  5321. return scanTemplate();
  5322. }
  5323. // Possible identifier start in a surrogate pair.
  5324. if (cp >= 0xD800 && cp < 0xDFFF) {
  5325. cp = codePointAt(index);
  5326. if (isIdentifierStart(cp)) {
  5327. return scanIdentifier();
  5328. }
  5329. }
  5330. return scanPunctuator();
  5331. }
  5332. function collectToken() {
  5333. var loc, token, value, entry;
  5334. loc = {
  5335. start: {
  5336. line: lineNumber,
  5337. column: index - lineStart
  5338. }
  5339. };
  5340. token = advance();
  5341. loc.end = {
  5342. line: lineNumber,
  5343. column: index - lineStart
  5344. };
  5345. if (token.type !== Token.EOF) {
  5346. value = source.slice(token.start, token.end);
  5347. entry = {
  5348. type: TokenName[token.type],
  5349. value: value,
  5350. range: [token.start, token.end],
  5351. loc: loc
  5352. };
  5353. if (token.regex) {
  5354. entry.regex = {
  5355. pattern: token.regex.pattern,
  5356. flags: token.regex.flags
  5357. };
  5358. }
  5359. if (extra.tokenValues) {
  5360. extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
  5361. }
  5362. if (extra.tokenize) {
  5363. if (!extra.range) {
  5364. delete entry.range;
  5365. }
  5366. if (!extra.loc) {
  5367. delete entry.loc;
  5368. }
  5369. if (extra.delegate) {
  5370. entry = extra.delegate(entry);
  5371. }
  5372. }
  5373. extra.tokens.push(entry);
  5374. }
  5375. return token;
  5376. }
  5377. function lex() {
  5378. var token;
  5379. scanning = true;
  5380. lastIndex = index;
  5381. lastLineNumber = lineNumber;
  5382. lastLineStart = lineStart;
  5383. skipComment();
  5384. token = lookahead;
  5385. startIndex = index;
  5386. startLineNumber = lineNumber;
  5387. startLineStart = lineStart;
  5388. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5389. scanning = false;
  5390. return token;
  5391. }
  5392. function peek() {
  5393. scanning = true;
  5394. skipComment();
  5395. lastIndex = index;
  5396. lastLineNumber = lineNumber;
  5397. lastLineStart = lineStart;
  5398. startIndex = index;
  5399. startLineNumber = lineNumber;
  5400. startLineStart = lineStart;
  5401. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5402. scanning = false;
  5403. }
  5404. function Position() {
  5405. this.line = startLineNumber;
  5406. this.column = startIndex - startLineStart;
  5407. }
  5408. function SourceLocation() {
  5409. this.start = new Position();
  5410. this.end = null;
  5411. }
  5412. function WrappingSourceLocation(startToken) {
  5413. this.start = {
  5414. line: startToken.lineNumber,
  5415. column: startToken.start - startToken.lineStart
  5416. };
  5417. this.end = null;
  5418. }
  5419. function Node() {
  5420. if (extra.range) {
  5421. this.range = [startIndex, 0];
  5422. }
  5423. if (extra.loc) {
  5424. this.loc = new SourceLocation();
  5425. }
  5426. }
  5427. function WrappingNode(startToken) {
  5428. if (extra.range) {
  5429. this.range = [startToken.start, 0];
  5430. }
  5431. if (extra.loc) {
  5432. this.loc = new WrappingSourceLocation(startToken);
  5433. }
  5434. }
  5435. WrappingNode.prototype = Node.prototype = {
  5436. processComment: function () {
  5437. var lastChild,
  5438. innerComments,
  5439. leadingComments,
  5440. trailingComments,
  5441. bottomRight = extra.bottomRightStack,
  5442. i,
  5443. comment,
  5444. last = bottomRight[bottomRight.length - 1];
  5445. if (this.type === Syntax.Program) {
  5446. if (this.body.length > 0) {
  5447. return;
  5448. }
  5449. }
  5450. /**
  5451. * patch innnerComments for properties empty block
  5452. * `function a() {/** comments **\/}`
  5453. */
  5454. if (this.type === Syntax.BlockStatement && this.body.length === 0) {
  5455. innerComments = [];
  5456. for (i = extra.leadingComments.length - 1; i >= 0; --i) {
  5457. comment = extra.leadingComments[i];
  5458. if (this.range[1] >= comment.range[1]) {
  5459. innerComments.unshift(comment);
  5460. extra.leadingComments.splice(i, 1);
  5461. extra.trailingComments.splice(i, 1);
  5462. }
  5463. }
  5464. if (innerComments.length) {
  5465. this.innerComments = innerComments;
  5466. //bottomRight.push(this);
  5467. return;
  5468. }
  5469. }
  5470. if (extra.trailingComments.length > 0) {
  5471. trailingComments = [];
  5472. for (i = extra.trailingComments.length - 1; i >= 0; --i) {
  5473. comment = extra.trailingComments[i];
  5474. if (comment.range[0] >= this.range[1]) {
  5475. trailingComments.unshift(comment);
  5476. extra.trailingComments.splice(i, 1);
  5477. }
  5478. }
  5479. extra.trailingComments = [];
  5480. } else {
  5481. if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
  5482. trailingComments = last.trailingComments;
  5483. delete last.trailingComments;
  5484. }
  5485. }
  5486. // Eating the stack.
  5487. while (last && last.range[0] >= this.range[0]) {
  5488. lastChild = bottomRight.pop();
  5489. last = bottomRight[bottomRight.length - 1];
  5490. }
  5491. if (lastChild) {
  5492. if (lastChild.leadingComments) {
  5493. leadingComments = [];
  5494. for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
  5495. comment = lastChild.leadingComments[i];
  5496. if (comment.range[1] <= this.range[0]) {
  5497. leadingComments.unshift(comment);
  5498. lastChild.leadingComments.splice(i, 1);
  5499. }
  5500. }
  5501. if (!lastChild.leadingComments.length) {
  5502. lastChild.leadingComments = undefined;
  5503. }
  5504. }
  5505. } else if (extra.leadingComments.length > 0) {
  5506. leadingComments = [];
  5507. for (i = extra.leadingComments.length - 1; i >= 0; --i) {
  5508. comment = extra.leadingComments[i];
  5509. if (comment.range[1] <= this.range[0]) {
  5510. leadingComments.unshift(comment);
  5511. extra.leadingComments.splice(i, 1);
  5512. }
  5513. }
  5514. }
  5515. if (leadingComments && leadingComments.length > 0) {
  5516. this.leadingComments = leadingComments;
  5517. }
  5518. if (trailingComments && trailingComments.length > 0) {
  5519. this.trailingComments = trailingComments;
  5520. }
  5521. bottomRight.push(this);
  5522. },
  5523. finish: function () {
  5524. if (extra.range) {
  5525. this.range[1] = lastIndex;
  5526. }
  5527. if (extra.loc) {
  5528. this.loc.end = {
  5529. line: lastLineNumber,
  5530. column: lastIndex - lastLineStart
  5531. };
  5532. if (extra.source) {
  5533. this.loc.source = extra.source;
  5534. }
  5535. }
  5536. if (extra.attachComment) {
  5537. this.processComment();
  5538. }
  5539. },
  5540. finishArrayExpression: function (elements) {
  5541. this.type = Syntax.ArrayExpression;
  5542. this.elements = elements;
  5543. this.finish();
  5544. return this;
  5545. },
  5546. finishArrayPattern: function (elements) {
  5547. this.type = Syntax.ArrayPattern;
  5548. this.elements = elements;
  5549. this.finish();
  5550. return this;
  5551. },
  5552. finishArrowFunctionExpression: function (params, defaults, body, expression) {
  5553. this.type = Syntax.ArrowFunctionExpression;
  5554. this.id = null;
  5555. this.params = params;
  5556. this.defaults = defaults;
  5557. this.body = body;
  5558. this.generator = false;
  5559. this.expression = expression;
  5560. this.finish();
  5561. return this;
  5562. },
  5563. finishAssignmentExpression: function (operator, left, right) {
  5564. this.type = Syntax.AssignmentExpression;
  5565. this.operator = operator;
  5566. this.left = left;
  5567. this.right = right;
  5568. this.finish();
  5569. return this;
  5570. },
  5571. finishAssignmentPattern: function (left, right) {
  5572. this.type = Syntax.AssignmentPattern;
  5573. this.left = left;
  5574. this.right = right;
  5575. this.finish();
  5576. return this;
  5577. },
  5578. finishBinaryExpression: function (operator, left, right) {
  5579. this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
  5580. this.operator = operator;
  5581. this.left = left;
  5582. this.right = right;
  5583. this.finish();
  5584. return this;
  5585. },
  5586. finishBlockStatement: function (body) {
  5587. this.type = Syntax.BlockStatement;
  5588. this.body = body;
  5589. this.finish();
  5590. return this;
  5591. },
  5592. finishBreakStatement: function (label) {
  5593. this.type = Syntax.BreakStatement;
  5594. this.label = label;
  5595. this.finish();
  5596. return this;
  5597. },
  5598. finishCallExpression: function (callee, args) {
  5599. this.type = Syntax.CallExpression;
  5600. this.callee = callee;
  5601. this.arguments = args;
  5602. this.finish();
  5603. return this;
  5604. },
  5605. finishCatchClause: function (param, body) {
  5606. this.type = Syntax.CatchClause;
  5607. this.param = param;
  5608. this.body = body;
  5609. this.finish();
  5610. return this;
  5611. },
  5612. finishClassBody: function (body) {
  5613. this.type = Syntax.ClassBody;
  5614. this.body = body;
  5615. this.finish();
  5616. return this;
  5617. },
  5618. finishClassDeclaration: function (id, superClass, body) {
  5619. this.type = Syntax.ClassDeclaration;
  5620. this.id = id;
  5621. this.superClass = superClass;
  5622. this.body = body;
  5623. this.finish();
  5624. return this;
  5625. },
  5626. finishClassExpression: function (id, superClass, body) {
  5627. this.type = Syntax.ClassExpression;
  5628. this.id = id;
  5629. this.superClass = superClass;
  5630. this.body = body;
  5631. this.finish();
  5632. return this;
  5633. },
  5634. finishConditionalExpression: function (test, consequent, alternate) {
  5635. this.type = Syntax.ConditionalExpression;
  5636. this.test = test;
  5637. this.consequent = consequent;
  5638. this.alternate = alternate;
  5639. this.finish();
  5640. return this;
  5641. },
  5642. finishContinueStatement: function (label) {
  5643. this.type = Syntax.ContinueStatement;
  5644. this.label = label;
  5645. this.finish();
  5646. return this;
  5647. },
  5648. finishDebuggerStatement: function () {
  5649. this.type = Syntax.DebuggerStatement;
  5650. this.finish();
  5651. return this;
  5652. },
  5653. finishDoWhileStatement: function (body, test) {
  5654. this.type = Syntax.DoWhileStatement;
  5655. this.body = body;
  5656. this.test = test;
  5657. this.finish();
  5658. return this;
  5659. },
  5660. finishEmptyStatement: function () {
  5661. this.type = Syntax.EmptyStatement;
  5662. this.finish();
  5663. return this;
  5664. },
  5665. finishExpressionStatement: function (expression) {
  5666. this.type = Syntax.ExpressionStatement;
  5667. this.expression = expression;
  5668. this.finish();
  5669. return this;
  5670. },
  5671. finishForStatement: function (init, test, update, body) {
  5672. this.type = Syntax.ForStatement;
  5673. this.init = init;
  5674. this.test = test;
  5675. this.update = update;
  5676. this.body = body;
  5677. this.finish();
  5678. return this;
  5679. },
  5680. finishForOfStatement: function (left, right, body) {
  5681. this.type = Syntax.ForOfStatement;
  5682. this.left = left;
  5683. this.right = right;
  5684. this.body = body;
  5685. this.finish();
  5686. return this;
  5687. },
  5688. finishForInStatement: function (left, right, body) {
  5689. this.type = Syntax.ForInStatement;
  5690. this.left = left;
  5691. this.right = right;
  5692. this.body = body;
  5693. this.each = false;
  5694. this.finish();
  5695. return this;
  5696. },
  5697. finishFunctionDeclaration: function (id, params, defaults, body, generator) {
  5698. this.type = Syntax.FunctionDeclaration;
  5699. this.id = id;
  5700. this.params = params;
  5701. this.defaults = defaults;
  5702. this.body = body;
  5703. this.generator = generator;
  5704. this.expression = false;
  5705. this.finish();
  5706. return this;
  5707. },
  5708. finishFunctionExpression: function (id, params, defaults, body, generator) {
  5709. this.type = Syntax.FunctionExpression;
  5710. this.id = id;
  5711. this.params = params;
  5712. this.defaults = defaults;
  5713. this.body = body;
  5714. this.generator = generator;
  5715. this.expression = false;
  5716. this.finish();
  5717. return this;
  5718. },
  5719. finishIdentifier: function (name) {
  5720. this.type = Syntax.Identifier;
  5721. this.name = name;
  5722. this.finish();
  5723. return this;
  5724. },
  5725. finishIfStatement: function (test, consequent, alternate) {
  5726. this.type = Syntax.IfStatement;
  5727. this.test = test;
  5728. this.consequent = consequent;
  5729. this.alternate = alternate;
  5730. this.finish();
  5731. return this;
  5732. },
  5733. finishLabeledStatement: function (label, body) {
  5734. this.type = Syntax.LabeledStatement;
  5735. this.label = label;
  5736. this.body = body;
  5737. this.finish();
  5738. return this;
  5739. },
  5740. finishLiteral: function (token) {
  5741. this.type = Syntax.Literal;
  5742. this.value = token.value;
  5743. this.raw = source.slice(token.start, token.end);
  5744. if (token.regex) {
  5745. this.regex = token.regex;
  5746. }
  5747. this.finish();
  5748. return this;
  5749. },
  5750. finishMemberExpression: function (accessor, object, property) {
  5751. this.type = Syntax.MemberExpression;
  5752. this.computed = accessor === '[';
  5753. this.object = object;
  5754. this.property = property;
  5755. this.finish();
  5756. return this;
  5757. },
  5758. finishMetaProperty: function (meta, property) {
  5759. this.type = Syntax.MetaProperty;
  5760. this.meta = meta;
  5761. this.property = property;
  5762. this.finish();
  5763. return this;
  5764. },
  5765. finishNewExpression: function (callee, args) {
  5766. this.type = Syntax.NewExpression;
  5767. this.callee = callee;
  5768. this.arguments = args;
  5769. this.finish();
  5770. return this;
  5771. },
  5772. finishObjectExpression: function (properties) {
  5773. this.type = Syntax.ObjectExpression;
  5774. this.properties = properties;
  5775. this.finish();
  5776. return this;
  5777. },
  5778. finishObjectPattern: function (properties) {
  5779. this.type = Syntax.ObjectPattern;
  5780. this.properties = properties;
  5781. this.finish();
  5782. return this;
  5783. },
  5784. finishPostfixExpression: function (operator, argument) {
  5785. this.type = Syntax.UpdateExpression;
  5786. this.operator = operator;
  5787. this.argument = argument;
  5788. this.prefix = false;
  5789. this.finish();
  5790. return this;
  5791. },
  5792. finishProgram: function (body, sourceType) {
  5793. this.type = Syntax.Program;
  5794. this.body = body;
  5795. this.sourceType = sourceType;
  5796. this.finish();
  5797. return this;
  5798. },
  5799. finishProperty: function (kind, key, computed, value, method, shorthand) {
  5800. this.type = Syntax.Property;
  5801. this.key = key;
  5802. this.computed = computed;
  5803. this.value = value;
  5804. this.kind = kind;
  5805. this.method = method;
  5806. this.shorthand = shorthand;
  5807. this.finish();
  5808. return this;
  5809. },
  5810. finishRestElement: function (argument) {
  5811. this.type = Syntax.RestElement;
  5812. this.argument = argument;
  5813. this.finish();
  5814. return this;
  5815. },
  5816. finishReturnStatement: function (argument) {
  5817. this.type = Syntax.ReturnStatement;
  5818. this.argument = argument;
  5819. this.finish();
  5820. return this;
  5821. },
  5822. finishSequenceExpression: function (expressions) {
  5823. this.type = Syntax.SequenceExpression;
  5824. this.expressions = expressions;
  5825. this.finish();
  5826. return this;
  5827. },
  5828. finishSpreadElement: function (argument) {
  5829. this.type = Syntax.SpreadElement;
  5830. this.argument = argument;
  5831. this.finish();
  5832. return this;
  5833. },
  5834. finishSwitchCase: function (test, consequent) {
  5835. this.type = Syntax.SwitchCase;
  5836. this.test = test;
  5837. this.consequent = consequent;
  5838. this.finish();
  5839. return this;
  5840. },
  5841. finishSuper: function () {
  5842. this.type = Syntax.Super;
  5843. this.finish();
  5844. return this;
  5845. },
  5846. finishSwitchStatement: function (discriminant, cases) {
  5847. this.type = Syntax.SwitchStatement;
  5848. this.discriminant = discriminant;
  5849. this.cases = cases;
  5850. this.finish();
  5851. return this;
  5852. },
  5853. finishTaggedTemplateExpression: function (tag, quasi) {
  5854. this.type = Syntax.TaggedTemplateExpression;
  5855. this.tag = tag;
  5856. this.quasi = quasi;
  5857. this.finish();
  5858. return this;
  5859. },
  5860. finishTemplateElement: function (value, tail) {
  5861. this.type = Syntax.TemplateElement;
  5862. this.value = value;
  5863. this.tail = tail;
  5864. this.finish();
  5865. return this;
  5866. },
  5867. finishTemplateLiteral: function (quasis, expressions) {
  5868. this.type = Syntax.TemplateLiteral;
  5869. this.quasis = quasis;
  5870. this.expressions = expressions;
  5871. this.finish();
  5872. return this;
  5873. },
  5874. finishThisExpression: function () {
  5875. this.type = Syntax.ThisExpression;
  5876. this.finish();
  5877. return this;
  5878. },
  5879. finishThrowStatement: function (argument) {
  5880. this.type = Syntax.ThrowStatement;
  5881. this.argument = argument;
  5882. this.finish();
  5883. return this;
  5884. },
  5885. finishTryStatement: function (block, handler, finalizer) {
  5886. this.type = Syntax.TryStatement;
  5887. this.block = block;
  5888. this.guardedHandlers = [];
  5889. this.handlers = handler ? [handler] : [];
  5890. this.handler = handler;
  5891. this.finalizer = finalizer;
  5892. this.finish();
  5893. return this;
  5894. },
  5895. finishUnaryExpression: function (operator, argument) {
  5896. this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
  5897. this.operator = operator;
  5898. this.argument = argument;
  5899. this.prefix = true;
  5900. this.finish();
  5901. return this;
  5902. },
  5903. finishVariableDeclaration: function (declarations) {
  5904. this.type = Syntax.VariableDeclaration;
  5905. this.declarations = declarations;
  5906. this.kind = 'var';
  5907. this.finish();
  5908. return this;
  5909. },
  5910. finishLexicalDeclaration: function (declarations, kind) {
  5911. this.type = Syntax.VariableDeclaration;
  5912. this.declarations = declarations;
  5913. this.kind = kind;
  5914. this.finish();
  5915. return this;
  5916. },
  5917. finishVariableDeclarator: function (id, init) {
  5918. this.type = Syntax.VariableDeclarator;
  5919. this.id = id;
  5920. this.init = init;
  5921. this.finish();
  5922. return this;
  5923. },
  5924. finishWhileStatement: function (test, body) {
  5925. this.type = Syntax.WhileStatement;
  5926. this.test = test;
  5927. this.body = body;
  5928. this.finish();
  5929. return this;
  5930. },
  5931. finishWithStatement: function (object, body) {
  5932. this.type = Syntax.WithStatement;
  5933. this.object = object;
  5934. this.body = body;
  5935. this.finish();
  5936. return this;
  5937. },
  5938. finishExportSpecifier: function (local, exported) {
  5939. this.type = Syntax.ExportSpecifier;
  5940. this.exported = exported || local;
  5941. this.local = local;
  5942. this.finish();
  5943. return this;
  5944. },
  5945. finishImportDefaultSpecifier: function (local) {
  5946. this.type = Syntax.ImportDefaultSpecifier;
  5947. this.local = local;
  5948. this.finish();
  5949. return this;
  5950. },
  5951. finishImportNamespaceSpecifier: function (local) {
  5952. this.type = Syntax.ImportNamespaceSpecifier;
  5953. this.local = local;
  5954. this.finish();
  5955. return this;
  5956. },
  5957. finishExportNamedDeclaration: function (declaration, specifiers, src) {
  5958. this.type = Syntax.ExportNamedDeclaration;
  5959. this.declaration = declaration;
  5960. this.specifiers = specifiers;
  5961. this.source = src;
  5962. this.finish();
  5963. return this;
  5964. },
  5965. finishExportDefaultDeclaration: function (declaration) {
  5966. this.type = Syntax.ExportDefaultDeclaration;
  5967. this.declaration = declaration;
  5968. this.finish();
  5969. return this;
  5970. },
  5971. finishExportAllDeclaration: function (src) {
  5972. this.type = Syntax.ExportAllDeclaration;
  5973. this.source = src;
  5974. this.finish();
  5975. return this;
  5976. },
  5977. finishImportSpecifier: function (local, imported) {
  5978. this.type = Syntax.ImportSpecifier;
  5979. this.local = local || imported;
  5980. this.imported = imported;
  5981. this.finish();
  5982. return this;
  5983. },
  5984. finishImportDeclaration: function (specifiers, src) {
  5985. this.type = Syntax.ImportDeclaration;
  5986. this.specifiers = specifiers;
  5987. this.source = src;
  5988. this.finish();
  5989. return this;
  5990. },
  5991. finishYieldExpression: function (argument, delegate) {
  5992. this.type = Syntax.YieldExpression;
  5993. this.argument = argument;
  5994. this.delegate = delegate;
  5995. this.finish();
  5996. return this;
  5997. }
  5998. };
  5999. function recordError(error) {
  6000. var e, existing;
  6001. for (e = 0; e < extra.errors.length; e++) {
  6002. existing = extra.errors[e];
  6003. // Prevent duplicated error.
  6004. /* istanbul ignore next */
  6005. if (existing.index === error.index && existing.message === error.message) {
  6006. return;
  6007. }
  6008. }
  6009. extra.errors.push(error);
  6010. }
  6011. function constructError(msg, column) {
  6012. var error = new Error(msg);
  6013. try {
  6014. throw error;
  6015. } catch (base) {
  6016. /* istanbul ignore else */
  6017. if (Object.create && Object.defineProperty) {
  6018. error = Object.create(base);
  6019. Object.defineProperty(error, 'column', { value: column });
  6020. }
  6021. } finally {
  6022. return error;
  6023. }
  6024. }
  6025. function createError(line, pos, description) {
  6026. var msg, column, error;
  6027. msg = 'Line ' + line + ': ' + description;
  6028. column = pos - (scanning ? lineStart : lastLineStart) + 1;
  6029. error = constructError(msg, column);
  6030. error.lineNumber = line;
  6031. error.description = description;
  6032. error.index = pos;
  6033. return error;
  6034. }
  6035. // Throw an exception
  6036. function throwError(messageFormat) {
  6037. var args, msg;
  6038. args = Array.prototype.slice.call(arguments, 1);
  6039. msg = messageFormat.replace(/%(\d)/g,
  6040. function (whole, idx) {
  6041. assert(idx < args.length, 'Message reference must be in range');
  6042. return args[idx];
  6043. }
  6044. );
  6045. throw createError(lastLineNumber, lastIndex, msg);
  6046. }
  6047. function tolerateError(messageFormat) {
  6048. var args, msg, error;
  6049. args = Array.prototype.slice.call(arguments, 1);
  6050. /* istanbul ignore next */
  6051. msg = messageFormat.replace(/%(\d)/g,
  6052. function (whole, idx) {
  6053. assert(idx < args.length, 'Message reference must be in range');
  6054. return args[idx];
  6055. }
  6056. );
  6057. error = createError(lineNumber, lastIndex, msg);
  6058. if (extra.errors) {
  6059. recordError(error);
  6060. } else {
  6061. throw error;
  6062. }
  6063. }
  6064. // Throw an exception because of the token.
  6065. function unexpectedTokenError(token, message) {
  6066. var value, msg = message || Messages.UnexpectedToken;
  6067. if (token) {
  6068. if (!message) {
  6069. msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
  6070. (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
  6071. (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
  6072. (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
  6073. (token.type === Token.Template) ? Messages.UnexpectedTemplate :
  6074. Messages.UnexpectedToken;
  6075. if (token.type === Token.Keyword) {
  6076. if (isFutureReservedWord(token.value)) {
  6077. msg = Messages.UnexpectedReserved;
  6078. } else if (strict && isStrictModeReservedWord(token.value)) {
  6079. msg = Messages.StrictReservedWord;
  6080. }
  6081. }
  6082. }
  6083. value = (token.type === Token.Template) ? token.value.raw : token.value;
  6084. } else {
  6085. value = 'ILLEGAL';
  6086. }
  6087. msg = msg.replace('%0', value);
  6088. return (token && typeof token.lineNumber === 'number') ?
  6089. createError(token.lineNumber, token.start, msg) :
  6090. createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
  6091. }
  6092. function throwUnexpectedToken(token, message) {
  6093. throw unexpectedTokenError(token, message);
  6094. }
  6095. function tolerateUnexpectedToken(token, message) {
  6096. var error = unexpectedTokenError(token, message);
  6097. if (extra.errors) {
  6098. recordError(error);
  6099. } else {
  6100. throw error;
  6101. }
  6102. }
  6103. // Expect the next token to match the specified punctuator.
  6104. // If not, an exception will be thrown.
  6105. function expect(value) {
  6106. var token = lex();
  6107. if (token.type !== Token.Punctuator || token.value !== value) {
  6108. throwUnexpectedToken(token);
  6109. }
  6110. }
  6111. /**
  6112. * @name expectCommaSeparator
  6113. * @description Quietly expect a comma when in tolerant mode, otherwise delegates
  6114. * to <code>expect(value)</code>
  6115. * @since 2.0
  6116. */
  6117. function expectCommaSeparator() {
  6118. var token;
  6119. if (extra.errors) {
  6120. token = lookahead;
  6121. if (token.type === Token.Punctuator && token.value === ',') {
  6122. lex();
  6123. } else if (token.type === Token.Punctuator && token.value === ';') {
  6124. lex();
  6125. tolerateUnexpectedToken(token);
  6126. } else {
  6127. tolerateUnexpectedToken(token, Messages.UnexpectedToken);
  6128. }
  6129. } else {
  6130. expect(',');
  6131. }
  6132. }
  6133. // Expect the next token to match the specified keyword.
  6134. // If not, an exception will be thrown.
  6135. function expectKeyword(keyword) {
  6136. var token = lex();
  6137. if (token.type !== Token.Keyword || token.value !== keyword) {
  6138. throwUnexpectedToken(token);
  6139. }
  6140. }
  6141. // Return true if the next token matches the specified punctuator.
  6142. function match(value) {
  6143. return lookahead.type === Token.Punctuator && lookahead.value === value;
  6144. }
  6145. // Return true if the next token matches the specified keyword
  6146. function matchKeyword(keyword) {
  6147. return lookahead.type === Token.Keyword && lookahead.value === keyword;
  6148. }
  6149. // Return true if the next token matches the specified contextual keyword
  6150. // (where an identifier is sometimes a keyword depending on the context)
  6151. function matchContextualKeyword(keyword) {
  6152. return lookahead.type === Token.Identifier && lookahead.value === keyword;
  6153. }
  6154. // Return true if the next token is an assignment operator
  6155. function matchAssign() {
  6156. var op;
  6157. if (lookahead.type !== Token.Punctuator) {
  6158. return false;
  6159. }
  6160. op = lookahead.value;
  6161. return op === '=' ||
  6162. op === '*=' ||
  6163. op === '/=' ||
  6164. op === '%=' ||
  6165. op === '+=' ||
  6166. op === '-=' ||
  6167. op === '<<=' ||
  6168. op === '>>=' ||
  6169. op === '>>>=' ||
  6170. op === '&=' ||
  6171. op === '^=' ||
  6172. op === '|=';
  6173. }
  6174. function consumeSemicolon() {
  6175. // Catch the very common case first: immediately a semicolon (U+003B).
  6176. if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
  6177. lex();
  6178. return;
  6179. }
  6180. if (hasLineTerminator) {
  6181. return;
  6182. }
  6183. // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
  6184. lastIndex = startIndex;
  6185. lastLineNumber = startLineNumber;
  6186. lastLineStart = startLineStart;
  6187. if (lookahead.type !== Token.EOF && !match('}')) {
  6188. throwUnexpectedToken(lookahead);
  6189. }
  6190. }
  6191. // Cover grammar support.
  6192. //
  6193. // When an assignment expression position starts with an left parenthesis, the determination of the type
  6194. // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
  6195. // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
  6196. //
  6197. // There are three productions that can be parsed in a parentheses pair that needs to be determined
  6198. // after the outermost pair is closed. They are:
  6199. //
  6200. // 1. AssignmentExpression
  6201. // 2. BindingElements
  6202. // 3. AssignmentTargets
  6203. //
  6204. // In order to avoid exponential backtracking, we use two flags to denote if the production can be
  6205. // binding element or assignment target.
  6206. //
  6207. // The three productions have the relationship:
  6208. //
  6209. // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
  6210. //
  6211. // with a single exception that CoverInitializedName when used directly in an Expression, generates
  6212. // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
  6213. // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
  6214. //
  6215. // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
  6216. // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
  6217. // the CoverInitializedName check is conducted.
  6218. //
  6219. // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
  6220. // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
  6221. // pattern. The CoverInitializedName check is deferred.
  6222. function isolateCoverGrammar(parser) {
  6223. var oldIsBindingElement = isBindingElement,
  6224. oldIsAssignmentTarget = isAssignmentTarget,
  6225. oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
  6226. result;
  6227. isBindingElement = true;
  6228. isAssignmentTarget = true;
  6229. firstCoverInitializedNameError = null;
  6230. result = parser();
  6231. if (firstCoverInitializedNameError !== null) {
  6232. throwUnexpectedToken(firstCoverInitializedNameError);
  6233. }
  6234. isBindingElement = oldIsBindingElement;
  6235. isAssignmentTarget = oldIsAssignmentTarget;
  6236. firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
  6237. return result;
  6238. }
  6239. function inheritCoverGrammar(parser) {
  6240. var oldIsBindingElement = isBindingElement,
  6241. oldIsAssignmentTarget = isAssignmentTarget,
  6242. oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
  6243. result;
  6244. isBindingElement = true;
  6245. isAssignmentTarget = true;
  6246. firstCoverInitializedNameError = null;
  6247. result = parser();
  6248. isBindingElement = isBindingElement && oldIsBindingElement;
  6249. isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
  6250. firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
  6251. return result;
  6252. }
  6253. // ECMA-262 13.3.3 Destructuring Binding Patterns
  6254. function parseArrayPattern(params, kind) {
  6255. var node = new Node(), elements = [], rest, restNode;
  6256. expect('[');
  6257. while (!match(']')) {
  6258. if (match(',')) {
  6259. lex();
  6260. elements.push(null);
  6261. } else {
  6262. if (match('...')) {
  6263. restNode = new Node();
  6264. lex();
  6265. params.push(lookahead);
  6266. rest = parseVariableIdentifier(kind);
  6267. elements.push(restNode.finishRestElement(rest));
  6268. break;
  6269. } else {
  6270. elements.push(parsePatternWithDefault(params, kind));
  6271. }
  6272. if (!match(']')) {
  6273. expect(',');
  6274. }
  6275. }
  6276. }
  6277. expect(']');
  6278. return node.finishArrayPattern(elements);
  6279. }
  6280. function parsePropertyPattern(params, kind) {
  6281. var node = new Node(), key, keyToken, computed = match('['), init;
  6282. if (lookahead.type === Token.Identifier) {
  6283. keyToken = lookahead;
  6284. key = parseVariableIdentifier();
  6285. if (match('=')) {
  6286. params.push(keyToken);
  6287. lex();
  6288. init = parseAssignmentExpression();
  6289. return node.finishProperty(
  6290. 'init', key, false,
  6291. new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, false);
  6292. } else if (!match(':')) {
  6293. params.push(keyToken);
  6294. return node.finishProperty('init', key, false, key, false, true);
  6295. }
  6296. } else {
  6297. key = parseObjectPropertyKey();
  6298. }
  6299. expect(':');
  6300. init = parsePatternWithDefault(params, kind);
  6301. return node.finishProperty('init', key, computed, init, false, false);
  6302. }
  6303. function parseObjectPattern(params, kind) {
  6304. var node = new Node(), properties = [];
  6305. expect('{');
  6306. while (!match('}')) {
  6307. properties.push(parsePropertyPattern(params, kind));
  6308. if (!match('}')) {
  6309. expect(',');
  6310. }
  6311. }
  6312. lex();
  6313. return node.finishObjectPattern(properties);
  6314. }
  6315. function parsePattern(params, kind) {
  6316. if (match('[')) {
  6317. return parseArrayPattern(params, kind);
  6318. } else if (match('{')) {
  6319. return parseObjectPattern(params, kind);
  6320. } else if (matchKeyword('let')) {
  6321. if (kind === 'const' || kind === 'let') {
  6322. tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
  6323. }
  6324. }
  6325. params.push(lookahead);
  6326. return parseVariableIdentifier(kind);
  6327. }
  6328. function parsePatternWithDefault(params, kind) {
  6329. var startToken = lookahead, pattern, previousAllowYield, right;
  6330. pattern = parsePattern(params, kind);
  6331. if (match('=')) {
  6332. lex();
  6333. previousAllowYield = state.allowYield;
  6334. state.allowYield = true;
  6335. right = isolateCoverGrammar(parseAssignmentExpression);
  6336. state.allowYield = previousAllowYield;
  6337. pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
  6338. }
  6339. return pattern;
  6340. }
  6341. // ECMA-262 12.2.5 Array Initializer
  6342. function parseArrayInitializer() {
  6343. var elements = [], node = new Node(), restSpread;
  6344. expect('[');
  6345. while (!match(']')) {
  6346. if (match(',')) {
  6347. lex();
  6348. elements.push(null);
  6349. } else if (match('...')) {
  6350. restSpread = new Node();
  6351. lex();
  6352. restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
  6353. if (!match(']')) {
  6354. isAssignmentTarget = isBindingElement = false;
  6355. expect(',');
  6356. }
  6357. elements.push(restSpread);
  6358. } else {
  6359. elements.push(inheritCoverGrammar(parseAssignmentExpression));
  6360. if (!match(']')) {
  6361. expect(',');
  6362. }
  6363. }
  6364. }
  6365. lex();
  6366. return node.finishArrayExpression(elements);
  6367. }
  6368. // ECMA-262 12.2.6 Object Initializer
  6369. function parsePropertyFunction(node, paramInfo, isGenerator) {
  6370. var previousStrict, body;
  6371. isAssignmentTarget = isBindingElement = false;
  6372. previousStrict = strict;
  6373. body = isolateCoverGrammar(parseFunctionSourceElements);
  6374. if (strict && paramInfo.firstRestricted) {
  6375. tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
  6376. }
  6377. if (strict && paramInfo.stricted) {
  6378. tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
  6379. }
  6380. strict = previousStrict;
  6381. return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
  6382. }
  6383. function parsePropertyMethodFunction() {
  6384. var params, method, node = new Node(),
  6385. previousAllowYield = state.allowYield;
  6386. state.allowYield = false;
  6387. params = parseParams();
  6388. state.allowYield = previousAllowYield;
  6389. state.allowYield = false;
  6390. method = parsePropertyFunction(node, params, false);
  6391. state.allowYield = previousAllowYield;
  6392. return method;
  6393. }
  6394. function parseObjectPropertyKey() {
  6395. var token, node = new Node(), expr;
  6396. token = lex();
  6397. // Note: This function is called only from parseObjectProperty(), where
  6398. // EOF and Punctuator tokens are already filtered out.
  6399. switch (token.type) {
  6400. case Token.StringLiteral:
  6401. case Token.NumericLiteral:
  6402. if (strict && token.octal) {
  6403. tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
  6404. }
  6405. return node.finishLiteral(token);
  6406. case Token.Identifier:
  6407. case Token.BooleanLiteral:
  6408. case Token.NullLiteral:
  6409. case Token.Keyword:
  6410. return node.finishIdentifier(token.value);
  6411. case Token.Punctuator:
  6412. if (token.value === '[') {
  6413. expr = isolateCoverGrammar(parseAssignmentExpression);
  6414. expect(']');
  6415. return expr;
  6416. }
  6417. break;
  6418. }
  6419. throwUnexpectedToken(token);
  6420. }
  6421. function lookaheadPropertyName() {
  6422. switch (lookahead.type) {
  6423. case Token.Identifier:
  6424. case Token.StringLiteral:
  6425. case Token.BooleanLiteral:
  6426. case Token.NullLiteral:
  6427. case Token.NumericLiteral:
  6428. case Token.Keyword:
  6429. return true;
  6430. case Token.Punctuator:
  6431. return lookahead.value === '[';
  6432. }
  6433. return false;
  6434. }
  6435. // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
  6436. // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
  6437. // This can only be determined after we consumed up to the left parentheses.
  6438. //
  6439. // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
  6440. // is responsible to visit other options.
  6441. function tryParseMethodDefinition(token, key, computed, node) {
  6442. var value, options, methodNode, params,
  6443. previousAllowYield = state.allowYield;
  6444. if (token.type === Token.Identifier) {
  6445. // check for `get` and `set`;
  6446. if (token.value === 'get' && lookaheadPropertyName()) {
  6447. computed = match('[');
  6448. key = parseObjectPropertyKey();
  6449. methodNode = new Node();
  6450. expect('(');
  6451. expect(')');
  6452. state.allowYield = false;
  6453. value = parsePropertyFunction(methodNode, {
  6454. params: [],
  6455. defaults: [],
  6456. stricted: null,
  6457. firstRestricted: null,
  6458. message: null
  6459. }, false);
  6460. state.allowYield = previousAllowYield;
  6461. return node.finishProperty('get', key, computed, value, false, false);
  6462. } else if (token.value === 'set' && lookaheadPropertyName()) {
  6463. computed = match('[');
  6464. key = parseObjectPropertyKey();
  6465. methodNode = new Node();
  6466. expect('(');
  6467. options = {
  6468. params: [],
  6469. defaultCount: 0,
  6470. defaults: [],
  6471. firstRestricted: null,
  6472. paramSet: {}
  6473. };
  6474. if (match(')')) {
  6475. tolerateUnexpectedToken(lookahead);
  6476. } else {
  6477. state.allowYield = false;
  6478. parseParam(options);
  6479. state.allowYield = previousAllowYield;
  6480. if (options.defaultCount === 0) {
  6481. options.defaults = [];
  6482. }
  6483. }
  6484. expect(')');
  6485. state.allowYield = false;
  6486. value = parsePropertyFunction(methodNode, options, false);
  6487. state.allowYield = previousAllowYield;
  6488. return node.finishProperty('set', key, computed, value, false, false);
  6489. }
  6490. } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
  6491. computed = match('[');
  6492. key = parseObjectPropertyKey();
  6493. methodNode = new Node();
  6494. state.allowYield = true;
  6495. params = parseParams();
  6496. state.allowYield = previousAllowYield;
  6497. state.allowYield = false;
  6498. value = parsePropertyFunction(methodNode, params, true);
  6499. state.allowYield = previousAllowYield;
  6500. return node.finishProperty('init', key, computed, value, true, false);
  6501. }
  6502. if (key && match('(')) {
  6503. value = parsePropertyMethodFunction();
  6504. return node.finishProperty('init', key, computed, value, true, false);
  6505. }
  6506. // Not a MethodDefinition.
  6507. return null;
  6508. }
  6509. function parseObjectProperty(hasProto) {
  6510. var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;
  6511. computed = match('[');
  6512. if (match('*')) {
  6513. lex();
  6514. } else {
  6515. key = parseObjectPropertyKey();
  6516. }
  6517. maybeMethod = tryParseMethodDefinition(token, key, computed, node);
  6518. if (maybeMethod) {
  6519. return maybeMethod;
  6520. }
  6521. if (!key) {
  6522. throwUnexpectedToken(lookahead);
  6523. }
  6524. // Check for duplicated __proto__
  6525. if (!computed) {
  6526. proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
  6527. (key.type === Syntax.Literal && key.value === '__proto__');
  6528. if (hasProto.value && proto) {
  6529. tolerateError(Messages.DuplicateProtoProperty);
  6530. }
  6531. hasProto.value |= proto;
  6532. }
  6533. if (match(':')) {
  6534. lex();
  6535. value = inheritCoverGrammar(parseAssignmentExpression);
  6536. return node.finishProperty('init', key, computed, value, false, false);
  6537. }
  6538. if (token.type === Token.Identifier) {
  6539. if (match('=')) {
  6540. firstCoverInitializedNameError = lookahead;
  6541. lex();
  6542. value = isolateCoverGrammar(parseAssignmentExpression);
  6543. return node.finishProperty('init', key, computed,
  6544. new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
  6545. }
  6546. return node.finishProperty('init', key, computed, key, false, true);
  6547. }
  6548. throwUnexpectedToken(lookahead);
  6549. }
  6550. function parseObjectInitializer() {
  6551. var properties = [], hasProto = {value: false}, node = new Node();
  6552. expect('{');
  6553. while (!match('}')) {
  6554. properties.push(parseObjectProperty(hasProto));
  6555. if (!match('}')) {
  6556. expectCommaSeparator();
  6557. }
  6558. }
  6559. expect('}');
  6560. return node.finishObjectExpression(properties);
  6561. }
  6562. function reinterpretExpressionAsPattern(expr) {
  6563. var i;
  6564. switch (expr.type) {
  6565. case Syntax.Identifier:
  6566. case Syntax.MemberExpression:
  6567. case Syntax.RestElement:
  6568. case Syntax.AssignmentPattern:
  6569. break;
  6570. case Syntax.SpreadElement:
  6571. expr.type = Syntax.RestElement;
  6572. reinterpretExpressionAsPattern(expr.argument);
  6573. break;
  6574. case Syntax.ArrayExpression:
  6575. expr.type = Syntax.ArrayPattern;
  6576. for (i = 0; i < expr.elements.length; i++) {
  6577. if (expr.elements[i] !== null) {
  6578. reinterpretExpressionAsPattern(expr.elements[i]);
  6579. }
  6580. }
  6581. break;
  6582. case Syntax.ObjectExpression:
  6583. expr.type = Syntax.ObjectPattern;
  6584. for (i = 0; i < expr.properties.length; i++) {
  6585. reinterpretExpressionAsPattern(expr.properties[i].value);
  6586. }
  6587. break;
  6588. case Syntax.AssignmentExpression:
  6589. expr.type = Syntax.AssignmentPattern;
  6590. reinterpretExpressionAsPattern(expr.left);
  6591. break;
  6592. default:
  6593. // Allow other node type for tolerant parsing.
  6594. break;
  6595. }
  6596. }
  6597. // ECMA-262 12.2.9 Template Literals
  6598. function parseTemplateElement(option) {
  6599. var node, token;
  6600. if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
  6601. throwUnexpectedToken();
  6602. }
  6603. node = new Node();
  6604. token = lex();
  6605. return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
  6606. }
  6607. function parseTemplateLiteral() {
  6608. var quasi, quasis, expressions, node = new Node();
  6609. quasi = parseTemplateElement({ head: true });
  6610. quasis = [quasi];
  6611. expressions = [];
  6612. while (!quasi.tail) {
  6613. expressions.push(parseExpression());
  6614. quasi = parseTemplateElement({ head: false });
  6615. quasis.push(quasi);
  6616. }
  6617. return node.finishTemplateLiteral(quasis, expressions);
  6618. }
  6619. // ECMA-262 12.2.10 The Grouping Operator
  6620. function parseGroupExpression() {
  6621. var expr, expressions, startToken, i, params = [];
  6622. expect('(');
  6623. if (match(')')) {
  6624. lex();
  6625. if (!match('=>')) {
  6626. expect('=>');
  6627. }
  6628. return {
  6629. type: PlaceHolders.ArrowParameterPlaceHolder,
  6630. params: [],
  6631. rawParams: []
  6632. };
  6633. }
  6634. startToken = lookahead;
  6635. if (match('...')) {
  6636. expr = parseRestElement(params);
  6637. expect(')');
  6638. if (!match('=>')) {
  6639. expect('=>');
  6640. }
  6641. return {
  6642. type: PlaceHolders.ArrowParameterPlaceHolder,
  6643. params: [expr]
  6644. };
  6645. }
  6646. isBindingElement = true;
  6647. expr = inheritCoverGrammar(parseAssignmentExpression);
  6648. if (match(',')) {
  6649. isAssignmentTarget = false;
  6650. expressions = [expr];
  6651. while (startIndex < length) {
  6652. if (!match(',')) {
  6653. break;
  6654. }
  6655. lex();
  6656. if (match('...')) {
  6657. if (!isBindingElement) {
  6658. throwUnexpectedToken(lookahead);
  6659. }
  6660. expressions.push(parseRestElement(params));
  6661. expect(')');
  6662. if (!match('=>')) {
  6663. expect('=>');
  6664. }
  6665. isBindingElement = false;
  6666. for (i = 0; i < expressions.length; i++) {
  6667. reinterpretExpressionAsPattern(expressions[i]);
  6668. }
  6669. return {
  6670. type: PlaceHolders.ArrowParameterPlaceHolder,
  6671. params: expressions
  6672. };
  6673. }
  6674. expressions.push(inheritCoverGrammar(parseAssignmentExpression));
  6675. }
  6676. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  6677. }
  6678. expect(')');
  6679. if (match('=>')) {
  6680. if (expr.type === Syntax.Identifier && expr.name === 'yield') {
  6681. return {
  6682. type: PlaceHolders.ArrowParameterPlaceHolder,
  6683. params: [expr]
  6684. };
  6685. }
  6686. if (!isBindingElement) {
  6687. throwUnexpectedToken(lookahead);
  6688. }
  6689. if (expr.type === Syntax.SequenceExpression) {
  6690. for (i = 0; i < expr.expressions.length; i++) {
  6691. reinterpretExpressionAsPattern(expr.expressions[i]);
  6692. }
  6693. } else {
  6694. reinterpretExpressionAsPattern(expr);
  6695. }
  6696. expr = {
  6697. type: PlaceHolders.ArrowParameterPlaceHolder,
  6698. params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
  6699. };
  6700. }
  6701. isBindingElement = false;
  6702. return expr;
  6703. }
  6704. // ECMA-262 12.2 Primary Expressions
  6705. function parsePrimaryExpression() {
  6706. var type, token, expr, node;
  6707. if (match('(')) {
  6708. isBindingElement = false;
  6709. return inheritCoverGrammar(parseGroupExpression);
  6710. }
  6711. if (match('[')) {
  6712. return inheritCoverGrammar(parseArrayInitializer);
  6713. }
  6714. if (match('{')) {
  6715. return inheritCoverGrammar(parseObjectInitializer);
  6716. }
  6717. type = lookahead.type;
  6718. node = new Node();
  6719. if (type === Token.Identifier) {
  6720. if (state.sourceType === 'module' && lookahead.value === 'await') {
  6721. tolerateUnexpectedToken(lookahead);
  6722. }
  6723. expr = node.finishIdentifier(lex().value);
  6724. } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  6725. isAssignmentTarget = isBindingElement = false;
  6726. if (strict && lookahead.octal) {
  6727. tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
  6728. }
  6729. expr = node.finishLiteral(lex());
  6730. } else if (type === Token.Keyword) {
  6731. if (!strict && state.allowYield && matchKeyword('yield')) {
  6732. return parseNonComputedProperty();
  6733. }
  6734. isAssignmentTarget = isBindingElement = false;
  6735. if (matchKeyword('function')) {
  6736. return parseFunctionExpression();
  6737. }
  6738. if (matchKeyword('this')) {
  6739. lex();
  6740. return node.finishThisExpression();
  6741. }
  6742. if (matchKeyword('class')) {
  6743. return parseClassExpression();
  6744. }
  6745. if (!strict && matchKeyword('let')) {
  6746. return node.finishIdentifier(lex().value);
  6747. }
  6748. throwUnexpectedToken(lex());
  6749. } else if (type === Token.BooleanLiteral) {
  6750. isAssignmentTarget = isBindingElement = false;
  6751. token = lex();
  6752. token.value = (token.value === 'true');
  6753. expr = node.finishLiteral(token);
  6754. } else if (type === Token.NullLiteral) {
  6755. isAssignmentTarget = isBindingElement = false;
  6756. token = lex();
  6757. token.value = null;
  6758. expr = node.finishLiteral(token);
  6759. } else if (match('/') || match('/=')) {
  6760. isAssignmentTarget = isBindingElement = false;
  6761. index = startIndex;
  6762. if (typeof extra.tokens !== 'undefined') {
  6763. token = collectRegex();
  6764. } else {
  6765. token = scanRegExp();
  6766. }
  6767. lex();
  6768. expr = node.finishLiteral(token);
  6769. } else if (type === Token.Template) {
  6770. expr = parseTemplateLiteral();
  6771. } else {
  6772. throwUnexpectedToken(lex());
  6773. }
  6774. return expr;
  6775. }
  6776. // ECMA-262 12.3 Left-Hand-Side Expressions
  6777. function parseArguments() {
  6778. var args = [], expr;
  6779. expect('(');
  6780. if (!match(')')) {
  6781. while (startIndex < length) {
  6782. if (match('...')) {
  6783. expr = new Node();
  6784. lex();
  6785. expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
  6786. } else {
  6787. expr = isolateCoverGrammar(parseAssignmentExpression);
  6788. }
  6789. args.push(expr);
  6790. if (match(')')) {
  6791. break;
  6792. }
  6793. expectCommaSeparator();
  6794. }
  6795. }
  6796. expect(')');
  6797. return args;
  6798. }
  6799. function parseNonComputedProperty() {
  6800. var token, node = new Node();
  6801. token = lex();
  6802. if (!isIdentifierName(token)) {
  6803. throwUnexpectedToken(token);
  6804. }
  6805. return node.finishIdentifier(token.value);
  6806. }
  6807. function parseNonComputedMember() {
  6808. expect('.');
  6809. return parseNonComputedProperty();
  6810. }
  6811. function parseComputedMember() {
  6812. var expr;
  6813. expect('[');
  6814. expr = isolateCoverGrammar(parseExpression);
  6815. expect(']');
  6816. return expr;
  6817. }
  6818. // ECMA-262 12.3.3 The new Operator
  6819. function parseNewExpression() {
  6820. var callee, args, node = new Node();
  6821. expectKeyword('new');
  6822. if (match('.')) {
  6823. lex();
  6824. if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
  6825. if (state.inFunctionBody) {
  6826. lex();
  6827. return node.finishMetaProperty('new', 'target');
  6828. }
  6829. }
  6830. throwUnexpectedToken(lookahead);
  6831. }
  6832. callee = isolateCoverGrammar(parseLeftHandSideExpression);
  6833. args = match('(') ? parseArguments() : [];
  6834. isAssignmentTarget = isBindingElement = false;
  6835. return node.finishNewExpression(callee, args);
  6836. }
  6837. // ECMA-262 12.3.4 Function Calls
  6838. function parseLeftHandSideExpressionAllowCall() {
  6839. var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
  6840. startToken = lookahead;
  6841. state.allowIn = true;
  6842. if (matchKeyword('super') && state.inFunctionBody) {
  6843. expr = new Node();
  6844. lex();
  6845. expr = expr.finishSuper();
  6846. if (!match('(') && !match('.') && !match('[')) {
  6847. throwUnexpectedToken(lookahead);
  6848. }
  6849. } else {
  6850. expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
  6851. }
  6852. for (;;) {
  6853. if (match('.')) {
  6854. isBindingElement = false;
  6855. isAssignmentTarget = true;
  6856. property = parseNonComputedMember();
  6857. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6858. } else if (match('(')) {
  6859. isBindingElement = false;
  6860. isAssignmentTarget = false;
  6861. args = parseArguments();
  6862. expr = new WrappingNode(startToken).finishCallExpression(expr, args);
  6863. } else if (match('[')) {
  6864. isBindingElement = false;
  6865. isAssignmentTarget = true;
  6866. property = parseComputedMember();
  6867. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6868. } else if (lookahead.type === Token.Template && lookahead.head) {
  6869. quasi = parseTemplateLiteral();
  6870. expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
  6871. } else {
  6872. break;
  6873. }
  6874. }
  6875. state.allowIn = previousAllowIn;
  6876. return expr;
  6877. }
  6878. // ECMA-262 12.3 Left-Hand-Side Expressions
  6879. function parseLeftHandSideExpression() {
  6880. var quasi, expr, property, startToken;
  6881. assert(state.allowIn, 'callee of new expression always allow in keyword.');
  6882. startToken = lookahead;
  6883. if (matchKeyword('super') && state.inFunctionBody) {
  6884. expr = new Node();
  6885. lex();
  6886. expr = expr.finishSuper();
  6887. if (!match('[') && !match('.')) {
  6888. throwUnexpectedToken(lookahead);
  6889. }
  6890. } else {
  6891. expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
  6892. }
  6893. for (;;) {
  6894. if (match('[')) {
  6895. isBindingElement = false;
  6896. isAssignmentTarget = true;
  6897. property = parseComputedMember();
  6898. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6899. } else if (match('.')) {
  6900. isBindingElement = false;
  6901. isAssignmentTarget = true;
  6902. property = parseNonComputedMember();
  6903. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6904. } else if (lookahead.type === Token.Template && lookahead.head) {
  6905. quasi = parseTemplateLiteral();
  6906. expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
  6907. } else {
  6908. break;
  6909. }
  6910. }
  6911. return expr;
  6912. }
  6913. // ECMA-262 12.4 Postfix Expressions
  6914. function parsePostfixExpression() {
  6915. var expr, token, startToken = lookahead;
  6916. expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
  6917. if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
  6918. if (match('++') || match('--')) {
  6919. // ECMA-262 11.3.1, 11.3.2
  6920. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6921. tolerateError(Messages.StrictLHSPostfix);
  6922. }
  6923. if (!isAssignmentTarget) {
  6924. tolerateError(Messages.InvalidLHSInAssignment);
  6925. }
  6926. isAssignmentTarget = isBindingElement = false;
  6927. token = lex();
  6928. expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
  6929. }
  6930. }
  6931. return expr;
  6932. }
  6933. // ECMA-262 12.5 Unary Operators
  6934. function parseUnaryExpression() {
  6935. var token, expr, startToken;
  6936. if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
  6937. expr = parsePostfixExpression();
  6938. } else if (match('++') || match('--')) {
  6939. startToken = lookahead;
  6940. token = lex();
  6941. expr = inheritCoverGrammar(parseUnaryExpression);
  6942. // ECMA-262 11.4.4, 11.4.5
  6943. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6944. tolerateError(Messages.StrictLHSPrefix);
  6945. }
  6946. if (!isAssignmentTarget) {
  6947. tolerateError(Messages.InvalidLHSInAssignment);
  6948. }
  6949. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6950. isAssignmentTarget = isBindingElement = false;
  6951. } else if (match('+') || match('-') || match('~') || match('!')) {
  6952. startToken = lookahead;
  6953. token = lex();
  6954. expr = inheritCoverGrammar(parseUnaryExpression);
  6955. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6956. isAssignmentTarget = isBindingElement = false;
  6957. } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  6958. startToken = lookahead;
  6959. token = lex();
  6960. expr = inheritCoverGrammar(parseUnaryExpression);
  6961. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6962. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  6963. tolerateError(Messages.StrictDelete);
  6964. }
  6965. isAssignmentTarget = isBindingElement = false;
  6966. } else {
  6967. expr = parsePostfixExpression();
  6968. }
  6969. return expr;
  6970. }
  6971. function binaryPrecedence(token, allowIn) {
  6972. var prec = 0;
  6973. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  6974. return 0;
  6975. }
  6976. switch (token.value) {
  6977. case '||':
  6978. prec = 1;
  6979. break;
  6980. case '&&':
  6981. prec = 2;
  6982. break;
  6983. case '|':
  6984. prec = 3;
  6985. break;
  6986. case '^':
  6987. prec = 4;
  6988. break;
  6989. case '&':
  6990. prec = 5;
  6991. break;
  6992. case '==':
  6993. case '!=':
  6994. case '===':
  6995. case '!==':
  6996. prec = 6;
  6997. break;
  6998. case '<':
  6999. case '>':
  7000. case '<=':
  7001. case '>=':
  7002. case 'instanceof':
  7003. prec = 7;
  7004. break;
  7005. case 'in':
  7006. prec = allowIn ? 7 : 0;
  7007. break;
  7008. case '<<':
  7009. case '>>':
  7010. case '>>>':
  7011. prec = 8;
  7012. break;
  7013. case '+':
  7014. case '-':
  7015. prec = 9;
  7016. break;
  7017. case '*':
  7018. case '/':
  7019. case '%':
  7020. prec = 11;
  7021. break;
  7022. default:
  7023. break;
  7024. }
  7025. return prec;
  7026. }
  7027. // ECMA-262 12.6 Multiplicative Operators
  7028. // ECMA-262 12.7 Additive Operators
  7029. // ECMA-262 12.8 Bitwise Shift Operators
  7030. // ECMA-262 12.9 Relational Operators
  7031. // ECMA-262 12.10 Equality Operators
  7032. // ECMA-262 12.11 Binary Bitwise Operators
  7033. // ECMA-262 12.12 Binary Logical Operators
  7034. function parseBinaryExpression() {
  7035. var marker, markers, expr, token, prec, stack, right, operator, left, i;
  7036. marker = lookahead;
  7037. left = inheritCoverGrammar(parseUnaryExpression);
  7038. token = lookahead;
  7039. prec = binaryPrecedence(token, state.allowIn);
  7040. if (prec === 0) {
  7041. return left;
  7042. }
  7043. isAssignmentTarget = isBindingElement = false;
  7044. token.prec = prec;
  7045. lex();
  7046. markers = [marker, lookahead];
  7047. right = isolateCoverGrammar(parseUnaryExpression);
  7048. stack = [left, token, right];
  7049. while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
  7050. // Reduce: make a binary expression from the three topmost entries.
  7051. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  7052. right = stack.pop();
  7053. operator = stack.pop().value;
  7054. left = stack.pop();
  7055. markers.pop();
  7056. expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
  7057. stack.push(expr);
  7058. }
  7059. // Shift.
  7060. token = lex();
  7061. token.prec = prec;
  7062. stack.push(token);
  7063. markers.push(lookahead);
  7064. expr = isolateCoverGrammar(parseUnaryExpression);
  7065. stack.push(expr);
  7066. }
  7067. // Final reduce to clean-up the stack.
  7068. i = stack.length - 1;
  7069. expr = stack[i];
  7070. markers.pop();
  7071. while (i > 1) {
  7072. expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
  7073. i -= 2;
  7074. }
  7075. return expr;
  7076. }
  7077. // ECMA-262 12.13 Conditional Operator
  7078. function parseConditionalExpression() {
  7079. var expr, previousAllowIn, consequent, alternate, startToken;
  7080. startToken = lookahead;
  7081. expr = inheritCoverGrammar(parseBinaryExpression);
  7082. if (match('?')) {
  7083. lex();
  7084. previousAllowIn = state.allowIn;
  7085. state.allowIn = true;
  7086. consequent = isolateCoverGrammar(parseAssignmentExpression);
  7087. state.allowIn = previousAllowIn;
  7088. expect(':');
  7089. alternate = isolateCoverGrammar(parseAssignmentExpression);
  7090. expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
  7091. isAssignmentTarget = isBindingElement = false;
  7092. }
  7093. return expr;
  7094. }
  7095. // ECMA-262 14.2 Arrow Function Definitions
  7096. function parseConciseBody() {
  7097. if (match('{')) {
  7098. return parseFunctionSourceElements();
  7099. }
  7100. return isolateCoverGrammar(parseAssignmentExpression);
  7101. }
  7102. function checkPatternParam(options, param) {
  7103. var i;
  7104. switch (param.type) {
  7105. case Syntax.Identifier:
  7106. validateParam(options, param, param.name);
  7107. break;
  7108. case Syntax.RestElement:
  7109. checkPatternParam(options, param.argument);
  7110. break;
  7111. case Syntax.AssignmentPattern:
  7112. checkPatternParam(options, param.left);
  7113. break;
  7114. case Syntax.ArrayPattern:
  7115. for (i = 0; i < param.elements.length; i++) {
  7116. if (param.elements[i] !== null) {
  7117. checkPatternParam(options, param.elements[i]);
  7118. }
  7119. }
  7120. break;
  7121. case Syntax.YieldExpression:
  7122. break;
  7123. default:
  7124. assert(param.type === Syntax.ObjectPattern, 'Invalid type');
  7125. for (i = 0; i < param.properties.length; i++) {
  7126. checkPatternParam(options, param.properties[i].value);
  7127. }
  7128. break;
  7129. }
  7130. }
  7131. function reinterpretAsCoverFormalsList(expr) {
  7132. var i, len, param, params, defaults, defaultCount, options, token;
  7133. defaults = [];
  7134. defaultCount = 0;
  7135. params = [expr];
  7136. switch (expr.type) {
  7137. case Syntax.Identifier:
  7138. break;
  7139. case PlaceHolders.ArrowParameterPlaceHolder:
  7140. params = expr.params;
  7141. break;
  7142. default:
  7143. return null;
  7144. }
  7145. options = {
  7146. paramSet: {}
  7147. };
  7148. for (i = 0, len = params.length; i < len; i += 1) {
  7149. param = params[i];
  7150. switch (param.type) {
  7151. case Syntax.AssignmentPattern:
  7152. params[i] = param.left;
  7153. if (param.right.type === Syntax.YieldExpression) {
  7154. if (param.right.argument) {
  7155. throwUnexpectedToken(lookahead);
  7156. }
  7157. param.right.type = Syntax.Identifier;
  7158. param.right.name = 'yield';
  7159. delete param.right.argument;
  7160. delete param.right.delegate;
  7161. }
  7162. defaults.push(param.right);
  7163. ++defaultCount;
  7164. checkPatternParam(options, param.left);
  7165. break;
  7166. default:
  7167. checkPatternParam(options, param);
  7168. params[i] = param;
  7169. defaults.push(null);
  7170. break;
  7171. }
  7172. }
  7173. if (strict || !state.allowYield) {
  7174. for (i = 0, len = params.length; i < len; i += 1) {
  7175. param = params[i];
  7176. if (param.type === Syntax.YieldExpression) {
  7177. throwUnexpectedToken(lookahead);
  7178. }
  7179. }
  7180. }
  7181. if (options.message === Messages.StrictParamDupe) {
  7182. token = strict ? options.stricted : options.firstRestricted;
  7183. throwUnexpectedToken(token, options.message);
  7184. }
  7185. if (defaultCount === 0) {
  7186. defaults = [];
  7187. }
  7188. return {
  7189. params: params,
  7190. defaults: defaults,
  7191. stricted: options.stricted,
  7192. firstRestricted: options.firstRestricted,
  7193. message: options.message
  7194. };
  7195. }
  7196. function parseArrowFunctionExpression(options, node) {
  7197. var previousStrict, previousAllowYield, body;
  7198. if (hasLineTerminator) {
  7199. tolerateUnexpectedToken(lookahead);
  7200. }
  7201. expect('=>');
  7202. previousStrict = strict;
  7203. previousAllowYield = state.allowYield;
  7204. state.allowYield = true;
  7205. body = parseConciseBody();
  7206. if (strict && options.firstRestricted) {
  7207. throwUnexpectedToken(options.firstRestricted, options.message);
  7208. }
  7209. if (strict && options.stricted) {
  7210. tolerateUnexpectedToken(options.stricted, options.message);
  7211. }
  7212. strict = previousStrict;
  7213. state.allowYield = previousAllowYield;
  7214. return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
  7215. }
  7216. // ECMA-262 14.4 Yield expression
  7217. function parseYieldExpression() {
  7218. var argument, expr, delegate, previousAllowYield;
  7219. argument = null;
  7220. expr = new Node();
  7221. expectKeyword('yield');
  7222. if (!hasLineTerminator) {
  7223. previousAllowYield = state.allowYield;
  7224. state.allowYield = false;
  7225. delegate = match('*');
  7226. if (delegate) {
  7227. lex();
  7228. argument = parseAssignmentExpression();
  7229. } else {
  7230. if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
  7231. argument = parseAssignmentExpression();
  7232. }
  7233. }
  7234. state.allowYield = previousAllowYield;
  7235. }
  7236. return expr.finishYieldExpression(argument, delegate);
  7237. }
  7238. // ECMA-262 12.14 Assignment Operators
  7239. function parseAssignmentExpression() {
  7240. var token, expr, right, list, startToken;
  7241. startToken = lookahead;
  7242. token = lookahead;
  7243. if (!state.allowYield && matchKeyword('yield')) {
  7244. return parseYieldExpression();
  7245. }
  7246. expr = parseConditionalExpression();
  7247. if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
  7248. isAssignmentTarget = isBindingElement = false;
  7249. list = reinterpretAsCoverFormalsList(expr);
  7250. if (list) {
  7251. firstCoverInitializedNameError = null;
  7252. return parseArrowFunctionExpression(list, new WrappingNode(startToken));
  7253. }
  7254. return expr;
  7255. }
  7256. if (matchAssign()) {
  7257. if (!isAssignmentTarget) {
  7258. tolerateError(Messages.InvalidLHSInAssignment);
  7259. }
  7260. // ECMA-262 12.1.1
  7261. if (strict && expr.type === Syntax.Identifier) {
  7262. if (isRestrictedWord(expr.name)) {
  7263. tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
  7264. }
  7265. if (isStrictModeReservedWord(expr.name)) {
  7266. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7267. }
  7268. }
  7269. if (!match('=')) {
  7270. isAssignmentTarget = isBindingElement = false;
  7271. } else {
  7272. reinterpretExpressionAsPattern(expr);
  7273. }
  7274. token = lex();
  7275. right = isolateCoverGrammar(parseAssignmentExpression);
  7276. expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
  7277. firstCoverInitializedNameError = null;
  7278. }
  7279. return expr;
  7280. }
  7281. // ECMA-262 12.15 Comma Operator
  7282. function parseExpression() {
  7283. var expr, startToken = lookahead, expressions;
  7284. expr = isolateCoverGrammar(parseAssignmentExpression);
  7285. if (match(',')) {
  7286. expressions = [expr];
  7287. while (startIndex < length) {
  7288. if (!match(',')) {
  7289. break;
  7290. }
  7291. lex();
  7292. expressions.push(isolateCoverGrammar(parseAssignmentExpression));
  7293. }
  7294. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  7295. }
  7296. return expr;
  7297. }
  7298. // ECMA-262 13.2 Block
  7299. function parseStatementListItem() {
  7300. if (lookahead.type === Token.Keyword) {
  7301. switch (lookahead.value) {
  7302. case 'export':
  7303. if (state.sourceType !== 'module') {
  7304. tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
  7305. }
  7306. return parseExportDeclaration();
  7307. case 'import':
  7308. if (state.sourceType !== 'module') {
  7309. tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
  7310. }
  7311. return parseImportDeclaration();
  7312. case 'const':
  7313. return parseLexicalDeclaration({inFor: false});
  7314. case 'function':
  7315. return parseFunctionDeclaration(new Node());
  7316. case 'class':
  7317. return parseClassDeclaration();
  7318. }
  7319. }
  7320. if (matchKeyword('let') && isLexicalDeclaration()) {
  7321. return parseLexicalDeclaration({inFor: false});
  7322. }
  7323. return parseStatement();
  7324. }
  7325. function parseStatementList() {
  7326. var list = [];
  7327. while (startIndex < length) {
  7328. if (match('}')) {
  7329. break;
  7330. }
  7331. list.push(parseStatementListItem());
  7332. }
  7333. return list;
  7334. }
  7335. function parseBlock() {
  7336. var block, node = new Node();
  7337. expect('{');
  7338. block = parseStatementList();
  7339. expect('}');
  7340. return node.finishBlockStatement(block);
  7341. }
  7342. // ECMA-262 13.3.2 Variable Statement
  7343. function parseVariableIdentifier(kind) {
  7344. var token, node = new Node();
  7345. token = lex();
  7346. if (token.type === Token.Keyword && token.value === 'yield') {
  7347. if (strict) {
  7348. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7349. } if (!state.allowYield) {
  7350. throwUnexpectedToken(token);
  7351. }
  7352. } else if (token.type !== Token.Identifier) {
  7353. if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
  7354. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7355. } else {
  7356. if (strict || token.value !== 'let' || kind !== 'var') {
  7357. throwUnexpectedToken(token);
  7358. }
  7359. }
  7360. } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
  7361. tolerateUnexpectedToken(token);
  7362. }
  7363. return node.finishIdentifier(token.value);
  7364. }
  7365. function parseVariableDeclaration(options) {
  7366. var init = null, id, node = new Node(), params = [];
  7367. id = parsePattern(params, 'var');
  7368. // ECMA-262 12.2.1
  7369. if (strict && isRestrictedWord(id.name)) {
  7370. tolerateError(Messages.StrictVarName);
  7371. }
  7372. if (match('=')) {
  7373. lex();
  7374. init = isolateCoverGrammar(parseAssignmentExpression);
  7375. } else if (id.type !== Syntax.Identifier && !options.inFor) {
  7376. expect('=');
  7377. }
  7378. return node.finishVariableDeclarator(id, init);
  7379. }
  7380. function parseVariableDeclarationList(options) {
  7381. var list = [];
  7382. do {
  7383. list.push(parseVariableDeclaration({ inFor: options.inFor }));
  7384. if (!match(',')) {
  7385. break;
  7386. }
  7387. lex();
  7388. } while (startIndex < length);
  7389. return list;
  7390. }
  7391. function parseVariableStatement(node) {
  7392. var declarations;
  7393. expectKeyword('var');
  7394. declarations = parseVariableDeclarationList({ inFor: false });
  7395. consumeSemicolon();
  7396. return node.finishVariableDeclaration(declarations);
  7397. }
  7398. // ECMA-262 13.3.1 Let and Const Declarations
  7399. function parseLexicalBinding(kind, options) {
  7400. var init = null, id, node = new Node(), params = [];
  7401. id = parsePattern(params, kind);
  7402. // ECMA-262 12.2.1
  7403. if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
  7404. tolerateError(Messages.StrictVarName);
  7405. }
  7406. if (kind === 'const') {
  7407. if (!matchKeyword('in') && !matchContextualKeyword('of')) {
  7408. expect('=');
  7409. init = isolateCoverGrammar(parseAssignmentExpression);
  7410. }
  7411. } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
  7412. expect('=');
  7413. init = isolateCoverGrammar(parseAssignmentExpression);
  7414. }
  7415. return node.finishVariableDeclarator(id, init);
  7416. }
  7417. function parseBindingList(kind, options) {
  7418. var list = [];
  7419. do {
  7420. list.push(parseLexicalBinding(kind, options));
  7421. if (!match(',')) {
  7422. break;
  7423. }
  7424. lex();
  7425. } while (startIndex < length);
  7426. return list;
  7427. }
  7428. function tokenizerState() {
  7429. return {
  7430. index: index,
  7431. lineNumber: lineNumber,
  7432. lineStart: lineStart,
  7433. hasLineTerminator: hasLineTerminator,
  7434. lastIndex: lastIndex,
  7435. lastLineNumber: lastLineNumber,
  7436. lastLineStart: lastLineStart,
  7437. startIndex: startIndex,
  7438. startLineNumber: startLineNumber,
  7439. startLineStart: startLineStart,
  7440. lookahead: lookahead,
  7441. tokenCount: extra.tokens ? extra.tokens.length : 0
  7442. };
  7443. }
  7444. function resetTokenizerState(ts) {
  7445. index = ts.index;
  7446. lineNumber = ts.lineNumber;
  7447. lineStart = ts.lineStart;
  7448. hasLineTerminator = ts.hasLineTerminator;
  7449. lastIndex = ts.lastIndex;
  7450. lastLineNumber = ts.lastLineNumber;
  7451. lastLineStart = ts.lastLineStart;
  7452. startIndex = ts.startIndex;
  7453. startLineNumber = ts.startLineNumber;
  7454. startLineStart = ts.startLineStart;
  7455. lookahead = ts.lookahead;
  7456. if (extra.tokens) {
  7457. extra.tokens.splice(ts.tokenCount, extra.tokens.length);
  7458. }
  7459. }
  7460. function isLexicalDeclaration() {
  7461. var lexical, ts;
  7462. ts = tokenizerState();
  7463. lex();
  7464. lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
  7465. matchKeyword('let') || matchKeyword('yield');
  7466. resetTokenizerState(ts);
  7467. return lexical;
  7468. }
  7469. function parseLexicalDeclaration(options) {
  7470. var kind, declarations, node = new Node();
  7471. kind = lex().value;
  7472. assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
  7473. declarations = parseBindingList(kind, options);
  7474. consumeSemicolon();
  7475. return node.finishLexicalDeclaration(declarations, kind);
  7476. }
  7477. function parseRestElement(params) {
  7478. var param, node = new Node();
  7479. lex();
  7480. if (match('{')) {
  7481. throwError(Messages.ObjectPatternAsRestParameter);
  7482. }
  7483. params.push(lookahead);
  7484. param = parseVariableIdentifier();
  7485. if (match('=')) {
  7486. throwError(Messages.DefaultRestParameter);
  7487. }
  7488. if (!match(')')) {
  7489. throwError(Messages.ParameterAfterRestParameter);
  7490. }
  7491. return node.finishRestElement(param);
  7492. }
  7493. // ECMA-262 13.4 Empty Statement
  7494. function parseEmptyStatement(node) {
  7495. expect(';');
  7496. return node.finishEmptyStatement();
  7497. }
  7498. // ECMA-262 12.4 Expression Statement
  7499. function parseExpressionStatement(node) {
  7500. var expr = parseExpression();
  7501. consumeSemicolon();
  7502. return node.finishExpressionStatement(expr);
  7503. }
  7504. // ECMA-262 13.6 If statement
  7505. function parseIfStatement(node) {
  7506. var test, consequent, alternate;
  7507. expectKeyword('if');
  7508. expect('(');
  7509. test = parseExpression();
  7510. expect(')');
  7511. consequent = parseStatement();
  7512. if (matchKeyword('else')) {
  7513. lex();
  7514. alternate = parseStatement();
  7515. } else {
  7516. alternate = null;
  7517. }
  7518. return node.finishIfStatement(test, consequent, alternate);
  7519. }
  7520. // ECMA-262 13.7 Iteration Statements
  7521. function parseDoWhileStatement(node) {
  7522. var body, test, oldInIteration;
  7523. expectKeyword('do');
  7524. oldInIteration = state.inIteration;
  7525. state.inIteration = true;
  7526. body = parseStatement();
  7527. state.inIteration = oldInIteration;
  7528. expectKeyword('while');
  7529. expect('(');
  7530. test = parseExpression();
  7531. expect(')');
  7532. if (match(';')) {
  7533. lex();
  7534. }
  7535. return node.finishDoWhileStatement(body, test);
  7536. }
  7537. function parseWhileStatement(node) {
  7538. var test, body, oldInIteration;
  7539. expectKeyword('while');
  7540. expect('(');
  7541. test = parseExpression();
  7542. expect(')');
  7543. oldInIteration = state.inIteration;
  7544. state.inIteration = true;
  7545. body = parseStatement();
  7546. state.inIteration = oldInIteration;
  7547. return node.finishWhileStatement(test, body);
  7548. }
  7549. function parseForStatement(node) {
  7550. var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
  7551. body, oldInIteration, previousAllowIn = state.allowIn;
  7552. init = test = update = null;
  7553. forIn = true;
  7554. expectKeyword('for');
  7555. expect('(');
  7556. if (match(';')) {
  7557. lex();
  7558. } else {
  7559. if (matchKeyword('var')) {
  7560. init = new Node();
  7561. lex();
  7562. state.allowIn = false;
  7563. declarations = parseVariableDeclarationList({ inFor: true });
  7564. state.allowIn = previousAllowIn;
  7565. if (declarations.length === 1 && matchKeyword('in')) {
  7566. init = init.finishVariableDeclaration(declarations);
  7567. lex();
  7568. left = init;
  7569. right = parseExpression();
  7570. init = null;
  7571. } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
  7572. init = init.finishVariableDeclaration(declarations);
  7573. lex();
  7574. left = init;
  7575. right = parseAssignmentExpression();
  7576. init = null;
  7577. forIn = false;
  7578. } else {
  7579. init = init.finishVariableDeclaration(declarations);
  7580. expect(';');
  7581. }
  7582. } else if (matchKeyword('const') || matchKeyword('let')) {
  7583. init = new Node();
  7584. kind = lex().value;
  7585. if (!strict && lookahead.value === 'in') {
  7586. init = init.finishIdentifier(kind);
  7587. lex();
  7588. left = init;
  7589. right = parseExpression();
  7590. init = null;
  7591. } else {
  7592. state.allowIn = false;
  7593. declarations = parseBindingList(kind, {inFor: true});
  7594. state.allowIn = previousAllowIn;
  7595. if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
  7596. init = init.finishLexicalDeclaration(declarations, kind);
  7597. lex();
  7598. left = init;
  7599. right = parseExpression();
  7600. init = null;
  7601. } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
  7602. init = init.finishLexicalDeclaration(declarations, kind);
  7603. lex();
  7604. left = init;
  7605. right = parseAssignmentExpression();
  7606. init = null;
  7607. forIn = false;
  7608. } else {
  7609. consumeSemicolon();
  7610. init = init.finishLexicalDeclaration(declarations, kind);
  7611. }
  7612. }
  7613. } else {
  7614. initStartToken = lookahead;
  7615. state.allowIn = false;
  7616. init = inheritCoverGrammar(parseAssignmentExpression);
  7617. state.allowIn = previousAllowIn;
  7618. if (matchKeyword('in')) {
  7619. if (!isAssignmentTarget) {
  7620. tolerateError(Messages.InvalidLHSInForIn);
  7621. }
  7622. lex();
  7623. reinterpretExpressionAsPattern(init);
  7624. left = init;
  7625. right = parseExpression();
  7626. init = null;
  7627. } else if (matchContextualKeyword('of')) {
  7628. if (!isAssignmentTarget) {
  7629. tolerateError(Messages.InvalidLHSInForLoop);
  7630. }
  7631. lex();
  7632. reinterpretExpressionAsPattern(init);
  7633. left = init;
  7634. right = parseAssignmentExpression();
  7635. init = null;
  7636. forIn = false;
  7637. } else {
  7638. if (match(',')) {
  7639. initSeq = [init];
  7640. while (match(',')) {
  7641. lex();
  7642. initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
  7643. }
  7644. init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
  7645. }
  7646. expect(';');
  7647. }
  7648. }
  7649. }
  7650. if (typeof left === 'undefined') {
  7651. if (!match(';')) {
  7652. test = parseExpression();
  7653. }
  7654. expect(';');
  7655. if (!match(')')) {
  7656. update = parseExpression();
  7657. }
  7658. }
  7659. expect(')');
  7660. oldInIteration = state.inIteration;
  7661. state.inIteration = true;
  7662. body = isolateCoverGrammar(parseStatement);
  7663. state.inIteration = oldInIteration;
  7664. return (typeof left === 'undefined') ?
  7665. node.finishForStatement(init, test, update, body) :
  7666. forIn ? node.finishForInStatement(left, right, body) :
  7667. node.finishForOfStatement(left, right, body);
  7668. }
  7669. // ECMA-262 13.8 The continue statement
  7670. function parseContinueStatement(node) {
  7671. var label = null, key;
  7672. expectKeyword('continue');
  7673. // Optimize the most common form: 'continue;'.
  7674. if (source.charCodeAt(startIndex) === 0x3B) {
  7675. lex();
  7676. if (!state.inIteration) {
  7677. throwError(Messages.IllegalContinue);
  7678. }
  7679. return node.finishContinueStatement(null);
  7680. }
  7681. if (hasLineTerminator) {
  7682. if (!state.inIteration) {
  7683. throwError(Messages.IllegalContinue);
  7684. }
  7685. return node.finishContinueStatement(null);
  7686. }
  7687. if (lookahead.type === Token.Identifier) {
  7688. label = parseVariableIdentifier();
  7689. key = '$' + label.name;
  7690. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7691. throwError(Messages.UnknownLabel, label.name);
  7692. }
  7693. }
  7694. consumeSemicolon();
  7695. if (label === null && !state.inIteration) {
  7696. throwError(Messages.IllegalContinue);
  7697. }
  7698. return node.finishContinueStatement(label);
  7699. }
  7700. // ECMA-262 13.9 The break statement
  7701. function parseBreakStatement(node) {
  7702. var label = null, key;
  7703. expectKeyword('break');
  7704. // Catch the very common case first: immediately a semicolon (U+003B).
  7705. if (source.charCodeAt(lastIndex) === 0x3B) {
  7706. lex();
  7707. if (!(state.inIteration || state.inSwitch)) {
  7708. throwError(Messages.IllegalBreak);
  7709. }
  7710. return node.finishBreakStatement(null);
  7711. }
  7712. if (hasLineTerminator) {
  7713. if (!(state.inIteration || state.inSwitch)) {
  7714. throwError(Messages.IllegalBreak);
  7715. }
  7716. } else if (lookahead.type === Token.Identifier) {
  7717. label = parseVariableIdentifier();
  7718. key = '$' + label.name;
  7719. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7720. throwError(Messages.UnknownLabel, label.name);
  7721. }
  7722. }
  7723. consumeSemicolon();
  7724. if (label === null && !(state.inIteration || state.inSwitch)) {
  7725. throwError(Messages.IllegalBreak);
  7726. }
  7727. return node.finishBreakStatement(label);
  7728. }
  7729. // ECMA-262 13.10 The return statement
  7730. function parseReturnStatement(node) {
  7731. var argument = null;
  7732. expectKeyword('return');
  7733. if (!state.inFunctionBody) {
  7734. tolerateError(Messages.IllegalReturn);
  7735. }
  7736. // 'return' followed by a space and an identifier is very common.
  7737. if (source.charCodeAt(lastIndex) === 0x20) {
  7738. if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
  7739. argument = parseExpression();
  7740. consumeSemicolon();
  7741. return node.finishReturnStatement(argument);
  7742. }
  7743. }
  7744. if (hasLineTerminator) {
  7745. // HACK
  7746. return node.finishReturnStatement(null);
  7747. }
  7748. if (!match(';')) {
  7749. if (!match('}') && lookahead.type !== Token.EOF) {
  7750. argument = parseExpression();
  7751. }
  7752. }
  7753. consumeSemicolon();
  7754. return node.finishReturnStatement(argument);
  7755. }
  7756. // ECMA-262 13.11 The with statement
  7757. function parseWithStatement(node) {
  7758. var object, body;
  7759. if (strict) {
  7760. tolerateError(Messages.StrictModeWith);
  7761. }
  7762. expectKeyword('with');
  7763. expect('(');
  7764. object = parseExpression();
  7765. expect(')');
  7766. body = parseStatement();
  7767. return node.finishWithStatement(object, body);
  7768. }
  7769. // ECMA-262 13.12 The switch statement
  7770. function parseSwitchCase() {
  7771. var test, consequent = [], statement, node = new Node();
  7772. if (matchKeyword('default')) {
  7773. lex();
  7774. test = null;
  7775. } else {
  7776. expectKeyword('case');
  7777. test = parseExpression();
  7778. }
  7779. expect(':');
  7780. while (startIndex < length) {
  7781. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  7782. break;
  7783. }
  7784. statement = parseStatementListItem();
  7785. consequent.push(statement);
  7786. }
  7787. return node.finishSwitchCase(test, consequent);
  7788. }
  7789. function parseSwitchStatement(node) {
  7790. var discriminant, cases, clause, oldInSwitch, defaultFound;
  7791. expectKeyword('switch');
  7792. expect('(');
  7793. discriminant = parseExpression();
  7794. expect(')');
  7795. expect('{');
  7796. cases = [];
  7797. if (match('}')) {
  7798. lex();
  7799. return node.finishSwitchStatement(discriminant, cases);
  7800. }
  7801. oldInSwitch = state.inSwitch;
  7802. state.inSwitch = true;
  7803. defaultFound = false;
  7804. while (startIndex < length) {
  7805. if (match('}')) {
  7806. break;
  7807. }
  7808. clause = parseSwitchCase();
  7809. if (clause.test === null) {
  7810. if (defaultFound) {
  7811. throwError(Messages.MultipleDefaultsInSwitch);
  7812. }
  7813. defaultFound = true;
  7814. }
  7815. cases.push(clause);
  7816. }
  7817. state.inSwitch = oldInSwitch;
  7818. expect('}');
  7819. return node.finishSwitchStatement(discriminant, cases);
  7820. }
  7821. // ECMA-262 13.14 The throw statement
  7822. function parseThrowStatement(node) {
  7823. var argument;
  7824. expectKeyword('throw');
  7825. if (hasLineTerminator) {
  7826. throwError(Messages.NewlineAfterThrow);
  7827. }
  7828. argument = parseExpression();
  7829. consumeSemicolon();
  7830. return node.finishThrowStatement(argument);
  7831. }
  7832. // ECMA-262 13.15 The try statement
  7833. function parseCatchClause() {
  7834. var param, params = [], paramMap = {}, key, i, body, node = new Node();
  7835. expectKeyword('catch');
  7836. expect('(');
  7837. if (match(')')) {
  7838. throwUnexpectedToken(lookahead);
  7839. }
  7840. param = parsePattern(params);
  7841. for (i = 0; i < params.length; i++) {
  7842. key = '$' + params[i].value;
  7843. if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
  7844. tolerateError(Messages.DuplicateBinding, params[i].value);
  7845. }
  7846. paramMap[key] = true;
  7847. }
  7848. // ECMA-262 12.14.1
  7849. if (strict && isRestrictedWord(param.name)) {
  7850. tolerateError(Messages.StrictCatchVariable);
  7851. }
  7852. expect(')');
  7853. body = parseBlock();
  7854. return node.finishCatchClause(param, body);
  7855. }
  7856. function parseTryStatement(node) {
  7857. var block, handler = null, finalizer = null;
  7858. expectKeyword('try');
  7859. block = parseBlock();
  7860. if (matchKeyword('catch')) {
  7861. handler = parseCatchClause();
  7862. }
  7863. if (matchKeyword('finally')) {
  7864. lex();
  7865. finalizer = parseBlock();
  7866. }
  7867. if (!handler && !finalizer) {
  7868. throwError(Messages.NoCatchOrFinally);
  7869. }
  7870. return node.finishTryStatement(block, handler, finalizer);
  7871. }
  7872. // ECMA-262 13.16 The debugger statement
  7873. function parseDebuggerStatement(node) {
  7874. expectKeyword('debugger');
  7875. consumeSemicolon();
  7876. return node.finishDebuggerStatement();
  7877. }
  7878. // 13 Statements
  7879. function parseStatement() {
  7880. var type = lookahead.type,
  7881. expr,
  7882. labeledBody,
  7883. key,
  7884. node;
  7885. if (type === Token.EOF) {
  7886. throwUnexpectedToken(lookahead);
  7887. }
  7888. if (type === Token.Punctuator && lookahead.value === '{') {
  7889. return parseBlock();
  7890. }
  7891. isAssignmentTarget = isBindingElement = true;
  7892. node = new Node();
  7893. if (type === Token.Punctuator) {
  7894. switch (lookahead.value) {
  7895. case ';':
  7896. return parseEmptyStatement(node);
  7897. case '(':
  7898. return parseExpressionStatement(node);
  7899. default:
  7900. break;
  7901. }
  7902. } else if (type === Token.Keyword) {
  7903. switch (lookahead.value) {
  7904. case 'break':
  7905. return parseBreakStatement(node);
  7906. case 'continue':
  7907. return parseContinueStatement(node);
  7908. case 'debugger':
  7909. return parseDebuggerStatement(node);
  7910. case 'do':
  7911. return parseDoWhileStatement(node);
  7912. case 'for':
  7913. return parseForStatement(node);
  7914. case 'function':
  7915. return parseFunctionDeclaration(node);
  7916. case 'if':
  7917. return parseIfStatement(node);
  7918. case 'return':
  7919. return parseReturnStatement(node);
  7920. case 'switch':
  7921. return parseSwitchStatement(node);
  7922. case 'throw':
  7923. return parseThrowStatement(node);
  7924. case 'try':
  7925. return parseTryStatement(node);
  7926. case 'var':
  7927. return parseVariableStatement(node);
  7928. case 'while':
  7929. return parseWhileStatement(node);
  7930. case 'with':
  7931. return parseWithStatement(node);
  7932. default:
  7933. break;
  7934. }
  7935. }
  7936. expr = parseExpression();
  7937. // ECMA-262 12.12 Labelled Statements
  7938. if ((expr.type === Syntax.Identifier) && match(':')) {
  7939. lex();
  7940. key = '$' + expr.name;
  7941. if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7942. throwError(Messages.Redeclaration, 'Label', expr.name);
  7943. }
  7944. state.labelSet[key] = true;
  7945. labeledBody = parseStatement();
  7946. delete state.labelSet[key];
  7947. return node.finishLabeledStatement(expr, labeledBody);
  7948. }
  7949. consumeSemicolon();
  7950. return node.finishExpressionStatement(expr);
  7951. }
  7952. // ECMA-262 14.1 Function Definition
  7953. function parseFunctionSourceElements() {
  7954. var statement, body = [], token, directive, firstRestricted,
  7955. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
  7956. node = new Node();
  7957. expect('{');
  7958. while (startIndex < length) {
  7959. if (lookahead.type !== Token.StringLiteral) {
  7960. break;
  7961. }
  7962. token = lookahead;
  7963. statement = parseStatementListItem();
  7964. body.push(statement);
  7965. if (statement.expression.type !== Syntax.Literal) {
  7966. // this is not directive
  7967. break;
  7968. }
  7969. directive = source.slice(token.start + 1, token.end - 1);
  7970. if (directive === 'use strict') {
  7971. strict = true;
  7972. if (firstRestricted) {
  7973. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  7974. }
  7975. } else {
  7976. if (!firstRestricted && token.octal) {
  7977. firstRestricted = token;
  7978. }
  7979. }
  7980. }
  7981. oldLabelSet = state.labelSet;
  7982. oldInIteration = state.inIteration;
  7983. oldInSwitch = state.inSwitch;
  7984. oldInFunctionBody = state.inFunctionBody;
  7985. oldParenthesisCount = state.parenthesizedCount;
  7986. state.labelSet = {};
  7987. state.inIteration = false;
  7988. state.inSwitch = false;
  7989. state.inFunctionBody = true;
  7990. state.parenthesizedCount = 0;
  7991. while (startIndex < length) {
  7992. if (match('}')) {
  7993. break;
  7994. }
  7995. body.push(parseStatementListItem());
  7996. }
  7997. expect('}');
  7998. state.labelSet = oldLabelSet;
  7999. state.inIteration = oldInIteration;
  8000. state.inSwitch = oldInSwitch;
  8001. state.inFunctionBody = oldInFunctionBody;
  8002. state.parenthesizedCount = oldParenthesisCount;
  8003. return node.finishBlockStatement(body);
  8004. }
  8005. function validateParam(options, param, name) {
  8006. var key = '$' + name;
  8007. if (strict) {
  8008. if (isRestrictedWord(name)) {
  8009. options.stricted = param;
  8010. options.message = Messages.StrictParamName;
  8011. }
  8012. if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  8013. options.stricted = param;
  8014. options.message = Messages.StrictParamDupe;
  8015. }
  8016. } else if (!options.firstRestricted) {
  8017. if (isRestrictedWord(name)) {
  8018. options.firstRestricted = param;
  8019. options.message = Messages.StrictParamName;
  8020. } else if (isStrictModeReservedWord(name)) {
  8021. options.firstRestricted = param;
  8022. options.message = Messages.StrictReservedWord;
  8023. } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  8024. options.stricted = param;
  8025. options.message = Messages.StrictParamDupe;
  8026. }
  8027. }
  8028. options.paramSet[key] = true;
  8029. }
  8030. function parseParam(options) {
  8031. var token, param, params = [], i, def;
  8032. token = lookahead;
  8033. if (token.value === '...') {
  8034. param = parseRestElement(params);
  8035. validateParam(options, param.argument, param.argument.name);
  8036. options.params.push(param);
  8037. options.defaults.push(null);
  8038. return false;
  8039. }
  8040. param = parsePatternWithDefault(params);
  8041. for (i = 0; i < params.length; i++) {
  8042. validateParam(options, params[i], params[i].value);
  8043. }
  8044. if (param.type === Syntax.AssignmentPattern) {
  8045. def = param.right;
  8046. param = param.left;
  8047. ++options.defaultCount;
  8048. }
  8049. options.params.push(param);
  8050. options.defaults.push(def);
  8051. return !match(')');
  8052. }
  8053. function parseParams(firstRestricted) {
  8054. var options;
  8055. options = {
  8056. params: [],
  8057. defaultCount: 0,
  8058. defaults: [],
  8059. firstRestricted: firstRestricted
  8060. };
  8061. expect('(');
  8062. if (!match(')')) {
  8063. options.paramSet = {};
  8064. while (startIndex < length) {
  8065. if (!parseParam(options)) {
  8066. break;
  8067. }
  8068. expect(',');
  8069. }
  8070. }
  8071. expect(')');
  8072. if (options.defaultCount === 0) {
  8073. options.defaults = [];
  8074. }
  8075. return {
  8076. params: options.params,
  8077. defaults: options.defaults,
  8078. stricted: options.stricted,
  8079. firstRestricted: options.firstRestricted,
  8080. message: options.message
  8081. };
  8082. }
  8083. function parseFunctionDeclaration(node, identifierIsOptional) {
  8084. var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
  8085. isGenerator, previousAllowYield;
  8086. previousAllowYield = state.allowYield;
  8087. expectKeyword('function');
  8088. isGenerator = match('*');
  8089. if (isGenerator) {
  8090. lex();
  8091. }
  8092. if (!identifierIsOptional || !match('(')) {
  8093. token = lookahead;
  8094. id = parseVariableIdentifier();
  8095. if (strict) {
  8096. if (isRestrictedWord(token.value)) {
  8097. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  8098. }
  8099. } else {
  8100. if (isRestrictedWord(token.value)) {
  8101. firstRestricted = token;
  8102. message = Messages.StrictFunctionName;
  8103. } else if (isStrictModeReservedWord(token.value)) {
  8104. firstRestricted = token;
  8105. message = Messages.StrictReservedWord;
  8106. }
  8107. }
  8108. }
  8109. state.allowYield = !isGenerator;
  8110. tmp = parseParams(firstRestricted);
  8111. params = tmp.params;
  8112. defaults = tmp.defaults;
  8113. stricted = tmp.stricted;
  8114. firstRestricted = tmp.firstRestricted;
  8115. if (tmp.message) {
  8116. message = tmp.message;
  8117. }
  8118. previousStrict = strict;
  8119. body = parseFunctionSourceElements();
  8120. if (strict && firstRestricted) {
  8121. throwUnexpectedToken(firstRestricted, message);
  8122. }
  8123. if (strict && stricted) {
  8124. tolerateUnexpectedToken(stricted, message);
  8125. }
  8126. strict = previousStrict;
  8127. state.allowYield = previousAllowYield;
  8128. return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
  8129. }
  8130. function parseFunctionExpression() {
  8131. var token, id = null, stricted, firstRestricted, message, tmp,
  8132. params = [], defaults = [], body, previousStrict, node = new Node(),
  8133. isGenerator, previousAllowYield;
  8134. previousAllowYield = state.allowYield;
  8135. expectKeyword('function');
  8136. isGenerator = match('*');
  8137. if (isGenerator) {
  8138. lex();
  8139. }
  8140. state.allowYield = !isGenerator;
  8141. if (!match('(')) {
  8142. token = lookahead;
  8143. id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
  8144. if (strict) {
  8145. if (isRestrictedWord(token.value)) {
  8146. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  8147. }
  8148. } else {
  8149. if (isRestrictedWord(token.value)) {
  8150. firstRestricted = token;
  8151. message = Messages.StrictFunctionName;
  8152. } else if (isStrictModeReservedWord(token.value)) {
  8153. firstRestricted = token;
  8154. message = Messages.StrictReservedWord;
  8155. }
  8156. }
  8157. }
  8158. tmp = parseParams(firstRestricted);
  8159. params = tmp.params;
  8160. defaults = tmp.defaults;
  8161. stricted = tmp.stricted;
  8162. firstRestricted = tmp.firstRestricted;
  8163. if (tmp.message) {
  8164. message = tmp.message;
  8165. }
  8166. previousStrict = strict;
  8167. body = parseFunctionSourceElements();
  8168. if (strict && firstRestricted) {
  8169. throwUnexpectedToken(firstRestricted, message);
  8170. }
  8171. if (strict && stricted) {
  8172. tolerateUnexpectedToken(stricted, message);
  8173. }
  8174. strict = previousStrict;
  8175. state.allowYield = previousAllowYield;
  8176. return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
  8177. }
  8178. // ECMA-262 14.5 Class Definitions
  8179. function parseClassBody() {
  8180. var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
  8181. classBody = new Node();
  8182. expect('{');
  8183. body = [];
  8184. while (!match('}')) {
  8185. if (match(';')) {
  8186. lex();
  8187. } else {
  8188. method = new Node();
  8189. token = lookahead;
  8190. isStatic = false;
  8191. computed = match('[');
  8192. if (match('*')) {
  8193. lex();
  8194. } else {
  8195. key = parseObjectPropertyKey();
  8196. if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
  8197. token = lookahead;
  8198. isStatic = true;
  8199. computed = match('[');
  8200. if (match('*')) {
  8201. lex();
  8202. } else {
  8203. key = parseObjectPropertyKey();
  8204. }
  8205. }
  8206. }
  8207. method = tryParseMethodDefinition(token, key, computed, method);
  8208. if (method) {
  8209. method['static'] = isStatic; // jscs:ignore requireDotNotation
  8210. if (method.kind === 'init') {
  8211. method.kind = 'method';
  8212. }
  8213. if (!isStatic) {
  8214. if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
  8215. if (method.kind !== 'method' || !method.method || method.value.generator) {
  8216. throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
  8217. }
  8218. if (hasConstructor) {
  8219. throwUnexpectedToken(token, Messages.DuplicateConstructor);
  8220. } else {
  8221. hasConstructor = true;
  8222. }
  8223. method.kind = 'constructor';
  8224. }
  8225. } else {
  8226. if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
  8227. throwUnexpectedToken(token, Messages.StaticPrototype);
  8228. }
  8229. }
  8230. method.type = Syntax.MethodDefinition;
  8231. delete method.method;
  8232. delete method.shorthand;
  8233. body.push(method);
  8234. } else {
  8235. throwUnexpectedToken(lookahead);
  8236. }
  8237. }
  8238. }
  8239. lex();
  8240. return classBody.finishClassBody(body);
  8241. }
  8242. function parseClassDeclaration(identifierIsOptional) {
  8243. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  8244. strict = true;
  8245. expectKeyword('class');
  8246. if (!identifierIsOptional || lookahead.type === Token.Identifier) {
  8247. id = parseVariableIdentifier();
  8248. }
  8249. if (matchKeyword('extends')) {
  8250. lex();
  8251. superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
  8252. }
  8253. classBody = parseClassBody();
  8254. strict = previousStrict;
  8255. return classNode.finishClassDeclaration(id, superClass, classBody);
  8256. }
  8257. function parseClassExpression() {
  8258. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  8259. strict = true;
  8260. expectKeyword('class');
  8261. if (lookahead.type === Token.Identifier) {
  8262. id = parseVariableIdentifier();
  8263. }
  8264. if (matchKeyword('extends')) {
  8265. lex();
  8266. superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
  8267. }
  8268. classBody = parseClassBody();
  8269. strict = previousStrict;
  8270. return classNode.finishClassExpression(id, superClass, classBody);
  8271. }
  8272. // ECMA-262 15.2 Modules
  8273. function parseModuleSpecifier() {
  8274. var node = new Node();
  8275. if (lookahead.type !== Token.StringLiteral) {
  8276. throwError(Messages.InvalidModuleSpecifier);
  8277. }
  8278. return node.finishLiteral(lex());
  8279. }
  8280. // ECMA-262 15.2.3 Exports
  8281. function parseExportSpecifier() {
  8282. var exported, local, node = new Node(), def;
  8283. if (matchKeyword('default')) {
  8284. // export {default} from 'something';
  8285. def = new Node();
  8286. lex();
  8287. local = def.finishIdentifier('default');
  8288. } else {
  8289. local = parseVariableIdentifier();
  8290. }
  8291. if (matchContextualKeyword('as')) {
  8292. lex();
  8293. exported = parseNonComputedProperty();
  8294. }
  8295. return node.finishExportSpecifier(local, exported);
  8296. }
  8297. function parseExportNamedDeclaration(node) {
  8298. var declaration = null,
  8299. isExportFromIdentifier,
  8300. src = null, specifiers = [];
  8301. // non-default export
  8302. if (lookahead.type === Token.Keyword) {
  8303. // covers:
  8304. // export var f = 1;
  8305. switch (lookahead.value) {
  8306. case 'let':
  8307. case 'const':
  8308. declaration = parseLexicalDeclaration({inFor: false});
  8309. return node.finishExportNamedDeclaration(declaration, specifiers, null);
  8310. case 'var':
  8311. case 'class':
  8312. case 'function':
  8313. declaration = parseStatementListItem();
  8314. return node.finishExportNamedDeclaration(declaration, specifiers, null);
  8315. }
  8316. }
  8317. expect('{');
  8318. while (!match('}')) {
  8319. isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
  8320. specifiers.push(parseExportSpecifier());
  8321. if (!match('}')) {
  8322. expect(',');
  8323. if (match('}')) {
  8324. break;
  8325. }
  8326. }
  8327. }
  8328. expect('}');
  8329. if (matchContextualKeyword('from')) {
  8330. // covering:
  8331. // export {default} from 'foo';
  8332. // export {foo} from 'foo';
  8333. lex();
  8334. src = parseModuleSpecifier();
  8335. consumeSemicolon();
  8336. } else if (isExportFromIdentifier) {
  8337. // covering:
  8338. // export {default}; // missing fromClause
  8339. throwError(lookahead.value ?
  8340. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8341. } else {
  8342. // cover
  8343. // export {foo};
  8344. consumeSemicolon();
  8345. }
  8346. return node.finishExportNamedDeclaration(declaration, specifiers, src);
  8347. }
  8348. function parseExportDefaultDeclaration(node) {
  8349. var declaration = null,
  8350. expression = null;
  8351. // covers:
  8352. // export default ...
  8353. expectKeyword('default');
  8354. if (matchKeyword('function')) {
  8355. // covers:
  8356. // export default function foo () {}
  8357. // export default function () {}
  8358. declaration = parseFunctionDeclaration(new Node(), true);
  8359. return node.finishExportDefaultDeclaration(declaration);
  8360. }
  8361. if (matchKeyword('class')) {
  8362. declaration = parseClassDeclaration(true);
  8363. return node.finishExportDefaultDeclaration(declaration);
  8364. }
  8365. if (matchContextualKeyword('from')) {
  8366. throwError(Messages.UnexpectedToken, lookahead.value);
  8367. }
  8368. // covers:
  8369. // export default {};
  8370. // export default [];
  8371. // export default (1 + 2);
  8372. if (match('{')) {
  8373. expression = parseObjectInitializer();
  8374. } else if (match('[')) {
  8375. expression = parseArrayInitializer();
  8376. } else {
  8377. expression = parseAssignmentExpression();
  8378. }
  8379. consumeSemicolon();
  8380. return node.finishExportDefaultDeclaration(expression);
  8381. }
  8382. function parseExportAllDeclaration(node) {
  8383. var src;
  8384. // covers:
  8385. // export * from 'foo';
  8386. expect('*');
  8387. if (!matchContextualKeyword('from')) {
  8388. throwError(lookahead.value ?
  8389. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8390. }
  8391. lex();
  8392. src = parseModuleSpecifier();
  8393. consumeSemicolon();
  8394. return node.finishExportAllDeclaration(src);
  8395. }
  8396. function parseExportDeclaration() {
  8397. var node = new Node();
  8398. if (state.inFunctionBody) {
  8399. throwError(Messages.IllegalExportDeclaration);
  8400. }
  8401. expectKeyword('export');
  8402. if (matchKeyword('default')) {
  8403. return parseExportDefaultDeclaration(node);
  8404. }
  8405. if (match('*')) {
  8406. return parseExportAllDeclaration(node);
  8407. }
  8408. return parseExportNamedDeclaration(node);
  8409. }
  8410. // ECMA-262 15.2.2 Imports
  8411. function parseImportSpecifier() {
  8412. // import {<foo as bar>} ...;
  8413. var local, imported, node = new Node();
  8414. imported = parseNonComputedProperty();
  8415. if (matchContextualKeyword('as')) {
  8416. lex();
  8417. local = parseVariableIdentifier();
  8418. }
  8419. return node.finishImportSpecifier(local, imported);
  8420. }
  8421. function parseNamedImports() {
  8422. var specifiers = [];
  8423. // {foo, bar as bas}
  8424. expect('{');
  8425. while (!match('}')) {
  8426. specifiers.push(parseImportSpecifier());
  8427. if (!match('}')) {
  8428. expect(',');
  8429. if (match('}')) {
  8430. break;
  8431. }
  8432. }
  8433. }
  8434. expect('}');
  8435. return specifiers;
  8436. }
  8437. function parseImportDefaultSpecifier() {
  8438. // import <foo> ...;
  8439. var local, node = new Node();
  8440. local = parseNonComputedProperty();
  8441. return node.finishImportDefaultSpecifier(local);
  8442. }
  8443. function parseImportNamespaceSpecifier() {
  8444. // import <* as foo> ...;
  8445. var local, node = new Node();
  8446. expect('*');
  8447. if (!matchContextualKeyword('as')) {
  8448. throwError(Messages.NoAsAfterImportNamespace);
  8449. }
  8450. lex();
  8451. local = parseNonComputedProperty();
  8452. return node.finishImportNamespaceSpecifier(local);
  8453. }
  8454. function parseImportDeclaration() {
  8455. var specifiers = [], src, node = new Node();
  8456. if (state.inFunctionBody) {
  8457. throwError(Messages.IllegalImportDeclaration);
  8458. }
  8459. expectKeyword('import');
  8460. if (lookahead.type === Token.StringLiteral) {
  8461. // import 'foo';
  8462. src = parseModuleSpecifier();
  8463. } else {
  8464. if (match('{')) {
  8465. // import {bar}
  8466. specifiers = specifiers.concat(parseNamedImports());
  8467. } else if (match('*')) {
  8468. // import * as foo
  8469. specifiers.push(parseImportNamespaceSpecifier());
  8470. } else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
  8471. // import foo
  8472. specifiers.push(parseImportDefaultSpecifier());
  8473. if (match(',')) {
  8474. lex();
  8475. if (match('*')) {
  8476. // import foo, * as foo
  8477. specifiers.push(parseImportNamespaceSpecifier());
  8478. } else if (match('{')) {
  8479. // import foo, {bar}
  8480. specifiers = specifiers.concat(parseNamedImports());
  8481. } else {
  8482. throwUnexpectedToken(lookahead);
  8483. }
  8484. }
  8485. } else {
  8486. throwUnexpectedToken(lex());
  8487. }
  8488. if (!matchContextualKeyword('from')) {
  8489. throwError(lookahead.value ?
  8490. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8491. }
  8492. lex();
  8493. src = parseModuleSpecifier();
  8494. }
  8495. consumeSemicolon();
  8496. return node.finishImportDeclaration(specifiers, src);
  8497. }
  8498. // ECMA-262 15.1 Scripts
  8499. function parseScriptBody() {
  8500. var statement, body = [], token, directive, firstRestricted;
  8501. while (startIndex < length) {
  8502. token = lookahead;
  8503. if (token.type !== Token.StringLiteral) {
  8504. break;
  8505. }
  8506. statement = parseStatementListItem();
  8507. body.push(statement);
  8508. if (statement.expression.type !== Syntax.Literal) {
  8509. // this is not directive
  8510. break;
  8511. }
  8512. directive = source.slice(token.start + 1, token.end - 1);
  8513. if (directive === 'use strict') {
  8514. strict = true;
  8515. if (firstRestricted) {
  8516. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  8517. }
  8518. } else {
  8519. if (!firstRestricted && token.octal) {
  8520. firstRestricted = token;
  8521. }
  8522. }
  8523. }
  8524. while (startIndex < length) {
  8525. statement = parseStatementListItem();
  8526. /* istanbul ignore if */
  8527. if (typeof statement === 'undefined') {
  8528. break;
  8529. }
  8530. body.push(statement);
  8531. }
  8532. return body;
  8533. }
  8534. function parseProgram() {
  8535. var body, node;
  8536. peek();
  8537. node = new Node();
  8538. body = parseScriptBody();
  8539. return node.finishProgram(body, state.sourceType);
  8540. }
  8541. function filterTokenLocation() {
  8542. var i, entry, token, tokens = [];
  8543. for (i = 0; i < extra.tokens.length; ++i) {
  8544. entry = extra.tokens[i];
  8545. token = {
  8546. type: entry.type,
  8547. value: entry.value
  8548. };
  8549. if (entry.regex) {
  8550. token.regex = {
  8551. pattern: entry.regex.pattern,
  8552. flags: entry.regex.flags
  8553. };
  8554. }
  8555. if (extra.range) {
  8556. token.range = entry.range;
  8557. }
  8558. if (extra.loc) {
  8559. token.loc = entry.loc;
  8560. }
  8561. tokens.push(token);
  8562. }
  8563. extra.tokens = tokens;
  8564. }
  8565. function tokenize(code, options, delegate) {
  8566. var toString,
  8567. tokens;
  8568. toString = String;
  8569. if (typeof code !== 'string' && !(code instanceof String)) {
  8570. code = toString(code);
  8571. }
  8572. source = code;
  8573. index = 0;
  8574. lineNumber = (source.length > 0) ? 1 : 0;
  8575. lineStart = 0;
  8576. startIndex = index;
  8577. startLineNumber = lineNumber;
  8578. startLineStart = lineStart;
  8579. length = source.length;
  8580. lookahead = null;
  8581. state = {
  8582. allowIn: true,
  8583. allowYield: true,
  8584. labelSet: {},
  8585. inFunctionBody: false,
  8586. inIteration: false,
  8587. inSwitch: false,
  8588. lastCommentStart: -1,
  8589. curlyStack: []
  8590. };
  8591. extra = {};
  8592. // Options matching.
  8593. options = options || {};
  8594. // Of course we collect tokens here.
  8595. options.tokens = true;
  8596. extra.tokens = [];
  8597. extra.tokenValues = [];
  8598. extra.tokenize = true;
  8599. extra.delegate = delegate;
  8600. // The following two fields are necessary to compute the Regex tokens.
  8601. extra.openParenToken = -1;
  8602. extra.openCurlyToken = -1;
  8603. extra.range = (typeof options.range === 'boolean') && options.range;
  8604. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  8605. if (typeof options.comment === 'boolean' && options.comment) {
  8606. extra.comments = [];
  8607. }
  8608. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  8609. extra.errors = [];
  8610. }
  8611. try {
  8612. peek();
  8613. if (lookahead.type === Token.EOF) {
  8614. return extra.tokens;
  8615. }
  8616. lex();
  8617. while (lookahead.type !== Token.EOF) {
  8618. try {
  8619. lex();
  8620. } catch (lexError) {
  8621. if (extra.errors) {
  8622. recordError(lexError);
  8623. // We have to break on the first error
  8624. // to avoid infinite loops.
  8625. break;
  8626. } else {
  8627. throw lexError;
  8628. }
  8629. }
  8630. }
  8631. tokens = extra.tokens;
  8632. if (typeof extra.errors !== 'undefined') {
  8633. tokens.errors = extra.errors;
  8634. }
  8635. } catch (e) {
  8636. throw e;
  8637. } finally {
  8638. extra = {};
  8639. }
  8640. return tokens;
  8641. }
  8642. function parse(code, options) {
  8643. var program, toString;
  8644. toString = String;
  8645. if (typeof code !== 'string' && !(code instanceof String)) {
  8646. code = toString(code);
  8647. }
  8648. source = code;
  8649. index = 0;
  8650. lineNumber = (source.length > 0) ? 1 : 0;
  8651. lineStart = 0;
  8652. startIndex = index;
  8653. startLineNumber = lineNumber;
  8654. startLineStart = lineStart;
  8655. length = source.length;
  8656. lookahead = null;
  8657. state = {
  8658. allowIn: true,
  8659. allowYield: true,
  8660. labelSet: {},
  8661. inFunctionBody: false,
  8662. inIteration: false,
  8663. inSwitch: false,
  8664. lastCommentStart: -1,
  8665. curlyStack: [],
  8666. sourceType: 'script'
  8667. };
  8668. strict = false;
  8669. extra = {};
  8670. if (typeof options !== 'undefined') {
  8671. extra.range = (typeof options.range === 'boolean') && options.range;
  8672. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  8673. extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
  8674. if (extra.loc && options.source !== null && options.source !== undefined) {
  8675. extra.source = toString(options.source);
  8676. }
  8677. if (typeof options.tokens === 'boolean' && options.tokens) {
  8678. extra.tokens = [];
  8679. }
  8680. if (typeof options.comment === 'boolean' && options.comment) {
  8681. extra.comments = [];
  8682. }
  8683. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  8684. extra.errors = [];
  8685. }
  8686. if (extra.attachComment) {
  8687. extra.range = true;
  8688. extra.comments = [];
  8689. extra.bottomRightStack = [];
  8690. extra.trailingComments = [];
  8691. extra.leadingComments = [];
  8692. }
  8693. if (options.sourceType === 'module') {
  8694. // very restrictive condition for now
  8695. state.sourceType = options.sourceType;
  8696. strict = true;
  8697. }
  8698. }
  8699. try {
  8700. program = parseProgram();
  8701. if (typeof extra.comments !== 'undefined') {
  8702. program.comments = extra.comments;
  8703. }
  8704. if (typeof extra.tokens !== 'undefined') {
  8705. filterTokenLocation();
  8706. program.tokens = extra.tokens;
  8707. }
  8708. if (typeof extra.errors !== 'undefined') {
  8709. program.errors = extra.errors;
  8710. }
  8711. } catch (e) {
  8712. throw e;
  8713. } finally {
  8714. extra = {};
  8715. }
  8716. return program;
  8717. }
  8718. // Sync with *.json manifests.
  8719. exports.version = '2.7.0';
  8720. exports.tokenize = tokenize;
  8721. exports.parse = parse;
  8722. // Deep copy.
  8723. /* istanbul ignore next */
  8724. exports.Syntax = (function () {
  8725. var name, types = {};
  8726. if (typeof Object.create === 'function') {
  8727. types = Object.create(null);
  8728. }
  8729. for (name in Syntax) {
  8730. if (Syntax.hasOwnProperty(name)) {
  8731. types[name] = Syntax[name];
  8732. }
  8733. }
  8734. if (typeof Object.freeze === 'function') {
  8735. Object.freeze(types);
  8736. }
  8737. return types;
  8738. }());
  8739. }));
  8740. /* vim: set sw=4 ts=4 et tw=80 : */
  8741. /**
  8742. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  8743. * Available via the MIT or new BSD license.
  8744. * see: http://github.com/jrburke/requirejs for details
  8745. */
  8746. /*global define, Reflect */
  8747. /*
  8748. * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
  8749. * and the recursive nature of esprima can cause it to overflow pretty
  8750. * quickly. So favor it built in Reflect parser:
  8751. * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  8752. */
  8753. define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
  8754. if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
  8755. return Reflect;
  8756. } else {
  8757. return esprima;
  8758. }
  8759. });
  8760. (function webpackUniversalModuleDefinition(root, factory) {
  8761. var exports, module;
  8762. if(typeof exports === 'object' && typeof module === 'object')
  8763. module.exports = factory();
  8764. else if(typeof define === 'function' && define.amd)
  8765. define('source-map', [], factory);
  8766. else if(typeof exports === 'object')
  8767. exports["sourceMap"] = factory();
  8768. else
  8769. root["sourceMap"] = factory();
  8770. })(this, function() {
  8771. return /******/ (function(modules) { // webpackBootstrap
  8772. /******/ // The module cache
  8773. /******/ var installedModules = {};
  8774. /******/ // The require function
  8775. /******/ function __webpack_require__(moduleId) {
  8776. /******/ // Check if module is in cache
  8777. /******/ if(installedModules[moduleId])
  8778. /******/ return installedModules[moduleId].exports;
  8779. /******/ // Create a new module (and put it into the cache)
  8780. /******/ var module = installedModules[moduleId] = {
  8781. /******/ exports: {},
  8782. /******/ id: moduleId,
  8783. /******/ loaded: false
  8784. /******/ };
  8785. /******/ // Execute the module function
  8786. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8787. /******/ // Flag the module as loaded
  8788. /******/ module.loaded = true;
  8789. /******/ // Return the exports of the module
  8790. /******/ return module.exports;
  8791. /******/ }
  8792. /******/ // expose the modules object (__webpack_modules__)
  8793. /******/ __webpack_require__.m = modules;
  8794. /******/ // expose the module cache
  8795. /******/ __webpack_require__.c = installedModules;
  8796. /******/ // __webpack_public_path__
  8797. /******/ __webpack_require__.p = "";
  8798. /******/ // Load entry module and return exports
  8799. /******/ return __webpack_require__(0);
  8800. /******/ })
  8801. /************************************************************************/
  8802. /******/ ([
  8803. /* 0 */
  8804. /***/ function(module, exports, __webpack_require__) {
  8805. /*
  8806. * Copyright 2009-2011 Mozilla Foundation and contributors
  8807. * Licensed under the New BSD license. See LICENSE.txt or:
  8808. * http://opensource.org/licenses/BSD-3-Clause
  8809. */
  8810. exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  8811. exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer;
  8812. exports.SourceNode = __webpack_require__(10).SourceNode;
  8813. /***/ },
  8814. /* 1 */
  8815. /***/ function(module, exports, __webpack_require__) {
  8816. /* -*- Mode: js; js-indent-level: 2; -*- */
  8817. /*
  8818. * Copyright 2011 Mozilla Foundation and contributors
  8819. * Licensed under the New BSD license. See LICENSE or:
  8820. * http://opensource.org/licenses/BSD-3-Clause
  8821. */
  8822. {
  8823. var base64VLQ = __webpack_require__(2);
  8824. var util = __webpack_require__(4);
  8825. var ArraySet = __webpack_require__(5).ArraySet;
  8826. var MappingList = __webpack_require__(6).MappingList;
  8827. /**
  8828. * An instance of the SourceMapGenerator represents a source map which is
  8829. * being built incrementally. You may pass an object with the following
  8830. * properties:
  8831. *
  8832. * - file: The filename of the generated source.
  8833. * - sourceRoot: A root for all relative URLs in this source map.
  8834. */
  8835. function SourceMapGenerator(aArgs) {
  8836. if (!aArgs) {
  8837. aArgs = {};
  8838. }
  8839. this._file = util.getArg(aArgs, 'file', null);
  8840. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8841. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8842. this._sources = new ArraySet();
  8843. this._names = new ArraySet();
  8844. this._mappings = new MappingList();
  8845. this._sourcesContents = null;
  8846. }
  8847. SourceMapGenerator.prototype._version = 3;
  8848. /**
  8849. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8850. *
  8851. * @param aSourceMapConsumer The SourceMap.
  8852. */
  8853. SourceMapGenerator.fromSourceMap =
  8854. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8855. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8856. var generator = new SourceMapGenerator({
  8857. file: aSourceMapConsumer.file,
  8858. sourceRoot: sourceRoot
  8859. });
  8860. aSourceMapConsumer.eachMapping(function (mapping) {
  8861. var newMapping = {
  8862. generated: {
  8863. line: mapping.generatedLine,
  8864. column: mapping.generatedColumn
  8865. }
  8866. };
  8867. if (mapping.source != null) {
  8868. newMapping.source = mapping.source;
  8869. if (sourceRoot != null) {
  8870. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8871. }
  8872. newMapping.original = {
  8873. line: mapping.originalLine,
  8874. column: mapping.originalColumn
  8875. };
  8876. if (mapping.name != null) {
  8877. newMapping.name = mapping.name;
  8878. }
  8879. }
  8880. generator.addMapping(newMapping);
  8881. });
  8882. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8883. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8884. if (content != null) {
  8885. generator.setSourceContent(sourceFile, content);
  8886. }
  8887. });
  8888. return generator;
  8889. };
  8890. /**
  8891. * Add a single mapping from original source line and column to the generated
  8892. * source's line and column for this source map being created. The mapping
  8893. * object should have the following properties:
  8894. *
  8895. * - generated: An object with the generated line and column positions.
  8896. * - original: An object with the original line and column positions.
  8897. * - source: The original source file (relative to the sourceRoot).
  8898. * - name: An optional original token name for this mapping.
  8899. */
  8900. SourceMapGenerator.prototype.addMapping =
  8901. function SourceMapGenerator_addMapping(aArgs) {
  8902. var generated = util.getArg(aArgs, 'generated');
  8903. var original = util.getArg(aArgs, 'original', null);
  8904. var source = util.getArg(aArgs, 'source', null);
  8905. var name = util.getArg(aArgs, 'name', null);
  8906. if (!this._skipValidation) {
  8907. this._validateMapping(generated, original, source, name);
  8908. }
  8909. if (source != null && !this._sources.has(source)) {
  8910. this._sources.add(source);
  8911. }
  8912. if (name != null && !this._names.has(name)) {
  8913. this._names.add(name);
  8914. }
  8915. this._mappings.add({
  8916. generatedLine: generated.line,
  8917. generatedColumn: generated.column,
  8918. originalLine: original != null && original.line,
  8919. originalColumn: original != null && original.column,
  8920. source: source,
  8921. name: name
  8922. });
  8923. };
  8924. /**
  8925. * Set the source content for a source file.
  8926. */
  8927. SourceMapGenerator.prototype.setSourceContent =
  8928. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8929. var source = aSourceFile;
  8930. if (this._sourceRoot != null) {
  8931. source = util.relative(this._sourceRoot, source);
  8932. }
  8933. if (aSourceContent != null) {
  8934. // Add the source content to the _sourcesContents map.
  8935. // Create a new _sourcesContents map if the property is null.
  8936. if (!this._sourcesContents) {
  8937. this._sourcesContents = {};
  8938. }
  8939. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8940. } else if (this._sourcesContents) {
  8941. // Remove the source file from the _sourcesContents map.
  8942. // If the _sourcesContents map is empty, set the property to null.
  8943. delete this._sourcesContents[util.toSetString(source)];
  8944. if (Object.keys(this._sourcesContents).length === 0) {
  8945. this._sourcesContents = null;
  8946. }
  8947. }
  8948. };
  8949. /**
  8950. * Applies the mappings of a sub-source-map for a specific source file to the
  8951. * source map being generated. Each mapping to the supplied source file is
  8952. * rewritten using the supplied source map. Note: The resolution for the
  8953. * resulting mappings is the minimium of this map and the supplied map.
  8954. *
  8955. * @param aSourceMapConsumer The source map to be applied.
  8956. * @param aSourceFile Optional. The filename of the source file.
  8957. * If omitted, SourceMapConsumer's file property will be used.
  8958. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8959. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8960. * This parameter is needed when the two source maps aren't in the same
  8961. * directory, and the source map to be applied contains relative source
  8962. * paths. If so, those relative source paths need to be rewritten
  8963. * relative to the SourceMapGenerator.
  8964. */
  8965. SourceMapGenerator.prototype.applySourceMap =
  8966. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8967. var sourceFile = aSourceFile;
  8968. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8969. if (aSourceFile == null) {
  8970. if (aSourceMapConsumer.file == null) {
  8971. throw new Error(
  8972. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8973. 'or the source map\'s "file" property. Both were omitted.'
  8974. );
  8975. }
  8976. sourceFile = aSourceMapConsumer.file;
  8977. }
  8978. var sourceRoot = this._sourceRoot;
  8979. // Make "sourceFile" relative if an absolute Url is passed.
  8980. if (sourceRoot != null) {
  8981. sourceFile = util.relative(sourceRoot, sourceFile);
  8982. }
  8983. // Applying the SourceMap can add and remove items from the sources and
  8984. // the names array.
  8985. var newSources = new ArraySet();
  8986. var newNames = new ArraySet();
  8987. // Find mappings for the "sourceFile"
  8988. this._mappings.unsortedForEach(function (mapping) {
  8989. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8990. // Check if it can be mapped by the source map, then update the mapping.
  8991. var original = aSourceMapConsumer.originalPositionFor({
  8992. line: mapping.originalLine,
  8993. column: mapping.originalColumn
  8994. });
  8995. if (original.source != null) {
  8996. // Copy mapping
  8997. mapping.source = original.source;
  8998. if (aSourceMapPath != null) {
  8999. mapping.source = util.join(aSourceMapPath, mapping.source)
  9000. }
  9001. if (sourceRoot != null) {
  9002. mapping.source = util.relative(sourceRoot, mapping.source);
  9003. }
  9004. mapping.originalLine = original.line;
  9005. mapping.originalColumn = original.column;
  9006. if (original.name != null) {
  9007. mapping.name = original.name;
  9008. }
  9009. }
  9010. }
  9011. var source = mapping.source;
  9012. if (source != null && !newSources.has(source)) {
  9013. newSources.add(source);
  9014. }
  9015. var name = mapping.name;
  9016. if (name != null && !newNames.has(name)) {
  9017. newNames.add(name);
  9018. }
  9019. }, this);
  9020. this._sources = newSources;
  9021. this._names = newNames;
  9022. // Copy sourcesContents of applied map.
  9023. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  9024. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  9025. if (content != null) {
  9026. if (aSourceMapPath != null) {
  9027. sourceFile = util.join(aSourceMapPath, sourceFile);
  9028. }
  9029. if (sourceRoot != null) {
  9030. sourceFile = util.relative(sourceRoot, sourceFile);
  9031. }
  9032. this.setSourceContent(sourceFile, content);
  9033. }
  9034. }, this);
  9035. };
  9036. /**
  9037. * A mapping can have one of the three levels of data:
  9038. *
  9039. * 1. Just the generated position.
  9040. * 2. The Generated position, original position, and original source.
  9041. * 3. Generated and original position, original source, as well as a name
  9042. * token.
  9043. *
  9044. * To maintain consistency, we validate that any new mapping being added falls
  9045. * in to one of these categories.
  9046. */
  9047. SourceMapGenerator.prototype._validateMapping =
  9048. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  9049. aName) {
  9050. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  9051. && aGenerated.line > 0 && aGenerated.column >= 0
  9052. && !aOriginal && !aSource && !aName) {
  9053. // Case 1.
  9054. return;
  9055. }
  9056. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  9057. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  9058. && aGenerated.line > 0 && aGenerated.column >= 0
  9059. && aOriginal.line > 0 && aOriginal.column >= 0
  9060. && aSource) {
  9061. // Cases 2 and 3.
  9062. return;
  9063. }
  9064. else {
  9065. throw new Error('Invalid mapping: ' + JSON.stringify({
  9066. generated: aGenerated,
  9067. source: aSource,
  9068. original: aOriginal,
  9069. name: aName
  9070. }));
  9071. }
  9072. };
  9073. /**
  9074. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  9075. * specified by the source map format.
  9076. */
  9077. SourceMapGenerator.prototype._serializeMappings =
  9078. function SourceMapGenerator_serializeMappings() {
  9079. var previousGeneratedColumn = 0;
  9080. var previousGeneratedLine = 1;
  9081. var previousOriginalColumn = 0;
  9082. var previousOriginalLine = 0;
  9083. var previousName = 0;
  9084. var previousSource = 0;
  9085. var result = '';
  9086. var mapping;
  9087. var nameIdx;
  9088. var sourceIdx;
  9089. var mappings = this._mappings.toArray();
  9090. for (var i = 0, len = mappings.length; i < len; i++) {
  9091. mapping = mappings[i];
  9092. if (mapping.generatedLine !== previousGeneratedLine) {
  9093. previousGeneratedColumn = 0;
  9094. while (mapping.generatedLine !== previousGeneratedLine) {
  9095. result += ';';
  9096. previousGeneratedLine++;
  9097. }
  9098. }
  9099. else {
  9100. if (i > 0) {
  9101. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  9102. continue;
  9103. }
  9104. result += ',';
  9105. }
  9106. }
  9107. result += base64VLQ.encode(mapping.generatedColumn
  9108. - previousGeneratedColumn);
  9109. previousGeneratedColumn = mapping.generatedColumn;
  9110. if (mapping.source != null) {
  9111. sourceIdx = this._sources.indexOf(mapping.source);
  9112. result += base64VLQ.encode(sourceIdx - previousSource);
  9113. previousSource = sourceIdx;
  9114. // lines are stored 0-based in SourceMap spec version 3
  9115. result += base64VLQ.encode(mapping.originalLine - 1
  9116. - previousOriginalLine);
  9117. previousOriginalLine = mapping.originalLine - 1;
  9118. result += base64VLQ.encode(mapping.originalColumn
  9119. - previousOriginalColumn);
  9120. previousOriginalColumn = mapping.originalColumn;
  9121. if (mapping.name != null) {
  9122. nameIdx = this._names.indexOf(mapping.name);
  9123. result += base64VLQ.encode(nameIdx - previousName);
  9124. previousName = nameIdx;
  9125. }
  9126. }
  9127. }
  9128. return result;
  9129. };
  9130. SourceMapGenerator.prototype._generateSourcesContent =
  9131. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9132. return aSources.map(function (source) {
  9133. if (!this._sourcesContents) {
  9134. return null;
  9135. }
  9136. if (aSourceRoot != null) {
  9137. source = util.relative(aSourceRoot, source);
  9138. }
  9139. var key = util.toSetString(source);
  9140. return Object.prototype.hasOwnProperty.call(this._sourcesContents,
  9141. key)
  9142. ? this._sourcesContents[key]
  9143. : null;
  9144. }, this);
  9145. };
  9146. /**
  9147. * Externalize the source map.
  9148. */
  9149. SourceMapGenerator.prototype.toJSON =
  9150. function SourceMapGenerator_toJSON() {
  9151. var map = {
  9152. version: this._version,
  9153. sources: this._sources.toArray(),
  9154. names: this._names.toArray(),
  9155. mappings: this._serializeMappings()
  9156. };
  9157. if (this._file != null) {
  9158. map.file = this._file;
  9159. }
  9160. if (this._sourceRoot != null) {
  9161. map.sourceRoot = this._sourceRoot;
  9162. }
  9163. if (this._sourcesContents) {
  9164. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9165. }
  9166. return map;
  9167. };
  9168. /**
  9169. * Render the source map being generated to a string.
  9170. */
  9171. SourceMapGenerator.prototype.toString =
  9172. function SourceMapGenerator_toString() {
  9173. return JSON.stringify(this.toJSON());
  9174. };
  9175. exports.SourceMapGenerator = SourceMapGenerator;
  9176. }
  9177. /***/ },
  9178. /* 2 */
  9179. /***/ function(module, exports, __webpack_require__) {
  9180. /* -*- Mode: js; js-indent-level: 2; -*- */
  9181. /*
  9182. * Copyright 2011 Mozilla Foundation and contributors
  9183. * Licensed under the New BSD license. See LICENSE or:
  9184. * http://opensource.org/licenses/BSD-3-Clause
  9185. *
  9186. * Based on the Base 64 VLQ implementation in Closure Compiler:
  9187. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  9188. *
  9189. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  9190. * Redistribution and use in source and binary forms, with or without
  9191. * modification, are permitted provided that the following conditions are
  9192. * met:
  9193. *
  9194. * * Redistributions of source code must retain the above copyright
  9195. * notice, this list of conditions and the following disclaimer.
  9196. * * Redistributions in binary form must reproduce the above
  9197. * copyright notice, this list of conditions and the following
  9198. * disclaimer in the documentation and/or other materials provided
  9199. * with the distribution.
  9200. * * Neither the name of Google Inc. nor the names of its
  9201. * contributors may be used to endorse or promote products derived
  9202. * from this software without specific prior written permission.
  9203. *
  9204. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9205. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9206. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9207. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9208. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9209. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9210. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9211. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9212. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9213. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9214. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9215. */
  9216. {
  9217. var base64 = __webpack_require__(3);
  9218. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  9219. // length quantities we use in the source map spec, the first bit is the sign,
  9220. // the next four bits are the actual value, and the 6th bit is the
  9221. // continuation bit. The continuation bit tells us whether there are more
  9222. // digits in this value following this digit.
  9223. //
  9224. // Continuation
  9225. // | Sign
  9226. // | |
  9227. // V V
  9228. // 101011
  9229. var VLQ_BASE_SHIFT = 5;
  9230. // binary: 100000
  9231. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  9232. // binary: 011111
  9233. var VLQ_BASE_MASK = VLQ_BASE - 1;
  9234. // binary: 100000
  9235. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  9236. /**
  9237. * Converts from a two-complement value to a value where the sign bit is
  9238. * placed in the least significant bit. For example, as decimals:
  9239. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  9240. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  9241. */
  9242. function toVLQSigned(aValue) {
  9243. return aValue < 0
  9244. ? ((-aValue) << 1) + 1
  9245. : (aValue << 1) + 0;
  9246. }
  9247. /**
  9248. * Converts to a two-complement value from a value where the sign bit is
  9249. * placed in the least significant bit. For example, as decimals:
  9250. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  9251. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  9252. */
  9253. function fromVLQSigned(aValue) {
  9254. var isNegative = (aValue & 1) === 1;
  9255. var shifted = aValue >> 1;
  9256. return isNegative
  9257. ? -shifted
  9258. : shifted;
  9259. }
  9260. /**
  9261. * Returns the base 64 VLQ encoded value.
  9262. */
  9263. exports.encode = function base64VLQ_encode(aValue) {
  9264. var encoded = "";
  9265. var digit;
  9266. var vlq = toVLQSigned(aValue);
  9267. do {
  9268. digit = vlq & VLQ_BASE_MASK;
  9269. vlq >>>= VLQ_BASE_SHIFT;
  9270. if (vlq > 0) {
  9271. // There are still more digits in this value, so we must make sure the
  9272. // continuation bit is marked.
  9273. digit |= VLQ_CONTINUATION_BIT;
  9274. }
  9275. encoded += base64.encode(digit);
  9276. } while (vlq > 0);
  9277. return encoded;
  9278. };
  9279. /**
  9280. * Decodes the next base 64 VLQ value from the given string and returns the
  9281. * value and the rest of the string via the out parameter.
  9282. */
  9283. exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  9284. var strLen = aStr.length;
  9285. var result = 0;
  9286. var shift = 0;
  9287. var continuation, digit;
  9288. do {
  9289. if (aIndex >= strLen) {
  9290. throw new Error("Expected more digits in base 64 VLQ value.");
  9291. }
  9292. digit = base64.decode(aStr.charCodeAt(aIndex++));
  9293. if (digit === -1) {
  9294. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  9295. }
  9296. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  9297. digit &= VLQ_BASE_MASK;
  9298. result = result + (digit << shift);
  9299. shift += VLQ_BASE_SHIFT;
  9300. } while (continuation);
  9301. aOutParam.value = fromVLQSigned(result);
  9302. aOutParam.rest = aIndex;
  9303. };
  9304. }
  9305. /***/ },
  9306. /* 3 */
  9307. /***/ function(module, exports) {
  9308. /* -*- Mode: js; js-indent-level: 2; -*- */
  9309. /*
  9310. * Copyright 2011 Mozilla Foundation and contributors
  9311. * Licensed under the New BSD license. See LICENSE or:
  9312. * http://opensource.org/licenses/BSD-3-Clause
  9313. */
  9314. {
  9315. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  9316. /**
  9317. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  9318. */
  9319. exports.encode = function (number) {
  9320. if (0 <= number && number < intToCharMap.length) {
  9321. return intToCharMap[number];
  9322. }
  9323. throw new TypeError("Must be between 0 and 63: " + number);
  9324. };
  9325. /**
  9326. * Decode a single base 64 character code digit to an integer. Returns -1 on
  9327. * failure.
  9328. */
  9329. exports.decode = function (charCode) {
  9330. var bigA = 65; // 'A'
  9331. var bigZ = 90; // 'Z'
  9332. var littleA = 97; // 'a'
  9333. var littleZ = 122; // 'z'
  9334. var zero = 48; // '0'
  9335. var nine = 57; // '9'
  9336. var plus = 43; // '+'
  9337. var slash = 47; // '/'
  9338. var littleOffset = 26;
  9339. var numberOffset = 52;
  9340. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  9341. if (bigA <= charCode && charCode <= bigZ) {
  9342. return (charCode - bigA);
  9343. }
  9344. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  9345. if (littleA <= charCode && charCode <= littleZ) {
  9346. return (charCode - littleA + littleOffset);
  9347. }
  9348. // 52 - 61: 0123456789
  9349. if (zero <= charCode && charCode <= nine) {
  9350. return (charCode - zero + numberOffset);
  9351. }
  9352. // 62: +
  9353. if (charCode == plus) {
  9354. return 62;
  9355. }
  9356. // 63: /
  9357. if (charCode == slash) {
  9358. return 63;
  9359. }
  9360. // Invalid base64 digit.
  9361. return -1;
  9362. };
  9363. }
  9364. /***/ },
  9365. /* 4 */
  9366. /***/ function(module, exports) {
  9367. /* -*- Mode: js; js-indent-level: 2; -*- */
  9368. /*
  9369. * Copyright 2011 Mozilla Foundation and contributors
  9370. * Licensed under the New BSD license. See LICENSE or:
  9371. * http://opensource.org/licenses/BSD-3-Clause
  9372. */
  9373. {
  9374. /**
  9375. * This is a helper function for getting values from parameter/options
  9376. * objects.
  9377. *
  9378. * @param args The object we are extracting values from
  9379. * @param name The name of the property we are getting.
  9380. * @param defaultValue An optional value to return if the property is missing
  9381. * from the object. If this is not specified and the property is missing, an
  9382. * error will be thrown.
  9383. */
  9384. function getArg(aArgs, aName, aDefaultValue) {
  9385. if (aName in aArgs) {
  9386. return aArgs[aName];
  9387. } else if (arguments.length === 3) {
  9388. return aDefaultValue;
  9389. } else {
  9390. throw new Error('"' + aName + '" is a required argument.');
  9391. }
  9392. }
  9393. exports.getArg = getArg;
  9394. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  9395. var dataUrlRegexp = /^data:.+\,.+$/;
  9396. function urlParse(aUrl) {
  9397. var match = aUrl.match(urlRegexp);
  9398. if (!match) {
  9399. return null;
  9400. }
  9401. return {
  9402. scheme: match[1],
  9403. auth: match[2],
  9404. host: match[3],
  9405. port: match[4],
  9406. path: match[5]
  9407. };
  9408. }
  9409. exports.urlParse = urlParse;
  9410. function urlGenerate(aParsedUrl) {
  9411. var url = '';
  9412. if (aParsedUrl.scheme) {
  9413. url += aParsedUrl.scheme + ':';
  9414. }
  9415. url += '//';
  9416. if (aParsedUrl.auth) {
  9417. url += aParsedUrl.auth + '@';
  9418. }
  9419. if (aParsedUrl.host) {
  9420. url += aParsedUrl.host;
  9421. }
  9422. if (aParsedUrl.port) {
  9423. url += ":" + aParsedUrl.port
  9424. }
  9425. if (aParsedUrl.path) {
  9426. url += aParsedUrl.path;
  9427. }
  9428. return url;
  9429. }
  9430. exports.urlGenerate = urlGenerate;
  9431. /**
  9432. * Normalizes a path, or the path portion of a URL:
  9433. *
  9434. * - Replaces consequtive slashes with one slash.
  9435. * - Removes unnecessary '.' parts.
  9436. * - Removes unnecessary '<dir>/..' parts.
  9437. *
  9438. * Based on code in the Node.js 'path' core module.
  9439. *
  9440. * @param aPath The path or url to normalize.
  9441. */
  9442. function normalize(aPath) {
  9443. var path = aPath;
  9444. var url = urlParse(aPath);
  9445. if (url) {
  9446. if (!url.path) {
  9447. return aPath;
  9448. }
  9449. path = url.path;
  9450. }
  9451. var isAbsolute = exports.isAbsolute(path);
  9452. var parts = path.split(/\/+/);
  9453. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  9454. part = parts[i];
  9455. if (part === '.') {
  9456. parts.splice(i, 1);
  9457. } else if (part === '..') {
  9458. up++;
  9459. } else if (up > 0) {
  9460. if (part === '') {
  9461. // The first part is blank if the path is absolute. Trying to go
  9462. // above the root is a no-op. Therefore we can remove all '..' parts
  9463. // directly after the root.
  9464. parts.splice(i + 1, up);
  9465. up = 0;
  9466. } else {
  9467. parts.splice(i, 2);
  9468. up--;
  9469. }
  9470. }
  9471. }
  9472. path = parts.join('/');
  9473. if (path === '') {
  9474. path = isAbsolute ? '/' : '.';
  9475. }
  9476. if (url) {
  9477. url.path = path;
  9478. return urlGenerate(url);
  9479. }
  9480. return path;
  9481. }
  9482. exports.normalize = normalize;
  9483. /**
  9484. * Joins two paths/URLs.
  9485. *
  9486. * @param aRoot The root path or URL.
  9487. * @param aPath The path or URL to be joined with the root.
  9488. *
  9489. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  9490. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  9491. * first.
  9492. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  9493. * is updated with the result and aRoot is returned. Otherwise the result
  9494. * is returned.
  9495. * - If aPath is absolute, the result is aPath.
  9496. * - Otherwise the two paths are joined with a slash.
  9497. * - Joining for example 'http://' and 'www.example.com' is also supported.
  9498. */
  9499. function join(aRoot, aPath) {
  9500. if (aRoot === "") {
  9501. aRoot = ".";
  9502. }
  9503. if (aPath === "") {
  9504. aPath = ".";
  9505. }
  9506. var aPathUrl = urlParse(aPath);
  9507. var aRootUrl = urlParse(aRoot);
  9508. if (aRootUrl) {
  9509. aRoot = aRootUrl.path || '/';
  9510. }
  9511. // `join(foo, '//www.example.org')`
  9512. if (aPathUrl && !aPathUrl.scheme) {
  9513. if (aRootUrl) {
  9514. aPathUrl.scheme = aRootUrl.scheme;
  9515. }
  9516. return urlGenerate(aPathUrl);
  9517. }
  9518. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  9519. return aPath;
  9520. }
  9521. // `join('http://', 'www.example.com')`
  9522. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  9523. aRootUrl.host = aPath;
  9524. return urlGenerate(aRootUrl);
  9525. }
  9526. var joined = aPath.charAt(0) === '/'
  9527. ? aPath
  9528. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  9529. if (aRootUrl) {
  9530. aRootUrl.path = joined;
  9531. return urlGenerate(aRootUrl);
  9532. }
  9533. return joined;
  9534. }
  9535. exports.join = join;
  9536. exports.isAbsolute = function (aPath) {
  9537. return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
  9538. };
  9539. /**
  9540. * Make a path relative to a URL or another path.
  9541. *
  9542. * @param aRoot The root path or URL.
  9543. * @param aPath The path or URL to be made relative to aRoot.
  9544. */
  9545. function relative(aRoot, aPath) {
  9546. if (aRoot === "") {
  9547. aRoot = ".";
  9548. }
  9549. aRoot = aRoot.replace(/\/$/, '');
  9550. // It is possible for the path to be above the root. In this case, simply
  9551. // checking whether the root is a prefix of the path won't work. Instead, we
  9552. // need to remove components from the root one by one, until either we find
  9553. // a prefix that fits, or we run out of components to remove.
  9554. var level = 0;
  9555. while (aPath.indexOf(aRoot + '/') !== 0) {
  9556. var index = aRoot.lastIndexOf("/");
  9557. if (index < 0) {
  9558. return aPath;
  9559. }
  9560. // If the only part of the root that is left is the scheme (i.e. http://,
  9561. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  9562. // have exhausted all components, so the path is not relative to the root.
  9563. aRoot = aRoot.slice(0, index);
  9564. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  9565. return aPath;
  9566. }
  9567. ++level;
  9568. }
  9569. // Make sure we add a "../" for each component we removed from the root.
  9570. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  9571. }
  9572. exports.relative = relative;
  9573. /**
  9574. * Because behavior goes wacky when you set `__proto__` on objects, we
  9575. * have to prefix all the strings in our set with an arbitrary character.
  9576. *
  9577. * See https://github.com/mozilla/source-map/pull/31 and
  9578. * https://github.com/mozilla/source-map/issues/30
  9579. *
  9580. * @param String aStr
  9581. */
  9582. function toSetString(aStr) {
  9583. return '$' + aStr;
  9584. }
  9585. exports.toSetString = toSetString;
  9586. function fromSetString(aStr) {
  9587. return aStr.substr(1);
  9588. }
  9589. exports.fromSetString = fromSetString;
  9590. /**
  9591. * Comparator between two mappings where the original positions are compared.
  9592. *
  9593. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  9594. * mappings with the same original source/line/column, but different generated
  9595. * line and column the same. Useful when searching for a mapping with a
  9596. * stubbed out mapping.
  9597. */
  9598. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  9599. var cmp = mappingA.source - mappingB.source;
  9600. if (cmp !== 0) {
  9601. return cmp;
  9602. }
  9603. cmp = mappingA.originalLine - mappingB.originalLine;
  9604. if (cmp !== 0) {
  9605. return cmp;
  9606. }
  9607. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9608. if (cmp !== 0 || onlyCompareOriginal) {
  9609. return cmp;
  9610. }
  9611. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9612. if (cmp !== 0) {
  9613. return cmp;
  9614. }
  9615. cmp = mappingA.generatedLine - mappingB.generatedLine;
  9616. if (cmp !== 0) {
  9617. return cmp;
  9618. }
  9619. return mappingA.name - mappingB.name;
  9620. }
  9621. exports.compareByOriginalPositions = compareByOriginalPositions;
  9622. /**
  9623. * Comparator between two mappings with deflated source and name indices where
  9624. * the generated positions are compared.
  9625. *
  9626. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  9627. * mappings with the same generated line and column, but different
  9628. * source/name/original line and column the same. Useful when searching for a
  9629. * mapping with a stubbed out mapping.
  9630. */
  9631. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  9632. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  9633. if (cmp !== 0) {
  9634. return cmp;
  9635. }
  9636. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9637. if (cmp !== 0 || onlyCompareGenerated) {
  9638. return cmp;
  9639. }
  9640. cmp = mappingA.source - mappingB.source;
  9641. if (cmp !== 0) {
  9642. return cmp;
  9643. }
  9644. cmp = mappingA.originalLine - mappingB.originalLine;
  9645. if (cmp !== 0) {
  9646. return cmp;
  9647. }
  9648. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9649. if (cmp !== 0) {
  9650. return cmp;
  9651. }
  9652. return mappingA.name - mappingB.name;
  9653. }
  9654. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  9655. function strcmp(aStr1, aStr2) {
  9656. if (aStr1 === aStr2) {
  9657. return 0;
  9658. }
  9659. if (aStr1 > aStr2) {
  9660. return 1;
  9661. }
  9662. return -1;
  9663. }
  9664. /**
  9665. * Comparator between two mappings with inflated source and name strings where
  9666. * the generated positions are compared.
  9667. */
  9668. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  9669. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  9670. if (cmp !== 0) {
  9671. return cmp;
  9672. }
  9673. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9674. if (cmp !== 0) {
  9675. return cmp;
  9676. }
  9677. cmp = strcmp(mappingA.source, mappingB.source);
  9678. if (cmp !== 0) {
  9679. return cmp;
  9680. }
  9681. cmp = mappingA.originalLine - mappingB.originalLine;
  9682. if (cmp !== 0) {
  9683. return cmp;
  9684. }
  9685. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9686. if (cmp !== 0) {
  9687. return cmp;
  9688. }
  9689. return strcmp(mappingA.name, mappingB.name);
  9690. }
  9691. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  9692. }
  9693. /***/ },
  9694. /* 5 */
  9695. /***/ function(module, exports, __webpack_require__) {
  9696. /* -*- Mode: js; js-indent-level: 2; -*- */
  9697. /*
  9698. * Copyright 2011 Mozilla Foundation and contributors
  9699. * Licensed under the New BSD license. See LICENSE or:
  9700. * http://opensource.org/licenses/BSD-3-Clause
  9701. */
  9702. {
  9703. var util = __webpack_require__(4);
  9704. /**
  9705. * A data structure which is a combination of an array and a set. Adding a new
  9706. * member is O(1), testing for membership is O(1), and finding the index of an
  9707. * element is O(1). Removing elements from the set is not supported. Only
  9708. * strings are supported for membership.
  9709. */
  9710. function ArraySet() {
  9711. this._array = [];
  9712. this._set = {};
  9713. }
  9714. /**
  9715. * Static method for creating ArraySet instances from an existing array.
  9716. */
  9717. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  9718. var set = new ArraySet();
  9719. for (var i = 0, len = aArray.length; i < len; i++) {
  9720. set.add(aArray[i], aAllowDuplicates);
  9721. }
  9722. return set;
  9723. };
  9724. /**
  9725. * Return how many unique items are in this ArraySet. If duplicates have been
  9726. * added, than those do not count towards the size.
  9727. *
  9728. * @returns Number
  9729. */
  9730. ArraySet.prototype.size = function ArraySet_size() {
  9731. return Object.getOwnPropertyNames(this._set).length;
  9732. };
  9733. /**
  9734. * Add the given string to this set.
  9735. *
  9736. * @param String aStr
  9737. */
  9738. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  9739. var sStr = util.toSetString(aStr);
  9740. var isDuplicate = this._set.hasOwnProperty(sStr);
  9741. var idx = this._array.length;
  9742. if (!isDuplicate || aAllowDuplicates) {
  9743. this._array.push(aStr);
  9744. }
  9745. if (!isDuplicate) {
  9746. this._set[sStr] = idx;
  9747. }
  9748. };
  9749. /**
  9750. * Is the given string a member of this set?
  9751. *
  9752. * @param String aStr
  9753. */
  9754. ArraySet.prototype.has = function ArraySet_has(aStr) {
  9755. var sStr = util.toSetString(aStr);
  9756. return this._set.hasOwnProperty(sStr);
  9757. };
  9758. /**
  9759. * What is the index of the given string in the array?
  9760. *
  9761. * @param String aStr
  9762. */
  9763. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  9764. var sStr = util.toSetString(aStr);
  9765. if (this._set.hasOwnProperty(sStr)) {
  9766. return this._set[sStr];
  9767. }
  9768. throw new Error('"' + aStr + '" is not in the set.');
  9769. };
  9770. /**
  9771. * What is the element at the given index?
  9772. *
  9773. * @param Number aIdx
  9774. */
  9775. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  9776. if (aIdx >= 0 && aIdx < this._array.length) {
  9777. return this._array[aIdx];
  9778. }
  9779. throw new Error('No element indexed by ' + aIdx);
  9780. };
  9781. /**
  9782. * Returns the array representation of this set (which has the proper indices
  9783. * indicated by indexOf). Note that this is a copy of the internal array used
  9784. * for storing the members so that no one can mess with internal state.
  9785. */
  9786. ArraySet.prototype.toArray = function ArraySet_toArray() {
  9787. return this._array.slice();
  9788. };
  9789. exports.ArraySet = ArraySet;
  9790. }
  9791. /***/ },
  9792. /* 6 */
  9793. /***/ function(module, exports, __webpack_require__) {
  9794. /* -*- Mode: js; js-indent-level: 2; -*- */
  9795. /*
  9796. * Copyright 2014 Mozilla Foundation and contributors
  9797. * Licensed under the New BSD license. See LICENSE or:
  9798. * http://opensource.org/licenses/BSD-3-Clause
  9799. */
  9800. {
  9801. var util = __webpack_require__(4);
  9802. /**
  9803. * Determine whether mappingB is after mappingA with respect to generated
  9804. * position.
  9805. */
  9806. function generatedPositionAfter(mappingA, mappingB) {
  9807. // Optimized for most common case
  9808. var lineA = mappingA.generatedLine;
  9809. var lineB = mappingB.generatedLine;
  9810. var columnA = mappingA.generatedColumn;
  9811. var columnB = mappingB.generatedColumn;
  9812. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  9813. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  9814. }
  9815. /**
  9816. * A data structure to provide a sorted view of accumulated mappings in a
  9817. * performance conscious manner. It trades a neglibable overhead in general
  9818. * case for a large speedup in case of mappings being added in order.
  9819. */
  9820. function MappingList() {
  9821. this._array = [];
  9822. this._sorted = true;
  9823. // Serves as infimum
  9824. this._last = {generatedLine: -1, generatedColumn: 0};
  9825. }
  9826. /**
  9827. * Iterate through internal items. This method takes the same arguments that
  9828. * `Array.prototype.forEach` takes.
  9829. *
  9830. * NOTE: The order of the mappings is NOT guaranteed.
  9831. */
  9832. MappingList.prototype.unsortedForEach =
  9833. function MappingList_forEach(aCallback, aThisArg) {
  9834. this._array.forEach(aCallback, aThisArg);
  9835. };
  9836. /**
  9837. * Add the given source mapping.
  9838. *
  9839. * @param Object aMapping
  9840. */
  9841. MappingList.prototype.add = function MappingList_add(aMapping) {
  9842. if (generatedPositionAfter(this._last, aMapping)) {
  9843. this._last = aMapping;
  9844. this._array.push(aMapping);
  9845. } else {
  9846. this._sorted = false;
  9847. this._array.push(aMapping);
  9848. }
  9849. };
  9850. /**
  9851. * Returns the flat, sorted array of mappings. The mappings are sorted by
  9852. * generated position.
  9853. *
  9854. * WARNING: This method returns internal data without copying, for
  9855. * performance. The return value must NOT be mutated, and should be treated as
  9856. * an immutable borrow. If you want to take ownership, you must make your own
  9857. * copy.
  9858. */
  9859. MappingList.prototype.toArray = function MappingList_toArray() {
  9860. if (!this._sorted) {
  9861. this._array.sort(util.compareByGeneratedPositionsInflated);
  9862. this._sorted = true;
  9863. }
  9864. return this._array;
  9865. };
  9866. exports.MappingList = MappingList;
  9867. }
  9868. /***/ },
  9869. /* 7 */
  9870. /***/ function(module, exports, __webpack_require__) {
  9871. /* -*- Mode: js; js-indent-level: 2; -*- */
  9872. /*
  9873. * Copyright 2011 Mozilla Foundation and contributors
  9874. * Licensed under the New BSD license. See LICENSE or:
  9875. * http://opensource.org/licenses/BSD-3-Clause
  9876. */
  9877. {
  9878. var util = __webpack_require__(4);
  9879. var binarySearch = __webpack_require__(8);
  9880. var ArraySet = __webpack_require__(5).ArraySet;
  9881. var base64VLQ = __webpack_require__(2);
  9882. var quickSort = __webpack_require__(9).quickSort;
  9883. function SourceMapConsumer(aSourceMap) {
  9884. var sourceMap = aSourceMap;
  9885. if (typeof aSourceMap === 'string') {
  9886. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  9887. }
  9888. return sourceMap.sections != null
  9889. ? new IndexedSourceMapConsumer(sourceMap)
  9890. : new BasicSourceMapConsumer(sourceMap);
  9891. }
  9892. SourceMapConsumer.fromSourceMap = function(aSourceMap) {
  9893. return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
  9894. }
  9895. /**
  9896. * The version of the source mapping spec that we are consuming.
  9897. */
  9898. SourceMapConsumer.prototype._version = 3;
  9899. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9900. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9901. // are lazily instantiated, accessed via the `_generatedMappings` and
  9902. // `_originalMappings` getters respectively, and we only parse the mappings
  9903. // and create these arrays once queried for a source location. We jump through
  9904. // these hoops because there can be many thousands of mappings, and parsing
  9905. // them is expensive, so we only want to do it if we must.
  9906. //
  9907. // Each object in the arrays is of the form:
  9908. //
  9909. // {
  9910. // generatedLine: The line number in the generated code,
  9911. // generatedColumn: The column number in the generated code,
  9912. // source: The path to the original source file that generated this
  9913. // chunk of code,
  9914. // originalLine: The line number in the original source that
  9915. // corresponds to this chunk of generated code,
  9916. // originalColumn: The column number in the original source that
  9917. // corresponds to this chunk of generated code,
  9918. // name: The name of the original symbol which generated this chunk of
  9919. // code.
  9920. // }
  9921. //
  9922. // All properties except for `generatedLine` and `generatedColumn` can be
  9923. // `null`.
  9924. //
  9925. // `_generatedMappings` is ordered by the generated positions.
  9926. //
  9927. // `_originalMappings` is ordered by the original positions.
  9928. SourceMapConsumer.prototype.__generatedMappings = null;
  9929. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9930. get: function () {
  9931. if (!this.__generatedMappings) {
  9932. this._parseMappings(this._mappings, this.sourceRoot);
  9933. }
  9934. return this.__generatedMappings;
  9935. }
  9936. });
  9937. SourceMapConsumer.prototype.__originalMappings = null;
  9938. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9939. get: function () {
  9940. if (!this.__originalMappings) {
  9941. this._parseMappings(this._mappings, this.sourceRoot);
  9942. }
  9943. return this.__originalMappings;
  9944. }
  9945. });
  9946. SourceMapConsumer.prototype._charIsMappingSeparator =
  9947. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9948. var c = aStr.charAt(index);
  9949. return c === ";" || c === ",";
  9950. };
  9951. /**
  9952. * Parse the mappings in a string in to a data structure which we can easily
  9953. * query (the ordered arrays in the `this.__generatedMappings` and
  9954. * `this.__originalMappings` properties).
  9955. */
  9956. SourceMapConsumer.prototype._parseMappings =
  9957. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9958. throw new Error("Subclasses must implement _parseMappings");
  9959. };
  9960. SourceMapConsumer.GENERATED_ORDER = 1;
  9961. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9962. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9963. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9964. /**
  9965. * Iterate over each mapping between an original source/line/column and a
  9966. * generated line/column in this source map.
  9967. *
  9968. * @param Function aCallback
  9969. * The function that is called with each mapping.
  9970. * @param Object aContext
  9971. * Optional. If specified, this object will be the value of `this` every
  9972. * time that `aCallback` is called.
  9973. * @param aOrder
  9974. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9975. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9976. * iterate over the mappings sorted by the generated file's line/column
  9977. * order or the original's source/line/column order, respectively. Defaults to
  9978. * `SourceMapConsumer.GENERATED_ORDER`.
  9979. */
  9980. SourceMapConsumer.prototype.eachMapping =
  9981. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9982. var context = aContext || null;
  9983. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9984. var mappings;
  9985. switch (order) {
  9986. case SourceMapConsumer.GENERATED_ORDER:
  9987. mappings = this._generatedMappings;
  9988. break;
  9989. case SourceMapConsumer.ORIGINAL_ORDER:
  9990. mappings = this._originalMappings;
  9991. break;
  9992. default:
  9993. throw new Error("Unknown order of iteration.");
  9994. }
  9995. var sourceRoot = this.sourceRoot;
  9996. mappings.map(function (mapping) {
  9997. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9998. if (source != null && sourceRoot != null) {
  9999. source = util.join(sourceRoot, source);
  10000. }
  10001. return {
  10002. source: source,
  10003. generatedLine: mapping.generatedLine,
  10004. generatedColumn: mapping.generatedColumn,
  10005. originalLine: mapping.originalLine,
  10006. originalColumn: mapping.originalColumn,
  10007. name: mapping.name === null ? null : this._names.at(mapping.name)
  10008. };
  10009. }, this).forEach(aCallback, context);
  10010. };
  10011. /**
  10012. * Returns all generated line and column information for the original source,
  10013. * line, and column provided. If no column is provided, returns all mappings
  10014. * corresponding to a either the line we are searching for or the next
  10015. * closest line that has any mappings. Otherwise, returns all mappings
  10016. * corresponding to the given line and either the column we are searching for
  10017. * or the next closest column that has any offsets.
  10018. *
  10019. * The only argument is an object with the following properties:
  10020. *
  10021. * - source: The filename of the original source.
  10022. * - line: The line number in the original source.
  10023. * - column: Optional. the column number in the original source.
  10024. *
  10025. * and an array of objects is returned, each with the following properties:
  10026. *
  10027. * - line: The line number in the generated source, or null.
  10028. * - column: The column number in the generated source, or null.
  10029. */
  10030. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  10031. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  10032. var line = util.getArg(aArgs, 'line');
  10033. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  10034. // returns the index of the closest mapping less than the needle. By
  10035. // setting needle.originalColumn to 0, we thus find the last mapping for
  10036. // the given line, provided such a mapping exists.
  10037. var needle = {
  10038. source: util.getArg(aArgs, 'source'),
  10039. originalLine: line,
  10040. originalColumn: util.getArg(aArgs, 'column', 0)
  10041. };
  10042. if (this.sourceRoot != null) {
  10043. needle.source = util.relative(this.sourceRoot, needle.source);
  10044. }
  10045. if (!this._sources.has(needle.source)) {
  10046. return [];
  10047. }
  10048. needle.source = this._sources.indexOf(needle.source);
  10049. var mappings = [];
  10050. var index = this._findMapping(needle,
  10051. this._originalMappings,
  10052. "originalLine",
  10053. "originalColumn",
  10054. util.compareByOriginalPositions,
  10055. binarySearch.LEAST_UPPER_BOUND);
  10056. if (index >= 0) {
  10057. var mapping = this._originalMappings[index];
  10058. if (aArgs.column === undefined) {
  10059. var originalLine = mapping.originalLine;
  10060. // Iterate until either we run out of mappings, or we run into
  10061. // a mapping for a different line than the one we found. Since
  10062. // mappings are sorted, this is guaranteed to find all mappings for
  10063. // the line we found.
  10064. while (mapping && mapping.originalLine === originalLine) {
  10065. mappings.push({
  10066. line: util.getArg(mapping, 'generatedLine', null),
  10067. column: util.getArg(mapping, 'generatedColumn', null),
  10068. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  10069. });
  10070. mapping = this._originalMappings[++index];
  10071. }
  10072. } else {
  10073. var originalColumn = mapping.originalColumn;
  10074. // Iterate until either we run out of mappings, or we run into
  10075. // a mapping for a different line than the one we were searching for.
  10076. // Since mappings are sorted, this is guaranteed to find all mappings for
  10077. // the line we are searching for.
  10078. while (mapping &&
  10079. mapping.originalLine === line &&
  10080. mapping.originalColumn == originalColumn) {
  10081. mappings.push({
  10082. line: util.getArg(mapping, 'generatedLine', null),
  10083. column: util.getArg(mapping, 'generatedColumn', null),
  10084. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  10085. });
  10086. mapping = this._originalMappings[++index];
  10087. }
  10088. }
  10089. }
  10090. return mappings;
  10091. };
  10092. exports.SourceMapConsumer = SourceMapConsumer;
  10093. /**
  10094. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  10095. * query for information about the original file positions by giving it a file
  10096. * position in the generated source.
  10097. *
  10098. * The only parameter is the raw source map (either as a JSON string, or
  10099. * already parsed to an object). According to the spec, source maps have the
  10100. * following attributes:
  10101. *
  10102. * - version: Which version of the source map spec this map is following.
  10103. * - sources: An array of URLs to the original source files.
  10104. * - names: An array of identifiers which can be referrenced by individual mappings.
  10105. * - sourceRoot: Optional. The URL root from which all sources are relative.
  10106. * - sourcesContent: Optional. An array of contents of the original source files.
  10107. * - mappings: A string of base64 VLQs which contain the actual mappings.
  10108. * - file: Optional. The generated file this source map is associated with.
  10109. *
  10110. * Here is an example source map, taken from the source map spec[0]:
  10111. *
  10112. * {
  10113. * version : 3,
  10114. * file: "out.js",
  10115. * sourceRoot : "",
  10116. * sources: ["foo.js", "bar.js"],
  10117. * names: ["src", "maps", "are", "fun"],
  10118. * mappings: "AA,AB;;ABCDE;"
  10119. * }
  10120. *
  10121. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  10122. */
  10123. function BasicSourceMapConsumer(aSourceMap) {
  10124. var sourceMap = aSourceMap;
  10125. if (typeof aSourceMap === 'string') {
  10126. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  10127. }
  10128. var version = util.getArg(sourceMap, 'version');
  10129. var sources = util.getArg(sourceMap, 'sources');
  10130. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  10131. // requires the array) to play nice here.
  10132. var names = util.getArg(sourceMap, 'names', []);
  10133. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  10134. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  10135. var mappings = util.getArg(sourceMap, 'mappings');
  10136. var file = util.getArg(sourceMap, 'file', null);
  10137. // Once again, Sass deviates from the spec and supplies the version as a
  10138. // string rather than a number, so we use loose equality checking here.
  10139. if (version != this._version) {
  10140. throw new Error('Unsupported version: ' + version);
  10141. }
  10142. sources = sources
  10143. // Some source maps produce relative source paths like "./foo.js" instead of
  10144. // "foo.js". Normalize these first so that future comparisons will succeed.
  10145. // See bugzil.la/1090768.
  10146. .map(util.normalize)
  10147. // Always ensure that absolute sources are internally stored relative to
  10148. // the source root, if the source root is absolute. Not doing this would
  10149. // be particularly problematic when the source root is a prefix of the
  10150. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  10151. .map(function (source) {
  10152. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  10153. ? util.relative(sourceRoot, source)
  10154. : source;
  10155. });
  10156. // Pass `true` below to allow duplicate names and sources. While source maps
  10157. // are intended to be compressed and deduplicated, the TypeScript compiler
  10158. // sometimes generates source maps with duplicates in them. See Github issue
  10159. // #72 and bugzil.la/889492.
  10160. this._names = ArraySet.fromArray(names, true);
  10161. this._sources = ArraySet.fromArray(sources, true);
  10162. this.sourceRoot = sourceRoot;
  10163. this.sourcesContent = sourcesContent;
  10164. this._mappings = mappings;
  10165. this.file = file;
  10166. }
  10167. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10168. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  10169. /**
  10170. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  10171. *
  10172. * @param SourceMapGenerator aSourceMap
  10173. * The source map that will be consumed.
  10174. * @returns BasicSourceMapConsumer
  10175. */
  10176. BasicSourceMapConsumer.fromSourceMap =
  10177. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  10178. var smc = Object.create(BasicSourceMapConsumer.prototype);
  10179. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  10180. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  10181. smc.sourceRoot = aSourceMap._sourceRoot;
  10182. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  10183. smc.sourceRoot);
  10184. smc.file = aSourceMap._file;
  10185. // Because we are modifying the entries (by converting string sources and
  10186. // names to indices into the sources and names ArraySets), we have to make
  10187. // a copy of the entry or else bad things happen. Shared mutable state
  10188. // strikes again! See github issue #191.
  10189. var generatedMappings = aSourceMap._mappings.toArray().slice();
  10190. var destGeneratedMappings = smc.__generatedMappings = [];
  10191. var destOriginalMappings = smc.__originalMappings = [];
  10192. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  10193. var srcMapping = generatedMappings[i];
  10194. var destMapping = new Mapping;
  10195. destMapping.generatedLine = srcMapping.generatedLine;
  10196. destMapping.generatedColumn = srcMapping.generatedColumn;
  10197. if (srcMapping.source) {
  10198. destMapping.source = sources.indexOf(srcMapping.source);
  10199. destMapping.originalLine = srcMapping.originalLine;
  10200. destMapping.originalColumn = srcMapping.originalColumn;
  10201. if (srcMapping.name) {
  10202. destMapping.name = names.indexOf(srcMapping.name);
  10203. }
  10204. destOriginalMappings.push(destMapping);
  10205. }
  10206. destGeneratedMappings.push(destMapping);
  10207. }
  10208. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  10209. return smc;
  10210. };
  10211. /**
  10212. * The version of the source mapping spec that we are consuming.
  10213. */
  10214. BasicSourceMapConsumer.prototype._version = 3;
  10215. /**
  10216. * The list of original sources.
  10217. */
  10218. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  10219. get: function () {
  10220. return this._sources.toArray().map(function (s) {
  10221. return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
  10222. }, this);
  10223. }
  10224. });
  10225. /**
  10226. * Provide the JIT with a nice shape / hidden class.
  10227. */
  10228. function Mapping() {
  10229. this.generatedLine = 0;
  10230. this.generatedColumn = 0;
  10231. this.source = null;
  10232. this.originalLine = null;
  10233. this.originalColumn = null;
  10234. this.name = null;
  10235. }
  10236. /**
  10237. * Parse the mappings in a string in to a data structure which we can easily
  10238. * query (the ordered arrays in the `this.__generatedMappings` and
  10239. * `this.__originalMappings` properties).
  10240. */
  10241. BasicSourceMapConsumer.prototype._parseMappings =
  10242. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10243. var generatedLine = 1;
  10244. var previousGeneratedColumn = 0;
  10245. var previousOriginalLine = 0;
  10246. var previousOriginalColumn = 0;
  10247. var previousSource = 0;
  10248. var previousName = 0;
  10249. var length = aStr.length;
  10250. var index = 0;
  10251. var cachedSegments = {};
  10252. var temp = {};
  10253. var originalMappings = [];
  10254. var generatedMappings = [];
  10255. var mapping, str, segment, end, value;
  10256. while (index < length) {
  10257. if (aStr.charAt(index) === ';') {
  10258. generatedLine++;
  10259. index++;
  10260. previousGeneratedColumn = 0;
  10261. }
  10262. else if (aStr.charAt(index) === ',') {
  10263. index++;
  10264. }
  10265. else {
  10266. mapping = new Mapping();
  10267. mapping.generatedLine = generatedLine;
  10268. // Because each offset is encoded relative to the previous one,
  10269. // many segments often have the same encoding. We can exploit this
  10270. // fact by caching the parsed variable length fields of each segment,
  10271. // allowing us to avoid a second parse if we encounter the same
  10272. // segment again.
  10273. for (end = index; end < length; end++) {
  10274. if (this._charIsMappingSeparator(aStr, end)) {
  10275. break;
  10276. }
  10277. }
  10278. str = aStr.slice(index, end);
  10279. segment = cachedSegments[str];
  10280. if (segment) {
  10281. index += str.length;
  10282. } else {
  10283. segment = [];
  10284. while (index < end) {
  10285. base64VLQ.decode(aStr, index, temp);
  10286. value = temp.value;
  10287. index = temp.rest;
  10288. segment.push(value);
  10289. }
  10290. if (segment.length === 2) {
  10291. throw new Error('Found a source, but no line and column');
  10292. }
  10293. if (segment.length === 3) {
  10294. throw new Error('Found a source and line, but no column');
  10295. }
  10296. cachedSegments[str] = segment;
  10297. }
  10298. // Generated column.
  10299. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  10300. previousGeneratedColumn = mapping.generatedColumn;
  10301. if (segment.length > 1) {
  10302. // Original source.
  10303. mapping.source = previousSource + segment[1];
  10304. previousSource += segment[1];
  10305. // Original line.
  10306. mapping.originalLine = previousOriginalLine + segment[2];
  10307. previousOriginalLine = mapping.originalLine;
  10308. // Lines are stored 0-based
  10309. mapping.originalLine += 1;
  10310. // Original column.
  10311. mapping.originalColumn = previousOriginalColumn + segment[3];
  10312. previousOriginalColumn = mapping.originalColumn;
  10313. if (segment.length > 4) {
  10314. // Original name.
  10315. mapping.name = previousName + segment[4];
  10316. previousName += segment[4];
  10317. }
  10318. }
  10319. generatedMappings.push(mapping);
  10320. if (typeof mapping.originalLine === 'number') {
  10321. originalMappings.push(mapping);
  10322. }
  10323. }
  10324. }
  10325. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  10326. this.__generatedMappings = generatedMappings;
  10327. quickSort(originalMappings, util.compareByOriginalPositions);
  10328. this.__originalMappings = originalMappings;
  10329. };
  10330. /**
  10331. * Find the mapping that best matches the hypothetical "needle" mapping that
  10332. * we are searching for in the given "haystack" of mappings.
  10333. */
  10334. BasicSourceMapConsumer.prototype._findMapping =
  10335. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  10336. aColumnName, aComparator, aBias) {
  10337. // To return the position we are searching for, we must first find the
  10338. // mapping for the given position and then return the opposite position it
  10339. // points to. Because the mappings are sorted, we can use binary search to
  10340. // find the best mapping.
  10341. if (aNeedle[aLineName] <= 0) {
  10342. throw new TypeError('Line must be greater than or equal to 1, got '
  10343. + aNeedle[aLineName]);
  10344. }
  10345. if (aNeedle[aColumnName] < 0) {
  10346. throw new TypeError('Column must be greater than or equal to 0, got '
  10347. + aNeedle[aColumnName]);
  10348. }
  10349. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  10350. };
  10351. /**
  10352. * Compute the last column for each generated mapping. The last column is
  10353. * inclusive.
  10354. */
  10355. BasicSourceMapConsumer.prototype.computeColumnSpans =
  10356. function SourceMapConsumer_computeColumnSpans() {
  10357. for (var index = 0; index < this._generatedMappings.length; ++index) {
  10358. var mapping = this._generatedMappings[index];
  10359. // Mappings do not contain a field for the last generated columnt. We
  10360. // can come up with an optimistic estimate, however, by assuming that
  10361. // mappings are contiguous (i.e. given two consecutive mappings, the
  10362. // first mapping ends where the second one starts).
  10363. if (index + 1 < this._generatedMappings.length) {
  10364. var nextMapping = this._generatedMappings[index + 1];
  10365. if (mapping.generatedLine === nextMapping.generatedLine) {
  10366. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  10367. continue;
  10368. }
  10369. }
  10370. // The last mapping for each line spans the entire line.
  10371. mapping.lastGeneratedColumn = Infinity;
  10372. }
  10373. };
  10374. /**
  10375. * Returns the original source, line, and column information for the generated
  10376. * source's line and column positions provided. The only argument is an object
  10377. * with the following properties:
  10378. *
  10379. * - line: The line number in the generated source.
  10380. * - column: The column number in the generated source.
  10381. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10382. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10383. * closest element that is smaller than or greater than the one we are
  10384. * searching for, respectively, if the exact element cannot be found.
  10385. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10386. *
  10387. * and an object is returned with the following properties:
  10388. *
  10389. * - source: The original source file, or null.
  10390. * - line: The line number in the original source, or null.
  10391. * - column: The column number in the original source, or null.
  10392. * - name: The original identifier, or null.
  10393. */
  10394. BasicSourceMapConsumer.prototype.originalPositionFor =
  10395. function SourceMapConsumer_originalPositionFor(aArgs) {
  10396. var needle = {
  10397. generatedLine: util.getArg(aArgs, 'line'),
  10398. generatedColumn: util.getArg(aArgs, 'column')
  10399. };
  10400. var index = this._findMapping(
  10401. needle,
  10402. this._generatedMappings,
  10403. "generatedLine",
  10404. "generatedColumn",
  10405. util.compareByGeneratedPositionsDeflated,
  10406. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10407. );
  10408. if (index >= 0) {
  10409. var mapping = this._generatedMappings[index];
  10410. if (mapping.generatedLine === needle.generatedLine) {
  10411. var source = util.getArg(mapping, 'source', null);
  10412. if (source !== null) {
  10413. source = this._sources.at(source);
  10414. if (this.sourceRoot != null) {
  10415. source = util.join(this.sourceRoot, source);
  10416. }
  10417. }
  10418. var name = util.getArg(mapping, 'name', null);
  10419. if (name !== null) {
  10420. name = this._names.at(name);
  10421. }
  10422. return {
  10423. source: source,
  10424. line: util.getArg(mapping, 'originalLine', null),
  10425. column: util.getArg(mapping, 'originalColumn', null),
  10426. name: name
  10427. };
  10428. }
  10429. }
  10430. return {
  10431. source: null,
  10432. line: null,
  10433. column: null,
  10434. name: null
  10435. };
  10436. };
  10437. /**
  10438. * Return true if we have the source content for every source in the source
  10439. * map, false otherwise.
  10440. */
  10441. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  10442. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  10443. if (!this.sourcesContent) {
  10444. return false;
  10445. }
  10446. return this.sourcesContent.length >= this._sources.size() &&
  10447. !this.sourcesContent.some(function (sc) { return sc == null; });
  10448. };
  10449. /**
  10450. * Returns the original source content. The only argument is the url of the
  10451. * original source file. Returns null if no original source content is
  10452. * available.
  10453. */
  10454. BasicSourceMapConsumer.prototype.sourceContentFor =
  10455. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10456. if (!this.sourcesContent) {
  10457. return null;
  10458. }
  10459. if (this.sourceRoot != null) {
  10460. aSource = util.relative(this.sourceRoot, aSource);
  10461. }
  10462. if (this._sources.has(aSource)) {
  10463. return this.sourcesContent[this._sources.indexOf(aSource)];
  10464. }
  10465. var url;
  10466. if (this.sourceRoot != null
  10467. && (url = util.urlParse(this.sourceRoot))) {
  10468. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  10469. // many users. We can help them out when they expect file:// URIs to
  10470. // behave like it would if they were running a local HTTP server. See
  10471. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  10472. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  10473. if (url.scheme == "file"
  10474. && this._sources.has(fileUriAbsPath)) {
  10475. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  10476. }
  10477. if ((!url.path || url.path == "/")
  10478. && this._sources.has("/" + aSource)) {
  10479. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  10480. }
  10481. }
  10482. // This function is used recursively from
  10483. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  10484. // don't want to throw if we can't find the source - we just want to
  10485. // return null, so we provide a flag to exit gracefully.
  10486. if (nullOnMissing) {
  10487. return null;
  10488. }
  10489. else {
  10490. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10491. }
  10492. };
  10493. /**
  10494. * Returns the generated line and column information for the original source,
  10495. * line, and column positions provided. The only argument is an object with
  10496. * the following properties:
  10497. *
  10498. * - source: The filename of the original source.
  10499. * - line: The line number in the original source.
  10500. * - column: The column number in the original source.
  10501. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10502. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10503. * closest element that is smaller than or greater than the one we are
  10504. * searching for, respectively, if the exact element cannot be found.
  10505. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10506. *
  10507. * and an object is returned with the following properties:
  10508. *
  10509. * - line: The line number in the generated source, or null.
  10510. * - column: The column number in the generated source, or null.
  10511. */
  10512. BasicSourceMapConsumer.prototype.generatedPositionFor =
  10513. function SourceMapConsumer_generatedPositionFor(aArgs) {
  10514. var source = util.getArg(aArgs, 'source');
  10515. if (this.sourceRoot != null) {
  10516. source = util.relative(this.sourceRoot, source);
  10517. }
  10518. if (!this._sources.has(source)) {
  10519. return {
  10520. line: null,
  10521. column: null,
  10522. lastColumn: null
  10523. };
  10524. }
  10525. source = this._sources.indexOf(source);
  10526. var needle = {
  10527. source: source,
  10528. originalLine: util.getArg(aArgs, 'line'),
  10529. originalColumn: util.getArg(aArgs, 'column')
  10530. };
  10531. var index = this._findMapping(
  10532. needle,
  10533. this._originalMappings,
  10534. "originalLine",
  10535. "originalColumn",
  10536. util.compareByOriginalPositions,
  10537. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10538. );
  10539. if (index >= 0) {
  10540. var mapping = this._originalMappings[index];
  10541. if (mapping.source === needle.source) {
  10542. return {
  10543. line: util.getArg(mapping, 'generatedLine', null),
  10544. column: util.getArg(mapping, 'generatedColumn', null),
  10545. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  10546. };
  10547. }
  10548. }
  10549. return {
  10550. line: null,
  10551. column: null,
  10552. lastColumn: null
  10553. };
  10554. };
  10555. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10556. /**
  10557. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10558. * we can query for information. It differs from BasicSourceMapConsumer in
  10559. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10560. * input.
  10561. *
  10562. * The only parameter is a raw source map (either as a JSON string, or already
  10563. * parsed to an object). According to the spec for indexed source maps, they
  10564. * have the following attributes:
  10565. *
  10566. * - version: Which version of the source map spec this map is following.
  10567. * - file: Optional. The generated file this source map is associated with.
  10568. * - sections: A list of section definitions.
  10569. *
  10570. * Each value under the "sections" field has two fields:
  10571. * - offset: The offset into the original specified at which this section
  10572. * begins to apply, defined as an object with a "line" and "column"
  10573. * field.
  10574. * - map: A source map definition. This source map could also be indexed,
  10575. * but doesn't have to be.
  10576. *
  10577. * Instead of the "map" field, it's also possible to have a "url" field
  10578. * specifying a URL to retrieve a source map from, but that's currently
  10579. * unsupported.
  10580. *
  10581. * Here's an example source map, taken from the source map spec[0], but
  10582. * modified to omit a section which uses the "url" field.
  10583. *
  10584. * {
  10585. * version : 3,
  10586. * file: "app.js",
  10587. * sections: [{
  10588. * offset: {line:100, column:10},
  10589. * map: {
  10590. * version : 3,
  10591. * file: "section.js",
  10592. * sources: ["foo.js", "bar.js"],
  10593. * names: ["src", "maps", "are", "fun"],
  10594. * mappings: "AAAA,E;;ABCDE;"
  10595. * }
  10596. * }],
  10597. * }
  10598. *
  10599. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10600. */
  10601. function IndexedSourceMapConsumer(aSourceMap) {
  10602. var sourceMap = aSourceMap;
  10603. if (typeof aSourceMap === 'string') {
  10604. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  10605. }
  10606. var version = util.getArg(sourceMap, 'version');
  10607. var sections = util.getArg(sourceMap, 'sections');
  10608. if (version != this._version) {
  10609. throw new Error('Unsupported version: ' + version);
  10610. }
  10611. this._sources = new ArraySet();
  10612. this._names = new ArraySet();
  10613. var lastOffset = {
  10614. line: -1,
  10615. column: 0
  10616. };
  10617. this._sections = sections.map(function (s) {
  10618. if (s.url) {
  10619. // The url field will require support for asynchronicity.
  10620. // See https://github.com/mozilla/source-map/issues/16
  10621. throw new Error('Support for url field in sections not implemented.');
  10622. }
  10623. var offset = util.getArg(s, 'offset');
  10624. var offsetLine = util.getArg(offset, 'line');
  10625. var offsetColumn = util.getArg(offset, 'column');
  10626. if (offsetLine < lastOffset.line ||
  10627. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10628. throw new Error('Section offsets must be ordered and non-overlapping.');
  10629. }
  10630. lastOffset = offset;
  10631. return {
  10632. generatedOffset: {
  10633. // The offset fields are 0-based, but we use 1-based indices when
  10634. // encoding/decoding from VLQ.
  10635. generatedLine: offsetLine + 1,
  10636. generatedColumn: offsetColumn + 1
  10637. },
  10638. consumer: new SourceMapConsumer(util.getArg(s, 'map'))
  10639. }
  10640. });
  10641. }
  10642. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10643. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10644. /**
  10645. * The version of the source mapping spec that we are consuming.
  10646. */
  10647. IndexedSourceMapConsumer.prototype._version = 3;
  10648. /**
  10649. * The list of original sources.
  10650. */
  10651. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10652. get: function () {
  10653. var sources = [];
  10654. for (var i = 0; i < this._sections.length; i++) {
  10655. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10656. sources.push(this._sections[i].consumer.sources[j]);
  10657. }
  10658. }
  10659. return sources;
  10660. }
  10661. });
  10662. /**
  10663. * Returns the original source, line, and column information for the generated
  10664. * source's line and column positions provided. The only argument is an object
  10665. * with the following properties:
  10666. *
  10667. * - line: The line number in the generated source.
  10668. * - column: The column number in the generated source.
  10669. *
  10670. * and an object is returned with the following properties:
  10671. *
  10672. * - source: The original source file, or null.
  10673. * - line: The line number in the original source, or null.
  10674. * - column: The column number in the original source, or null.
  10675. * - name: The original identifier, or null.
  10676. */
  10677. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10678. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10679. var needle = {
  10680. generatedLine: util.getArg(aArgs, 'line'),
  10681. generatedColumn: util.getArg(aArgs, 'column')
  10682. };
  10683. // Find the section containing the generated position we're trying to map
  10684. // to an original position.
  10685. var sectionIndex = binarySearch.search(needle, this._sections,
  10686. function(needle, section) {
  10687. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10688. if (cmp) {
  10689. return cmp;
  10690. }
  10691. return (needle.generatedColumn -
  10692. section.generatedOffset.generatedColumn);
  10693. });
  10694. var section = this._sections[sectionIndex];
  10695. if (!section) {
  10696. return {
  10697. source: null,
  10698. line: null,
  10699. column: null,
  10700. name: null
  10701. };
  10702. }
  10703. return section.consumer.originalPositionFor({
  10704. line: needle.generatedLine -
  10705. (section.generatedOffset.generatedLine - 1),
  10706. column: needle.generatedColumn -
  10707. (section.generatedOffset.generatedLine === needle.generatedLine
  10708. ? section.generatedOffset.generatedColumn - 1
  10709. : 0),
  10710. bias: aArgs.bias
  10711. });
  10712. };
  10713. /**
  10714. * Return true if we have the source content for every source in the source
  10715. * map, false otherwise.
  10716. */
  10717. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10718. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10719. return this._sections.every(function (s) {
  10720. return s.consumer.hasContentsOfAllSources();
  10721. });
  10722. };
  10723. /**
  10724. * Returns the original source content. The only argument is the url of the
  10725. * original source file. Returns null if no original source content is
  10726. * available.
  10727. */
  10728. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10729. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10730. for (var i = 0; i < this._sections.length; i++) {
  10731. var section = this._sections[i];
  10732. var content = section.consumer.sourceContentFor(aSource, true);
  10733. if (content) {
  10734. return content;
  10735. }
  10736. }
  10737. if (nullOnMissing) {
  10738. return null;
  10739. }
  10740. else {
  10741. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10742. }
  10743. };
  10744. /**
  10745. * Returns the generated line and column information for the original source,
  10746. * line, and column positions provided. The only argument is an object with
  10747. * the following properties:
  10748. *
  10749. * - source: The filename of the original source.
  10750. * - line: The line number in the original source.
  10751. * - column: The column number in the original source.
  10752. *
  10753. * and an object is returned with the following properties:
  10754. *
  10755. * - line: The line number in the generated source, or null.
  10756. * - column: The column number in the generated source, or null.
  10757. */
  10758. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10759. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10760. for (var i = 0; i < this._sections.length; i++) {
  10761. var section = this._sections[i];
  10762. // Only consider this section if the requested source is in the list of
  10763. // sources of the consumer.
  10764. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
  10765. continue;
  10766. }
  10767. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10768. if (generatedPosition) {
  10769. var ret = {
  10770. line: generatedPosition.line +
  10771. (section.generatedOffset.generatedLine - 1),
  10772. column: generatedPosition.column +
  10773. (section.generatedOffset.generatedLine === generatedPosition.line
  10774. ? section.generatedOffset.generatedColumn - 1
  10775. : 0)
  10776. };
  10777. return ret;
  10778. }
  10779. }
  10780. return {
  10781. line: null,
  10782. column: null
  10783. };
  10784. };
  10785. /**
  10786. * Parse the mappings in a string in to a data structure which we can easily
  10787. * query (the ordered arrays in the `this.__generatedMappings` and
  10788. * `this.__originalMappings` properties).
  10789. */
  10790. IndexedSourceMapConsumer.prototype._parseMappings =
  10791. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10792. this.__generatedMappings = [];
  10793. this.__originalMappings = [];
  10794. for (var i = 0; i < this._sections.length; i++) {
  10795. var section = this._sections[i];
  10796. var sectionMappings = section.consumer._generatedMappings;
  10797. for (var j = 0; j < sectionMappings.length; j++) {
  10798. var mapping = sectionMappings[j];
  10799. var source = section.consumer._sources.at(mapping.source);
  10800. if (section.consumer.sourceRoot !== null) {
  10801. source = util.join(section.consumer.sourceRoot, source);
  10802. }
  10803. this._sources.add(source);
  10804. source = this._sources.indexOf(source);
  10805. var name = section.consumer._names.at(mapping.name);
  10806. this._names.add(name);
  10807. name = this._names.indexOf(name);
  10808. // The mappings coming from the consumer for the section have
  10809. // generated positions relative to the start of the section, so we
  10810. // need to offset them to be relative to the start of the concatenated
  10811. // generated file.
  10812. var adjustedMapping = {
  10813. source: source,
  10814. generatedLine: mapping.generatedLine +
  10815. (section.generatedOffset.generatedLine - 1),
  10816. generatedColumn: mapping.generatedColumn +
  10817. (section.generatedOffset.generatedLine === mapping.generatedLine
  10818. ? section.generatedOffset.generatedColumn - 1
  10819. : 0),
  10820. originalLine: mapping.originalLine,
  10821. originalColumn: mapping.originalColumn,
  10822. name: name
  10823. };
  10824. this.__generatedMappings.push(adjustedMapping);
  10825. if (typeof adjustedMapping.originalLine === 'number') {
  10826. this.__originalMappings.push(adjustedMapping);
  10827. }
  10828. }
  10829. }
  10830. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10831. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10832. };
  10833. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10834. }
  10835. /***/ },
  10836. /* 8 */
  10837. /***/ function(module, exports) {
  10838. /* -*- Mode: js; js-indent-level: 2; -*- */
  10839. /*
  10840. * Copyright 2011 Mozilla Foundation and contributors
  10841. * Licensed under the New BSD license. See LICENSE or:
  10842. * http://opensource.org/licenses/BSD-3-Clause
  10843. */
  10844. {
  10845. exports.GREATEST_LOWER_BOUND = 1;
  10846. exports.LEAST_UPPER_BOUND = 2;
  10847. /**
  10848. * Recursive implementation of binary search.
  10849. *
  10850. * @param aLow Indices here and lower do not contain the needle.
  10851. * @param aHigh Indices here and higher do not contain the needle.
  10852. * @param aNeedle The element being searched for.
  10853. * @param aHaystack The non-empty array being searched.
  10854. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  10855. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  10856. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  10857. * closest element that is smaller than or greater than the one we are
  10858. * searching for, respectively, if the exact element cannot be found.
  10859. */
  10860. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  10861. // This function terminates when one of the following is true:
  10862. //
  10863. // 1. We find the exact element we are looking for.
  10864. //
  10865. // 2. We did not find the exact element, but we can return the index of
  10866. // the next-closest element.
  10867. //
  10868. // 3. We did not find the exact element, and there is no next-closest
  10869. // element than the one we are searching for, so we return -1.
  10870. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  10871. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  10872. if (cmp === 0) {
  10873. // Found the element we are looking for.
  10874. return mid;
  10875. }
  10876. else if (cmp > 0) {
  10877. // Our needle is greater than aHaystack[mid].
  10878. if (aHigh - mid > 1) {
  10879. // The element is in the upper half.
  10880. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  10881. }
  10882. // The exact needle element was not found in this haystack. Determine if
  10883. // we are in termination case (3) or (2) and return the appropriate thing.
  10884. if (aBias == exports.LEAST_UPPER_BOUND) {
  10885. return aHigh < aHaystack.length ? aHigh : -1;
  10886. } else {
  10887. return mid;
  10888. }
  10889. }
  10890. else {
  10891. // Our needle is less than aHaystack[mid].
  10892. if (mid - aLow > 1) {
  10893. // The element is in the lower half.
  10894. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  10895. }
  10896. // we are in termination case (3) or (2) and return the appropriate thing.
  10897. if (aBias == exports.LEAST_UPPER_BOUND) {
  10898. return mid;
  10899. } else {
  10900. return aLow < 0 ? -1 : aLow;
  10901. }
  10902. }
  10903. }
  10904. /**
  10905. * This is an implementation of binary search which will always try and return
  10906. * the index of the closest element if there is no exact hit. This is because
  10907. * mappings between original and generated line/col pairs are single points,
  10908. * and there is an implicit region between each of them, so a miss just means
  10909. * that you aren't on the very start of a region.
  10910. *
  10911. * @param aNeedle The element you are looking for.
  10912. * @param aHaystack The array that is being searched.
  10913. * @param aCompare A function which takes the needle and an element in the
  10914. * array and returns -1, 0, or 1 depending on whether the needle is less
  10915. * than, equal to, or greater than the element, respectively.
  10916. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  10917. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  10918. * closest element that is smaller than or greater than the one we are
  10919. * searching for, respectively, if the exact element cannot be found.
  10920. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  10921. */
  10922. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  10923. if (aHaystack.length === 0) {
  10924. return -1;
  10925. }
  10926. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  10927. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  10928. if (index < 0) {
  10929. return -1;
  10930. }
  10931. // We have found either the exact element, or the next-closest element than
  10932. // the one we are searching for. However, there may be more than one such
  10933. // element. Make sure we always return the smallest of these.
  10934. while (index - 1 >= 0) {
  10935. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  10936. break;
  10937. }
  10938. --index;
  10939. }
  10940. return index;
  10941. };
  10942. }
  10943. /***/ },
  10944. /* 9 */
  10945. /***/ function(module, exports) {
  10946. /* -*- Mode: js; js-indent-level: 2; -*- */
  10947. /*
  10948. * Copyright 2011 Mozilla Foundation and contributors
  10949. * Licensed under the New BSD license. See LICENSE or:
  10950. * http://opensource.org/licenses/BSD-3-Clause
  10951. */
  10952. {
  10953. // It turns out that some (most?) JavaScript engines don't self-host
  10954. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  10955. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  10956. // custom comparator function, calling back and forth between the VM's C++ and
  10957. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  10958. // worse generated code for the comparator function than would be optimal. In
  10959. // fact, when sorting with a comparator, these costs outweigh the benefits of
  10960. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  10961. // a ~3500ms mean speed-up in `bench/bench.html`.
  10962. /**
  10963. * Swap the elements indexed by `x` and `y` in the array `ary`.
  10964. *
  10965. * @param {Array} ary
  10966. * The array.
  10967. * @param {Number} x
  10968. * The index of the first item.
  10969. * @param {Number} y
  10970. * The index of the second item.
  10971. */
  10972. function swap(ary, x, y) {
  10973. var temp = ary[x];
  10974. ary[x] = ary[y];
  10975. ary[y] = temp;
  10976. }
  10977. /**
  10978. * Returns a random integer within the range `low .. high` inclusive.
  10979. *
  10980. * @param {Number} low
  10981. * The lower bound on the range.
  10982. * @param {Number} high
  10983. * The upper bound on the range.
  10984. */
  10985. function randomIntInRange(low, high) {
  10986. return Math.round(low + (Math.random() * (high - low)));
  10987. }
  10988. /**
  10989. * The Quick Sort algorithm.
  10990. *
  10991. * @param {Array} ary
  10992. * An array to sort.
  10993. * @param {function} comparator
  10994. * Function to use to compare two items.
  10995. * @param {Number} p
  10996. * Start index of the array
  10997. * @param {Number} r
  10998. * End index of the array
  10999. */
  11000. function doQuickSort(ary, comparator, p, r) {
  11001. // If our lower bound is less than our upper bound, we (1) partition the
  11002. // array into two pieces and (2) recurse on each half. If it is not, this is
  11003. // the empty array and our base case.
  11004. if (p < r) {
  11005. // (1) Partitioning.
  11006. //
  11007. // The partitioning chooses a pivot between `p` and `r` and moves all
  11008. // elements that are less than or equal to the pivot to the before it, and
  11009. // all the elements that are greater than it after it. The effect is that
  11010. // once partition is done, the pivot is in the exact place it will be when
  11011. // the array is put in sorted order, and it will not need to be moved
  11012. // again. This runs in O(n) time.
  11013. // Always choose a random pivot so that an input array which is reverse
  11014. // sorted does not cause O(n^2) running time.
  11015. var pivotIndex = randomIntInRange(p, r);
  11016. var i = p - 1;
  11017. swap(ary, pivotIndex, r);
  11018. var pivot = ary[r];
  11019. // Immediately after `j` is incremented in this loop, the following hold
  11020. // true:
  11021. //
  11022. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  11023. //
  11024. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  11025. for (var j = p; j < r; j++) {
  11026. if (comparator(ary[j], pivot) <= 0) {
  11027. i += 1;
  11028. swap(ary, i, j);
  11029. }
  11030. }
  11031. swap(ary, i + 1, j);
  11032. var q = i + 1;
  11033. // (2) Recurse on each half.
  11034. doQuickSort(ary, comparator, p, q - 1);
  11035. doQuickSort(ary, comparator, q + 1, r);
  11036. }
  11037. }
  11038. /**
  11039. * Sort the given array in-place with the given comparator function.
  11040. *
  11041. * @param {Array} ary
  11042. * An array to sort.
  11043. * @param {function} comparator
  11044. * Function to use to compare two items.
  11045. */
  11046. exports.quickSort = function (ary, comparator) {
  11047. doQuickSort(ary, comparator, 0, ary.length - 1);
  11048. };
  11049. }
  11050. /***/ },
  11051. /* 10 */
  11052. /***/ function(module, exports, __webpack_require__) {
  11053. /* -*- Mode: js; js-indent-level: 2; -*- */
  11054. /*
  11055. * Copyright 2011 Mozilla Foundation and contributors
  11056. * Licensed under the New BSD license. See LICENSE or:
  11057. * http://opensource.org/licenses/BSD-3-Clause
  11058. */
  11059. {
  11060. var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  11061. var util = __webpack_require__(4);
  11062. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  11063. // operating systems these days (capturing the result).
  11064. var REGEX_NEWLINE = /(\r?\n)/;
  11065. // Newline character code for charCodeAt() comparisons
  11066. var NEWLINE_CODE = 10;
  11067. // Private symbol for identifying `SourceNode`s when multiple versions of
  11068. // the source-map library are loaded. This MUST NOT CHANGE across
  11069. // versions!
  11070. var isSourceNode = "$$$isSourceNode$$$";
  11071. /**
  11072. * SourceNodes provide a way to abstract over interpolating/concatenating
  11073. * snippets of generated JavaScript source code while maintaining the line and
  11074. * column information associated with the original source code.
  11075. *
  11076. * @param aLine The original line number.
  11077. * @param aColumn The original column number.
  11078. * @param aSource The original source's filename.
  11079. * @param aChunks Optional. An array of strings which are snippets of
  11080. * generated JS, or other SourceNodes.
  11081. * @param aName The original identifier.
  11082. */
  11083. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  11084. this.children = [];
  11085. this.sourceContents = {};
  11086. this.line = aLine == null ? null : aLine;
  11087. this.column = aColumn == null ? null : aColumn;
  11088. this.source = aSource == null ? null : aSource;
  11089. this.name = aName == null ? null : aName;
  11090. this[isSourceNode] = true;
  11091. if (aChunks != null) this.add(aChunks);
  11092. }
  11093. /**
  11094. * Creates a SourceNode from generated code and a SourceMapConsumer.
  11095. *
  11096. * @param aGeneratedCode The generated code
  11097. * @param aSourceMapConsumer The SourceMap for the generated code
  11098. * @param aRelativePath Optional. The path that relative sources in the
  11099. * SourceMapConsumer should be relative to.
  11100. */
  11101. SourceNode.fromStringWithSourceMap =
  11102. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  11103. // The SourceNode we want to fill with the generated code
  11104. // and the SourceMap
  11105. var node = new SourceNode();
  11106. // All even indices of this array are one line of the generated code,
  11107. // while all odd indices are the newlines between two adjacent lines
  11108. // (since `REGEX_NEWLINE` captures its match).
  11109. // Processed fragments are removed from this array, by calling `shiftNextLine`.
  11110. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  11111. var shiftNextLine = function() {
  11112. var lineContents = remainingLines.shift();
  11113. // The last line of a file might not have a newline.
  11114. var newLine = remainingLines.shift() || "";
  11115. return lineContents + newLine;
  11116. };
  11117. // We need to remember the position of "remainingLines"
  11118. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  11119. // The generate SourceNodes we need a code range.
  11120. // To extract it current and last mapping is used.
  11121. // Here we store the last mapping.
  11122. var lastMapping = null;
  11123. aSourceMapConsumer.eachMapping(function (mapping) {
  11124. if (lastMapping !== null) {
  11125. // We add the code from "lastMapping" to "mapping":
  11126. // First check if there is a new line in between.
  11127. if (lastGeneratedLine < mapping.generatedLine) {
  11128. // Associate first line with "lastMapping"
  11129. addMappingWithCode(lastMapping, shiftNextLine());
  11130. lastGeneratedLine++;
  11131. lastGeneratedColumn = 0;
  11132. // The remaining code is added without mapping
  11133. } else {
  11134. // There is no new line in between.
  11135. // Associate the code between "lastGeneratedColumn" and
  11136. // "mapping.generatedColumn" with "lastMapping"
  11137. var nextLine = remainingLines[0];
  11138. var code = nextLine.substr(0, mapping.generatedColumn -
  11139. lastGeneratedColumn);
  11140. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  11141. lastGeneratedColumn);
  11142. lastGeneratedColumn = mapping.generatedColumn;
  11143. addMappingWithCode(lastMapping, code);
  11144. // No more remaining code, continue
  11145. lastMapping = mapping;
  11146. return;
  11147. }
  11148. }
  11149. // We add the generated code until the first mapping
  11150. // to the SourceNode without any mapping.
  11151. // Each line is added as separate string.
  11152. while (lastGeneratedLine < mapping.generatedLine) {
  11153. node.add(shiftNextLine());
  11154. lastGeneratedLine++;
  11155. }
  11156. if (lastGeneratedColumn < mapping.generatedColumn) {
  11157. var nextLine = remainingLines[0];
  11158. node.add(nextLine.substr(0, mapping.generatedColumn));
  11159. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  11160. lastGeneratedColumn = mapping.generatedColumn;
  11161. }
  11162. lastMapping = mapping;
  11163. }, this);
  11164. // We have processed all mappings.
  11165. if (remainingLines.length > 0) {
  11166. if (lastMapping) {
  11167. // Associate the remaining code in the current line with "lastMapping"
  11168. addMappingWithCode(lastMapping, shiftNextLine());
  11169. }
  11170. // and add the remaining lines without any mapping
  11171. node.add(remainingLines.join(""));
  11172. }
  11173. // Copy sourcesContent into SourceNode
  11174. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  11175. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  11176. if (content != null) {
  11177. if (aRelativePath != null) {
  11178. sourceFile = util.join(aRelativePath, sourceFile);
  11179. }
  11180. node.setSourceContent(sourceFile, content);
  11181. }
  11182. });
  11183. return node;
  11184. function addMappingWithCode(mapping, code) {
  11185. if (mapping === null || mapping.source === undefined) {
  11186. node.add(code);
  11187. } else {
  11188. var source = aRelativePath
  11189. ? util.join(aRelativePath, mapping.source)
  11190. : mapping.source;
  11191. node.add(new SourceNode(mapping.originalLine,
  11192. mapping.originalColumn,
  11193. source,
  11194. code,
  11195. mapping.name));
  11196. }
  11197. }
  11198. };
  11199. /**
  11200. * Add a chunk of generated JS to this source node.
  11201. *
  11202. * @param aChunk A string snippet of generated JS code, another instance of
  11203. * SourceNode, or an array where each member is one of those things.
  11204. */
  11205. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  11206. if (Array.isArray(aChunk)) {
  11207. aChunk.forEach(function (chunk) {
  11208. this.add(chunk);
  11209. }, this);
  11210. }
  11211. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  11212. if (aChunk) {
  11213. this.children.push(aChunk);
  11214. }
  11215. }
  11216. else {
  11217. throw new TypeError(
  11218. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  11219. );
  11220. }
  11221. return this;
  11222. };
  11223. /**
  11224. * Add a chunk of generated JS to the beginning of this source node.
  11225. *
  11226. * @param aChunk A string snippet of generated JS code, another instance of
  11227. * SourceNode, or an array where each member is one of those things.
  11228. */
  11229. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  11230. if (Array.isArray(aChunk)) {
  11231. for (var i = aChunk.length-1; i >= 0; i--) {
  11232. this.prepend(aChunk[i]);
  11233. }
  11234. }
  11235. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  11236. this.children.unshift(aChunk);
  11237. }
  11238. else {
  11239. throw new TypeError(
  11240. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  11241. );
  11242. }
  11243. return this;
  11244. };
  11245. /**
  11246. * Walk over the tree of JS snippets in this node and its children. The
  11247. * walking function is called once for each snippet of JS and is passed that
  11248. * snippet and the its original associated source's line/column location.
  11249. *
  11250. * @param aFn The traversal function.
  11251. */
  11252. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  11253. var chunk;
  11254. for (var i = 0, len = this.children.length; i < len; i++) {
  11255. chunk = this.children[i];
  11256. if (chunk[isSourceNode]) {
  11257. chunk.walk(aFn);
  11258. }
  11259. else {
  11260. if (chunk !== '') {
  11261. aFn(chunk, { source: this.source,
  11262. line: this.line,
  11263. column: this.column,
  11264. name: this.name });
  11265. }
  11266. }
  11267. }
  11268. };
  11269. /**
  11270. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  11271. * each of `this.children`.
  11272. *
  11273. * @param aSep The separator.
  11274. */
  11275. SourceNode.prototype.join = function SourceNode_join(aSep) {
  11276. var newChildren;
  11277. var i;
  11278. var len = this.children.length;
  11279. if (len > 0) {
  11280. newChildren = [];
  11281. for (i = 0; i < len-1; i++) {
  11282. newChildren.push(this.children[i]);
  11283. newChildren.push(aSep);
  11284. }
  11285. newChildren.push(this.children[i]);
  11286. this.children = newChildren;
  11287. }
  11288. return this;
  11289. };
  11290. /**
  11291. * Call String.prototype.replace on the very right-most source snippet. Useful
  11292. * for trimming whitespace from the end of a source node, etc.
  11293. *
  11294. * @param aPattern The pattern to replace.
  11295. * @param aReplacement The thing to replace the pattern with.
  11296. */
  11297. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  11298. var lastChild = this.children[this.children.length - 1];
  11299. if (lastChild[isSourceNode]) {
  11300. lastChild.replaceRight(aPattern, aReplacement);
  11301. }
  11302. else if (typeof lastChild === 'string') {
  11303. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  11304. }
  11305. else {
  11306. this.children.push(''.replace(aPattern, aReplacement));
  11307. }
  11308. return this;
  11309. };
  11310. /**
  11311. * Set the source content for a source file. This will be added to the SourceMapGenerator
  11312. * in the sourcesContent field.
  11313. *
  11314. * @param aSourceFile The filename of the source file
  11315. * @param aSourceContent The content of the source file
  11316. */
  11317. SourceNode.prototype.setSourceContent =
  11318. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  11319. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  11320. };
  11321. /**
  11322. * Walk over the tree of SourceNodes. The walking function is called for each
  11323. * source file content and is passed the filename and source content.
  11324. *
  11325. * @param aFn The traversal function.
  11326. */
  11327. SourceNode.prototype.walkSourceContents =
  11328. function SourceNode_walkSourceContents(aFn) {
  11329. for (var i = 0, len = this.children.length; i < len; i++) {
  11330. if (this.children[i][isSourceNode]) {
  11331. this.children[i].walkSourceContents(aFn);
  11332. }
  11333. }
  11334. var sources = Object.keys(this.sourceContents);
  11335. for (var i = 0, len = sources.length; i < len; i++) {
  11336. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  11337. }
  11338. };
  11339. /**
  11340. * Return the string representation of this source node. Walks over the tree
  11341. * and concatenates all the various snippets together to one string.
  11342. */
  11343. SourceNode.prototype.toString = function SourceNode_toString() {
  11344. var str = "";
  11345. this.walk(function (chunk) {
  11346. str += chunk;
  11347. });
  11348. return str;
  11349. };
  11350. /**
  11351. * Returns the string representation of this source node along with a source
  11352. * map.
  11353. */
  11354. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  11355. var generated = {
  11356. code: "",
  11357. line: 1,
  11358. column: 0
  11359. };
  11360. var map = new SourceMapGenerator(aArgs);
  11361. var sourceMappingActive = false;
  11362. var lastOriginalSource = null;
  11363. var lastOriginalLine = null;
  11364. var lastOriginalColumn = null;
  11365. var lastOriginalName = null;
  11366. this.walk(function (chunk, original) {
  11367. generated.code += chunk;
  11368. if (original.source !== null
  11369. && original.line !== null
  11370. && original.column !== null) {
  11371. if(lastOriginalSource !== original.source
  11372. || lastOriginalLine !== original.line
  11373. || lastOriginalColumn !== original.column
  11374. || lastOriginalName !== original.name) {
  11375. map.addMapping({
  11376. source: original.source,
  11377. original: {
  11378. line: original.line,
  11379. column: original.column
  11380. },
  11381. generated: {
  11382. line: generated.line,
  11383. column: generated.column
  11384. },
  11385. name: original.name
  11386. });
  11387. }
  11388. lastOriginalSource = original.source;
  11389. lastOriginalLine = original.line;
  11390. lastOriginalColumn = original.column;
  11391. lastOriginalName = original.name;
  11392. sourceMappingActive = true;
  11393. } else if (sourceMappingActive) {
  11394. map.addMapping({
  11395. generated: {
  11396. line: generated.line,
  11397. column: generated.column
  11398. }
  11399. });
  11400. lastOriginalSource = null;
  11401. sourceMappingActive = false;
  11402. }
  11403. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  11404. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  11405. generated.line++;
  11406. generated.column = 0;
  11407. // Mappings end at eol
  11408. if (idx + 1 === length) {
  11409. lastOriginalSource = null;
  11410. sourceMappingActive = false;
  11411. } else if (sourceMappingActive) {
  11412. map.addMapping({
  11413. source: original.source,
  11414. original: {
  11415. line: original.line,
  11416. column: original.column
  11417. },
  11418. generated: {
  11419. line: generated.line,
  11420. column: generated.column
  11421. },
  11422. name: original.name
  11423. });
  11424. }
  11425. } else {
  11426. generated.column++;
  11427. }
  11428. }
  11429. });
  11430. this.walkSourceContents(function (sourceFile, sourceContent) {
  11431. map.setSourceContent(sourceFile, sourceContent);
  11432. });
  11433. return { code: generated.code, map: map };
  11434. };
  11435. exports.SourceNode = SourceNode;
  11436. }
  11437. /***/ }
  11438. /******/ ])
  11439. });
  11440. ;define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
  11441. /**
  11442. * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
  11443. * All rights reserved.
  11444. *
  11445. * Redistribution and use in source and binary forms, with or without
  11446. * modification, are permitted provided that the following conditions
  11447. * are met:
  11448. *
  11449. * * Redistributions of source code must retain the above
  11450. * copyright notice, this list of conditions and the following
  11451. * disclaimer.
  11452. *
  11453. * * Redistributions in binary form must reproduce the above
  11454. * copyright notice, this list of conditions and the following
  11455. * disclaimer in the documentation and/or other materials
  11456. * provided with the distribution.
  11457. *
  11458. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
  11459. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11460. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  11461. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  11462. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  11463. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  11464. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11465. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11466. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  11467. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  11468. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11469. * SUCH DAMAGE.
  11470. */
  11471. /**
  11472. * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
  11473. * >UglifyJS</a> with consolidation of null, Boolean, and String values.
  11474. * <p>Also known as aliasing, this feature has been deprecated in <a href=
  11475. * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
  11476. * initial release, where it is unavailable from the <abbr title=
  11477. * "command line interface">CLI</a>. The Closure Compiler allows one to log and
  11478. * influence this process. In contrast, this implementation does not introduce
  11479. * any variable declarations in global code and derives String values from
  11480. * identifier names used as property accessors.</p>
  11481. * <p>Consolidating literals may worsen the data compression ratio when an <a
  11482. * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
  11483. * transformation</a> is applied. For instance, <a href=
  11484. * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
  11485. * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
  11486. * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
  11487. * then compressed to 33154 bytes (13.36% of the original) using <a href=
  11488. * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
  11489. * version of UglifyJS 1.2.5 patched with the implementation of consolidation
  11490. * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
  11491. * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
  11492. * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
  11493. * 33154 bytes).</p>
  11494. * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
  11495. * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
  11496. * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
  11497. * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
  11498. * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
  11499. * discouraged use of the {@code function} tag and the {@code namespace} tag).
  11500. * 100% typed for the <a href=
  11501. * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
  11502. * >Closure Compiler Version 1741</a>.</p>
  11503. * <p>Should you find this software useful, please consider <a href=
  11504. * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
  11505. * >a donation</a>.</p>
  11506. * @author follow.me@RGustBardon (Robert Gust-Bardon)
  11507. * @supported Tested with:
  11508. * <ul>
  11509. * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
  11510. * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
  11511. * v1.2.5</a>.</li>
  11512. * </ul>
  11513. */
  11514. /*global console:false, exports:true, module:false, require:false */
  11515. /*jshint sub:true */
  11516. /**
  11517. * Consolidates null, Boolean, and String values found inside an <abbr title=
  11518. * "abstract syntax tree">AST</abbr>.
  11519. * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
  11520. * representing an <abbr title="abstract syntax tree">AST</abbr>.
  11521. * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
  11522. * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
  11523. * String values consolidated.
  11524. */
  11525. // TODO(user) Consolidation of mathematical values found in numeric literals.
  11526. // TODO(user) Unconsolidation.
  11527. // TODO(user) Consolidation of ECMA-262 6th Edition programs.
  11528. // TODO(user) Rewrite in ECMA-262 6th Edition.
  11529. exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
  11530. 'use strict';
  11531. /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
  11532. latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
  11533. onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
  11534. sub:false, trailing:true */
  11535. var _,
  11536. /**
  11537. * A record consisting of data about one or more source elements.
  11538. * @constructor
  11539. * @nosideeffects
  11540. */
  11541. TSourceElementsData = function() {
  11542. /**
  11543. * The category of the elements.
  11544. * @type {number}
  11545. * @see ESourceElementCategories
  11546. */
  11547. this.nCategory = ESourceElementCategories.N_OTHER;
  11548. /**
  11549. * The number of occurrences (within the elements) of each primitive
  11550. * value that could be consolidated.
  11551. * @type {!Array.<!Object.<string, number>>}
  11552. */
  11553. this.aCount = [];
  11554. this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
  11555. this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
  11556. this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
  11557. {};
  11558. /**
  11559. * Identifier names found within the elements.
  11560. * @type {!Array.<string>}
  11561. */
  11562. this.aIdentifiers = [];
  11563. /**
  11564. * Prefixed representation Strings of each primitive value that could be
  11565. * consolidated within the elements.
  11566. * @type {!Array.<string>}
  11567. */
  11568. this.aPrimitiveValues = [];
  11569. },
  11570. /**
  11571. * A record consisting of data about a primitive value that could be
  11572. * consolidated.
  11573. * @constructor
  11574. * @nosideeffects
  11575. */
  11576. TPrimitiveValue = function() {
  11577. /**
  11578. * The difference in the number of terminal symbols between the original
  11579. * source text and the one with the primitive value consolidated. If the
  11580. * difference is positive, the primitive value is considered worthwhile.
  11581. * @type {number}
  11582. */
  11583. this.nSaving = 0;
  11584. /**
  11585. * An identifier name of the variable that will be declared and assigned
  11586. * the primitive value if the primitive value is consolidated.
  11587. * @type {string}
  11588. */
  11589. this.sName = '';
  11590. },
  11591. /**
  11592. * A record consisting of data on what to consolidate within the range of
  11593. * source elements that is currently being considered.
  11594. * @constructor
  11595. * @nosideeffects
  11596. */
  11597. TSolution = function() {
  11598. /**
  11599. * An object whose keys are prefixed representation Strings of each
  11600. * primitive value that could be consolidated within the elements and
  11601. * whose values are corresponding data about those primitive values.
  11602. * @type {!Object.<string, {nSaving: number, sName: string}>}
  11603. * @see TPrimitiveValue
  11604. */
  11605. this.oPrimitiveValues = {};
  11606. /**
  11607. * The difference in the number of terminal symbols between the original
  11608. * source text and the one with all the worthwhile primitive values
  11609. * consolidated.
  11610. * @type {number}
  11611. * @see TPrimitiveValue#nSaving
  11612. */
  11613. this.nSavings = 0;
  11614. },
  11615. /**
  11616. * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
  11617. * in UglifyJS.
  11618. * @namespace
  11619. * @type {!TProcessor}
  11620. */
  11621. oProcessor = (/** @type {!TProcessor} */ require('./process')),
  11622. /**
  11623. * A record consisting of a number of constants that represent the
  11624. * difference in the number of terminal symbols between a source text with
  11625. * a modified syntactic code unit and the original one.
  11626. * @namespace
  11627. * @type {!Object.<string, number>}
  11628. */
  11629. oWeights = {
  11630. /**
  11631. * The difference in the number of punctuators required by the bracket
  11632. * notation and the dot notation.
  11633. * <p><code>'[]'.length - '.'.length</code></p>
  11634. * @const
  11635. * @type {number}
  11636. */
  11637. N_PROPERTY_ACCESSOR: 1,
  11638. /**
  11639. * The number of punctuators required by a variable declaration with an
  11640. * initialiser.
  11641. * <p><code>':'.length + ';'.length</code></p>
  11642. * @const
  11643. * @type {number}
  11644. */
  11645. N_VARIABLE_DECLARATION: 2,
  11646. /**
  11647. * The number of terminal symbols required to introduce a variable
  11648. * statement (excluding its variable declaration list).
  11649. * <p><code>'var '.length</code></p>
  11650. * @const
  11651. * @type {number}
  11652. */
  11653. N_VARIABLE_STATEMENT_AFFIXATION: 4,
  11654. /**
  11655. * The number of terminal symbols needed to enclose source elements
  11656. * within a function call with no argument values to a function with an
  11657. * empty parameter list.
  11658. * <p><code>'(function(){}());'.length</code></p>
  11659. * @const
  11660. * @type {number}
  11661. */
  11662. N_CLOSURE: 17
  11663. },
  11664. /**
  11665. * Categories of primary expressions from which primitive values that
  11666. * could be consolidated are derivable.
  11667. * @namespace
  11668. * @enum {number}
  11669. */
  11670. EPrimaryExpressionCategories = {
  11671. /**
  11672. * Identifier names used as property accessors.
  11673. * @type {number}
  11674. */
  11675. N_IDENTIFIER_NAMES: 0,
  11676. /**
  11677. * String literals.
  11678. * @type {number}
  11679. */
  11680. N_STRING_LITERALS: 1,
  11681. /**
  11682. * Null and Boolean literals.
  11683. * @type {number}
  11684. */
  11685. N_NULL_AND_BOOLEAN_LITERALS: 2
  11686. },
  11687. /**
  11688. * Prefixes of primitive values that could be consolidated.
  11689. * The String values of the prefixes must have same number of characters.
  11690. * The prefixes must not be used in any properties defined in any version
  11691. * of <a href=
  11692. * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
  11693. * >ECMA-262</a>.
  11694. * @namespace
  11695. * @enum {string}
  11696. */
  11697. EValuePrefixes = {
  11698. /**
  11699. * Identifies String values.
  11700. * @type {string}
  11701. */
  11702. S_STRING: '#S',
  11703. /**
  11704. * Identifies null and Boolean values.
  11705. * @type {string}
  11706. */
  11707. S_SYMBOLIC: '#O'
  11708. },
  11709. /**
  11710. * Categories of source elements in terms of their appropriateness of
  11711. * having their primitive values consolidated.
  11712. * @namespace
  11713. * @enum {number}
  11714. */
  11715. ESourceElementCategories = {
  11716. /**
  11717. * Identifies a source element that includes the <a href=
  11718. * "http://es5.github.com/#x12.10">{@code with}</a> statement.
  11719. * @type {number}
  11720. */
  11721. N_WITH: 0,
  11722. /**
  11723. * Identifies a source element that includes the <a href=
  11724. * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
  11725. * @type {number}
  11726. */
  11727. N_EVAL: 1,
  11728. /**
  11729. * Identifies a source element that must be excluded from the process
  11730. * unless its whole scope is examined.
  11731. * @type {number}
  11732. */
  11733. N_EXCLUDABLE: 2,
  11734. /**
  11735. * Identifies source elements not posing any problems.
  11736. * @type {number}
  11737. */
  11738. N_OTHER: 3
  11739. },
  11740. /**
  11741. * The list of literals (other than the String ones) whose primitive
  11742. * values can be consolidated.
  11743. * @const
  11744. * @type {!Array.<string>}
  11745. */
  11746. A_OTHER_SUBSTITUTABLE_LITERALS = [
  11747. 'null', // The null literal.
  11748. 'false', // The Boolean literal {@code false}.
  11749. 'true' // The Boolean literal {@code true}.
  11750. ];
  11751. (/**
  11752. * Consolidates all worthwhile primitive values in a syntactic code unit.
  11753. * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
  11754. * representing the branch of the abstract syntax tree representing the
  11755. * syntactic code unit along with its scope.
  11756. * @see TPrimitiveValue#nSaving
  11757. */
  11758. function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
  11759. var _,
  11760. /**
  11761. * Indicates whether the syntactic code unit represents global code.
  11762. * @type {boolean}
  11763. */
  11764. bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
  11765. /**
  11766. * Indicates whether the whole scope is being examined.
  11767. * @type {boolean}
  11768. */
  11769. bIsWhollyExaminable = !bIsGlobal,
  11770. /**
  11771. * An array-like object representing source elements that constitute a
  11772. * syntactic code unit.
  11773. * @type {!TSyntacticCodeUnit}
  11774. */
  11775. oSourceElements,
  11776. /**
  11777. * A record consisting of data about the source element that is
  11778. * currently being examined.
  11779. * @type {!TSourceElementsData}
  11780. */
  11781. oSourceElementData,
  11782. /**
  11783. * The scope of the syntactic code unit.
  11784. * @type {!TScope}
  11785. */
  11786. oScope,
  11787. /**
  11788. * An instance of an object that allows the traversal of an <abbr
  11789. * title="abstract syntax tree">AST</abbr>.
  11790. * @type {!TWalker}
  11791. */
  11792. oWalker,
  11793. /**
  11794. * An object encompassing collections of functions used during the
  11795. * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
  11796. * @namespace
  11797. * @type {!Object.<string, !Object.<string, function(...[*])>>}
  11798. */
  11799. oWalkers = {
  11800. /**
  11801. * A collection of functions used during the surveyance of source
  11802. * elements.
  11803. * @namespace
  11804. * @type {!Object.<string, function(...[*])>}
  11805. */
  11806. oSurveySourceElement: {
  11807. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  11808. /**
  11809. * Classifies the source element as excludable if it does not
  11810. * contain a {@code with} statement or the {@code eval} identifier
  11811. * name. Adds the identifier of the function and its formal
  11812. * parameters to the list of identifier names found.
  11813. * @param {string} sIdentifier The identifier of the function.
  11814. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  11815. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  11816. */
  11817. 'defun': function(
  11818. sIdentifier,
  11819. aFormalParameterList,
  11820. oFunctionBody) {
  11821. fClassifyAsExcludable();
  11822. fAddIdentifier(sIdentifier);
  11823. aFormalParameterList.forEach(fAddIdentifier);
  11824. },
  11825. /**
  11826. * Increments the count of the number of occurrences of the String
  11827. * value that is equivalent to the sequence of terminal symbols
  11828. * that constitute the encountered identifier name.
  11829. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  11830. * MemberExpression.
  11831. * @param {string} sIdentifierName The identifier name used as the
  11832. * property accessor.
  11833. * @return {!Array} The encountered branch of an <abbr title=
  11834. * "abstract syntax tree">AST</abbr> with its nonterminal
  11835. * MemberExpression traversed.
  11836. */
  11837. 'dot': function(oExpression, sIdentifierName) {
  11838. fCountPrimaryExpression(
  11839. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
  11840. EValuePrefixes.S_STRING + sIdentifierName);
  11841. return ['dot', oWalker.walk(oExpression), sIdentifierName];
  11842. },
  11843. /**
  11844. * Adds the optional identifier of the function and its formal
  11845. * parameters to the list of identifier names found.
  11846. * @param {?string} sIdentifier The optional identifier of the
  11847. * function.
  11848. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  11849. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  11850. */
  11851. 'function': function(
  11852. sIdentifier,
  11853. aFormalParameterList,
  11854. oFunctionBody) {
  11855. if ('string' === typeof sIdentifier) {
  11856. fAddIdentifier(sIdentifier);
  11857. }
  11858. aFormalParameterList.forEach(fAddIdentifier);
  11859. },
  11860. /**
  11861. * Either increments the count of the number of occurrences of the
  11862. * encountered null or Boolean value or classifies a source element
  11863. * as containing the {@code eval} identifier name.
  11864. * @param {string} sIdentifier The identifier encountered.
  11865. */
  11866. 'name': function(sIdentifier) {
  11867. if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
  11868. fCountPrimaryExpression(
  11869. EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
  11870. EValuePrefixes.S_SYMBOLIC + sIdentifier);
  11871. } else {
  11872. if ('eval' === sIdentifier) {
  11873. oSourceElementData.nCategory =
  11874. ESourceElementCategories.N_EVAL;
  11875. }
  11876. fAddIdentifier(sIdentifier);
  11877. }
  11878. },
  11879. /**
  11880. * Classifies the source element as excludable if it does not
  11881. * contain a {@code with} statement or the {@code eval} identifier
  11882. * name.
  11883. * @param {TSyntacticCodeUnit} oExpression The expression whose
  11884. * value is to be returned.
  11885. */
  11886. 'return': function(oExpression) {
  11887. fClassifyAsExcludable();
  11888. },
  11889. /**
  11890. * Increments the count of the number of occurrences of the
  11891. * encountered String value.
  11892. * @param {string} sStringValue The String value of the string
  11893. * literal encountered.
  11894. */
  11895. 'string': function(sStringValue) {
  11896. if (sStringValue.length > 0) {
  11897. fCountPrimaryExpression(
  11898. EPrimaryExpressionCategories.N_STRING_LITERALS,
  11899. EValuePrefixes.S_STRING + sStringValue);
  11900. }
  11901. },
  11902. /**
  11903. * Adds the identifier reserved for an exception to the list of
  11904. * identifier names found.
  11905. * @param {!TSyntacticCodeUnit} oTry A block of code in which an
  11906. * exception can occur.
  11907. * @param {Array} aCatch The identifier reserved for an exception
  11908. * and a block of code to handle the exception.
  11909. * @param {TSyntacticCodeUnit} oFinally An optional block of code
  11910. * to be evaluated regardless of whether an exception occurs.
  11911. */
  11912. 'try': function(oTry, aCatch, oFinally) {
  11913. if (Array.isArray(aCatch)) {
  11914. fAddIdentifier(aCatch[0]);
  11915. }
  11916. },
  11917. /**
  11918. * Classifies the source element as excludable if it does not
  11919. * contain a {@code with} statement or the {@code eval} identifier
  11920. * name. Adds the identifier of each declared variable to the list
  11921. * of identifier names found.
  11922. * @param {!Array.<!Array>} aVariableDeclarationList Variable
  11923. * declarations.
  11924. */
  11925. 'var': function(aVariableDeclarationList) {
  11926. fClassifyAsExcludable();
  11927. aVariableDeclarationList.forEach(fAddVariable);
  11928. },
  11929. /**
  11930. * Classifies a source element as containing the {@code with}
  11931. * statement.
  11932. * @param {!TSyntacticCodeUnit} oExpression An expression whose
  11933. * value is to be converted to a value of type Object and
  11934. * become the binding object of a new object environment
  11935. * record of a new lexical environment in which the statement
  11936. * is to be executed.
  11937. * @param {!TSyntacticCodeUnit} oStatement The statement to be
  11938. * executed in the augmented lexical environment.
  11939. * @return {!Array} An empty array to stop the traversal.
  11940. */
  11941. 'with': function(oExpression, oStatement) {
  11942. oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
  11943. return [];
  11944. }
  11945. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  11946. },
  11947. /**
  11948. * A collection of functions used while looking for nested functions.
  11949. * @namespace
  11950. * @type {!Object.<string, function(...[*])>}
  11951. */
  11952. oExamineFunctions: {
  11953. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  11954. /**
  11955. * Orders an examination of a nested function declaration.
  11956. * @this {!TSyntacticCodeUnit} An array-like object representing
  11957. * the branch of an <abbr title="abstract syntax tree"
  11958. * >AST</abbr> representing the syntactic code unit along with
  11959. * its scope.
  11960. * @return {!Array} An empty array to stop the traversal.
  11961. */
  11962. 'defun': function() {
  11963. fExamineSyntacticCodeUnit(this);
  11964. return [];
  11965. },
  11966. /**
  11967. * Orders an examination of a nested function expression.
  11968. * @this {!TSyntacticCodeUnit} An array-like object representing
  11969. * the branch of an <abbr title="abstract syntax tree"
  11970. * >AST</abbr> representing the syntactic code unit along with
  11971. * its scope.
  11972. * @return {!Array} An empty array to stop the traversal.
  11973. */
  11974. 'function': function() {
  11975. fExamineSyntacticCodeUnit(this);
  11976. return [];
  11977. }
  11978. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  11979. }
  11980. },
  11981. /**
  11982. * Records containing data about source elements.
  11983. * @type {Array.<TSourceElementsData>}
  11984. */
  11985. aSourceElementsData = [],
  11986. /**
  11987. * The index (in the source text order) of the source element
  11988. * immediately following a <a href="http://es5.github.com/#x14.1"
  11989. * >Directive Prologue</a>.
  11990. * @type {number}
  11991. */
  11992. nAfterDirectivePrologue = 0,
  11993. /**
  11994. * The index (in the source text order) of the source element that is
  11995. * currently being considered.
  11996. * @type {number}
  11997. */
  11998. nPosition,
  11999. /**
  12000. * The index (in the source text order) of the source element that is
  12001. * the last element of the range of source elements that is currently
  12002. * being considered.
  12003. * @type {(undefined|number)}
  12004. */
  12005. nTo,
  12006. /**
  12007. * Initiates the traversal of a source element.
  12008. * @param {!TWalker} oWalker An instance of an object that allows the
  12009. * traversal of an abstract syntax tree.
  12010. * @param {!TSyntacticCodeUnit} oSourceElement A source element from
  12011. * which the traversal should commence.
  12012. * @return {function(): !TSyntacticCodeUnit} A function that is able to
  12013. * initiate the traversal from a given source element.
  12014. */
  12015. cContext = function(oWalker, oSourceElement) {
  12016. /**
  12017. * @return {!TSyntacticCodeUnit} A function that is able to
  12018. * initiate the traversal from a given source element.
  12019. */
  12020. var fLambda = function() {
  12021. return oWalker.walk(oSourceElement);
  12022. };
  12023. return fLambda;
  12024. },
  12025. /**
  12026. * Classifies the source element as excludable if it does not
  12027. * contain a {@code with} statement or the {@code eval} identifier
  12028. * name.
  12029. */
  12030. fClassifyAsExcludable = function() {
  12031. if (oSourceElementData.nCategory ===
  12032. ESourceElementCategories.N_OTHER) {
  12033. oSourceElementData.nCategory =
  12034. ESourceElementCategories.N_EXCLUDABLE;
  12035. }
  12036. },
  12037. /**
  12038. * Adds an identifier to the list of identifier names found.
  12039. * @param {string} sIdentifier The identifier to be added.
  12040. */
  12041. fAddIdentifier = function(sIdentifier) {
  12042. if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
  12043. oSourceElementData.aIdentifiers.push(sIdentifier);
  12044. }
  12045. },
  12046. /**
  12047. * Adds the identifier of a variable to the list of identifier names
  12048. * found.
  12049. * @param {!Array} aVariableDeclaration A variable declaration.
  12050. */
  12051. fAddVariable = function(aVariableDeclaration) {
  12052. fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
  12053. },
  12054. /**
  12055. * Increments the count of the number of occurrences of the prefixed
  12056. * String representation attributed to the primary expression.
  12057. * @param {number} nCategory The category of the primary expression.
  12058. * @param {string} sName The prefixed String representation attributed
  12059. * to the primary expression.
  12060. */
  12061. fCountPrimaryExpression = function(nCategory, sName) {
  12062. if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
  12063. oSourceElementData.aCount[nCategory][sName] = 0;
  12064. if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
  12065. oSourceElementData.aPrimitiveValues.push(sName);
  12066. }
  12067. }
  12068. oSourceElementData.aCount[nCategory][sName] += 1;
  12069. },
  12070. /**
  12071. * Consolidates all worthwhile primitive values in a range of source
  12072. * elements.
  12073. * @param {number} nFrom The index (in the source text order) of the
  12074. * source element that is the first element of the range.
  12075. * @param {number} nTo The index (in the source text order) of the
  12076. * source element that is the last element of the range.
  12077. * @param {boolean} bEnclose Indicates whether the range should be
  12078. * enclosed within a function call with no argument values to a
  12079. * function with an empty parameter list if any primitive values
  12080. * are consolidated.
  12081. * @see TPrimitiveValue#nSaving
  12082. */
  12083. fExamineSourceElements = function(nFrom, nTo, bEnclose) {
  12084. var _,
  12085. /**
  12086. * The index of the last mangled name.
  12087. * @type {number}
  12088. */
  12089. nIndex = oScope.cname,
  12090. /**
  12091. * The index of the source element that is currently being
  12092. * considered.
  12093. * @type {number}
  12094. */
  12095. nPosition,
  12096. /**
  12097. * A collection of functions used during the consolidation of
  12098. * primitive values and identifier names used as property
  12099. * accessors.
  12100. * @namespace
  12101. * @type {!Object.<string, function(...[*])>}
  12102. */
  12103. oWalkersTransformers = {
  12104. /**
  12105. * If the String value that is equivalent to the sequence of
  12106. * terminal symbols that constitute the encountered identifier
  12107. * name is worthwhile, a syntactic conversion from the dot
  12108. * notation to the bracket notation ensues with that sequence
  12109. * being substituted by an identifier name to which the value
  12110. * is assigned.
  12111. * Applies to property accessors that use the dot notation.
  12112. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  12113. * MemberExpression.
  12114. * @param {string} sIdentifierName The identifier name used as
  12115. * the property accessor.
  12116. * @return {!Array} A syntactic code unit that is equivalent to
  12117. * the one encountered.
  12118. * @see TPrimitiveValue#nSaving
  12119. */
  12120. 'dot': function(oExpression, sIdentifierName) {
  12121. /**
  12122. * The prefixed String value that is equivalent to the
  12123. * sequence of terminal symbols that constitute the
  12124. * encountered identifier name.
  12125. * @type {string}
  12126. */
  12127. var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
  12128. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  12129. sPrefixed) &&
  12130. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  12131. ['sub',
  12132. oWalker.walk(oExpression),
  12133. ['name',
  12134. oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
  12135. ['dot', oWalker.walk(oExpression), sIdentifierName];
  12136. },
  12137. /**
  12138. * If the encountered identifier is a null or Boolean literal
  12139. * and its value is worthwhile, the identifier is substituted
  12140. * by an identifier name to which that value is assigned.
  12141. * Applies to identifier names.
  12142. * @param {string} sIdentifier The identifier encountered.
  12143. * @return {!Array} A syntactic code unit that is equivalent to
  12144. * the one encountered.
  12145. * @see TPrimitiveValue#nSaving
  12146. */
  12147. 'name': function(sIdentifier) {
  12148. /**
  12149. * The prefixed representation String of the identifier.
  12150. * @type {string}
  12151. */
  12152. var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
  12153. return [
  12154. 'name',
  12155. oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
  12156. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  12157. oSolutionBest.oPrimitiveValues[sPrefixed].sName :
  12158. sIdentifier
  12159. ];
  12160. },
  12161. /**
  12162. * If the encountered String value is worthwhile, it is
  12163. * substituted by an identifier name to which that value is
  12164. * assigned.
  12165. * Applies to String values.
  12166. * @param {string} sStringValue The String value of the string
  12167. * literal encountered.
  12168. * @return {!Array} A syntactic code unit that is equivalent to
  12169. * the one encountered.
  12170. * @see TPrimitiveValue#nSaving
  12171. */
  12172. 'string': function(sStringValue) {
  12173. /**
  12174. * The prefixed representation String of the primitive value
  12175. * of the literal.
  12176. * @type {string}
  12177. */
  12178. var sPrefixed =
  12179. EValuePrefixes.S_STRING + sStringValue;
  12180. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  12181. sPrefixed) &&
  12182. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  12183. ['name',
  12184. oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
  12185. ['string', sStringValue];
  12186. }
  12187. },
  12188. /**
  12189. * Such data on what to consolidate within the range of source
  12190. * elements that is currently being considered that lead to the
  12191. * greatest known reduction of the number of the terminal symbols
  12192. * in comparison to the original source text.
  12193. * @type {!TSolution}
  12194. */
  12195. oSolutionBest = new TSolution(),
  12196. /**
  12197. * Data representing an ongoing attempt to find a better
  12198. * reduction of the number of the terminal symbols in comparison
  12199. * to the original source text than the best one that is
  12200. * currently known.
  12201. * @type {!TSolution}
  12202. * @see oSolutionBest
  12203. */
  12204. oSolutionCandidate = new TSolution(),
  12205. /**
  12206. * A record consisting of data about the range of source elements
  12207. * that is currently being examined.
  12208. * @type {!TSourceElementsData}
  12209. */
  12210. oSourceElementsData = new TSourceElementsData(),
  12211. /**
  12212. * Variable declarations for each primitive value that is to be
  12213. * consolidated within the elements.
  12214. * @type {!Array.<!Array>}
  12215. */
  12216. aVariableDeclarations = [],
  12217. /**
  12218. * Augments a list with a prefixed representation String.
  12219. * @param {!Array.<string>} aList A list that is to be augmented.
  12220. * @return {function(string)} A function that augments a list
  12221. * with a prefixed representation String.
  12222. */
  12223. cAugmentList = function(aList) {
  12224. /**
  12225. * @param {string} sPrefixed Prefixed representation String of
  12226. * a primitive value that could be consolidated within the
  12227. * elements.
  12228. */
  12229. var fLambda = function(sPrefixed) {
  12230. if (-1 === aList.indexOf(sPrefixed)) {
  12231. aList.push(sPrefixed);
  12232. }
  12233. };
  12234. return fLambda;
  12235. },
  12236. /**
  12237. * Adds the number of occurrences of a primitive value of a given
  12238. * category that could be consolidated in the source element with
  12239. * a given index to the count of occurrences of that primitive
  12240. * value within the range of source elements that is currently
  12241. * being considered.
  12242. * @param {number} nPosition The index (in the source text order)
  12243. * of a source element.
  12244. * @param {number} nCategory The category of the primary
  12245. * expression from which the primitive value is derived.
  12246. * @return {function(string)} A function that performs the
  12247. * addition.
  12248. * @see cAddOccurrencesInCategory
  12249. */
  12250. cAddOccurrences = function(nPosition, nCategory) {
  12251. /**
  12252. * @param {string} sPrefixed The prefixed representation String
  12253. * of a primitive value.
  12254. */
  12255. var fLambda = function(sPrefixed) {
  12256. if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
  12257. sPrefixed)) {
  12258. oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
  12259. }
  12260. oSourceElementsData.aCount[nCategory][sPrefixed] +=
  12261. aSourceElementsData[nPosition].aCount[nCategory][
  12262. sPrefixed];
  12263. };
  12264. return fLambda;
  12265. },
  12266. /**
  12267. * Adds the number of occurrences of each primitive value of a
  12268. * given category that could be consolidated in the source
  12269. * element with a given index to the count of occurrences of that
  12270. * primitive values within the range of source elements that is
  12271. * currently being considered.
  12272. * @param {number} nPosition The index (in the source text order)
  12273. * of a source element.
  12274. * @return {function(number)} A function that performs the
  12275. * addition.
  12276. * @see fAddOccurrences
  12277. */
  12278. cAddOccurrencesInCategory = function(nPosition) {
  12279. /**
  12280. * @param {number} nCategory The category of the primary
  12281. * expression from which the primitive value is derived.
  12282. */
  12283. var fLambda = function(nCategory) {
  12284. Object.keys(
  12285. aSourceElementsData[nPosition].aCount[nCategory]
  12286. ).forEach(cAddOccurrences(nPosition, nCategory));
  12287. };
  12288. return fLambda;
  12289. },
  12290. /**
  12291. * Adds the number of occurrences of each primitive value that
  12292. * could be consolidated in the source element with a given index
  12293. * to the count of occurrences of that primitive values within
  12294. * the range of source elements that is currently being
  12295. * considered.
  12296. * @param {number} nPosition The index (in the source text order)
  12297. * of a source element.
  12298. */
  12299. fAddOccurrences = function(nPosition) {
  12300. Object.keys(aSourceElementsData[nPosition].aCount).forEach(
  12301. cAddOccurrencesInCategory(nPosition));
  12302. },
  12303. /**
  12304. * Creates a variable declaration for a primitive value if that
  12305. * primitive value is to be consolidated within the elements.
  12306. * @param {string} sPrefixed Prefixed representation String of a
  12307. * primitive value that could be consolidated within the
  12308. * elements.
  12309. * @see aVariableDeclarations
  12310. */
  12311. cAugmentVariableDeclarations = function(sPrefixed) {
  12312. if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
  12313. aVariableDeclarations.push([
  12314. oSolutionBest.oPrimitiveValues[sPrefixed].sName,
  12315. [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
  12316. 'name' : 'string',
  12317. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
  12318. ]);
  12319. }
  12320. },
  12321. /**
  12322. * Sorts primitive values with regard to the difference in the
  12323. * number of terminal symbols between the original source text
  12324. * and the one with those primitive values consolidated.
  12325. * @param {string} sPrefixed0 The prefixed representation String
  12326. * of the first of the two primitive values that are being
  12327. * compared.
  12328. * @param {string} sPrefixed1 The prefixed representation String
  12329. * of the second of the two primitive values that are being
  12330. * compared.
  12331. * @return {number}
  12332. * <dl>
  12333. * <dt>-1</dt>
  12334. * <dd>if the first primitive value must be placed before
  12335. * the other one,</dd>
  12336. * <dt>0</dt>
  12337. * <dd>if the first primitive value may be placed before
  12338. * the other one,</dd>
  12339. * <dt>1</dt>
  12340. * <dd>if the first primitive value must not be placed
  12341. * before the other one.</dd>
  12342. * </dl>
  12343. * @see TSolution.oPrimitiveValues
  12344. */
  12345. cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
  12346. /**
  12347. * The difference between:
  12348. * <ol>
  12349. * <li>the difference in the number of terminal symbols
  12350. * between the original source text and the one with the
  12351. * first primitive value consolidated, and</li>
  12352. * <li>the difference in the number of terminal symbols
  12353. * between the original source text and the one with the
  12354. * second primitive value consolidated.</li>
  12355. * </ol>
  12356. * @type {number}
  12357. */
  12358. var nDifference =
  12359. oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
  12360. oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
  12361. return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
  12362. },
  12363. /**
  12364. * Assigns an identifier name to a primitive value and calculates
  12365. * whether instances of that primitive value are worth
  12366. * consolidating.
  12367. * @param {string} sPrefixed The prefixed representation String
  12368. * of a primitive value that is being evaluated.
  12369. */
  12370. fEvaluatePrimitiveValue = function(sPrefixed) {
  12371. var _,
  12372. /**
  12373. * The index of the last mangled name.
  12374. * @type {number}
  12375. */
  12376. nIndex,
  12377. /**
  12378. * The representation String of the primitive value that is
  12379. * being evaluated.
  12380. * @type {string}
  12381. */
  12382. sName =
  12383. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
  12384. /**
  12385. * The number of source characters taken up by the
  12386. * representation String of the primitive value that is
  12387. * being evaluated.
  12388. * @type {number}
  12389. */
  12390. nLengthOriginal = sName.length,
  12391. /**
  12392. * The number of source characters taken up by the
  12393. * identifier name that could substitute the primitive
  12394. * value that is being evaluated.
  12395. * substituted.
  12396. * @type {number}
  12397. */
  12398. nLengthSubstitution,
  12399. /**
  12400. * The number of source characters taken up by by the
  12401. * representation String of the primitive value that is
  12402. * being evaluated when it is represented by a string
  12403. * literal.
  12404. * @type {number}
  12405. */
  12406. nLengthString = oProcessor.make_string(sName).length;
  12407. oSolutionCandidate.oPrimitiveValues[sPrefixed] =
  12408. new TPrimitiveValue();
  12409. do { // Find an identifier unused in this or any nested scope.
  12410. nIndex = oScope.cname;
  12411. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
  12412. oScope.next_mangled();
  12413. } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
  12414. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
  12415. nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
  12416. sPrefixed].sName.length;
  12417. if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
  12418. // foo:null, or foo:null;
  12419. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  12420. nLengthSubstitution + nLengthOriginal +
  12421. oWeights.N_VARIABLE_DECLARATION;
  12422. // null vs foo
  12423. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  12424. oSourceElementsData.aCount[
  12425. EPrimaryExpressionCategories.
  12426. N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
  12427. (nLengthOriginal - nLengthSubstitution);
  12428. } else {
  12429. // foo:'fromCharCode';
  12430. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  12431. nLengthSubstitution + nLengthString +
  12432. oWeights.N_VARIABLE_DECLARATION;
  12433. // .fromCharCode vs [foo]
  12434. if (oSourceElementsData.aCount[
  12435. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  12436. ].hasOwnProperty(sPrefixed)) {
  12437. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  12438. oSourceElementsData.aCount[
  12439. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  12440. ][sPrefixed] *
  12441. (nLengthOriginal - nLengthSubstitution -
  12442. oWeights.N_PROPERTY_ACCESSOR);
  12443. }
  12444. // 'fromCharCode' vs foo
  12445. if (oSourceElementsData.aCount[
  12446. EPrimaryExpressionCategories.N_STRING_LITERALS
  12447. ].hasOwnProperty(sPrefixed)) {
  12448. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  12449. oSourceElementsData.aCount[
  12450. EPrimaryExpressionCategories.N_STRING_LITERALS
  12451. ][sPrefixed] *
  12452. (nLengthString - nLengthSubstitution);
  12453. }
  12454. }
  12455. if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
  12456. 0) {
  12457. oSolutionCandidate.nSavings +=
  12458. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
  12459. } else {
  12460. oScope.cname = nIndex; // Free the identifier name.
  12461. }
  12462. },
  12463. /**
  12464. * Adds a variable declaration to an existing variable statement.
  12465. * @param {!Array} aVariableDeclaration A variable declaration
  12466. * with an initialiser.
  12467. */
  12468. cAddVariableDeclaration = function(aVariableDeclaration) {
  12469. (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
  12470. aVariableDeclaration);
  12471. };
  12472. if (nFrom > nTo) {
  12473. return;
  12474. }
  12475. // If the range is a closure, reuse the closure.
  12476. if (nFrom === nTo &&
  12477. 'stat' === oSourceElements[nFrom][0] &&
  12478. 'call' === oSourceElements[nFrom][1][0] &&
  12479. 'function' === oSourceElements[nFrom][1][1][0]) {
  12480. fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
  12481. return;
  12482. }
  12483. // Create a list of all derived primitive values within the range.
  12484. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  12485. aSourceElementsData[nPosition].aPrimitiveValues.forEach(
  12486. cAugmentList(oSourceElementsData.aPrimitiveValues));
  12487. }
  12488. if (0 === oSourceElementsData.aPrimitiveValues.length) {
  12489. return;
  12490. }
  12491. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  12492. // Add the number of occurrences to the total count.
  12493. fAddOccurrences(nPosition);
  12494. // Add identifiers of this or any nested scope to the list.
  12495. aSourceElementsData[nPosition].aIdentifiers.forEach(
  12496. cAugmentList(oSourceElementsData.aIdentifiers));
  12497. }
  12498. // Distribute identifier names among derived primitive values.
  12499. do { // If there was any progress, find a better distribution.
  12500. oSolutionBest = oSolutionCandidate;
  12501. if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
  12502. // Sort primitive values descending by their worthwhileness.
  12503. oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
  12504. }
  12505. oSolutionCandidate = new TSolution();
  12506. oSourceElementsData.aPrimitiveValues.forEach(
  12507. fEvaluatePrimitiveValue);
  12508. oScope.cname = nIndex;
  12509. } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
  12510. // Take the necessity of adding a variable statement into account.
  12511. if ('var' !== oSourceElements[nFrom][0]) {
  12512. oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
  12513. }
  12514. if (bEnclose) {
  12515. // Take the necessity of forming a closure into account.
  12516. oSolutionBest.nSavings -= oWeights.N_CLOSURE;
  12517. }
  12518. if (oSolutionBest.nSavings > 0) {
  12519. // Create variable declarations suitable for UglifyJS.
  12520. Object.keys(oSolutionBest.oPrimitiveValues).forEach(
  12521. cAugmentVariableDeclarations);
  12522. // Rewrite expressions that contain worthwhile primitive values.
  12523. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  12524. oWalker = oProcessor.ast_walker();
  12525. oSourceElements[nPosition] =
  12526. oWalker.with_walkers(
  12527. oWalkersTransformers,
  12528. cContext(oWalker, oSourceElements[nPosition]));
  12529. }
  12530. if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
  12531. (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
  12532. )).forEach(cAddVariableDeclaration);
  12533. } else { // Add a variable statement.
  12534. Array.prototype.splice.call(
  12535. oSourceElements,
  12536. nFrom,
  12537. 0,
  12538. ['var', aVariableDeclarations]);
  12539. nTo += 1;
  12540. }
  12541. if (bEnclose) {
  12542. // Add a closure.
  12543. Array.prototype.splice.call(
  12544. oSourceElements,
  12545. nFrom,
  12546. 0,
  12547. ['stat', ['call', ['function', null, [], []], []]]);
  12548. // Copy source elements into the closure.
  12549. for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
  12550. Array.prototype.unshift.call(
  12551. oSourceElements[nFrom][1][1][3],
  12552. oSourceElements[nPosition]);
  12553. }
  12554. // Remove source elements outside the closure.
  12555. Array.prototype.splice.call(
  12556. oSourceElements,
  12557. nFrom + 1,
  12558. nTo - nFrom + 1);
  12559. }
  12560. }
  12561. if (bEnclose) {
  12562. // Restore the availability of identifier names.
  12563. oScope.cname = nIndex;
  12564. }
  12565. };
  12566. oSourceElements = (/** @type {!TSyntacticCodeUnit} */
  12567. oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
  12568. if (0 === oSourceElements.length) {
  12569. return;
  12570. }
  12571. oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
  12572. // Skip a Directive Prologue.
  12573. while (nAfterDirectivePrologue < oSourceElements.length &&
  12574. 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
  12575. nAfterDirectivePrologue += 1;
  12576. aSourceElementsData.push(null);
  12577. }
  12578. if (oSourceElements.length === nAfterDirectivePrologue) {
  12579. return;
  12580. }
  12581. for (nPosition = nAfterDirectivePrologue;
  12582. nPosition < oSourceElements.length;
  12583. nPosition += 1) {
  12584. oSourceElementData = new TSourceElementsData();
  12585. oWalker = oProcessor.ast_walker();
  12586. // Classify a source element.
  12587. // Find its derived primitive values and count their occurrences.
  12588. // Find all identifiers used (including nested scopes).
  12589. oWalker.with_walkers(
  12590. oWalkers.oSurveySourceElement,
  12591. cContext(oWalker, oSourceElements[nPosition]));
  12592. // Establish whether the scope is still wholly examinable.
  12593. bIsWhollyExaminable = bIsWhollyExaminable &&
  12594. ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
  12595. ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
  12596. aSourceElementsData.push(oSourceElementData);
  12597. }
  12598. if (bIsWhollyExaminable) { // Examine the whole scope.
  12599. fExamineSourceElements(
  12600. nAfterDirectivePrologue,
  12601. oSourceElements.length - 1,
  12602. false);
  12603. } else { // Examine unexcluded ranges of source elements.
  12604. for (nPosition = oSourceElements.length - 1;
  12605. nPosition >= nAfterDirectivePrologue;
  12606. nPosition -= 1) {
  12607. oSourceElementData = (/** @type {!TSourceElementsData} */
  12608. aSourceElementsData[nPosition]);
  12609. if (ESourceElementCategories.N_OTHER ===
  12610. oSourceElementData.nCategory) {
  12611. if ('undefined' === typeof nTo) {
  12612. nTo = nPosition; // Indicate the end of a range.
  12613. }
  12614. // Examine the range if it immediately follows a Directive Prologue.
  12615. if (nPosition === nAfterDirectivePrologue) {
  12616. fExamineSourceElements(nPosition, nTo, true);
  12617. }
  12618. } else {
  12619. if ('undefined' !== typeof nTo) {
  12620. // Examine the range that immediately follows this source element.
  12621. fExamineSourceElements(nPosition + 1, nTo, true);
  12622. nTo = void 0; // Obliterate the range.
  12623. }
  12624. // Examine nested functions.
  12625. oWalker = oProcessor.ast_walker();
  12626. oWalker.with_walkers(
  12627. oWalkers.oExamineFunctions,
  12628. cContext(oWalker, oSourceElements[nPosition]));
  12629. }
  12630. }
  12631. }
  12632. }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
  12633. return oAbstractSyntaxTree;
  12634. };
  12635. /*jshint sub:false */
  12636. /* Local Variables: */
  12637. /* mode: js */
  12638. /* coding: utf-8 */
  12639. /* indent-tabs-mode: nil */
  12640. /* tab-width: 2 */
  12641. /* End: */
  12642. /* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
  12643. /* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
  12644. });
  12645. define('uglifyjs/parse-js', ["exports"], function(exports) {
  12646. /***********************************************************************
  12647. A JavaScript tokenizer / parser / beautifier / compressor.
  12648. This version is suitable for Node.js. With minimal changes (the
  12649. exports stuff) it should work on any JS platform.
  12650. This file contains the tokenizer/parser. It is a port to JavaScript
  12651. of parse-js [1], a JavaScript parser library written in Common Lisp
  12652. by Marijn Haverbeke. Thank you Marijn!
  12653. [1] http://marijn.haverbeke.nl/parse-js/
  12654. Exported functions:
  12655. - tokenizer(code) -- returns a function. Call the returned
  12656. function to fetch the next token.
  12657. - parse(code) -- returns an AST of the given JavaScript code.
  12658. -------------------------------- (C) ---------------------------------
  12659. Author: Mihai Bazon
  12660. <mihai.bazon@gmail.com>
  12661. http://mihai.bazon.net/blog
  12662. Distributed under the BSD license:
  12663. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  12664. Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  12665. Redistribution and use in source and binary forms, with or without
  12666. modification, are permitted provided that the following conditions
  12667. are met:
  12668. * Redistributions of source code must retain the above
  12669. copyright notice, this list of conditions and the following
  12670. disclaimer.
  12671. * Redistributions in binary form must reproduce the above
  12672. copyright notice, this list of conditions and the following
  12673. disclaimer in the documentation and/or other materials
  12674. provided with the distribution.
  12675. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  12676. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12677. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  12678. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  12679. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  12680. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  12681. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  12682. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12683. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  12684. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  12685. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12686. SUCH DAMAGE.
  12687. ***********************************************************************/
  12688. /* -----[ Tokenizer (constants) ]----- */
  12689. var KEYWORDS = array_to_hash([
  12690. "break",
  12691. "case",
  12692. "catch",
  12693. "const",
  12694. "continue",
  12695. "debugger",
  12696. "default",
  12697. "delete",
  12698. "do",
  12699. "else",
  12700. "finally",
  12701. "for",
  12702. "function",
  12703. "if",
  12704. "in",
  12705. "instanceof",
  12706. "new",
  12707. "return",
  12708. "switch",
  12709. "throw",
  12710. "try",
  12711. "typeof",
  12712. "var",
  12713. "void",
  12714. "while",
  12715. "with"
  12716. ]);
  12717. var RESERVED_WORDS = array_to_hash([
  12718. "abstract",
  12719. "boolean",
  12720. "byte",
  12721. "char",
  12722. "class",
  12723. "double",
  12724. "enum",
  12725. "export",
  12726. "extends",
  12727. "final",
  12728. "float",
  12729. "goto",
  12730. "implements",
  12731. "import",
  12732. "int",
  12733. "interface",
  12734. "long",
  12735. "native",
  12736. "package",
  12737. "private",
  12738. "protected",
  12739. "public",
  12740. "short",
  12741. "static",
  12742. "super",
  12743. "synchronized",
  12744. "throws",
  12745. "transient",
  12746. "volatile"
  12747. ]);
  12748. var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
  12749. "return",
  12750. "new",
  12751. "delete",
  12752. "throw",
  12753. "else",
  12754. "case"
  12755. ]);
  12756. var KEYWORDS_ATOM = array_to_hash([
  12757. "false",
  12758. "null",
  12759. "true",
  12760. "undefined"
  12761. ]);
  12762. var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
  12763. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  12764. var RE_OCT_NUMBER = /^0[0-7]+$/;
  12765. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  12766. var OPERATORS = array_to_hash([
  12767. "in",
  12768. "instanceof",
  12769. "typeof",
  12770. "new",
  12771. "void",
  12772. "delete",
  12773. "++",
  12774. "--",
  12775. "+",
  12776. "-",
  12777. "!",
  12778. "~",
  12779. "&",
  12780. "|",
  12781. "^",
  12782. "*",
  12783. "/",
  12784. "%",
  12785. ">>",
  12786. "<<",
  12787. ">>>",
  12788. "<",
  12789. ">",
  12790. "<=",
  12791. ">=",
  12792. "==",
  12793. "===",
  12794. "!=",
  12795. "!==",
  12796. "?",
  12797. "=",
  12798. "+=",
  12799. "-=",
  12800. "/=",
  12801. "*=",
  12802. "%=",
  12803. ">>=",
  12804. "<<=",
  12805. ">>>=",
  12806. "|=",
  12807. "^=",
  12808. "&=",
  12809. "&&",
  12810. "||"
  12811. ]);
  12812. 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"));
  12813. var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
  12814. var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
  12815. var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
  12816. /* -----[ Tokenizer ]----- */
  12817. var UNICODE = { // Unicode 6.1
  12818. 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]"),
  12819. 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]"),
  12820. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
  12821. 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]")
  12822. };
  12823. function is_letter(ch) {
  12824. return UNICODE.letter.test(ch);
  12825. };
  12826. function is_digit(ch) {
  12827. ch = ch.charCodeAt(0);
  12828. return ch >= 48 && ch <= 57;
  12829. };
  12830. function is_unicode_digit(ch) {
  12831. return UNICODE.digit.test(ch);
  12832. }
  12833. function is_alphanumeric_char(ch) {
  12834. return is_digit(ch) || is_letter(ch);
  12835. };
  12836. function is_unicode_combining_mark(ch) {
  12837. return UNICODE.combining_mark.test(ch);
  12838. };
  12839. function is_unicode_connector_punctuation(ch) {
  12840. return UNICODE.connector_punctuation.test(ch);
  12841. };
  12842. function is_identifier_start(ch) {
  12843. return ch == "$" || ch == "_" || is_letter(ch);
  12844. };
  12845. function is_identifier_char(ch) {
  12846. return is_identifier_start(ch)
  12847. || is_unicode_combining_mark(ch)
  12848. || is_unicode_digit(ch)
  12849. || is_unicode_connector_punctuation(ch)
  12850. || ch == "\u200c" // zero-width non-joiner <ZWNJ>
  12851. || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  12852. ;
  12853. };
  12854. function parse_js_number(num) {
  12855. if (RE_HEX_NUMBER.test(num)) {
  12856. return parseInt(num.substr(2), 16);
  12857. } else if (RE_OCT_NUMBER.test(num)) {
  12858. return parseInt(num.substr(1), 8);
  12859. } else if (RE_DEC_NUMBER.test(num)) {
  12860. return parseFloat(num);
  12861. }
  12862. };
  12863. function JS_Parse_Error(message, line, col, pos) {
  12864. this.message = message;
  12865. this.line = line + 1;
  12866. this.col = col + 1;
  12867. this.pos = pos + 1;
  12868. this.stack = new Error().stack;
  12869. };
  12870. JS_Parse_Error.prototype.toString = function() {
  12871. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  12872. };
  12873. function js_error(message, line, col, pos) {
  12874. throw new JS_Parse_Error(message, line, col, pos);
  12875. };
  12876. function is_token(token, type, val) {
  12877. return token.type == type && (val == null || token.value == val);
  12878. };
  12879. var EX_EOF = {};
  12880. function tokenizer($TEXT) {
  12881. var S = {
  12882. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
  12883. pos : 0,
  12884. tokpos : 0,
  12885. line : 0,
  12886. tokline : 0,
  12887. col : 0,
  12888. tokcol : 0,
  12889. newline_before : false,
  12890. regex_allowed : false,
  12891. comments_before : []
  12892. };
  12893. function peek() { return S.text.charAt(S.pos); };
  12894. function next(signal_eof, in_string) {
  12895. var ch = S.text.charAt(S.pos++);
  12896. if (signal_eof && !ch)
  12897. throw EX_EOF;
  12898. if (ch == "\n") {
  12899. S.newline_before = S.newline_before || !in_string;
  12900. ++S.line;
  12901. S.col = 0;
  12902. } else {
  12903. ++S.col;
  12904. }
  12905. return ch;
  12906. };
  12907. function eof() {
  12908. return !S.peek();
  12909. };
  12910. function find(what, signal_eof) {
  12911. var pos = S.text.indexOf(what, S.pos);
  12912. if (signal_eof && pos == -1) throw EX_EOF;
  12913. return pos;
  12914. };
  12915. function start_token() {
  12916. S.tokline = S.line;
  12917. S.tokcol = S.col;
  12918. S.tokpos = S.pos;
  12919. };
  12920. function token(type, value, is_comment) {
  12921. S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
  12922. (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
  12923. (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
  12924. var ret = {
  12925. type : type,
  12926. value : value,
  12927. line : S.tokline,
  12928. col : S.tokcol,
  12929. pos : S.tokpos,
  12930. endpos : S.pos,
  12931. nlb : S.newline_before
  12932. };
  12933. if (!is_comment) {
  12934. ret.comments_before = S.comments_before;
  12935. S.comments_before = [];
  12936. // make note of any newlines in the comments that came before
  12937. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  12938. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  12939. }
  12940. }
  12941. S.newline_before = false;
  12942. return ret;
  12943. };
  12944. function skip_whitespace() {
  12945. while (HOP(WHITESPACE_CHARS, peek()))
  12946. next();
  12947. };
  12948. function read_while(pred) {
  12949. var ret = "", ch = peek(), i = 0;
  12950. while (ch && pred(ch, i++)) {
  12951. ret += next();
  12952. ch = peek();
  12953. }
  12954. return ret;
  12955. };
  12956. function parse_error(err) {
  12957. js_error(err, S.tokline, S.tokcol, S.tokpos);
  12958. };
  12959. function read_num(prefix) {
  12960. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  12961. var num = read_while(function(ch, i){
  12962. if (ch == "x" || ch == "X") {
  12963. if (has_x) return false;
  12964. return has_x = true;
  12965. }
  12966. if (!has_x && (ch == "E" || ch == "e")) {
  12967. if (has_e) return false;
  12968. return has_e = after_e = true;
  12969. }
  12970. if (ch == "-") {
  12971. if (after_e || (i == 0 && !prefix)) return true;
  12972. return false;
  12973. }
  12974. if (ch == "+") return after_e;
  12975. after_e = false;
  12976. if (ch == ".") {
  12977. if (!has_dot && !has_x && !has_e)
  12978. return has_dot = true;
  12979. return false;
  12980. }
  12981. return is_alphanumeric_char(ch);
  12982. });
  12983. if (prefix)
  12984. num = prefix + num;
  12985. var valid = parse_js_number(num);
  12986. if (!isNaN(valid)) {
  12987. return token("num", valid);
  12988. } else {
  12989. parse_error("Invalid syntax: " + num);
  12990. }
  12991. };
  12992. function read_escaped_char(in_string) {
  12993. var ch = next(true, in_string);
  12994. switch (ch) {
  12995. case "n" : return "\n";
  12996. case "r" : return "\r";
  12997. case "t" : return "\t";
  12998. case "b" : return "\b";
  12999. case "v" : return "\u000b";
  13000. case "f" : return "\f";
  13001. case "0" : return "\0";
  13002. case "x" : return String.fromCharCode(hex_bytes(2));
  13003. case "u" : return String.fromCharCode(hex_bytes(4));
  13004. case "\n": return "";
  13005. default : return ch;
  13006. }
  13007. };
  13008. function hex_bytes(n) {
  13009. var num = 0;
  13010. for (; n > 0; --n) {
  13011. var digit = parseInt(next(true), 16);
  13012. if (isNaN(digit))
  13013. parse_error("Invalid hex-character pattern in string");
  13014. num = (num << 4) | digit;
  13015. }
  13016. return num;
  13017. };
  13018. function read_string() {
  13019. return with_eof_error("Unterminated string constant", function(){
  13020. var quote = next(), ret = "";
  13021. for (;;) {
  13022. var ch = next(true);
  13023. if (ch == "\\") {
  13024. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  13025. // https://github.com/mishoo/UglifyJS/issues/178
  13026. var octal_len = 0, first = null;
  13027. ch = read_while(function(ch){
  13028. if (ch >= "0" && ch <= "7") {
  13029. if (!first) {
  13030. first = ch;
  13031. return ++octal_len;
  13032. }
  13033. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  13034. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  13035. }
  13036. return false;
  13037. });
  13038. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  13039. else ch = read_escaped_char(true);
  13040. }
  13041. else if (ch == quote) break;
  13042. else if (ch == "\n") throw EX_EOF;
  13043. ret += ch;
  13044. }
  13045. return token("string", ret);
  13046. });
  13047. };
  13048. function read_line_comment() {
  13049. next();
  13050. var i = find("\n"), ret;
  13051. if (i == -1) {
  13052. ret = S.text.substr(S.pos);
  13053. S.pos = S.text.length;
  13054. } else {
  13055. ret = S.text.substring(S.pos, i);
  13056. S.pos = i;
  13057. }
  13058. return token("comment1", ret, true);
  13059. };
  13060. function read_multiline_comment() {
  13061. next();
  13062. return with_eof_error("Unterminated multiline comment", function(){
  13063. var i = find("*/", true),
  13064. text = S.text.substring(S.pos, i);
  13065. S.pos = i + 2;
  13066. S.line += text.split("\n").length - 1;
  13067. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  13068. // https://github.com/mishoo/UglifyJS/issues/#issue/100
  13069. if (/^@cc_on/i.test(text)) {
  13070. warn("WARNING: at line " + S.line);
  13071. warn("*** Found \"conditional comment\": " + text);
  13072. warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
  13073. }
  13074. return token("comment2", text, true);
  13075. });
  13076. };
  13077. function read_name() {
  13078. var backslash = false, name = "", ch, escaped = false, hex;
  13079. while ((ch = peek()) != null) {
  13080. if (!backslash) {
  13081. if (ch == "\\") escaped = backslash = true, next();
  13082. else if (is_identifier_char(ch)) name += next();
  13083. else break;
  13084. }
  13085. else {
  13086. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  13087. ch = read_escaped_char();
  13088. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  13089. name += ch;
  13090. backslash = false;
  13091. }
  13092. }
  13093. if (HOP(KEYWORDS, name) && escaped) {
  13094. hex = name.charCodeAt(0).toString(16).toUpperCase();
  13095. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  13096. }
  13097. return name;
  13098. };
  13099. function read_regexp(regexp) {
  13100. return with_eof_error("Unterminated regular expression", function(){
  13101. var prev_backslash = false, ch, in_class = false;
  13102. while ((ch = next(true))) if (prev_backslash) {
  13103. regexp += "\\" + ch;
  13104. prev_backslash = false;
  13105. } else if (ch == "[") {
  13106. in_class = true;
  13107. regexp += ch;
  13108. } else if (ch == "]" && in_class) {
  13109. in_class = false;
  13110. regexp += ch;
  13111. } else if (ch == "/" && !in_class) {
  13112. break;
  13113. } else if (ch == "\\") {
  13114. prev_backslash = true;
  13115. } else {
  13116. regexp += ch;
  13117. }
  13118. var mods = read_name();
  13119. return token("regexp", [ regexp, mods ]);
  13120. });
  13121. };
  13122. function read_operator(prefix) {
  13123. function grow(op) {
  13124. if (!peek()) return op;
  13125. var bigger = op + peek();
  13126. if (HOP(OPERATORS, bigger)) {
  13127. next();
  13128. return grow(bigger);
  13129. } else {
  13130. return op;
  13131. }
  13132. };
  13133. return token("operator", grow(prefix || next()));
  13134. };
  13135. function handle_slash() {
  13136. next();
  13137. var regex_allowed = S.regex_allowed;
  13138. switch (peek()) {
  13139. case "/":
  13140. S.comments_before.push(read_line_comment());
  13141. S.regex_allowed = regex_allowed;
  13142. return next_token();
  13143. case "*":
  13144. S.comments_before.push(read_multiline_comment());
  13145. S.regex_allowed = regex_allowed;
  13146. return next_token();
  13147. }
  13148. return S.regex_allowed ? read_regexp("") : read_operator("/");
  13149. };
  13150. function handle_dot() {
  13151. next();
  13152. return is_digit(peek())
  13153. ? read_num(".")
  13154. : token("punc", ".");
  13155. };
  13156. function read_word() {
  13157. var word = read_name();
  13158. return !HOP(KEYWORDS, word)
  13159. ? token("name", word)
  13160. : HOP(OPERATORS, word)
  13161. ? token("operator", word)
  13162. : HOP(KEYWORDS_ATOM, word)
  13163. ? token("atom", word)
  13164. : token("keyword", word);
  13165. };
  13166. function with_eof_error(eof_error, cont) {
  13167. try {
  13168. return cont();
  13169. } catch(ex) {
  13170. if (ex === EX_EOF) parse_error(eof_error);
  13171. else throw ex;
  13172. }
  13173. };
  13174. function next_token(force_regexp) {
  13175. if (force_regexp != null)
  13176. return read_regexp(force_regexp);
  13177. skip_whitespace();
  13178. start_token();
  13179. var ch = peek();
  13180. if (!ch) return token("eof");
  13181. if (is_digit(ch)) return read_num();
  13182. if (ch == '"' || ch == "'") return read_string();
  13183. if (HOP(PUNC_CHARS, ch)) return token("punc", next());
  13184. if (ch == ".") return handle_dot();
  13185. if (ch == "/") return handle_slash();
  13186. if (HOP(OPERATOR_CHARS, ch)) return read_operator();
  13187. if (ch == "\\" || is_identifier_start(ch)) return read_word();
  13188. parse_error("Unexpected character '" + ch + "'");
  13189. };
  13190. next_token.context = function(nc) {
  13191. if (nc) S = nc;
  13192. return S;
  13193. };
  13194. return next_token;
  13195. };
  13196. /* -----[ Parser (constants) ]----- */
  13197. var UNARY_PREFIX = array_to_hash([
  13198. "typeof",
  13199. "void",
  13200. "delete",
  13201. "--",
  13202. "++",
  13203. "!",
  13204. "~",
  13205. "-",
  13206. "+"
  13207. ]);
  13208. var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
  13209. var ASSIGNMENT = (function(a, ret, i){
  13210. while (i < a.length) {
  13211. ret[a[i]] = a[i].substr(0, a[i].length - 1);
  13212. i++;
  13213. }
  13214. return ret;
  13215. })(
  13216. ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
  13217. { "=": true },
  13218. 0
  13219. );
  13220. var PRECEDENCE = (function(a, ret){
  13221. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  13222. var b = a[i];
  13223. for (var j = 0; j < b.length; ++j) {
  13224. ret[b[j]] = n;
  13225. }
  13226. }
  13227. return ret;
  13228. })(
  13229. [
  13230. ["||"],
  13231. ["&&"],
  13232. ["|"],
  13233. ["^"],
  13234. ["&"],
  13235. ["==", "===", "!=", "!=="],
  13236. ["<", ">", "<=", ">=", "in", "instanceof"],
  13237. [">>", "<<", ">>>"],
  13238. ["+", "-"],
  13239. ["*", "/", "%"]
  13240. ],
  13241. {}
  13242. );
  13243. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  13244. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  13245. /* -----[ Parser ]----- */
  13246. function NodeWithToken(str, start, end) {
  13247. this.name = str;
  13248. this.start = start;
  13249. this.end = end;
  13250. };
  13251. NodeWithToken.prototype.toString = function() { return this.name; };
  13252. function parse($TEXT, exigent_mode, embed_tokens) {
  13253. var S = {
  13254. input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
  13255. token : null,
  13256. prev : null,
  13257. peeked : null,
  13258. in_function : 0,
  13259. in_directives : true,
  13260. in_loop : 0,
  13261. labels : []
  13262. };
  13263. S.token = next();
  13264. function is(type, value) {
  13265. return is_token(S.token, type, value);
  13266. };
  13267. function peek() { return S.peeked || (S.peeked = S.input()); };
  13268. function next() {
  13269. S.prev = S.token;
  13270. if (S.peeked) {
  13271. S.token = S.peeked;
  13272. S.peeked = null;
  13273. } else {
  13274. S.token = S.input();
  13275. }
  13276. S.in_directives = S.in_directives && (
  13277. S.token.type == "string" || is("punc", ";")
  13278. );
  13279. return S.token;
  13280. };
  13281. function prev() {
  13282. return S.prev;
  13283. };
  13284. function croak(msg, line, col, pos) {
  13285. var ctx = S.input.context();
  13286. js_error(msg,
  13287. line != null ? line : ctx.tokline,
  13288. col != null ? col : ctx.tokcol,
  13289. pos != null ? pos : ctx.tokpos);
  13290. };
  13291. function token_error(token, msg) {
  13292. croak(msg, token.line, token.col);
  13293. };
  13294. function unexpected(token) {
  13295. if (token == null)
  13296. token = S.token;
  13297. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  13298. };
  13299. function expect_token(type, val) {
  13300. if (is(type, val)) {
  13301. return next();
  13302. }
  13303. token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
  13304. };
  13305. function expect(punc) { return expect_token("punc", punc); };
  13306. function can_insert_semicolon() {
  13307. return !exigent_mode && (
  13308. S.token.nlb || is("eof") || is("punc", "}")
  13309. );
  13310. };
  13311. function semicolon() {
  13312. if (is("punc", ";")) next();
  13313. else if (!can_insert_semicolon()) unexpected();
  13314. };
  13315. function as() {
  13316. return slice(arguments);
  13317. };
  13318. function parenthesised() {
  13319. expect("(");
  13320. var ex = expression();
  13321. expect(")");
  13322. return ex;
  13323. };
  13324. function add_tokens(str, start, end) {
  13325. return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
  13326. };
  13327. function maybe_embed_tokens(parser) {
  13328. if (embed_tokens) return function() {
  13329. var start = S.token;
  13330. var ast = parser.apply(this, arguments);
  13331. ast[0] = add_tokens(ast[0], start, prev());
  13332. return ast;
  13333. };
  13334. else return parser;
  13335. };
  13336. var statement = maybe_embed_tokens(function() {
  13337. if (is("operator", "/") || is("operator", "/=")) {
  13338. S.peeked = null;
  13339. S.token = S.input(S.token.value.substr(1)); // force regexp
  13340. }
  13341. switch (S.token.type) {
  13342. case "string":
  13343. var dir = S.in_directives, stat = simple_statement();
  13344. if (dir && stat[1][0] == "string" && !is("punc", ","))
  13345. return as("directive", stat[1][1]);
  13346. return stat;
  13347. case "num":
  13348. case "regexp":
  13349. case "operator":
  13350. case "atom":
  13351. return simple_statement();
  13352. case "name":
  13353. return is_token(peek(), "punc", ":")
  13354. ? labeled_statement(prog1(S.token.value, next, next))
  13355. : simple_statement();
  13356. case "punc":
  13357. switch (S.token.value) {
  13358. case "{":
  13359. return as("block", block_());
  13360. case "[":
  13361. case "(":
  13362. return simple_statement();
  13363. case ";":
  13364. next();
  13365. return as("block");
  13366. default:
  13367. unexpected();
  13368. }
  13369. case "keyword":
  13370. switch (prog1(S.token.value, next)) {
  13371. case "break":
  13372. return break_cont("break");
  13373. case "continue":
  13374. return break_cont("continue");
  13375. case "debugger":
  13376. semicolon();
  13377. return as("debugger");
  13378. case "do":
  13379. return (function(body){
  13380. expect_token("keyword", "while");
  13381. return as("do", prog1(parenthesised, semicolon), body);
  13382. })(in_loop(statement));
  13383. case "for":
  13384. return for_();
  13385. case "function":
  13386. return function_(true);
  13387. case "if":
  13388. return if_();
  13389. case "return":
  13390. if (S.in_function == 0)
  13391. croak("'return' outside of function");
  13392. return as("return",
  13393. is("punc", ";")
  13394. ? (next(), null)
  13395. : can_insert_semicolon()
  13396. ? null
  13397. : prog1(expression, semicolon));
  13398. case "switch":
  13399. return as("switch", parenthesised(), switch_block_());
  13400. case "throw":
  13401. if (S.token.nlb)
  13402. croak("Illegal newline after 'throw'");
  13403. return as("throw", prog1(expression, semicolon));
  13404. case "try":
  13405. return try_();
  13406. case "var":
  13407. return prog1(var_, semicolon);
  13408. case "const":
  13409. return prog1(const_, semicolon);
  13410. case "while":
  13411. return as("while", parenthesised(), in_loop(statement));
  13412. case "with":
  13413. return as("with", parenthesised(), statement());
  13414. default:
  13415. unexpected();
  13416. }
  13417. }
  13418. });
  13419. function labeled_statement(label) {
  13420. S.labels.push(label);
  13421. var start = S.token, stat = statement();
  13422. if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
  13423. unexpected(start);
  13424. S.labels.pop();
  13425. return as("label", label, stat);
  13426. };
  13427. function simple_statement() {
  13428. return as("stat", prog1(expression, semicolon));
  13429. };
  13430. function break_cont(type) {
  13431. var name;
  13432. if (!can_insert_semicolon()) {
  13433. name = is("name") ? S.token.value : null;
  13434. }
  13435. if (name != null) {
  13436. next();
  13437. if (!member(name, S.labels))
  13438. croak("Label " + name + " without matching loop or statement");
  13439. }
  13440. else if (S.in_loop == 0)
  13441. croak(type + " not inside a loop or switch");
  13442. semicolon();
  13443. return as(type, name);
  13444. };
  13445. function for_() {
  13446. expect("(");
  13447. var init = null;
  13448. if (!is("punc", ";")) {
  13449. init = is("keyword", "var")
  13450. ? (next(), var_(true))
  13451. : expression(true, true);
  13452. if (is("operator", "in")) {
  13453. if (init[0] == "var" && init[1].length > 1)
  13454. croak("Only one variable declaration allowed in for..in loop");
  13455. return for_in(init);
  13456. }
  13457. }
  13458. return regular_for(init);
  13459. };
  13460. function regular_for(init) {
  13461. expect(";");
  13462. var test = is("punc", ";") ? null : expression();
  13463. expect(";");
  13464. var step = is("punc", ")") ? null : expression();
  13465. expect(")");
  13466. return as("for", init, test, step, in_loop(statement));
  13467. };
  13468. function for_in(init) {
  13469. var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
  13470. next();
  13471. var obj = expression();
  13472. expect(")");
  13473. return as("for-in", init, lhs, obj, in_loop(statement));
  13474. };
  13475. var function_ = function(in_statement) {
  13476. var name = is("name") ? prog1(S.token.value, next) : null;
  13477. if (in_statement && !name)
  13478. unexpected();
  13479. expect("(");
  13480. return as(in_statement ? "defun" : "function",
  13481. name,
  13482. // arguments
  13483. (function(first, a){
  13484. while (!is("punc", ")")) {
  13485. if (first) first = false; else expect(",");
  13486. if (!is("name")) unexpected();
  13487. a.push(S.token.value);
  13488. next();
  13489. }
  13490. next();
  13491. return a;
  13492. })(true, []),
  13493. // body
  13494. (function(){
  13495. ++S.in_function;
  13496. var loop = S.in_loop;
  13497. S.in_directives = true;
  13498. S.in_loop = 0;
  13499. var a = block_();
  13500. --S.in_function;
  13501. S.in_loop = loop;
  13502. return a;
  13503. })());
  13504. };
  13505. function if_() {
  13506. var cond = parenthesised(), body = statement(), belse;
  13507. if (is("keyword", "else")) {
  13508. next();
  13509. belse = statement();
  13510. }
  13511. return as("if", cond, body, belse);
  13512. };
  13513. function block_() {
  13514. expect("{");
  13515. var a = [];
  13516. while (!is("punc", "}")) {
  13517. if (is("eof")) unexpected();
  13518. a.push(statement());
  13519. }
  13520. next();
  13521. return a;
  13522. };
  13523. var switch_block_ = curry(in_loop, function(){
  13524. expect("{");
  13525. var a = [], cur = null;
  13526. while (!is("punc", "}")) {
  13527. if (is("eof")) unexpected();
  13528. if (is("keyword", "case")) {
  13529. next();
  13530. cur = [];
  13531. a.push([ expression(), cur ]);
  13532. expect(":");
  13533. }
  13534. else if (is("keyword", "default")) {
  13535. next();
  13536. expect(":");
  13537. cur = [];
  13538. a.push([ null, cur ]);
  13539. }
  13540. else {
  13541. if (!cur) unexpected();
  13542. cur.push(statement());
  13543. }
  13544. }
  13545. next();
  13546. return a;
  13547. });
  13548. function try_() {
  13549. var body = block_(), bcatch, bfinally;
  13550. if (is("keyword", "catch")) {
  13551. next();
  13552. expect("(");
  13553. if (!is("name"))
  13554. croak("Name expected");
  13555. var name = S.token.value;
  13556. next();
  13557. expect(")");
  13558. bcatch = [ name, block_() ];
  13559. }
  13560. if (is("keyword", "finally")) {
  13561. next();
  13562. bfinally = block_();
  13563. }
  13564. if (!bcatch && !bfinally)
  13565. croak("Missing catch/finally blocks");
  13566. return as("try", body, bcatch, bfinally);
  13567. };
  13568. function vardefs(no_in) {
  13569. var a = [];
  13570. for (;;) {
  13571. if (!is("name"))
  13572. unexpected();
  13573. var name = S.token.value;
  13574. next();
  13575. if (is("operator", "=")) {
  13576. next();
  13577. a.push([ name, expression(false, no_in) ]);
  13578. } else {
  13579. a.push([ name ]);
  13580. }
  13581. if (!is("punc", ","))
  13582. break;
  13583. next();
  13584. }
  13585. return a;
  13586. };
  13587. function var_(no_in) {
  13588. return as("var", vardefs(no_in));
  13589. };
  13590. function const_() {
  13591. return as("const", vardefs());
  13592. };
  13593. function new_() {
  13594. var newexp = expr_atom(false), args;
  13595. if (is("punc", "(")) {
  13596. next();
  13597. args = expr_list(")");
  13598. } else {
  13599. args = [];
  13600. }
  13601. return subscripts(as("new", newexp, args), true);
  13602. };
  13603. var expr_atom = maybe_embed_tokens(function(allow_calls) {
  13604. if (is("operator", "new")) {
  13605. next();
  13606. return new_();
  13607. }
  13608. if (is("punc")) {
  13609. switch (S.token.value) {
  13610. case "(":
  13611. next();
  13612. return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
  13613. case "[":
  13614. next();
  13615. return subscripts(array_(), allow_calls);
  13616. case "{":
  13617. next();
  13618. return subscripts(object_(), allow_calls);
  13619. }
  13620. unexpected();
  13621. }
  13622. if (is("keyword", "function")) {
  13623. next();
  13624. return subscripts(function_(false), allow_calls);
  13625. }
  13626. if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
  13627. var atom = S.token.type == "regexp"
  13628. ? as("regexp", S.token.value[0], S.token.value[1])
  13629. : as(S.token.type, S.token.value);
  13630. return subscripts(prog1(atom, next), allow_calls);
  13631. }
  13632. unexpected();
  13633. });
  13634. function expr_list(closing, allow_trailing_comma, allow_empty) {
  13635. var first = true, a = [];
  13636. while (!is("punc", closing)) {
  13637. if (first) first = false; else expect(",");
  13638. if (allow_trailing_comma && is("punc", closing)) break;
  13639. if (is("punc", ",") && allow_empty) {
  13640. a.push([ "atom", "undefined" ]);
  13641. } else {
  13642. a.push(expression(false));
  13643. }
  13644. }
  13645. next();
  13646. return a;
  13647. };
  13648. function array_() {
  13649. return as("array", expr_list("]", !exigent_mode, true));
  13650. };
  13651. function object_() {
  13652. var first = true, a = [];
  13653. while (!is("punc", "}")) {
  13654. if (first) first = false; else expect(",");
  13655. if (!exigent_mode && is("punc", "}"))
  13656. // allow trailing comma
  13657. break;
  13658. var type = S.token.type;
  13659. var name = as_property_name();
  13660. if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
  13661. a.push([ as_name(), function_(false), name ]);
  13662. } else {
  13663. expect(":");
  13664. a.push([ name, expression(false) ]);
  13665. }
  13666. }
  13667. next();
  13668. return as("object", a);
  13669. };
  13670. function as_property_name() {
  13671. switch (S.token.type) {
  13672. case "num":
  13673. case "string":
  13674. return prog1(S.token.value, next);
  13675. }
  13676. return as_name();
  13677. };
  13678. function as_name() {
  13679. switch (S.token.type) {
  13680. case "name":
  13681. case "operator":
  13682. case "keyword":
  13683. case "atom":
  13684. return prog1(S.token.value, next);
  13685. default:
  13686. unexpected();
  13687. }
  13688. };
  13689. function subscripts(expr, allow_calls) {
  13690. if (is("punc", ".")) {
  13691. next();
  13692. return subscripts(as("dot", expr, as_name()), allow_calls);
  13693. }
  13694. if (is("punc", "[")) {
  13695. next();
  13696. return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
  13697. }
  13698. if (allow_calls && is("punc", "(")) {
  13699. next();
  13700. return subscripts(as("call", expr, expr_list(")")), true);
  13701. }
  13702. return expr;
  13703. };
  13704. function maybe_unary(allow_calls) {
  13705. if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
  13706. return make_unary("unary-prefix",
  13707. prog1(S.token.value, next),
  13708. maybe_unary(allow_calls));
  13709. }
  13710. var val = expr_atom(allow_calls);
  13711. while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
  13712. val = make_unary("unary-postfix", S.token.value, val);
  13713. next();
  13714. }
  13715. return val;
  13716. };
  13717. function make_unary(tag, op, expr) {
  13718. if ((op == "++" || op == "--") && !is_assignable(expr))
  13719. croak("Invalid use of " + op + " operator");
  13720. return as(tag, op, expr);
  13721. };
  13722. function expr_op(left, min_prec, no_in) {
  13723. var op = is("operator") ? S.token.value : null;
  13724. if (op && op == "in" && no_in) op = null;
  13725. var prec = op != null ? PRECEDENCE[op] : null;
  13726. if (prec != null && prec > min_prec) {
  13727. next();
  13728. var right = expr_op(maybe_unary(true), prec, no_in);
  13729. return expr_op(as("binary", op, left, right), min_prec, no_in);
  13730. }
  13731. return left;
  13732. };
  13733. function expr_ops(no_in) {
  13734. return expr_op(maybe_unary(true), 0, no_in);
  13735. };
  13736. function maybe_conditional(no_in) {
  13737. var expr = expr_ops(no_in);
  13738. if (is("operator", "?")) {
  13739. next();
  13740. var yes = expression(false);
  13741. expect(":");
  13742. return as("conditional", expr, yes, expression(false, no_in));
  13743. }
  13744. return expr;
  13745. };
  13746. function is_assignable(expr) {
  13747. if (!exigent_mode) return true;
  13748. switch (expr[0]+"") {
  13749. case "dot":
  13750. case "sub":
  13751. case "new":
  13752. case "call":
  13753. return true;
  13754. case "name":
  13755. return expr[1] != "this";
  13756. }
  13757. };
  13758. function maybe_assign(no_in) {
  13759. var left = maybe_conditional(no_in), val = S.token.value;
  13760. if (is("operator") && HOP(ASSIGNMENT, val)) {
  13761. if (is_assignable(left)) {
  13762. next();
  13763. return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
  13764. }
  13765. croak("Invalid assignment");
  13766. }
  13767. return left;
  13768. };
  13769. var expression = maybe_embed_tokens(function(commas, no_in) {
  13770. if (arguments.length == 0)
  13771. commas = true;
  13772. var expr = maybe_assign(no_in);
  13773. if (commas && is("punc", ",")) {
  13774. next();
  13775. return as("seq", expr, expression(true, no_in));
  13776. }
  13777. return expr;
  13778. });
  13779. function in_loop(cont) {
  13780. try {
  13781. ++S.in_loop;
  13782. return cont();
  13783. } finally {
  13784. --S.in_loop;
  13785. }
  13786. };
  13787. return as("toplevel", (function(a){
  13788. while (!is("eof"))
  13789. a.push(statement());
  13790. return a;
  13791. })([]));
  13792. };
  13793. /* -----[ Utilities ]----- */
  13794. function curry(f) {
  13795. var args = slice(arguments, 1);
  13796. return function() { return f.apply(this, args.concat(slice(arguments))); };
  13797. };
  13798. function prog1(ret) {
  13799. if (ret instanceof Function)
  13800. ret = ret();
  13801. for (var i = 1, n = arguments.length; --n > 0; ++i)
  13802. arguments[i]();
  13803. return ret;
  13804. };
  13805. function array_to_hash(a) {
  13806. var ret = {};
  13807. for (var i = 0; i < a.length; ++i)
  13808. ret[a[i]] = true;
  13809. return ret;
  13810. };
  13811. function slice(a, start) {
  13812. return Array.prototype.slice.call(a, start || 0);
  13813. };
  13814. function characters(str) {
  13815. return str.split("");
  13816. };
  13817. function member(name, array) {
  13818. for (var i = array.length; --i >= 0;)
  13819. if (array[i] == name)
  13820. return true;
  13821. return false;
  13822. };
  13823. function HOP(obj, prop) {
  13824. return Object.prototype.hasOwnProperty.call(obj, prop);
  13825. };
  13826. var warn = function() {};
  13827. /* -----[ Exports ]----- */
  13828. exports.tokenizer = tokenizer;
  13829. exports.parse = parse;
  13830. exports.slice = slice;
  13831. exports.curry = curry;
  13832. exports.member = member;
  13833. exports.array_to_hash = array_to_hash;
  13834. exports.PRECEDENCE = PRECEDENCE;
  13835. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  13836. exports.RESERVED_WORDS = RESERVED_WORDS;
  13837. exports.KEYWORDS = KEYWORDS;
  13838. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  13839. exports.OPERATORS = OPERATORS;
  13840. exports.is_alphanumeric_char = is_alphanumeric_char;
  13841. exports.is_identifier_start = is_identifier_start;
  13842. exports.is_identifier_char = is_identifier_char;
  13843. exports.set_logger = function(logger) {
  13844. warn = logger;
  13845. };
  13846. // Local variables:
  13847. // js-indent-level: 4
  13848. // End:
  13849. });define('uglifyjs/squeeze-more', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  13850. var jsp = require("./parse-js"),
  13851. pro = require("./process"),
  13852. slice = jsp.slice,
  13853. member = jsp.member,
  13854. curry = jsp.curry,
  13855. MAP = pro.MAP,
  13856. PRECEDENCE = jsp.PRECEDENCE,
  13857. OPERATORS = jsp.OPERATORS;
  13858. function ast_squeeze_more(ast) {
  13859. var w = pro.ast_walker(), walk = w.walk, scope;
  13860. function with_scope(s, cont) {
  13861. var save = scope, ret;
  13862. scope = s;
  13863. ret = cont();
  13864. scope = save;
  13865. return ret;
  13866. };
  13867. function _lambda(name, args, body) {
  13868. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  13869. };
  13870. return w.with_walkers({
  13871. "toplevel": function(body) {
  13872. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  13873. },
  13874. "function": _lambda,
  13875. "defun": _lambda,
  13876. "new": function(ctor, args) {
  13877. if (ctor[0] == "name") {
  13878. if (ctor[1] == "Array" && !scope.has("Array")) {
  13879. if (args.length != 1) {
  13880. return [ "array", args ];
  13881. } else {
  13882. return walk([ "call", [ "name", "Array" ], args ]);
  13883. }
  13884. } else if (ctor[1] == "Object" && !scope.has("Object")) {
  13885. if (!args.length) {
  13886. return [ "object", [] ];
  13887. } else {
  13888. return walk([ "call", [ "name", "Object" ], args ]);
  13889. }
  13890. } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
  13891. return walk([ "call", [ "name", ctor[1] ], args]);
  13892. }
  13893. }
  13894. },
  13895. "call": function(expr, args) {
  13896. if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
  13897. && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
  13898. return [ "call", [ "dot", expr[1], "slice"], args];
  13899. }
  13900. if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
  13901. // foo.toString() ==> foo+""
  13902. if (expr[1][0] == "string") return expr[1];
  13903. return [ "binary", "+", expr[1], [ "string", "" ]];
  13904. }
  13905. if (expr[0] == "name") {
  13906. if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
  13907. return [ "array", args ];
  13908. }
  13909. if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
  13910. return [ "object", [] ];
  13911. }
  13912. if (expr[1] == "String" && !scope.has("String")) {
  13913. return [ "binary", "+", args[0], [ "string", "" ]];
  13914. }
  13915. }
  13916. }
  13917. }, function() {
  13918. return walk(pro.ast_add_scope(ast));
  13919. });
  13920. };
  13921. exports.ast_squeeze_more = ast_squeeze_more;
  13922. // Local variables:
  13923. // js-indent-level: 4
  13924. // End:
  13925. });
  13926. define('uglifyjs/process', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  13927. /***********************************************************************
  13928. A JavaScript tokenizer / parser / beautifier / compressor.
  13929. This version is suitable for Node.js. With minimal changes (the
  13930. exports stuff) it should work on any JS platform.
  13931. This file implements some AST processors. They work on data built
  13932. by parse-js.
  13933. Exported functions:
  13934. - ast_mangle(ast, options) -- mangles the variable/function names
  13935. in the AST. Returns an AST.
  13936. - ast_squeeze(ast) -- employs various optimizations to make the
  13937. final generated code even smaller. Returns an AST.
  13938. - gen_code(ast, options) -- generates JS code from the AST. Pass
  13939. true (or an object, see the code for some options) as second
  13940. argument to get "pretty" (indented) code.
  13941. -------------------------------- (C) ---------------------------------
  13942. Author: Mihai Bazon
  13943. <mihai.bazon@gmail.com>
  13944. http://mihai.bazon.net/blog
  13945. Distributed under the BSD license:
  13946. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13947. Redistribution and use in source and binary forms, with or without
  13948. modification, are permitted provided that the following conditions
  13949. are met:
  13950. * Redistributions of source code must retain the above
  13951. copyright notice, this list of conditions and the following
  13952. disclaimer.
  13953. * Redistributions in binary form must reproduce the above
  13954. copyright notice, this list of conditions and the following
  13955. disclaimer in the documentation and/or other materials
  13956. provided with the distribution.
  13957. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13958. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13959. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13960. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13961. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13962. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13963. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13964. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13965. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13966. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13967. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13968. SUCH DAMAGE.
  13969. ***********************************************************************/
  13970. var jsp = require("./parse-js"),
  13971. curry = jsp.curry,
  13972. slice = jsp.slice,
  13973. member = jsp.member,
  13974. is_identifier_char = jsp.is_identifier_char,
  13975. PRECEDENCE = jsp.PRECEDENCE,
  13976. OPERATORS = jsp.OPERATORS;
  13977. /* -----[ helper for AST traversal ]----- */
  13978. function ast_walker() {
  13979. function _vardefs(defs) {
  13980. return [ this[0], MAP(defs, function(def){
  13981. var a = [ def[0] ];
  13982. if (def.length > 1)
  13983. a[1] = walk(def[1]);
  13984. return a;
  13985. }) ];
  13986. };
  13987. function _block(statements) {
  13988. var out = [ this[0] ];
  13989. if (statements != null)
  13990. out.push(MAP(statements, walk));
  13991. return out;
  13992. };
  13993. var walkers = {
  13994. "string": function(str) {
  13995. return [ this[0], str ];
  13996. },
  13997. "num": function(num) {
  13998. return [ this[0], num ];
  13999. },
  14000. "name": function(name) {
  14001. return [ this[0], name ];
  14002. },
  14003. "toplevel": function(statements) {
  14004. return [ this[0], MAP(statements, walk) ];
  14005. },
  14006. "block": _block,
  14007. "splice": _block,
  14008. "var": _vardefs,
  14009. "const": _vardefs,
  14010. "try": function(t, c, f) {
  14011. return [
  14012. this[0],
  14013. MAP(t, walk),
  14014. c != null ? [ c[0], MAP(c[1], walk) ] : null,
  14015. f != null ? MAP(f, walk) : null
  14016. ];
  14017. },
  14018. "throw": function(expr) {
  14019. return [ this[0], walk(expr) ];
  14020. },
  14021. "new": function(ctor, args) {
  14022. return [ this[0], walk(ctor), MAP(args, walk) ];
  14023. },
  14024. "switch": function(expr, body) {
  14025. return [ this[0], walk(expr), MAP(body, function(branch){
  14026. return [ branch[0] ? walk(branch[0]) : null,
  14027. MAP(branch[1], walk) ];
  14028. }) ];
  14029. },
  14030. "break": function(label) {
  14031. return [ this[0], label ];
  14032. },
  14033. "continue": function(label) {
  14034. return [ this[0], label ];
  14035. },
  14036. "conditional": function(cond, t, e) {
  14037. return [ this[0], walk(cond), walk(t), walk(e) ];
  14038. },
  14039. "assign": function(op, lvalue, rvalue) {
  14040. return [ this[0], op, walk(lvalue), walk(rvalue) ];
  14041. },
  14042. "dot": function(expr) {
  14043. return [ this[0], walk(expr) ].concat(slice(arguments, 1));
  14044. },
  14045. "call": function(expr, args) {
  14046. return [ this[0], walk(expr), MAP(args, walk) ];
  14047. },
  14048. "function": function(name, args, body) {
  14049. return [ this[0], name, args.slice(), MAP(body, walk) ];
  14050. },
  14051. "debugger": function() {
  14052. return [ this[0] ];
  14053. },
  14054. "defun": function(name, args, body) {
  14055. return [ this[0], name, args.slice(), MAP(body, walk) ];
  14056. },
  14057. "if": function(conditional, t, e) {
  14058. return [ this[0], walk(conditional), walk(t), walk(e) ];
  14059. },
  14060. "for": function(init, cond, step, block) {
  14061. return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
  14062. },
  14063. "for-in": function(vvar, key, hash, block) {
  14064. return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
  14065. },
  14066. "while": function(cond, block) {
  14067. return [ this[0], walk(cond), walk(block) ];
  14068. },
  14069. "do": function(cond, block) {
  14070. return [ this[0], walk(cond), walk(block) ];
  14071. },
  14072. "return": function(expr) {
  14073. return [ this[0], walk(expr) ];
  14074. },
  14075. "binary": function(op, left, right) {
  14076. return [ this[0], op, walk(left), walk(right) ];
  14077. },
  14078. "unary-prefix": function(op, expr) {
  14079. return [ this[0], op, walk(expr) ];
  14080. },
  14081. "unary-postfix": function(op, expr) {
  14082. return [ this[0], op, walk(expr) ];
  14083. },
  14084. "sub": function(expr, subscript) {
  14085. return [ this[0], walk(expr), walk(subscript) ];
  14086. },
  14087. "object": function(props) {
  14088. return [ this[0], MAP(props, function(p){
  14089. return p.length == 2
  14090. ? [ p[0], walk(p[1]) ]
  14091. : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
  14092. }) ];
  14093. },
  14094. "regexp": function(rx, mods) {
  14095. return [ this[0], rx, mods ];
  14096. },
  14097. "array": function(elements) {
  14098. return [ this[0], MAP(elements, walk) ];
  14099. },
  14100. "stat": function(stat) {
  14101. return [ this[0], walk(stat) ];
  14102. },
  14103. "seq": function() {
  14104. return [ this[0] ].concat(MAP(slice(arguments), walk));
  14105. },
  14106. "label": function(name, block) {
  14107. return [ this[0], name, walk(block) ];
  14108. },
  14109. "with": function(expr, block) {
  14110. return [ this[0], walk(expr), walk(block) ];
  14111. },
  14112. "atom": function(name) {
  14113. return [ this[0], name ];
  14114. },
  14115. "directive": function(dir) {
  14116. return [ this[0], dir ];
  14117. }
  14118. };
  14119. var user = {};
  14120. var stack = [];
  14121. function walk(ast) {
  14122. if (ast == null)
  14123. return null;
  14124. try {
  14125. stack.push(ast);
  14126. var type = ast[0];
  14127. var gen = user[type];
  14128. if (gen) {
  14129. var ret = gen.apply(ast, ast.slice(1));
  14130. if (ret != null)
  14131. return ret;
  14132. }
  14133. gen = walkers[type];
  14134. return gen.apply(ast, ast.slice(1));
  14135. } finally {
  14136. stack.pop();
  14137. }
  14138. };
  14139. function dive(ast) {
  14140. if (ast == null)
  14141. return null;
  14142. try {
  14143. stack.push(ast);
  14144. return walkers[ast[0]].apply(ast, ast.slice(1));
  14145. } finally {
  14146. stack.pop();
  14147. }
  14148. };
  14149. function with_walkers(walkers, cont){
  14150. var save = {}, i;
  14151. for (i in walkers) if (HOP(walkers, i)) {
  14152. save[i] = user[i];
  14153. user[i] = walkers[i];
  14154. }
  14155. var ret = cont();
  14156. for (i in save) if (HOP(save, i)) {
  14157. if (!save[i]) delete user[i];
  14158. else user[i] = save[i];
  14159. }
  14160. return ret;
  14161. };
  14162. return {
  14163. walk: walk,
  14164. dive: dive,
  14165. with_walkers: with_walkers,
  14166. parent: function() {
  14167. return stack[stack.length - 2]; // last one is current node
  14168. },
  14169. stack: function() {
  14170. return stack;
  14171. }
  14172. };
  14173. };
  14174. /* -----[ Scope and mangling ]----- */
  14175. function Scope(parent) {
  14176. this.names = {}; // names defined in this scope
  14177. this.mangled = {}; // mangled names (orig.name => mangled)
  14178. this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
  14179. this.cname = -1; // current mangled name
  14180. this.refs = {}; // names referenced from this scope
  14181. this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
  14182. this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
  14183. this.directives = []; // directives activated from this scope
  14184. this.parent = parent; // parent scope
  14185. this.children = []; // sub-scopes
  14186. if (parent) {
  14187. this.level = parent.level + 1;
  14188. parent.children.push(this);
  14189. } else {
  14190. this.level = 0;
  14191. }
  14192. };
  14193. function base54_digits() {
  14194. if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
  14195. return DIGITS_OVERRIDE_FOR_TESTING;
  14196. else
  14197. return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
  14198. }
  14199. var base54 = (function(){
  14200. var DIGITS = base54_digits();
  14201. return function(num) {
  14202. var ret = "", base = 54;
  14203. do {
  14204. ret += DIGITS.charAt(num % base);
  14205. num = Math.floor(num / base);
  14206. base = 64;
  14207. } while (num > 0);
  14208. return ret;
  14209. };
  14210. })();
  14211. Scope.prototype = {
  14212. has: function(name) {
  14213. for (var s = this; s; s = s.parent)
  14214. if (HOP(s.names, name))
  14215. return s;
  14216. },
  14217. has_mangled: function(mname) {
  14218. for (var s = this; s; s = s.parent)
  14219. if (HOP(s.rev_mangled, mname))
  14220. return s;
  14221. },
  14222. toJSON: function() {
  14223. return {
  14224. names: this.names,
  14225. uses_eval: this.uses_eval,
  14226. uses_with: this.uses_with
  14227. };
  14228. },
  14229. next_mangled: function() {
  14230. // we must be careful that the new mangled name:
  14231. //
  14232. // 1. doesn't shadow a mangled name from a parent
  14233. // scope, unless we don't reference the original
  14234. // name from this scope OR from any sub-scopes!
  14235. // This will get slow.
  14236. //
  14237. // 2. doesn't shadow an original name from a parent
  14238. // scope, in the event that the name is not mangled
  14239. // in the parent scope and we reference that name
  14240. // here OR IN ANY SUBSCOPES!
  14241. //
  14242. // 3. doesn't shadow a name that is referenced but not
  14243. // defined (possibly global defined elsewhere).
  14244. for (;;) {
  14245. var m = base54(++this.cname), prior;
  14246. // case 1.
  14247. prior = this.has_mangled(m);
  14248. if (prior && this.refs[prior.rev_mangled[m]] === prior)
  14249. continue;
  14250. // case 2.
  14251. prior = this.has(m);
  14252. if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
  14253. continue;
  14254. // case 3.
  14255. if (HOP(this.refs, m) && this.refs[m] == null)
  14256. continue;
  14257. // I got "do" once. :-/
  14258. if (!is_identifier(m))
  14259. continue;
  14260. return m;
  14261. }
  14262. },
  14263. set_mangle: function(name, m) {
  14264. this.rev_mangled[m] = name;
  14265. return this.mangled[name] = m;
  14266. },
  14267. get_mangled: function(name, newMangle) {
  14268. if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
  14269. var s = this.has(name);
  14270. if (!s) return name; // not in visible scope, no mangle
  14271. if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
  14272. if (!newMangle) return name; // not found and no mangling requested
  14273. return s.set_mangle(name, s.next_mangled());
  14274. },
  14275. references: function(name) {
  14276. return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
  14277. },
  14278. define: function(name, type) {
  14279. if (name != null) {
  14280. if (type == "var" || !HOP(this.names, name))
  14281. this.names[name] = type || "var";
  14282. return name;
  14283. }
  14284. },
  14285. active_directive: function(dir) {
  14286. return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
  14287. }
  14288. };
  14289. function ast_add_scope(ast) {
  14290. var current_scope = null;
  14291. var w = ast_walker(), walk = w.walk;
  14292. var having_eval = [];
  14293. function with_new_scope(cont) {
  14294. current_scope = new Scope(current_scope);
  14295. current_scope.labels = new Scope();
  14296. var ret = current_scope.body = cont();
  14297. ret.scope = current_scope;
  14298. current_scope = current_scope.parent;
  14299. return ret;
  14300. };
  14301. function define(name, type) {
  14302. return current_scope.define(name, type);
  14303. };
  14304. function reference(name) {
  14305. current_scope.refs[name] = true;
  14306. };
  14307. function _lambda(name, args, body) {
  14308. var is_defun = this[0] == "defun";
  14309. return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
  14310. if (!is_defun) define(name, "lambda");
  14311. MAP(args, function(name){ define(name, "arg") });
  14312. return MAP(body, walk);
  14313. })];
  14314. };
  14315. function _vardefs(type) {
  14316. return function(defs) {
  14317. MAP(defs, function(d){
  14318. define(d[0], type);
  14319. if (d[1]) reference(d[0]);
  14320. });
  14321. };
  14322. };
  14323. function _breacont(label) {
  14324. if (label)
  14325. current_scope.labels.refs[label] = true;
  14326. };
  14327. return with_new_scope(function(){
  14328. // process AST
  14329. var ret = w.with_walkers({
  14330. "function": _lambda,
  14331. "defun": _lambda,
  14332. "label": function(name, stat) { current_scope.labels.define(name) },
  14333. "break": _breacont,
  14334. "continue": _breacont,
  14335. "with": function(expr, block) {
  14336. for (var s = current_scope; s; s = s.parent)
  14337. s.uses_with = true;
  14338. },
  14339. "var": _vardefs("var"),
  14340. "const": _vardefs("const"),
  14341. "try": function(t, c, f) {
  14342. if (c != null) return [
  14343. this[0],
  14344. MAP(t, walk),
  14345. [ define(c[0], "catch"), MAP(c[1], walk) ],
  14346. f != null ? MAP(f, walk) : null
  14347. ];
  14348. },
  14349. "name": function(name) {
  14350. if (name == "eval")
  14351. having_eval.push(current_scope);
  14352. reference(name);
  14353. }
  14354. }, function(){
  14355. return walk(ast);
  14356. });
  14357. // the reason why we need an additional pass here is
  14358. // that names can be used prior to their definition.
  14359. // scopes where eval was detected and their parents
  14360. // are marked with uses_eval, unless they define the
  14361. // "eval" name.
  14362. MAP(having_eval, function(scope){
  14363. if (!scope.has("eval")) while (scope) {
  14364. scope.uses_eval = true;
  14365. scope = scope.parent;
  14366. }
  14367. });
  14368. // for referenced names it might be useful to know
  14369. // their origin scope. current_scope here is the
  14370. // toplevel one.
  14371. function fixrefs(scope, i) {
  14372. // do children first; order shouldn't matter
  14373. for (i = scope.children.length; --i >= 0;)
  14374. fixrefs(scope.children[i]);
  14375. for (i in scope.refs) if (HOP(scope.refs, i)) {
  14376. // find origin scope and propagate the reference to origin
  14377. for (var origin = scope.has(i), s = scope; s; s = s.parent) {
  14378. s.refs[i] = origin;
  14379. if (s === origin) break;
  14380. }
  14381. }
  14382. };
  14383. fixrefs(current_scope);
  14384. return ret;
  14385. });
  14386. };
  14387. /* -----[ mangle names ]----- */
  14388. function ast_mangle(ast, options) {
  14389. var w = ast_walker(), walk = w.walk, scope;
  14390. options = defaults(options, {
  14391. mangle : true,
  14392. toplevel : false,
  14393. defines : null,
  14394. except : null,
  14395. no_functions : false
  14396. });
  14397. function get_mangled(name, newMangle) {
  14398. if (!options.mangle) return name;
  14399. if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
  14400. if (options.except && member(name, options.except))
  14401. return name;
  14402. if (options.no_functions && HOP(scope.names, name) &&
  14403. (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
  14404. return name;
  14405. return scope.get_mangled(name, newMangle);
  14406. };
  14407. function get_define(name) {
  14408. if (options.defines) {
  14409. // we always lookup a defined symbol for the current scope FIRST, so declared
  14410. // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
  14411. if (!scope.has(name)) {
  14412. if (HOP(options.defines, name)) {
  14413. return options.defines[name];
  14414. }
  14415. }
  14416. return null;
  14417. }
  14418. };
  14419. function _lambda(name, args, body) {
  14420. if (!options.no_functions && options.mangle) {
  14421. var is_defun = this[0] == "defun", extra;
  14422. if (name) {
  14423. if (is_defun) name = get_mangled(name);
  14424. else if (body.scope.references(name)) {
  14425. extra = {};
  14426. if (!(scope.uses_eval || scope.uses_with))
  14427. name = extra[name] = scope.next_mangled();
  14428. else
  14429. extra[name] = name;
  14430. }
  14431. else name = null;
  14432. }
  14433. }
  14434. body = with_scope(body.scope, function(){
  14435. args = MAP(args, function(name){ return get_mangled(name) });
  14436. return MAP(body, walk);
  14437. }, extra);
  14438. return [ this[0], name, args, body ];
  14439. };
  14440. function with_scope(s, cont, extra) {
  14441. var _scope = scope;
  14442. scope = s;
  14443. if (extra) for (var i in extra) if (HOP(extra, i)) {
  14444. s.set_mangle(i, extra[i]);
  14445. }
  14446. for (var i in s.names) if (HOP(s.names, i)) {
  14447. get_mangled(i, true);
  14448. }
  14449. var ret = cont();
  14450. ret.scope = s;
  14451. scope = _scope;
  14452. return ret;
  14453. };
  14454. function _vardefs(defs) {
  14455. return [ this[0], MAP(defs, function(d){
  14456. return [ get_mangled(d[0]), walk(d[1]) ];
  14457. }) ];
  14458. };
  14459. function _breacont(label) {
  14460. if (label) return [ this[0], scope.labels.get_mangled(label) ];
  14461. };
  14462. return w.with_walkers({
  14463. "function": _lambda,
  14464. "defun": function() {
  14465. // move function declarations to the top when
  14466. // they are not in some block.
  14467. var ast = _lambda.apply(this, arguments);
  14468. switch (w.parent()[0]) {
  14469. case "toplevel":
  14470. case "function":
  14471. case "defun":
  14472. return MAP.at_top(ast);
  14473. }
  14474. return ast;
  14475. },
  14476. "label": function(label, stat) {
  14477. if (scope.labels.refs[label]) return [
  14478. this[0],
  14479. scope.labels.get_mangled(label, true),
  14480. walk(stat)
  14481. ];
  14482. return walk(stat);
  14483. },
  14484. "break": _breacont,
  14485. "continue": _breacont,
  14486. "var": _vardefs,
  14487. "const": _vardefs,
  14488. "name": function(name) {
  14489. return get_define(name) || [ this[0], get_mangled(name) ];
  14490. },
  14491. "try": function(t, c, f) {
  14492. return [ this[0],
  14493. MAP(t, walk),
  14494. c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
  14495. f != null ? MAP(f, walk) : null ];
  14496. },
  14497. "toplevel": function(body) {
  14498. var self = this;
  14499. return with_scope(self.scope, function(){
  14500. return [ self[0], MAP(body, walk) ];
  14501. });
  14502. },
  14503. "directive": function() {
  14504. return MAP.at_top(this);
  14505. }
  14506. }, function() {
  14507. return walk(ast_add_scope(ast));
  14508. });
  14509. };
  14510. /* -----[
  14511. - compress foo["bar"] into foo.bar,
  14512. - remove block brackets {} where possible
  14513. - join consecutive var declarations
  14514. - various optimizations for IFs:
  14515. - if (cond) foo(); else bar(); ==> cond?foo():bar();
  14516. - if (cond) foo(); ==> cond&&foo();
  14517. - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
  14518. - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
  14519. ]----- */
  14520. var warn = function(){};
  14521. function best_of(ast1, ast2) {
  14522. return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
  14523. };
  14524. function last_stat(b) {
  14525. if (b[0] == "block" && b[1] && b[1].length > 0)
  14526. return b[1][b[1].length - 1];
  14527. return b;
  14528. }
  14529. function aborts(t) {
  14530. if (t) switch (last_stat(t)[0]) {
  14531. case "return":
  14532. case "break":
  14533. case "continue":
  14534. case "throw":
  14535. return true;
  14536. }
  14537. };
  14538. function boolean_expr(expr) {
  14539. return ( (expr[0] == "unary-prefix"
  14540. && member(expr[1], [ "!", "delete" ])) ||
  14541. (expr[0] == "binary"
  14542. && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
  14543. (expr[0] == "binary"
  14544. && member(expr[1], [ "&&", "||" ])
  14545. && boolean_expr(expr[2])
  14546. && boolean_expr(expr[3])) ||
  14547. (expr[0] == "conditional"
  14548. && boolean_expr(expr[2])
  14549. && boolean_expr(expr[3])) ||
  14550. (expr[0] == "assign"
  14551. && expr[1] === true
  14552. && boolean_expr(expr[3])) ||
  14553. (expr[0] == "seq"
  14554. && boolean_expr(expr[expr.length - 1]))
  14555. );
  14556. };
  14557. function empty(b) {
  14558. return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
  14559. };
  14560. function is_string(node) {
  14561. return (node[0] == "string" ||
  14562. node[0] == "unary-prefix" && node[1] == "typeof" ||
  14563. node[0] == "binary" && node[1] == "+" &&
  14564. (is_string(node[2]) || is_string(node[3])));
  14565. };
  14566. var when_constant = (function(){
  14567. var $NOT_CONSTANT = {};
  14568. // this can only evaluate constant expressions. If it finds anything
  14569. // not constant, it throws $NOT_CONSTANT.
  14570. function evaluate(expr) {
  14571. switch (expr[0]) {
  14572. case "string":
  14573. case "num":
  14574. return expr[1];
  14575. case "name":
  14576. case "atom":
  14577. switch (expr[1]) {
  14578. case "true": return true;
  14579. case "false": return false;
  14580. case "null": return null;
  14581. }
  14582. break;
  14583. case "unary-prefix":
  14584. switch (expr[1]) {
  14585. case "!": return !evaluate(expr[2]);
  14586. case "typeof": return typeof evaluate(expr[2]);
  14587. case "~": return ~evaluate(expr[2]);
  14588. case "-": return -evaluate(expr[2]);
  14589. case "+": return +evaluate(expr[2]);
  14590. }
  14591. break;
  14592. case "binary":
  14593. var left = expr[2], right = expr[3];
  14594. switch (expr[1]) {
  14595. case "&&" : return evaluate(left) && evaluate(right);
  14596. case "||" : return evaluate(left) || evaluate(right);
  14597. case "|" : return evaluate(left) | evaluate(right);
  14598. case "&" : return evaluate(left) & evaluate(right);
  14599. case "^" : return evaluate(left) ^ evaluate(right);
  14600. case "+" : return evaluate(left) + evaluate(right);
  14601. case "*" : return evaluate(left) * evaluate(right);
  14602. case "/" : return evaluate(left) / evaluate(right);
  14603. case "%" : return evaluate(left) % evaluate(right);
  14604. case "-" : return evaluate(left) - evaluate(right);
  14605. case "<<" : return evaluate(left) << evaluate(right);
  14606. case ">>" : return evaluate(left) >> evaluate(right);
  14607. case ">>>" : return evaluate(left) >>> evaluate(right);
  14608. case "==" : return evaluate(left) == evaluate(right);
  14609. case "===" : return evaluate(left) === evaluate(right);
  14610. case "!=" : return evaluate(left) != evaluate(right);
  14611. case "!==" : return evaluate(left) !== evaluate(right);
  14612. case "<" : return evaluate(left) < evaluate(right);
  14613. case "<=" : return evaluate(left) <= evaluate(right);
  14614. case ">" : return evaluate(left) > evaluate(right);
  14615. case ">=" : return evaluate(left) >= evaluate(right);
  14616. case "in" : return evaluate(left) in evaluate(right);
  14617. case "instanceof" : return evaluate(left) instanceof evaluate(right);
  14618. }
  14619. }
  14620. throw $NOT_CONSTANT;
  14621. };
  14622. return function(expr, yes, no) {
  14623. try {
  14624. var val = evaluate(expr), ast;
  14625. switch (typeof val) {
  14626. case "string": ast = [ "string", val ]; break;
  14627. case "number": ast = [ "num", val ]; break;
  14628. case "boolean": ast = [ "name", String(val) ]; break;
  14629. default:
  14630. if (val === null) { ast = [ "atom", "null" ]; break; }
  14631. throw new Error("Can't handle constant of type: " + (typeof val));
  14632. }
  14633. return yes.call(expr, ast, val);
  14634. } catch(ex) {
  14635. if (ex === $NOT_CONSTANT) {
  14636. if (expr[0] == "binary"
  14637. && (expr[1] == "===" || expr[1] == "!==")
  14638. && ((is_string(expr[2]) && is_string(expr[3]))
  14639. || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
  14640. expr[1] = expr[1].substr(0, 2);
  14641. }
  14642. else if (no && expr[0] == "binary"
  14643. && (expr[1] == "||" || expr[1] == "&&")) {
  14644. // the whole expression is not constant but the lval may be...
  14645. try {
  14646. var lval = evaluate(expr[2]);
  14647. expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
  14648. (expr[1] == "||" && (lval ? lval : expr[3])) ||
  14649. expr);
  14650. } catch(ex2) {
  14651. // IGNORE... lval is not constant
  14652. }
  14653. }
  14654. return no ? no.call(expr, expr) : null;
  14655. }
  14656. else throw ex;
  14657. }
  14658. };
  14659. })();
  14660. function warn_unreachable(ast) {
  14661. if (!empty(ast))
  14662. warn("Dropping unreachable code: " + gen_code(ast, true));
  14663. };
  14664. function prepare_ifs(ast) {
  14665. var w = ast_walker(), walk = w.walk;
  14666. // In this first pass, we rewrite ifs which abort with no else with an
  14667. // if-else. For example:
  14668. //
  14669. // if (x) {
  14670. // blah();
  14671. // return y;
  14672. // }
  14673. // foobar();
  14674. //
  14675. // is rewritten into:
  14676. //
  14677. // if (x) {
  14678. // blah();
  14679. // return y;
  14680. // } else {
  14681. // foobar();
  14682. // }
  14683. function redo_if(statements) {
  14684. statements = MAP(statements, walk);
  14685. for (var i = 0; i < statements.length; ++i) {
  14686. var fi = statements[i];
  14687. if (fi[0] != "if") continue;
  14688. if (fi[3]) continue;
  14689. var t = fi[2];
  14690. if (!aborts(t)) continue;
  14691. var conditional = walk(fi[1]);
  14692. var e_body = redo_if(statements.slice(i + 1));
  14693. var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
  14694. return statements.slice(0, i).concat([ [
  14695. fi[0], // "if"
  14696. conditional, // conditional
  14697. t, // then
  14698. e // else
  14699. ] ]);
  14700. }
  14701. return statements;
  14702. };
  14703. function redo_if_lambda(name, args, body) {
  14704. body = redo_if(body);
  14705. return [ this[0], name, args, body ];
  14706. };
  14707. function redo_if_block(statements) {
  14708. return [ this[0], statements != null ? redo_if(statements) : null ];
  14709. };
  14710. return w.with_walkers({
  14711. "defun": redo_if_lambda,
  14712. "function": redo_if_lambda,
  14713. "block": redo_if_block,
  14714. "splice": redo_if_block,
  14715. "toplevel": function(statements) {
  14716. return [ this[0], redo_if(statements) ];
  14717. },
  14718. "try": function(t, c, f) {
  14719. return [
  14720. this[0],
  14721. redo_if(t),
  14722. c != null ? [ c[0], redo_if(c[1]) ] : null,
  14723. f != null ? redo_if(f) : null
  14724. ];
  14725. }
  14726. }, function() {
  14727. return walk(ast);
  14728. });
  14729. };
  14730. function for_side_effects(ast, handler) {
  14731. var w = ast_walker(), walk = w.walk;
  14732. var $stop = {}, $restart = {};
  14733. function stop() { throw $stop };
  14734. function restart() { throw $restart };
  14735. function found(){ return handler.call(this, this, w, stop, restart) };
  14736. function unary(op) {
  14737. if (op == "++" || op == "--")
  14738. return found.apply(this, arguments);
  14739. };
  14740. function binary(op) {
  14741. if (op == "&&" || op == "||")
  14742. return found.apply(this, arguments);
  14743. };
  14744. return w.with_walkers({
  14745. "try": found,
  14746. "throw": found,
  14747. "return": found,
  14748. "new": found,
  14749. "switch": found,
  14750. "break": found,
  14751. "continue": found,
  14752. "assign": found,
  14753. "call": found,
  14754. "if": found,
  14755. "for": found,
  14756. "for-in": found,
  14757. "while": found,
  14758. "do": found,
  14759. "return": found,
  14760. "unary-prefix": unary,
  14761. "unary-postfix": unary,
  14762. "conditional": found,
  14763. "binary": binary,
  14764. "defun": found
  14765. }, function(){
  14766. while (true) try {
  14767. walk(ast);
  14768. break;
  14769. } catch(ex) {
  14770. if (ex === $stop) break;
  14771. if (ex === $restart) continue;
  14772. throw ex;
  14773. }
  14774. });
  14775. };
  14776. function ast_lift_variables(ast) {
  14777. var w = ast_walker(), walk = w.walk, scope;
  14778. function do_body(body, env) {
  14779. var _scope = scope;
  14780. scope = env;
  14781. body = MAP(body, walk);
  14782. var hash = {}, names = MAP(env.names, function(type, name){
  14783. if (type != "var") return MAP.skip;
  14784. if (!env.references(name)) return MAP.skip;
  14785. hash[name] = true;
  14786. return [ name ];
  14787. });
  14788. if (names.length > 0) {
  14789. // looking for assignments to any of these variables.
  14790. // we can save considerable space by moving the definitions
  14791. // in the var declaration.
  14792. for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
  14793. if (ast[0] == "assign"
  14794. && ast[1] === true
  14795. && ast[2][0] == "name"
  14796. && HOP(hash, ast[2][1])) {
  14797. // insert the definition into the var declaration
  14798. for (var i = names.length; --i >= 0;) {
  14799. if (names[i][0] == ast[2][1]) {
  14800. if (names[i][1]) // this name already defined, we must stop
  14801. stop();
  14802. names[i][1] = ast[3]; // definition
  14803. names.push(names.splice(i, 1)[0]);
  14804. break;
  14805. }
  14806. }
  14807. // remove this assignment from the AST.
  14808. var p = walker.parent();
  14809. if (p[0] == "seq") {
  14810. var a = p[2];
  14811. a.unshift(0, p.length);
  14812. p.splice.apply(p, a);
  14813. }
  14814. else if (p[0] == "stat") {
  14815. p.splice(0, p.length, "block"); // empty statement
  14816. }
  14817. else {
  14818. stop();
  14819. }
  14820. restart();
  14821. }
  14822. stop();
  14823. });
  14824. body.unshift([ "var", names ]);
  14825. }
  14826. scope = _scope;
  14827. return body;
  14828. };
  14829. function _vardefs(defs) {
  14830. var ret = null;
  14831. for (var i = defs.length; --i >= 0;) {
  14832. var d = defs[i];
  14833. if (!d[1]) continue;
  14834. d = [ "assign", true, [ "name", d[0] ], d[1] ];
  14835. if (ret == null) ret = d;
  14836. else ret = [ "seq", d, ret ];
  14837. }
  14838. if (ret == null && w.parent()[0] != "for") {
  14839. if (w.parent()[0] == "for-in")
  14840. return [ "name", defs[0][0] ];
  14841. return MAP.skip;
  14842. }
  14843. return [ "stat", ret ];
  14844. };
  14845. function _toplevel(body) {
  14846. return [ this[0], do_body(body, this.scope) ];
  14847. };
  14848. return w.with_walkers({
  14849. "function": function(name, args, body){
  14850. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  14851. args.pop();
  14852. if (!body.scope.references(name)) name = null;
  14853. return [ this[0], name, args, do_body(body, body.scope) ];
  14854. },
  14855. "defun": function(name, args, body){
  14856. if (!scope.references(name)) return MAP.skip;
  14857. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  14858. args.pop();
  14859. return [ this[0], name, args, do_body(body, body.scope) ];
  14860. },
  14861. "var": _vardefs,
  14862. "toplevel": _toplevel
  14863. }, function(){
  14864. return walk(ast_add_scope(ast));
  14865. });
  14866. };
  14867. function ast_squeeze(ast, options) {
  14868. ast = squeeze_1(ast, options);
  14869. ast = squeeze_2(ast, options);
  14870. return ast;
  14871. };
  14872. function squeeze_1(ast, options) {
  14873. options = defaults(options, {
  14874. make_seqs : true,
  14875. dead_code : true,
  14876. no_warnings : false,
  14877. keep_comps : true,
  14878. unsafe : false
  14879. });
  14880. var w = ast_walker(), walk = w.walk, scope;
  14881. function negate(c) {
  14882. var not_c = [ "unary-prefix", "!", c ];
  14883. switch (c[0]) {
  14884. case "unary-prefix":
  14885. return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
  14886. case "seq":
  14887. c = slice(c);
  14888. c[c.length - 1] = negate(c[c.length - 1]);
  14889. return c;
  14890. case "conditional":
  14891. return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
  14892. case "binary":
  14893. var op = c[1], left = c[2], right = c[3];
  14894. if (!options.keep_comps) switch (op) {
  14895. case "<=" : return [ "binary", ">", left, right ];
  14896. case "<" : return [ "binary", ">=", left, right ];
  14897. case ">=" : return [ "binary", "<", left, right ];
  14898. case ">" : return [ "binary", "<=", left, right ];
  14899. }
  14900. switch (op) {
  14901. case "==" : return [ "binary", "!=", left, right ];
  14902. case "!=" : return [ "binary", "==", left, right ];
  14903. case "===" : return [ "binary", "!==", left, right ];
  14904. case "!==" : return [ "binary", "===", left, right ];
  14905. case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
  14906. case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
  14907. }
  14908. break;
  14909. }
  14910. return not_c;
  14911. };
  14912. function make_conditional(c, t, e) {
  14913. var make_real_conditional = function() {
  14914. if (c[0] == "unary-prefix" && c[1] == "!") {
  14915. return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
  14916. } else {
  14917. return e ? best_of(
  14918. [ "conditional", c, t, e ],
  14919. [ "conditional", negate(c), e, t ]
  14920. ) : [ "binary", "&&", c, t ];
  14921. }
  14922. };
  14923. // shortcut the conditional if the expression has a constant value
  14924. return when_constant(c, function(ast, val){
  14925. warn_unreachable(val ? e : t);
  14926. return (val ? t : e);
  14927. }, make_real_conditional);
  14928. };
  14929. function rmblock(block) {
  14930. if (block != null && block[0] == "block" && block[1]) {
  14931. if (block[1].length == 1)
  14932. block = block[1][0];
  14933. else if (block[1].length == 0)
  14934. block = [ "block" ];
  14935. }
  14936. return block;
  14937. };
  14938. function _lambda(name, args, body) {
  14939. return [ this[0], name, args, tighten(body, "lambda") ];
  14940. };
  14941. // this function does a few things:
  14942. // 1. discard useless blocks
  14943. // 2. join consecutive var declarations
  14944. // 3. remove obviously dead code
  14945. // 4. transform consecutive statements using the comma operator
  14946. // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
  14947. function tighten(statements, block_type) {
  14948. statements = MAP(statements, walk);
  14949. statements = statements.reduce(function(a, stat){
  14950. if (stat[0] == "block") {
  14951. if (stat[1]) {
  14952. a.push.apply(a, stat[1]);
  14953. }
  14954. } else {
  14955. a.push(stat);
  14956. }
  14957. return a;
  14958. }, []);
  14959. statements = (function(a, prev){
  14960. statements.forEach(function(cur){
  14961. if (prev && ((cur[0] == "var" && prev[0] == "var") ||
  14962. (cur[0] == "const" && prev[0] == "const"))) {
  14963. prev[1] = prev[1].concat(cur[1]);
  14964. } else {
  14965. a.push(cur);
  14966. prev = cur;
  14967. }
  14968. });
  14969. return a;
  14970. })([]);
  14971. if (options.dead_code) statements = (function(a, has_quit){
  14972. statements.forEach(function(st){
  14973. if (has_quit) {
  14974. if (st[0] == "function" || st[0] == "defun") {
  14975. a.push(st);
  14976. }
  14977. else if (st[0] == "var" || st[0] == "const") {
  14978. if (!options.no_warnings)
  14979. warn("Variables declared in unreachable code");
  14980. st[1] = MAP(st[1], function(def){
  14981. if (def[1] && !options.no_warnings)
  14982. warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
  14983. return [ def[0] ];
  14984. });
  14985. a.push(st);
  14986. }
  14987. else if (!options.no_warnings)
  14988. warn_unreachable(st);
  14989. }
  14990. else {
  14991. a.push(st);
  14992. if (member(st[0], [ "return", "throw", "break", "continue" ]))
  14993. has_quit = true;
  14994. }
  14995. });
  14996. return a;
  14997. })([]);
  14998. if (options.make_seqs) statements = (function(a, prev) {
  14999. statements.forEach(function(cur){
  15000. if (prev && prev[0] == "stat" && cur[0] == "stat") {
  15001. prev[1] = [ "seq", prev[1], cur[1] ];
  15002. } else {
  15003. a.push(cur);
  15004. prev = cur;
  15005. }
  15006. });
  15007. if (a.length >= 2
  15008. && a[a.length-2][0] == "stat"
  15009. && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
  15010. && a[a.length-1][1])
  15011. {
  15012. a.splice(a.length - 2, 2,
  15013. [ a[a.length-1][0],
  15014. [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
  15015. }
  15016. return a;
  15017. })([]);
  15018. // this increases jQuery by 1K. Probably not such a good idea after all..
  15019. // part of this is done in prepare_ifs anyway.
  15020. // if (block_type == "lambda") statements = (function(i, a, stat){
  15021. // while (i < statements.length) {
  15022. // stat = statements[i++];
  15023. // if (stat[0] == "if" && !stat[3]) {
  15024. // if (stat[2][0] == "return" && stat[2][1] == null) {
  15025. // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
  15026. // break;
  15027. // }
  15028. // var last = last_stat(stat[2]);
  15029. // if (last[0] == "return" && last[1] == null) {
  15030. // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
  15031. // break;
  15032. // }
  15033. // }
  15034. // a.push(stat);
  15035. // }
  15036. // return a;
  15037. // })(0, []);
  15038. return statements;
  15039. };
  15040. function make_if(c, t, e) {
  15041. return when_constant(c, function(ast, val){
  15042. if (val) {
  15043. t = walk(t);
  15044. warn_unreachable(e);
  15045. return t || [ "block" ];
  15046. } else {
  15047. e = walk(e);
  15048. warn_unreachable(t);
  15049. return e || [ "block" ];
  15050. }
  15051. }, function() {
  15052. return make_real_if(c, t, e);
  15053. });
  15054. };
  15055. function abort_else(c, t, e) {
  15056. var ret = [ [ "if", negate(c), e ] ];
  15057. if (t[0] == "block") {
  15058. if (t[1]) ret = ret.concat(t[1]);
  15059. } else {
  15060. ret.push(t);
  15061. }
  15062. return walk([ "block", ret ]);
  15063. };
  15064. function make_real_if(c, t, e) {
  15065. c = walk(c);
  15066. t = walk(t);
  15067. e = walk(e);
  15068. if (empty(e) && empty(t))
  15069. return [ "stat", c ];
  15070. if (empty(t)) {
  15071. c = negate(c);
  15072. t = e;
  15073. e = null;
  15074. } else if (empty(e)) {
  15075. e = null;
  15076. } else {
  15077. // if we have both else and then, maybe it makes sense to switch them?
  15078. (function(){
  15079. var a = gen_code(c);
  15080. var n = negate(c);
  15081. var b = gen_code(n);
  15082. if (b.length < a.length) {
  15083. var tmp = t;
  15084. t = e;
  15085. e = tmp;
  15086. c = n;
  15087. }
  15088. })();
  15089. }
  15090. var ret = [ "if", c, t, e ];
  15091. if (t[0] == "if" && empty(t[3]) && empty(e)) {
  15092. ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
  15093. }
  15094. else if (t[0] == "stat") {
  15095. if (e) {
  15096. if (e[0] == "stat")
  15097. ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
  15098. else if (aborts(e))
  15099. ret = abort_else(c, t, e);
  15100. }
  15101. else {
  15102. ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
  15103. }
  15104. }
  15105. else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
  15106. ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
  15107. }
  15108. else if (e && aborts(t)) {
  15109. ret = [ [ "if", c, t ] ];
  15110. if (e[0] == "block") {
  15111. if (e[1]) ret = ret.concat(e[1]);
  15112. }
  15113. else {
  15114. ret.push(e);
  15115. }
  15116. ret = walk([ "block", ret ]);
  15117. }
  15118. else if (t && aborts(e)) {
  15119. ret = abort_else(c, t, e);
  15120. }
  15121. return ret;
  15122. };
  15123. function _do_while(cond, body) {
  15124. return when_constant(cond, function(cond, val){
  15125. if (!val) {
  15126. warn_unreachable(body);
  15127. return [ "block" ];
  15128. } else {
  15129. return [ "for", null, null, null, walk(body) ];
  15130. }
  15131. });
  15132. };
  15133. return w.with_walkers({
  15134. "sub": function(expr, subscript) {
  15135. if (subscript[0] == "string") {
  15136. var name = subscript[1];
  15137. if (is_identifier(name))
  15138. return [ "dot", walk(expr), name ];
  15139. else if (/^[1-9][0-9]*$/.test(name) || name === "0")
  15140. return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
  15141. }
  15142. },
  15143. "if": make_if,
  15144. "toplevel": function(body) {
  15145. return [ "toplevel", tighten(body) ];
  15146. },
  15147. "switch": function(expr, body) {
  15148. var last = body.length - 1;
  15149. return [ "switch", walk(expr), MAP(body, function(branch, i){
  15150. var block = tighten(branch[1]);
  15151. if (i == last && block.length > 0) {
  15152. var node = block[block.length - 1];
  15153. if (node[0] == "break" && !node[1])
  15154. block.pop();
  15155. }
  15156. return [ branch[0] ? walk(branch[0]) : null, block ];
  15157. }) ];
  15158. },
  15159. "function": _lambda,
  15160. "defun": _lambda,
  15161. "block": function(body) {
  15162. if (body) return rmblock([ "block", tighten(body) ]);
  15163. },
  15164. "binary": function(op, left, right) {
  15165. return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
  15166. return best_of(walk(c), this);
  15167. }, function no() {
  15168. return function(){
  15169. if(op != "==" && op != "!=") return;
  15170. var l = walk(left), r = walk(right);
  15171. if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
  15172. left = ['num', +!l[2][1]];
  15173. else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
  15174. right = ['num', +!r[2][1]];
  15175. return ["binary", op, left, right];
  15176. }() || this;
  15177. });
  15178. },
  15179. "conditional": function(c, t, e) {
  15180. return make_conditional(walk(c), walk(t), walk(e));
  15181. },
  15182. "try": function(t, c, f) {
  15183. return [
  15184. "try",
  15185. tighten(t),
  15186. c != null ? [ c[0], tighten(c[1]) ] : null,
  15187. f != null ? tighten(f) : null
  15188. ];
  15189. },
  15190. "unary-prefix": function(op, expr) {
  15191. expr = walk(expr);
  15192. var ret = [ "unary-prefix", op, expr ];
  15193. if (op == "!")
  15194. ret = best_of(ret, negate(expr));
  15195. return when_constant(ret, function(ast, val){
  15196. return walk(ast); // it's either true or false, so minifies to !0 or !1
  15197. }, function() { return ret });
  15198. },
  15199. "name": function(name) {
  15200. switch (name) {
  15201. case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
  15202. case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
  15203. }
  15204. },
  15205. "while": _do_while,
  15206. "assign": function(op, lvalue, rvalue) {
  15207. lvalue = walk(lvalue);
  15208. rvalue = walk(rvalue);
  15209. var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  15210. if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
  15211. ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
  15212. rvalue[2][1] === lvalue[1]) {
  15213. return [ this[0], rvalue[1], lvalue, rvalue[3] ]
  15214. }
  15215. return [ this[0], op, lvalue, rvalue ];
  15216. },
  15217. "call": function(expr, args) {
  15218. expr = walk(expr);
  15219. if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
  15220. return expr[1];
  15221. }
  15222. return [ this[0], expr, MAP(args, walk) ];
  15223. },
  15224. "num": function (num) {
  15225. if (!isFinite(num))
  15226. return [ "binary", "/", num === 1 / 0
  15227. ? [ "num", 1 ] : num === -1 / 0
  15228. ? [ "unary-prefix", "-", [ "num", 1 ] ]
  15229. : [ "num", 0 ], [ "num", 0 ] ];
  15230. return [ this[0], num ];
  15231. }
  15232. }, function() {
  15233. return walk(prepare_ifs(walk(prepare_ifs(ast))));
  15234. });
  15235. };
  15236. function squeeze_2(ast, options) {
  15237. var w = ast_walker(), walk = w.walk, scope;
  15238. function with_scope(s, cont) {
  15239. var save = scope, ret;
  15240. scope = s;
  15241. ret = cont();
  15242. scope = save;
  15243. return ret;
  15244. };
  15245. function lambda(name, args, body) {
  15246. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  15247. };
  15248. return w.with_walkers({
  15249. "directive": function(dir) {
  15250. if (scope.active_directive(dir))
  15251. return [ "block" ];
  15252. scope.directives.push(dir);
  15253. },
  15254. "toplevel": function(body) {
  15255. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  15256. },
  15257. "function": lambda,
  15258. "defun": lambda
  15259. }, function(){
  15260. return walk(ast_add_scope(ast));
  15261. });
  15262. };
  15263. /* -----[ re-generate code from the AST ]----- */
  15264. var DOT_CALL_NO_PARENS = jsp.array_to_hash([
  15265. "name",
  15266. "array",
  15267. "object",
  15268. "string",
  15269. "dot",
  15270. "sub",
  15271. "call",
  15272. "regexp",
  15273. "defun"
  15274. ]);
  15275. function make_string(str, ascii_only) {
  15276. var dq = 0, sq = 0;
  15277. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  15278. switch (s) {
  15279. case "\\": return "\\\\";
  15280. case "\b": return "\\b";
  15281. case "\f": return "\\f";
  15282. case "\n": return "\\n";
  15283. case "\r": return "\\r";
  15284. case "\u2028": return "\\u2028";
  15285. case "\u2029": return "\\u2029";
  15286. case '"': ++dq; return '"';
  15287. case "'": ++sq; return "'";
  15288. case "\0": return "\\0";
  15289. }
  15290. return s;
  15291. });
  15292. if (ascii_only) str = to_ascii(str);
  15293. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  15294. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  15295. };
  15296. function to_ascii(str) {
  15297. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  15298. var code = ch.charCodeAt(0).toString(16);
  15299. while (code.length < 4) code = "0" + code;
  15300. return "\\u" + code;
  15301. });
  15302. };
  15303. var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
  15304. function gen_code(ast, options) {
  15305. options = defaults(options, {
  15306. indent_start : 0,
  15307. indent_level : 4,
  15308. quote_keys : false,
  15309. space_colon : false,
  15310. beautify : false,
  15311. ascii_only : false,
  15312. inline_script: false
  15313. });
  15314. var beautify = !!options.beautify;
  15315. var indentation = 0,
  15316. newline = beautify ? "\n" : "",
  15317. space = beautify ? " " : "";
  15318. function encode_string(str) {
  15319. var ret = make_string(str, options.ascii_only);
  15320. if (options.inline_script)
  15321. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  15322. return ret;
  15323. };
  15324. function make_name(name) {
  15325. name = name.toString();
  15326. if (options.ascii_only)
  15327. name = to_ascii(name);
  15328. return name;
  15329. };
  15330. function indent(line) {
  15331. if (line == null)
  15332. line = "";
  15333. if (beautify)
  15334. line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
  15335. return line;
  15336. };
  15337. function with_indent(cont, incr) {
  15338. if (incr == null) incr = 1;
  15339. indentation += incr;
  15340. try { return cont.apply(null, slice(arguments, 1)); }
  15341. finally { indentation -= incr; }
  15342. };
  15343. function last_char(str) {
  15344. str = str.toString();
  15345. return str.charAt(str.length - 1);
  15346. };
  15347. function first_char(str) {
  15348. return str.toString().charAt(0);
  15349. };
  15350. function add_spaces(a) {
  15351. if (beautify)
  15352. return a.join(" ");
  15353. var b = [];
  15354. for (var i = 0; i < a.length; ++i) {
  15355. var next = a[i + 1];
  15356. b.push(a[i]);
  15357. if (next &&
  15358. ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
  15359. || first_char(next) == "\\")) ||
  15360. (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString()) ||
  15361. last_char(a[i]) == "/" && first_char(next) == "/"))) {
  15362. b.push(" ");
  15363. }
  15364. }
  15365. return b.join("");
  15366. };
  15367. function add_commas(a) {
  15368. return a.join("," + space);
  15369. };
  15370. function parenthesize(expr) {
  15371. var gen = make(expr);
  15372. for (var i = 1; i < arguments.length; ++i) {
  15373. var el = arguments[i];
  15374. if ((el instanceof Function && el(expr)) || expr[0] == el)
  15375. return "(" + gen + ")";
  15376. }
  15377. return gen;
  15378. };
  15379. function best_of(a) {
  15380. if (a.length == 1) {
  15381. return a[0];
  15382. }
  15383. if (a.length == 2) {
  15384. var b = a[1];
  15385. a = a[0];
  15386. return a.length <= b.length ? a : b;
  15387. }
  15388. return best_of([ a[0], best_of(a.slice(1)) ]);
  15389. };
  15390. function needs_parens(expr) {
  15391. if (expr[0] == "function" || expr[0] == "object") {
  15392. // dot/call on a literal function requires the
  15393. // function literal itself to be parenthesized
  15394. // only if it's the first "thing" in a
  15395. // statement. This means that the parent is
  15396. // "stat", but it could also be a "seq" and
  15397. // we're the first in this "seq" and the
  15398. // parent is "stat", and so on. Messy stuff,
  15399. // but it worths the trouble.
  15400. var a = slice(w.stack()), self = a.pop(), p = a.pop();
  15401. while (p) {
  15402. if (p[0] == "stat") return true;
  15403. if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
  15404. ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
  15405. self = p;
  15406. p = a.pop();
  15407. } else {
  15408. return false;
  15409. }
  15410. }
  15411. }
  15412. return !HOP(DOT_CALL_NO_PARENS, expr[0]);
  15413. };
  15414. function make_num(num) {
  15415. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  15416. if (Math.floor(num) === num) {
  15417. if (num >= 0) {
  15418. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  15419. "0" + num.toString(8)); // same.
  15420. } else {
  15421. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  15422. "-0" + (-num).toString(8)); // same.
  15423. }
  15424. if ((m = /^(.*?)(0+)$/.exec(num))) {
  15425. a.push(m[1] + "e" + m[2].length);
  15426. }
  15427. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  15428. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  15429. str.substr(str.indexOf(".")));
  15430. }
  15431. return best_of(a);
  15432. };
  15433. var w = ast_walker();
  15434. var make = w.walk;
  15435. return w.with_walkers({
  15436. "string": encode_string,
  15437. "num": make_num,
  15438. "name": make_name,
  15439. "debugger": function(){ return "debugger;" },
  15440. "toplevel": function(statements) {
  15441. return make_block_statements(statements)
  15442. .join(newline + newline);
  15443. },
  15444. "splice": function(statements) {
  15445. var parent = w.parent();
  15446. if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
  15447. // we need block brackets in this case
  15448. return make_block.apply(this, arguments);
  15449. } else {
  15450. return MAP(make_block_statements(statements, true),
  15451. function(line, i) {
  15452. // the first line is already indented
  15453. return i > 0 ? indent(line) : line;
  15454. }).join(newline);
  15455. }
  15456. },
  15457. "block": make_block,
  15458. "var": function(defs) {
  15459. return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
  15460. },
  15461. "const": function(defs) {
  15462. return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
  15463. },
  15464. "try": function(tr, ca, fi) {
  15465. var out = [ "try", make_block(tr) ];
  15466. if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
  15467. if (fi) out.push("finally", make_block(fi));
  15468. return add_spaces(out);
  15469. },
  15470. "throw": function(expr) {
  15471. return add_spaces([ "throw", make(expr) ]) + ";";
  15472. },
  15473. "new": function(ctor, args) {
  15474. args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
  15475. return parenthesize(expr, "seq");
  15476. })) + ")" : "";
  15477. return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
  15478. var w = ast_walker(), has_call = {};
  15479. try {
  15480. w.with_walkers({
  15481. "call": function() { throw has_call },
  15482. "function": function() { return this }
  15483. }, function(){
  15484. w.walk(expr);
  15485. });
  15486. } catch(ex) {
  15487. if (ex === has_call)
  15488. return true;
  15489. throw ex;
  15490. }
  15491. }) + args ]);
  15492. },
  15493. "switch": function(expr, body) {
  15494. return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
  15495. },
  15496. "break": function(label) {
  15497. var out = "break";
  15498. if (label != null)
  15499. out += " " + make_name(label);
  15500. return out + ";";
  15501. },
  15502. "continue": function(label) {
  15503. var out = "continue";
  15504. if (label != null)
  15505. out += " " + make_name(label);
  15506. return out + ";";
  15507. },
  15508. "conditional": function(co, th, el) {
  15509. return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
  15510. parenthesize(th, "seq"), ":",
  15511. parenthesize(el, "seq") ]);
  15512. },
  15513. "assign": function(op, lvalue, rvalue) {
  15514. if (op && op !== true) op += "=";
  15515. else op = "=";
  15516. return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
  15517. },
  15518. "dot": function(expr) {
  15519. var out = make(expr), i = 1;
  15520. if (expr[0] == "num") {
  15521. if (!/[a-f.]/i.test(out))
  15522. out += ".";
  15523. } else if (expr[0] != "function" && needs_parens(expr))
  15524. out = "(" + out + ")";
  15525. while (i < arguments.length)
  15526. out += "." + make_name(arguments[i++]);
  15527. return out;
  15528. },
  15529. "call": function(func, args) {
  15530. var f = make(func);
  15531. if (f.charAt(0) != "(" && needs_parens(func))
  15532. f = "(" + f + ")";
  15533. return f + "(" + add_commas(MAP(args, function(expr){
  15534. return parenthesize(expr, "seq");
  15535. })) + ")";
  15536. },
  15537. "function": make_function,
  15538. "defun": make_function,
  15539. "if": function(co, th, el) {
  15540. var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
  15541. if (el) {
  15542. out.push("else", make(el));
  15543. }
  15544. return add_spaces(out);
  15545. },
  15546. "for": function(init, cond, step, block) {
  15547. var out = [ "for" ];
  15548. init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
  15549. cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
  15550. step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
  15551. var args = init + cond + step;
  15552. if (args == "; ; ") args = ";;";
  15553. out.push("(" + args + ")", make(block));
  15554. return add_spaces(out);
  15555. },
  15556. "for-in": function(vvar, key, hash, block) {
  15557. return add_spaces([ "for", "(" +
  15558. (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
  15559. "in",
  15560. make(hash) + ")", make(block) ]);
  15561. },
  15562. "while": function(condition, block) {
  15563. return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
  15564. },
  15565. "do": function(condition, block) {
  15566. return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
  15567. },
  15568. "return": function(expr) {
  15569. var out = [ "return" ];
  15570. if (expr != null) out.push(make(expr));
  15571. return add_spaces(out) + ";";
  15572. },
  15573. "binary": function(operator, lvalue, rvalue) {
  15574. var left = make(lvalue), right = make(rvalue);
  15575. // XXX: I'm pretty sure other cases will bite here.
  15576. // we need to be smarter.
  15577. // adding parens all the time is the safest bet.
  15578. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
  15579. lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
  15580. lvalue[0] == "function" && needs_parens(this)) {
  15581. left = "(" + left + ")";
  15582. }
  15583. if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
  15584. rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
  15585. !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
  15586. right = "(" + right + ")";
  15587. }
  15588. else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
  15589. && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
  15590. right = " " + right;
  15591. }
  15592. return add_spaces([ left, operator, right ]);
  15593. },
  15594. "unary-prefix": function(operator, expr) {
  15595. var val = make(expr);
  15596. if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  15597. val = "(" + val + ")";
  15598. return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
  15599. },
  15600. "unary-postfix": function(operator, expr) {
  15601. var val = make(expr);
  15602. if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  15603. val = "(" + val + ")";
  15604. return val + operator;
  15605. },
  15606. "sub": function(expr, subscript) {
  15607. var hash = make(expr);
  15608. if (needs_parens(expr))
  15609. hash = "(" + hash + ")";
  15610. return hash + "[" + make(subscript) + "]";
  15611. },
  15612. "object": function(props) {
  15613. var obj_needs_parens = needs_parens(this);
  15614. if (props.length == 0)
  15615. return obj_needs_parens ? "({})" : "{}";
  15616. var out = "{" + newline + with_indent(function(){
  15617. return MAP(props, function(p){
  15618. if (p.length == 3) {
  15619. // getter/setter. The name is in p[0], the arg.list in p[1][2], the
  15620. // body in p[1][3] and type ("get" / "set") in p[2].
  15621. return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
  15622. }
  15623. var key = p[0], val = parenthesize(p[1], "seq");
  15624. if (options.quote_keys) {
  15625. key = encode_string(key);
  15626. } else if ((typeof key == "number" || !beautify && +key + "" == key)
  15627. && parseFloat(key) >= 0) {
  15628. key = make_num(+key);
  15629. } else if (!is_identifier(key)) {
  15630. key = encode_string(key);
  15631. }
  15632. return indent(add_spaces(beautify && options.space_colon
  15633. ? [ key, ":", val ]
  15634. : [ key + ":", val ]));
  15635. }).join("," + newline);
  15636. }) + newline + indent("}");
  15637. return obj_needs_parens ? "(" + out + ")" : out;
  15638. },
  15639. "regexp": function(rx, mods) {
  15640. if (options.ascii_only) rx = to_ascii(rx);
  15641. return "/" + rx + "/" + mods;
  15642. },
  15643. "array": function(elements) {
  15644. if (elements.length == 0) return "[]";
  15645. return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
  15646. if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
  15647. return parenthesize(el, "seq");
  15648. })), "]" ]);
  15649. },
  15650. "stat": function(stmt) {
  15651. return stmt != null
  15652. ? make(stmt).replace(/;*\s*$/, ";")
  15653. : ";";
  15654. },
  15655. "seq": function() {
  15656. return add_commas(MAP(slice(arguments), make));
  15657. },
  15658. "label": function(name, block) {
  15659. return add_spaces([ make_name(name), ":", make(block) ]);
  15660. },
  15661. "with": function(expr, block) {
  15662. return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
  15663. },
  15664. "atom": function(name) {
  15665. return make_name(name);
  15666. },
  15667. "directive": function(dir) {
  15668. return make_string(dir) + ";";
  15669. }
  15670. }, function(){ return make(ast) });
  15671. // The squeezer replaces "block"-s that contain only a single
  15672. // statement with the statement itself; technically, the AST
  15673. // is correct, but this can create problems when we output an
  15674. // IF having an ELSE clause where the THEN clause ends in an
  15675. // IF *without* an ELSE block (then the outer ELSE would refer
  15676. // to the inner IF). This function checks for this case and
  15677. // adds the block brackets if needed.
  15678. function make_then(th) {
  15679. if (th == null) return ";";
  15680. if (th[0] == "do") {
  15681. // https://github.com/mishoo/UglifyJS/issues/#issue/57
  15682. // IE croaks with "syntax error" on code like this:
  15683. // if (foo) do ... while(cond); else ...
  15684. // we need block brackets around do/while
  15685. return make_block([ th ]);
  15686. }
  15687. var b = th;
  15688. while (true) {
  15689. var type = b[0];
  15690. if (type == "if") {
  15691. if (!b[3])
  15692. // no else, we must add the block
  15693. return make([ "block", [ th ]]);
  15694. b = b[3];
  15695. }
  15696. else if (type == "while" || type == "do") b = b[2];
  15697. else if (type == "for" || type == "for-in") b = b[4];
  15698. else break;
  15699. }
  15700. return make(th);
  15701. };
  15702. function make_function(name, args, body, keyword, no_parens) {
  15703. var out = keyword || "function";
  15704. if (name) {
  15705. out += " " + make_name(name);
  15706. }
  15707. out += "(" + add_commas(MAP(args, make_name)) + ")";
  15708. out = add_spaces([ out, make_block(body) ]);
  15709. return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
  15710. };
  15711. function must_has_semicolon(node) {
  15712. switch (node[0]) {
  15713. case "with":
  15714. case "while":
  15715. return empty(node[2]) || must_has_semicolon(node[2]);
  15716. case "for":
  15717. case "for-in":
  15718. return empty(node[4]) || must_has_semicolon(node[4]);
  15719. case "if":
  15720. if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
  15721. if (node[3]) {
  15722. if (empty(node[3])) return true; // `else' present but empty
  15723. return must_has_semicolon(node[3]); // dive into the `else' branch
  15724. }
  15725. return must_has_semicolon(node[2]); // dive into the `then' branch
  15726. case "directive":
  15727. return true;
  15728. }
  15729. };
  15730. function make_block_statements(statements, noindent) {
  15731. for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
  15732. var stat = statements[i];
  15733. var code = make(stat);
  15734. if (code != ";") {
  15735. if (!beautify && i == last && !must_has_semicolon(stat)) {
  15736. code = code.replace(/;+\s*$/, "");
  15737. }
  15738. a.push(code);
  15739. }
  15740. }
  15741. return noindent ? a : MAP(a, indent);
  15742. };
  15743. function make_switch_block(body) {
  15744. var n = body.length;
  15745. if (n == 0) return "{}";
  15746. return "{" + newline + MAP(body, function(branch, i){
  15747. var has_body = branch[1].length > 0, code = with_indent(function(){
  15748. return indent(branch[0]
  15749. ? add_spaces([ "case", make(branch[0]) + ":" ])
  15750. : "default:");
  15751. }, 0.5) + (has_body ? newline + with_indent(function(){
  15752. return make_block_statements(branch[1]).join(newline);
  15753. }) : "");
  15754. if (!beautify && has_body && i < n - 1)
  15755. code += ";";
  15756. return code;
  15757. }).join(newline) + newline + indent("}");
  15758. };
  15759. function make_block(statements) {
  15760. if (!statements) return ";";
  15761. if (statements.length == 0) return "{}";
  15762. return "{" + newline + with_indent(function(){
  15763. return make_block_statements(statements).join(newline);
  15764. }) + newline + indent("}");
  15765. };
  15766. function make_1vardef(def) {
  15767. var name = def[0], val = def[1];
  15768. if (val != null)
  15769. name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
  15770. return name;
  15771. };
  15772. };
  15773. function split_lines(code, max_line_length) {
  15774. var splits = [ 0 ];
  15775. jsp.parse(function(){
  15776. var next_token = jsp.tokenizer(code);
  15777. var last_split = 0;
  15778. var prev_token;
  15779. function current_length(tok) {
  15780. return tok.pos - last_split;
  15781. };
  15782. function split_here(tok) {
  15783. last_split = tok.pos;
  15784. splits.push(last_split);
  15785. };
  15786. function custom(){
  15787. var tok = next_token.apply(this, arguments);
  15788. out: {
  15789. if (prev_token) {
  15790. if (prev_token.type == "keyword") break out;
  15791. }
  15792. if (current_length(tok) > max_line_length) {
  15793. switch (tok.type) {
  15794. case "keyword":
  15795. case "atom":
  15796. case "name":
  15797. case "punc":
  15798. split_here(tok);
  15799. break out;
  15800. }
  15801. }
  15802. }
  15803. prev_token = tok;
  15804. return tok;
  15805. };
  15806. custom.context = function() {
  15807. return next_token.context.apply(this, arguments);
  15808. };
  15809. return custom;
  15810. }());
  15811. return splits.map(function(pos, i){
  15812. return code.substring(pos, splits[i + 1] || code.length);
  15813. }).join("\n");
  15814. };
  15815. /* -----[ Utilities ]----- */
  15816. function repeat_string(str, i) {
  15817. if (i <= 0) return "";
  15818. if (i == 1) return str;
  15819. var d = repeat_string(str, i >> 1);
  15820. d += d;
  15821. if (i & 1) d += str;
  15822. return d;
  15823. };
  15824. function defaults(args, defs) {
  15825. var ret = {};
  15826. if (args === true)
  15827. args = {};
  15828. for (var i in defs) if (HOP(defs, i)) {
  15829. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  15830. }
  15831. return ret;
  15832. };
  15833. function is_identifier(name) {
  15834. return /^[a-z_$][a-z0-9_$]*$/i.test(name)
  15835. && name != "this"
  15836. && !HOP(jsp.KEYWORDS_ATOM, name)
  15837. && !HOP(jsp.RESERVED_WORDS, name)
  15838. && !HOP(jsp.KEYWORDS, name);
  15839. };
  15840. function HOP(obj, prop) {
  15841. return Object.prototype.hasOwnProperty.call(obj, prop);
  15842. };
  15843. // some utilities
  15844. var MAP;
  15845. (function(){
  15846. MAP = function(a, f, o) {
  15847. var ret = [], top = [], i;
  15848. function doit() {
  15849. var val = f.call(o, a[i], i);
  15850. if (val instanceof AtTop) {
  15851. val = val.v;
  15852. if (val instanceof Splice) {
  15853. top.push.apply(top, val.v);
  15854. } else {
  15855. top.push(val);
  15856. }
  15857. }
  15858. else if (val != skip) {
  15859. if (val instanceof Splice) {
  15860. ret.push.apply(ret, val.v);
  15861. } else {
  15862. ret.push(val);
  15863. }
  15864. }
  15865. };
  15866. if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
  15867. else for (i in a) if (HOP(a, i)) doit();
  15868. return top.concat(ret);
  15869. };
  15870. MAP.at_top = function(val) { return new AtTop(val) };
  15871. MAP.splice = function(val) { return new Splice(val) };
  15872. var skip = MAP.skip = {};
  15873. function AtTop(val) { this.v = val };
  15874. function Splice(val) { this.v = val };
  15875. })();
  15876. /* -----[ Exports ]----- */
  15877. exports.ast_walker = ast_walker;
  15878. exports.ast_mangle = ast_mangle;
  15879. exports.ast_squeeze = ast_squeeze;
  15880. exports.ast_lift_variables = ast_lift_variables;
  15881. exports.gen_code = gen_code;
  15882. exports.ast_add_scope = ast_add_scope;
  15883. exports.set_logger = function(logger) { warn = logger };
  15884. exports.make_string = make_string;
  15885. exports.split_lines = split_lines;
  15886. exports.MAP = MAP;
  15887. // keep this last!
  15888. exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
  15889. // Local variables:
  15890. // js-indent-level: 4
  15891. // End:
  15892. });
  15893. define('uglifyjs/index', ["require", "exports", "module", "./parse-js", "./process", "./consolidator"], function(require, exports, module) {
  15894. //convienence function(src, [options]);
  15895. function uglify(orig_code, options){
  15896. options || (options = {});
  15897. var jsp = uglify.parser;
  15898. var pro = uglify.uglify;
  15899. var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
  15900. ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
  15901. ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
  15902. var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
  15903. return final_code;
  15904. };
  15905. uglify.parser = require("./parse-js");
  15906. uglify.uglify = require("./process");
  15907. uglify.consolidator = require("./consolidator");
  15908. module.exports = uglify
  15909. });//Distributed under the BSD license:
  15910. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  15911. define('uglifyjs2', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
  15912. /***********************************************************************
  15913. A JavaScript tokenizer / parser / beautifier / compressor.
  15914. https://github.com/mishoo/UglifyJS2
  15915. -------------------------------- (C) ---------------------------------
  15916. Author: Mihai Bazon
  15917. <mihai.bazon@gmail.com>
  15918. http://mihai.bazon.net/blog
  15919. Distributed under the BSD license:
  15920. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  15921. Redistribution and use in source and binary forms, with or without
  15922. modification, are permitted provided that the following conditions
  15923. are met:
  15924. * Redistributions of source code must retain the above
  15925. copyright notice, this list of conditions and the following
  15926. disclaimer.
  15927. * Redistributions in binary form must reproduce the above
  15928. copyright notice, this list of conditions and the following
  15929. disclaimer in the documentation and/or other materials
  15930. provided with the distribution.
  15931. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  15932. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15933. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  15934. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  15935. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  15936. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  15937. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  15938. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15939. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  15940. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  15941. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  15942. SUCH DAMAGE.
  15943. ***********************************************************************/
  15944. "use strict";
  15945. function array_to_hash(a) {
  15946. var ret = Object.create(null);
  15947. for (var i = 0; i < a.length; ++i)
  15948. ret[a[i]] = true;
  15949. return ret;
  15950. };
  15951. function slice(a, start) {
  15952. return Array.prototype.slice.call(a, start || 0);
  15953. };
  15954. function characters(str) {
  15955. return str.split("");
  15956. };
  15957. function member(name, array) {
  15958. for (var i = array.length; --i >= 0;)
  15959. if (array[i] == name)
  15960. return true;
  15961. return false;
  15962. };
  15963. function find_if(func, array) {
  15964. for (var i = 0, n = array.length; i < n; ++i) {
  15965. if (func(array[i]))
  15966. return array[i];
  15967. }
  15968. };
  15969. function repeat_string(str, i) {
  15970. if (i <= 0) return "";
  15971. if (i == 1) return str;
  15972. var d = repeat_string(str, i >> 1);
  15973. d += d;
  15974. if (i & 1) d += str;
  15975. return d;
  15976. };
  15977. function DefaultsError(msg, defs) {
  15978. Error.call(this, msg);
  15979. this.msg = msg;
  15980. this.defs = defs;
  15981. };
  15982. DefaultsError.prototype = Object.create(Error.prototype);
  15983. DefaultsError.prototype.constructor = DefaultsError;
  15984. DefaultsError.croak = function(msg, defs) {
  15985. throw new DefaultsError(msg, defs);
  15986. };
  15987. function defaults(args, defs, croak) {
  15988. if (args === true)
  15989. args = {};
  15990. var ret = args || {};
  15991. if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
  15992. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  15993. for (var i in defs) if (defs.hasOwnProperty(i)) {
  15994. ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
  15995. }
  15996. return ret;
  15997. };
  15998. function merge(obj, ext) {
  15999. var count = 0;
  16000. for (var i in ext) if (ext.hasOwnProperty(i)) {
  16001. obj[i] = ext[i];
  16002. count++;
  16003. }
  16004. return count;
  16005. };
  16006. function noop() {};
  16007. var MAP = (function(){
  16008. function MAP(a, f, backwards) {
  16009. var ret = [], top = [], i;
  16010. function doit() {
  16011. var val = f(a[i], i);
  16012. var is_last = val instanceof Last;
  16013. if (is_last) val = val.v;
  16014. if (val instanceof AtTop) {
  16015. val = val.v;
  16016. if (val instanceof Splice) {
  16017. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  16018. } else {
  16019. top.push(val);
  16020. }
  16021. }
  16022. else if (val !== skip) {
  16023. if (val instanceof Splice) {
  16024. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  16025. } else {
  16026. ret.push(val);
  16027. }
  16028. }
  16029. return is_last;
  16030. };
  16031. if (a instanceof Array) {
  16032. if (backwards) {
  16033. for (i = a.length; --i >= 0;) if (doit()) break;
  16034. ret.reverse();
  16035. top.reverse();
  16036. } else {
  16037. for (i = 0; i < a.length; ++i) if (doit()) break;
  16038. }
  16039. }
  16040. else {
  16041. for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
  16042. }
  16043. return top.concat(ret);
  16044. };
  16045. MAP.at_top = function(val) { return new AtTop(val) };
  16046. MAP.splice = function(val) { return new Splice(val) };
  16047. MAP.last = function(val) { return new Last(val) };
  16048. var skip = MAP.skip = {};
  16049. function AtTop(val) { this.v = val };
  16050. function Splice(val) { this.v = val };
  16051. function Last(val) { this.v = val };
  16052. return MAP;
  16053. })();
  16054. function push_uniq(array, el) {
  16055. if (array.indexOf(el) < 0)
  16056. array.push(el);
  16057. };
  16058. function string_template(text, props) {
  16059. return text.replace(/\{(.+?)\}/g, function(str, p){
  16060. return props[p];
  16061. });
  16062. };
  16063. function remove(array, el) {
  16064. for (var i = array.length; --i >= 0;) {
  16065. if (array[i] === el) array.splice(i, 1);
  16066. }
  16067. };
  16068. function mergeSort(array, cmp) {
  16069. if (array.length < 2) return array.slice();
  16070. function merge(a, b) {
  16071. var r = [], ai = 0, bi = 0, i = 0;
  16072. while (ai < a.length && bi < b.length) {
  16073. cmp(a[ai], b[bi]) <= 0
  16074. ? r[i++] = a[ai++]
  16075. : r[i++] = b[bi++];
  16076. }
  16077. if (ai < a.length) r.push.apply(r, a.slice(ai));
  16078. if (bi < b.length) r.push.apply(r, b.slice(bi));
  16079. return r;
  16080. };
  16081. function _ms(a) {
  16082. if (a.length <= 1)
  16083. return a;
  16084. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  16085. left = _ms(left);
  16086. right = _ms(right);
  16087. return merge(left, right);
  16088. };
  16089. return _ms(array);
  16090. };
  16091. function set_difference(a, b) {
  16092. return a.filter(function(el){
  16093. return b.indexOf(el) < 0;
  16094. });
  16095. };
  16096. function set_intersection(a, b) {
  16097. return a.filter(function(el){
  16098. return b.indexOf(el) >= 0;
  16099. });
  16100. };
  16101. // this function is taken from Acorn [1], written by Marijn Haverbeke
  16102. // [1] https://github.com/marijnh/acorn
  16103. function makePredicate(words) {
  16104. if (!(words instanceof Array)) words = words.split(" ");
  16105. var f = "", cats = [];
  16106. out: for (var i = 0; i < words.length; ++i) {
  16107. for (var j = 0; j < cats.length; ++j)
  16108. if (cats[j][0].length == words[i].length) {
  16109. cats[j].push(words[i]);
  16110. continue out;
  16111. }
  16112. cats.push([words[i]]);
  16113. }
  16114. function compareTo(arr) {
  16115. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  16116. f += "switch(str){";
  16117. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  16118. f += "return true}return false;";
  16119. }
  16120. // When there are more than three length categories, an outer
  16121. // switch first dispatches on the lengths, to save on comparisons.
  16122. if (cats.length > 3) {
  16123. cats.sort(function(a, b) {return b.length - a.length;});
  16124. f += "switch(str.length){";
  16125. for (var i = 0; i < cats.length; ++i) {
  16126. var cat = cats[i];
  16127. f += "case " + cat[0].length + ":";
  16128. compareTo(cat);
  16129. }
  16130. f += "}";
  16131. // Otherwise, simply generate a flat `switch` statement.
  16132. } else {
  16133. compareTo(words);
  16134. }
  16135. return new Function("str", f);
  16136. };
  16137. function all(array, predicate) {
  16138. for (var i = array.length; --i >= 0;)
  16139. if (!predicate(array[i]))
  16140. return false;
  16141. return true;
  16142. };
  16143. function Dictionary() {
  16144. this._values = Object.create(null);
  16145. this._size = 0;
  16146. };
  16147. Dictionary.prototype = {
  16148. set: function(key, val) {
  16149. if (!this.has(key)) ++this._size;
  16150. this._values["$" + key] = val;
  16151. return this;
  16152. },
  16153. add: function(key, val) {
  16154. if (this.has(key)) {
  16155. this.get(key).push(val);
  16156. } else {
  16157. this.set(key, [ val ]);
  16158. }
  16159. return this;
  16160. },
  16161. get: function(key) { return this._values["$" + key] },
  16162. del: function(key) {
  16163. if (this.has(key)) {
  16164. --this._size;
  16165. delete this._values["$" + key];
  16166. }
  16167. return this;
  16168. },
  16169. has: function(key) { return ("$" + key) in this._values },
  16170. each: function(f) {
  16171. for (var i in this._values)
  16172. f(this._values[i], i.substr(1));
  16173. },
  16174. size: function() {
  16175. return this._size;
  16176. },
  16177. map: function(f) {
  16178. var ret = [];
  16179. for (var i in this._values)
  16180. ret.push(f(this._values[i], i.substr(1)));
  16181. return ret;
  16182. },
  16183. toObject: function() { return this._values }
  16184. };
  16185. Dictionary.fromObject = function(obj) {
  16186. var dict = new Dictionary();
  16187. dict._size = merge(dict._values, obj);
  16188. return dict;
  16189. };
  16190. /***********************************************************************
  16191. A JavaScript tokenizer / parser / beautifier / compressor.
  16192. https://github.com/mishoo/UglifyJS2
  16193. -------------------------------- (C) ---------------------------------
  16194. Author: Mihai Bazon
  16195. <mihai.bazon@gmail.com>
  16196. http://mihai.bazon.net/blog
  16197. Distributed under the BSD license:
  16198. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16199. Redistribution and use in source and binary forms, with or without
  16200. modification, are permitted provided that the following conditions
  16201. are met:
  16202. * Redistributions of source code must retain the above
  16203. copyright notice, this list of conditions and the following
  16204. disclaimer.
  16205. * Redistributions in binary form must reproduce the above
  16206. copyright notice, this list of conditions and the following
  16207. disclaimer in the documentation and/or other materials
  16208. provided with the distribution.
  16209. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16210. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16211. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16212. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16213. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16214. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16215. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16216. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16217. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16218. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16219. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16220. SUCH DAMAGE.
  16221. ***********************************************************************/
  16222. "use strict";
  16223. function DEFNODE(type, props, methods, base) {
  16224. if (arguments.length < 4) base = AST_Node;
  16225. if (!props) props = [];
  16226. else props = props.split(/\s+/);
  16227. var self_props = props;
  16228. if (base && base.PROPS)
  16229. props = props.concat(base.PROPS);
  16230. var code = "return function AST_" + type + "(props){ if (props) { ";
  16231. for (var i = props.length; --i >= 0;) {
  16232. code += "this." + props[i] + " = props." + props[i] + ";";
  16233. }
  16234. var proto = base && new base;
  16235. if (proto && proto.initialize || (methods && methods.initialize))
  16236. code += "this.initialize();";
  16237. code += "}}";
  16238. var ctor = new Function(code)();
  16239. if (proto) {
  16240. ctor.prototype = proto;
  16241. ctor.BASE = base;
  16242. }
  16243. if (base) base.SUBCLASSES.push(ctor);
  16244. ctor.prototype.CTOR = ctor;
  16245. ctor.PROPS = props || null;
  16246. ctor.SELF_PROPS = self_props;
  16247. ctor.SUBCLASSES = [];
  16248. if (type) {
  16249. ctor.prototype.TYPE = ctor.TYPE = type;
  16250. }
  16251. if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
  16252. if (/^\$/.test(i)) {
  16253. ctor[i.substr(1)] = methods[i];
  16254. } else {
  16255. ctor.prototype[i] = methods[i];
  16256. }
  16257. }
  16258. ctor.DEFMETHOD = function(name, method) {
  16259. this.prototype[name] = method;
  16260. };
  16261. exports["AST_" + type] = ctor;
  16262. return ctor;
  16263. };
  16264. var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", {
  16265. }, null);
  16266. var AST_Node = DEFNODE("Node", "start end", {
  16267. clone: function() {
  16268. return new this.CTOR(this);
  16269. },
  16270. $documentation: "Base class of all AST nodes",
  16271. $propdoc: {
  16272. start: "[AST_Token] The first token of this node",
  16273. end: "[AST_Token] The last token of this node"
  16274. },
  16275. _walk: function(visitor) {
  16276. return visitor._visit(this);
  16277. },
  16278. walk: function(visitor) {
  16279. return this._walk(visitor); // not sure the indirection will be any help
  16280. }
  16281. }, null);
  16282. AST_Node.warn_function = null;
  16283. AST_Node.warn = function(txt, props) {
  16284. if (AST_Node.warn_function)
  16285. AST_Node.warn_function(string_template(txt, props));
  16286. };
  16287. /* -----[ statements ]----- */
  16288. var AST_Statement = DEFNODE("Statement", null, {
  16289. $documentation: "Base class of all statements",
  16290. });
  16291. var AST_Debugger = DEFNODE("Debugger", null, {
  16292. $documentation: "Represents a debugger statement",
  16293. }, AST_Statement);
  16294. var AST_Directive = DEFNODE("Directive", "value scope quote", {
  16295. $documentation: "Represents a directive, like \"use strict\";",
  16296. $propdoc: {
  16297. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  16298. scope: "[AST_Scope/S] The scope that this directive affects",
  16299. quote: "[string] the original quote character"
  16300. },
  16301. }, AST_Statement);
  16302. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  16303. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  16304. $propdoc: {
  16305. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  16306. },
  16307. _walk: function(visitor) {
  16308. return visitor._visit(this, function(){
  16309. this.body._walk(visitor);
  16310. });
  16311. }
  16312. }, AST_Statement);
  16313. function walk_body(node, visitor) {
  16314. if (node.body instanceof AST_Statement) {
  16315. node.body._walk(visitor);
  16316. }
  16317. else node.body.forEach(function(stat){
  16318. stat._walk(visitor);
  16319. });
  16320. };
  16321. var AST_Block = DEFNODE("Block", "body", {
  16322. $documentation: "A body of statements (usually bracketed)",
  16323. $propdoc: {
  16324. body: "[AST_Statement*] an array of statements"
  16325. },
  16326. _walk: function(visitor) {
  16327. return visitor._visit(this, function(){
  16328. walk_body(this, visitor);
  16329. });
  16330. }
  16331. }, AST_Statement);
  16332. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  16333. $documentation: "A block statement",
  16334. }, AST_Block);
  16335. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  16336. $documentation: "The empty statement (empty block or simply a semicolon)",
  16337. _walk: function(visitor) {
  16338. return visitor._visit(this);
  16339. }
  16340. }, AST_Statement);
  16341. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  16342. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  16343. $propdoc: {
  16344. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  16345. },
  16346. _walk: function(visitor) {
  16347. return visitor._visit(this, function(){
  16348. this.body._walk(visitor);
  16349. });
  16350. }
  16351. }, AST_Statement);
  16352. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  16353. $documentation: "Statement with a label",
  16354. $propdoc: {
  16355. label: "[AST_Label] a label definition"
  16356. },
  16357. _walk: function(visitor) {
  16358. return visitor._visit(this, function(){
  16359. this.label._walk(visitor);
  16360. this.body._walk(visitor);
  16361. });
  16362. }
  16363. }, AST_StatementWithBody);
  16364. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  16365. $documentation: "Internal class. All loops inherit from it."
  16366. }, AST_StatementWithBody);
  16367. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  16368. $documentation: "Base class for do/while statements",
  16369. $propdoc: {
  16370. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  16371. }
  16372. }, AST_IterationStatement);
  16373. var AST_Do = DEFNODE("Do", null, {
  16374. $documentation: "A `do` statement",
  16375. _walk: function(visitor) {
  16376. return visitor._visit(this, function(){
  16377. this.body._walk(visitor);
  16378. this.condition._walk(visitor);
  16379. });
  16380. }
  16381. }, AST_DWLoop);
  16382. var AST_While = DEFNODE("While", null, {
  16383. $documentation: "A `while` statement",
  16384. _walk: function(visitor) {
  16385. return visitor._visit(this, function(){
  16386. this.condition._walk(visitor);
  16387. this.body._walk(visitor);
  16388. });
  16389. }
  16390. }, AST_DWLoop);
  16391. var AST_For = DEFNODE("For", "init condition step", {
  16392. $documentation: "A `for` statement",
  16393. $propdoc: {
  16394. init: "[AST_Node?] the `for` initialization code, or null if empty",
  16395. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  16396. step: "[AST_Node?] the `for` update clause, or null if empty"
  16397. },
  16398. _walk: function(visitor) {
  16399. return visitor._visit(this, function(){
  16400. if (this.init) this.init._walk(visitor);
  16401. if (this.condition) this.condition._walk(visitor);
  16402. if (this.step) this.step._walk(visitor);
  16403. this.body._walk(visitor);
  16404. });
  16405. }
  16406. }, AST_IterationStatement);
  16407. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  16408. $documentation: "A `for ... in` statement",
  16409. $propdoc: {
  16410. init: "[AST_Node] the `for/in` initialization code",
  16411. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  16412. object: "[AST_Node] the object that we're looping through"
  16413. },
  16414. _walk: function(visitor) {
  16415. return visitor._visit(this, function(){
  16416. this.init._walk(visitor);
  16417. this.object._walk(visitor);
  16418. this.body._walk(visitor);
  16419. });
  16420. }
  16421. }, AST_IterationStatement);
  16422. var AST_With = DEFNODE("With", "expression", {
  16423. $documentation: "A `with` statement",
  16424. $propdoc: {
  16425. expression: "[AST_Node] the `with` expression"
  16426. },
  16427. _walk: function(visitor) {
  16428. return visitor._visit(this, function(){
  16429. this.expression._walk(visitor);
  16430. this.body._walk(visitor);
  16431. });
  16432. }
  16433. }, AST_StatementWithBody);
  16434. /* -----[ scope and functions ]----- */
  16435. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  16436. $documentation: "Base class for all statements introducing a lexical scope",
  16437. $propdoc: {
  16438. directives: "[string*/S] an array of directives declared in this scope",
  16439. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  16440. functions: "[Object/S] like `variables`, but only lists function declarations",
  16441. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  16442. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  16443. parent_scope: "[AST_Scope?/S] link to the parent scope",
  16444. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  16445. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  16446. },
  16447. }, AST_Block);
  16448. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  16449. $documentation: "The toplevel scope",
  16450. $propdoc: {
  16451. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  16452. },
  16453. wrap_enclose: function(arg_parameter_pairs) {
  16454. var self = this;
  16455. var args = [];
  16456. var parameters = [];
  16457. arg_parameter_pairs.forEach(function(pair) {
  16458. var splitAt = pair.lastIndexOf(":");
  16459. args.push(pair.substr(0, splitAt));
  16460. parameters.push(pair.substr(splitAt + 1));
  16461. });
  16462. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  16463. wrapped_tl = parse(wrapped_tl);
  16464. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  16465. if (node instanceof AST_Directive && node.value == "$ORIG") {
  16466. return MAP.splice(self.body);
  16467. }
  16468. }));
  16469. return wrapped_tl;
  16470. },
  16471. wrap_commonjs: function(name, export_all) {
  16472. var self = this;
  16473. var to_export = [];
  16474. if (export_all) {
  16475. self.figure_out_scope();
  16476. self.walk(new TreeWalker(function(node){
  16477. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  16478. if (!find_if(function(n){ return n.name == node.name }, to_export))
  16479. to_export.push(node);
  16480. }
  16481. }));
  16482. }
  16483. var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))";
  16484. wrapped_tl = parse(wrapped_tl);
  16485. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  16486. if (node instanceof AST_Directive) {
  16487. switch (node.value) {
  16488. case "$ORIG":
  16489. return MAP.splice(self.body);
  16490. case "$EXPORTS":
  16491. var body = [];
  16492. to_export.forEach(function(sym){
  16493. body.push(new AST_SimpleStatement({
  16494. body: new AST_Assign({
  16495. left: new AST_Sub({
  16496. expression: new AST_SymbolRef({ name: "exports" }),
  16497. property: new AST_String({ value: sym.name }),
  16498. }),
  16499. operator: "=",
  16500. right: new AST_SymbolRef(sym),
  16501. }),
  16502. }));
  16503. });
  16504. return MAP.splice(body);
  16505. }
  16506. }
  16507. }));
  16508. return wrapped_tl;
  16509. }
  16510. }, AST_Scope);
  16511. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  16512. $documentation: "Base class for functions",
  16513. $propdoc: {
  16514. name: "[AST_SymbolDeclaration?] the name of this function",
  16515. argnames: "[AST_SymbolFunarg*] array of function arguments",
  16516. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  16517. },
  16518. _walk: function(visitor) {
  16519. return visitor._visit(this, function(){
  16520. if (this.name) this.name._walk(visitor);
  16521. this.argnames.forEach(function(arg){
  16522. arg._walk(visitor);
  16523. });
  16524. walk_body(this, visitor);
  16525. });
  16526. }
  16527. }, AST_Scope);
  16528. var AST_Accessor = DEFNODE("Accessor", null, {
  16529. $documentation: "A setter/getter function. The `name` property is always null."
  16530. }, AST_Lambda);
  16531. var AST_Function = DEFNODE("Function", null, {
  16532. $documentation: "A function expression"
  16533. }, AST_Lambda);
  16534. var AST_Defun = DEFNODE("Defun", null, {
  16535. $documentation: "A function definition"
  16536. }, AST_Lambda);
  16537. /* -----[ JUMPS ]----- */
  16538. var AST_Jump = DEFNODE("Jump", null, {
  16539. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  16540. }, AST_Statement);
  16541. var AST_Exit = DEFNODE("Exit", "value", {
  16542. $documentation: "Base class for “exits” (`return` and `throw`)",
  16543. $propdoc: {
  16544. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  16545. },
  16546. _walk: function(visitor) {
  16547. return visitor._visit(this, this.value && function(){
  16548. this.value._walk(visitor);
  16549. });
  16550. }
  16551. }, AST_Jump);
  16552. var AST_Return = DEFNODE("Return", null, {
  16553. $documentation: "A `return` statement"
  16554. }, AST_Exit);
  16555. var AST_Throw = DEFNODE("Throw", null, {
  16556. $documentation: "A `throw` statement"
  16557. }, AST_Exit);
  16558. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  16559. $documentation: "Base class for loop control statements (`break` and `continue`)",
  16560. $propdoc: {
  16561. label: "[AST_LabelRef?] the label, or null if none",
  16562. },
  16563. _walk: function(visitor) {
  16564. return visitor._visit(this, this.label && function(){
  16565. this.label._walk(visitor);
  16566. });
  16567. }
  16568. }, AST_Jump);
  16569. var AST_Break = DEFNODE("Break", null, {
  16570. $documentation: "A `break` statement"
  16571. }, AST_LoopControl);
  16572. var AST_Continue = DEFNODE("Continue", null, {
  16573. $documentation: "A `continue` statement"
  16574. }, AST_LoopControl);
  16575. /* -----[ IF ]----- */
  16576. var AST_If = DEFNODE("If", "condition alternative", {
  16577. $documentation: "A `if` statement",
  16578. $propdoc: {
  16579. condition: "[AST_Node] the `if` condition",
  16580. alternative: "[AST_Statement?] the `else` part, or null if not present"
  16581. },
  16582. _walk: function(visitor) {
  16583. return visitor._visit(this, function(){
  16584. this.condition._walk(visitor);
  16585. this.body._walk(visitor);
  16586. if (this.alternative) this.alternative._walk(visitor);
  16587. });
  16588. }
  16589. }, AST_StatementWithBody);
  16590. /* -----[ SWITCH ]----- */
  16591. var AST_Switch = DEFNODE("Switch", "expression", {
  16592. $documentation: "A `switch` statement",
  16593. $propdoc: {
  16594. expression: "[AST_Node] the `switch` “discriminant”"
  16595. },
  16596. _walk: function(visitor) {
  16597. return visitor._visit(this, function(){
  16598. this.expression._walk(visitor);
  16599. walk_body(this, visitor);
  16600. });
  16601. }
  16602. }, AST_Block);
  16603. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  16604. $documentation: "Base class for `switch` branches",
  16605. }, AST_Block);
  16606. var AST_Default = DEFNODE("Default", null, {
  16607. $documentation: "A `default` switch branch",
  16608. }, AST_SwitchBranch);
  16609. var AST_Case = DEFNODE("Case", "expression", {
  16610. $documentation: "A `case` switch branch",
  16611. $propdoc: {
  16612. expression: "[AST_Node] the `case` expression"
  16613. },
  16614. _walk: function(visitor) {
  16615. return visitor._visit(this, function(){
  16616. this.expression._walk(visitor);
  16617. walk_body(this, visitor);
  16618. });
  16619. }
  16620. }, AST_SwitchBranch);
  16621. /* -----[ EXCEPTIONS ]----- */
  16622. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  16623. $documentation: "A `try` statement",
  16624. $propdoc: {
  16625. bcatch: "[AST_Catch?] the catch block, or null if not present",
  16626. bfinally: "[AST_Finally?] the finally block, or null if not present"
  16627. },
  16628. _walk: function(visitor) {
  16629. return visitor._visit(this, function(){
  16630. walk_body(this, visitor);
  16631. if (this.bcatch) this.bcatch._walk(visitor);
  16632. if (this.bfinally) this.bfinally._walk(visitor);
  16633. });
  16634. }
  16635. }, AST_Block);
  16636. var AST_Catch = DEFNODE("Catch", "argname", {
  16637. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  16638. $propdoc: {
  16639. argname: "[AST_SymbolCatch] symbol for the exception"
  16640. },
  16641. _walk: function(visitor) {
  16642. return visitor._visit(this, function(){
  16643. this.argname._walk(visitor);
  16644. walk_body(this, visitor);
  16645. });
  16646. }
  16647. }, AST_Block);
  16648. var AST_Finally = DEFNODE("Finally", null, {
  16649. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  16650. }, AST_Block);
  16651. /* -----[ VAR/CONST ]----- */
  16652. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  16653. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  16654. $propdoc: {
  16655. definitions: "[AST_VarDef*] array of variable definitions"
  16656. },
  16657. _walk: function(visitor) {
  16658. return visitor._visit(this, function(){
  16659. this.definitions.forEach(function(def){
  16660. def._walk(visitor);
  16661. });
  16662. });
  16663. }
  16664. }, AST_Statement);
  16665. var AST_Var = DEFNODE("Var", null, {
  16666. $documentation: "A `var` statement"
  16667. }, AST_Definitions);
  16668. var AST_Const = DEFNODE("Const", null, {
  16669. $documentation: "A `const` statement"
  16670. }, AST_Definitions);
  16671. var AST_VarDef = DEFNODE("VarDef", "name value", {
  16672. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  16673. $propdoc: {
  16674. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  16675. value: "[AST_Node?] initializer, or null of there's no initializer"
  16676. },
  16677. _walk: function(visitor) {
  16678. return visitor._visit(this, function(){
  16679. this.name._walk(visitor);
  16680. if (this.value) this.value._walk(visitor);
  16681. });
  16682. }
  16683. });
  16684. /* -----[ OTHER ]----- */
  16685. var AST_Call = DEFNODE("Call", "expression args", {
  16686. $documentation: "A function call expression",
  16687. $propdoc: {
  16688. expression: "[AST_Node] expression to invoke as function",
  16689. args: "[AST_Node*] array of arguments"
  16690. },
  16691. _walk: function(visitor) {
  16692. return visitor._visit(this, function(){
  16693. this.expression._walk(visitor);
  16694. this.args.forEach(function(arg){
  16695. arg._walk(visitor);
  16696. });
  16697. });
  16698. }
  16699. });
  16700. var AST_New = DEFNODE("New", null, {
  16701. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  16702. }, AST_Call);
  16703. var AST_Seq = DEFNODE("Seq", "car cdr", {
  16704. $documentation: "A sequence expression (two comma-separated expressions)",
  16705. $propdoc: {
  16706. car: "[AST_Node] first element in sequence",
  16707. cdr: "[AST_Node] second element in sequence"
  16708. },
  16709. $cons: function(x, y) {
  16710. var seq = new AST_Seq(x);
  16711. seq.car = x;
  16712. seq.cdr = y;
  16713. return seq;
  16714. },
  16715. $from_array: function(array) {
  16716. if (array.length == 0) return null;
  16717. if (array.length == 1) return array[0].clone();
  16718. var list = null;
  16719. for (var i = array.length; --i >= 0;) {
  16720. list = AST_Seq.cons(array[i], list);
  16721. }
  16722. var p = list;
  16723. while (p) {
  16724. if (p.cdr && !p.cdr.cdr) {
  16725. p.cdr = p.cdr.car;
  16726. break;
  16727. }
  16728. p = p.cdr;
  16729. }
  16730. return list;
  16731. },
  16732. to_array: function() {
  16733. var p = this, a = [];
  16734. while (p) {
  16735. a.push(p.car);
  16736. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  16737. a.push(p.cdr);
  16738. break;
  16739. }
  16740. p = p.cdr;
  16741. }
  16742. return a;
  16743. },
  16744. add: function(node) {
  16745. var p = this;
  16746. while (p) {
  16747. if (!(p.cdr instanceof AST_Seq)) {
  16748. var cell = AST_Seq.cons(p.cdr, node);
  16749. return p.cdr = cell;
  16750. }
  16751. p = p.cdr;
  16752. }
  16753. },
  16754. _walk: function(visitor) {
  16755. return visitor._visit(this, function(){
  16756. this.car._walk(visitor);
  16757. if (this.cdr) this.cdr._walk(visitor);
  16758. });
  16759. }
  16760. });
  16761. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  16762. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  16763. $propdoc: {
  16764. expression: "[AST_Node] the “container” expression",
  16765. 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"
  16766. }
  16767. });
  16768. var AST_Dot = DEFNODE("Dot", null, {
  16769. $documentation: "A dotted property access expression",
  16770. _walk: function(visitor) {
  16771. return visitor._visit(this, function(){
  16772. this.expression._walk(visitor);
  16773. });
  16774. }
  16775. }, AST_PropAccess);
  16776. var AST_Sub = DEFNODE("Sub", null, {
  16777. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  16778. _walk: function(visitor) {
  16779. return visitor._visit(this, function(){
  16780. this.expression._walk(visitor);
  16781. this.property._walk(visitor);
  16782. });
  16783. }
  16784. }, AST_PropAccess);
  16785. var AST_Unary = DEFNODE("Unary", "operator expression", {
  16786. $documentation: "Base class for unary expressions",
  16787. $propdoc: {
  16788. operator: "[string] the operator",
  16789. expression: "[AST_Node] expression that this unary operator applies to"
  16790. },
  16791. _walk: function(visitor) {
  16792. return visitor._visit(this, function(){
  16793. this.expression._walk(visitor);
  16794. });
  16795. }
  16796. });
  16797. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  16798. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  16799. }, AST_Unary);
  16800. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  16801. $documentation: "Unary postfix expression, i.e. `i++`"
  16802. }, AST_Unary);
  16803. var AST_Binary = DEFNODE("Binary", "left operator right", {
  16804. $documentation: "Binary expression, i.e. `a + b`",
  16805. $propdoc: {
  16806. left: "[AST_Node] left-hand side expression",
  16807. operator: "[string] the operator",
  16808. right: "[AST_Node] right-hand side expression"
  16809. },
  16810. _walk: function(visitor) {
  16811. return visitor._visit(this, function(){
  16812. this.left._walk(visitor);
  16813. this.right._walk(visitor);
  16814. });
  16815. }
  16816. });
  16817. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  16818. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  16819. $propdoc: {
  16820. condition: "[AST_Node]",
  16821. consequent: "[AST_Node]",
  16822. alternative: "[AST_Node]"
  16823. },
  16824. _walk: function(visitor) {
  16825. return visitor._visit(this, function(){
  16826. this.condition._walk(visitor);
  16827. this.consequent._walk(visitor);
  16828. this.alternative._walk(visitor);
  16829. });
  16830. }
  16831. });
  16832. var AST_Assign = DEFNODE("Assign", null, {
  16833. $documentation: "An assignment expression — `a = b + 5`",
  16834. }, AST_Binary);
  16835. /* -----[ LITERALS ]----- */
  16836. var AST_Array = DEFNODE("Array", "elements", {
  16837. $documentation: "An array literal",
  16838. $propdoc: {
  16839. elements: "[AST_Node*] array of elements"
  16840. },
  16841. _walk: function(visitor) {
  16842. return visitor._visit(this, function(){
  16843. this.elements.forEach(function(el){
  16844. el._walk(visitor);
  16845. });
  16846. });
  16847. }
  16848. });
  16849. var AST_Object = DEFNODE("Object", "properties", {
  16850. $documentation: "An object literal",
  16851. $propdoc: {
  16852. properties: "[AST_ObjectProperty*] array of properties"
  16853. },
  16854. _walk: function(visitor) {
  16855. return visitor._visit(this, function(){
  16856. this.properties.forEach(function(prop){
  16857. prop._walk(visitor);
  16858. });
  16859. });
  16860. }
  16861. });
  16862. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  16863. $documentation: "Base class for literal object properties",
  16864. $propdoc: {
  16865. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
  16866. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  16867. },
  16868. _walk: function(visitor) {
  16869. return visitor._visit(this, function(){
  16870. this.value._walk(visitor);
  16871. });
  16872. }
  16873. });
  16874. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
  16875. $documentation: "A key: value object property",
  16876. $propdoc: {
  16877. quote: "[string] the original quote character"
  16878. }
  16879. }, AST_ObjectProperty);
  16880. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  16881. $documentation: "An object setter property",
  16882. }, AST_ObjectProperty);
  16883. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  16884. $documentation: "An object getter property",
  16885. }, AST_ObjectProperty);
  16886. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  16887. $propdoc: {
  16888. name: "[string] name of this symbol",
  16889. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  16890. thedef: "[SymbolDef/S] the definition of this symbol"
  16891. },
  16892. $documentation: "Base class for all symbols",
  16893. });
  16894. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  16895. $documentation: "The name of a property accessor (setter/getter function)"
  16896. }, AST_Symbol);
  16897. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  16898. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  16899. $propdoc: {
  16900. init: "[AST_Node*/S] array of initializers for this declaration."
  16901. }
  16902. }, AST_Symbol);
  16903. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  16904. $documentation: "Symbol defining a variable",
  16905. }, AST_SymbolDeclaration);
  16906. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  16907. $documentation: "A constant declaration"
  16908. }, AST_SymbolDeclaration);
  16909. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  16910. $documentation: "Symbol naming a function argument",
  16911. }, AST_SymbolVar);
  16912. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  16913. $documentation: "Symbol defining a function",
  16914. }, AST_SymbolDeclaration);
  16915. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  16916. $documentation: "Symbol naming a function expression",
  16917. }, AST_SymbolDeclaration);
  16918. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  16919. $documentation: "Symbol naming the exception in catch",
  16920. }, AST_SymbolDeclaration);
  16921. var AST_Label = DEFNODE("Label", "references", {
  16922. $documentation: "Symbol naming a label (declaration)",
  16923. $propdoc: {
  16924. references: "[AST_LoopControl*] a list of nodes referring to this label"
  16925. },
  16926. initialize: function() {
  16927. this.references = [];
  16928. this.thedef = this;
  16929. }
  16930. }, AST_Symbol);
  16931. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  16932. $documentation: "Reference to some symbol (not definition/declaration)",
  16933. }, AST_Symbol);
  16934. var AST_LabelRef = DEFNODE("LabelRef", null, {
  16935. $documentation: "Reference to a label symbol",
  16936. }, AST_Symbol);
  16937. var AST_This = DEFNODE("This", null, {
  16938. $documentation: "The `this` symbol",
  16939. }, AST_Symbol);
  16940. var AST_Constant = DEFNODE("Constant", null, {
  16941. $documentation: "Base class for all constants",
  16942. getValue: function() {
  16943. return this.value;
  16944. }
  16945. });
  16946. var AST_String = DEFNODE("String", "value quote", {
  16947. $documentation: "A string literal",
  16948. $propdoc: {
  16949. value: "[string] the contents of this string",
  16950. quote: "[string] the original quote character"
  16951. }
  16952. }, AST_Constant);
  16953. var AST_Number = DEFNODE("Number", "value literal", {
  16954. $documentation: "A number literal",
  16955. $propdoc: {
  16956. value: "[number] the numeric value",
  16957. literal: "[string] numeric value as string (optional)"
  16958. }
  16959. }, AST_Constant);
  16960. var AST_RegExp = DEFNODE("RegExp", "value", {
  16961. $documentation: "A regexp literal",
  16962. $propdoc: {
  16963. value: "[RegExp] the actual regexp"
  16964. }
  16965. }, AST_Constant);
  16966. var AST_Atom = DEFNODE("Atom", null, {
  16967. $documentation: "Base class for atoms",
  16968. }, AST_Constant);
  16969. var AST_Null = DEFNODE("Null", null, {
  16970. $documentation: "The `null` atom",
  16971. value: null
  16972. }, AST_Atom);
  16973. var AST_NaN = DEFNODE("NaN", null, {
  16974. $documentation: "The impossible value",
  16975. value: 0/0
  16976. }, AST_Atom);
  16977. var AST_Undefined = DEFNODE("Undefined", null, {
  16978. $documentation: "The `undefined` value",
  16979. value: (function(){}())
  16980. }, AST_Atom);
  16981. var AST_Hole = DEFNODE("Hole", null, {
  16982. $documentation: "A hole in an array",
  16983. value: (function(){}())
  16984. }, AST_Atom);
  16985. var AST_Infinity = DEFNODE("Infinity", null, {
  16986. $documentation: "The `Infinity` value",
  16987. value: 1/0
  16988. }, AST_Atom);
  16989. var AST_Boolean = DEFNODE("Boolean", null, {
  16990. $documentation: "Base class for booleans",
  16991. }, AST_Atom);
  16992. var AST_False = DEFNODE("False", null, {
  16993. $documentation: "The `false` atom",
  16994. value: false
  16995. }, AST_Boolean);
  16996. var AST_True = DEFNODE("True", null, {
  16997. $documentation: "The `true` atom",
  16998. value: true
  16999. }, AST_Boolean);
  17000. /* -----[ TreeWalker ]----- */
  17001. function TreeWalker(callback) {
  17002. this.visit = callback;
  17003. this.stack = [];
  17004. this.directives = Object.create(null);
  17005. };
  17006. TreeWalker.prototype = {
  17007. _visit: function(node, descend) {
  17008. this.push(node);
  17009. var ret = this.visit(node, descend ? function(){
  17010. descend.call(node);
  17011. } : noop);
  17012. if (!ret && descend) {
  17013. descend.call(node);
  17014. }
  17015. this.pop(node);
  17016. return ret;
  17017. },
  17018. parent: function(n) {
  17019. return this.stack[this.stack.length - 2 - (n || 0)];
  17020. },
  17021. push: function (node) {
  17022. if (node instanceof AST_Lambda) {
  17023. this.directives = Object.create(this.directives);
  17024. } else if (node instanceof AST_Directive) {
  17025. this.directives[node.value] = this.directives[node.value] ? "up" : true;
  17026. }
  17027. this.stack.push(node);
  17028. },
  17029. pop: function(node) {
  17030. this.stack.pop();
  17031. if (node instanceof AST_Lambda) {
  17032. this.directives = Object.getPrototypeOf(this.directives);
  17033. }
  17034. },
  17035. self: function() {
  17036. return this.stack[this.stack.length - 1];
  17037. },
  17038. find_parent: function(type) {
  17039. var stack = this.stack;
  17040. for (var i = stack.length; --i >= 0;) {
  17041. var x = stack[i];
  17042. if (x instanceof type) return x;
  17043. }
  17044. },
  17045. has_directive: function(type) {
  17046. var dir = this.directives[type];
  17047. if (dir) return dir;
  17048. var node = this.stack[this.stack.length - 1];
  17049. if (node instanceof AST_Scope) {
  17050. for (var i = 0; i < node.body.length; ++i) {
  17051. var st = node.body[i];
  17052. if (!(st instanceof AST_Directive)) break;
  17053. if (st.value == type) return true;
  17054. }
  17055. }
  17056. },
  17057. in_boolean_context: function() {
  17058. var stack = this.stack;
  17059. var i = stack.length, self = stack[--i];
  17060. while (i > 0) {
  17061. var p = stack[--i];
  17062. if ((p instanceof AST_If && p.condition === self) ||
  17063. (p instanceof AST_Conditional && p.condition === self) ||
  17064. (p instanceof AST_DWLoop && p.condition === self) ||
  17065. (p instanceof AST_For && p.condition === self) ||
  17066. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  17067. {
  17068. return true;
  17069. }
  17070. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  17071. return false;
  17072. self = p;
  17073. }
  17074. },
  17075. loopcontrol_target: function(label) {
  17076. var stack = this.stack;
  17077. if (label) for (var i = stack.length; --i >= 0;) {
  17078. var x = stack[i];
  17079. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  17080. return x.body;
  17081. }
  17082. } else for (var i = stack.length; --i >= 0;) {
  17083. var x = stack[i];
  17084. if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
  17085. return x;
  17086. }
  17087. }
  17088. };
  17089. /***********************************************************************
  17090. A JavaScript tokenizer / parser / beautifier / compressor.
  17091. https://github.com/mishoo/UglifyJS2
  17092. -------------------------------- (C) ---------------------------------
  17093. Author: Mihai Bazon
  17094. <mihai.bazon@gmail.com>
  17095. http://mihai.bazon.net/blog
  17096. Distributed under the BSD license:
  17097. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  17098. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  17099. Redistribution and use in source and binary forms, with or without
  17100. modification, are permitted provided that the following conditions
  17101. are met:
  17102. * Redistributions of source code must retain the above
  17103. copyright notice, this list of conditions and the following
  17104. disclaimer.
  17105. * Redistributions in binary form must reproduce the above
  17106. copyright notice, this list of conditions and the following
  17107. disclaimer in the documentation and/or other materials
  17108. provided with the distribution.
  17109. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  17110. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17111. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17112. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  17113. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  17114. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  17115. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17116. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  17117. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  17118. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  17119. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  17120. SUCH DAMAGE.
  17121. ***********************************************************************/
  17122. "use strict";
  17123. 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';
  17124. var KEYWORDS_ATOM = 'false null true';
  17125. 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'
  17126. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  17127. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  17128. KEYWORDS = makePredicate(KEYWORDS);
  17129. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  17130. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  17131. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  17132. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  17133. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  17134. var RE_OCT_NUMBER = /^0[0-7]+$/;
  17135. var OPERATORS = makePredicate([
  17136. "in",
  17137. "instanceof",
  17138. "typeof",
  17139. "new",
  17140. "void",
  17141. "delete",
  17142. "++",
  17143. "--",
  17144. "+",
  17145. "-",
  17146. "!",
  17147. "~",
  17148. "&",
  17149. "|",
  17150. "^",
  17151. "*",
  17152. "/",
  17153. "%",
  17154. ">>",
  17155. "<<",
  17156. ">>>",
  17157. "<",
  17158. ">",
  17159. "<=",
  17160. ">=",
  17161. "==",
  17162. "===",
  17163. "!=",
  17164. "!==",
  17165. "?",
  17166. "=",
  17167. "+=",
  17168. "-=",
  17169. "/=",
  17170. "*=",
  17171. "%=",
  17172. ">>=",
  17173. "<<=",
  17174. ">>>=",
  17175. "|=",
  17176. "^=",
  17177. "&=",
  17178. "&&",
  17179. "||"
  17180. ]);
  17181. 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\uFEFF"));
  17182. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  17183. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  17184. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  17185. /* -----[ Tokenizer ]----- */
  17186. // regexps adapted from http://xregexp.com/plugins/#unicode
  17187. var UNICODE = {
  17188. 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\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\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-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\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-\\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-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\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-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\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]"),
  17189. 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\\u0DE6-\\u0DEF\\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\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"),
  17190. 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]"),
  17191. 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]"),
  17192. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  17193. };
  17194. function is_letter(code) {
  17195. return (code >= 97 && code <= 122)
  17196. || (code >= 65 && code <= 90)
  17197. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  17198. };
  17199. function is_digit(code) {
  17200. return code >= 48 && code <= 57;
  17201. };
  17202. function is_alphanumeric_char(code) {
  17203. return is_digit(code) || is_letter(code);
  17204. };
  17205. function is_unicode_digit(code) {
  17206. return UNICODE.digit.test(String.fromCharCode(code));
  17207. }
  17208. function is_unicode_combining_mark(ch) {
  17209. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  17210. };
  17211. function is_unicode_connector_punctuation(ch) {
  17212. return UNICODE.connector_punctuation.test(ch);
  17213. };
  17214. function is_identifier(name) {
  17215. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  17216. };
  17217. function is_identifier_start(code) {
  17218. return code == 36 || code == 95 || is_letter(code);
  17219. };
  17220. function is_identifier_char(ch) {
  17221. var code = ch.charCodeAt(0);
  17222. return is_identifier_start(code)
  17223. || is_digit(code)
  17224. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  17225. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  17226. || is_unicode_combining_mark(ch)
  17227. || is_unicode_connector_punctuation(ch)
  17228. || is_unicode_digit(code)
  17229. ;
  17230. };
  17231. function is_identifier_string(str){
  17232. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  17233. };
  17234. function parse_js_number(num) {
  17235. if (RE_HEX_NUMBER.test(num)) {
  17236. return parseInt(num.substr(2), 16);
  17237. } else if (RE_OCT_NUMBER.test(num)) {
  17238. return parseInt(num.substr(1), 8);
  17239. } else {
  17240. var val = parseFloat(num);
  17241. if (val == num) return val;
  17242. }
  17243. };
  17244. function JS_Parse_Error(message, filename, line, col, pos) {
  17245. this.message = message;
  17246. this.filename = filename;
  17247. this.line = line;
  17248. this.col = col;
  17249. this.pos = pos;
  17250. this.stack = new Error().stack;
  17251. };
  17252. JS_Parse_Error.prototype.toString = function() {
  17253. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  17254. };
  17255. function js_error(message, filename, line, col, pos) {
  17256. throw new JS_Parse_Error(message, filename, line, col, pos);
  17257. };
  17258. function is_token(token, type, val) {
  17259. return token.type == type && (val == null || token.value == val);
  17260. };
  17261. var EX_EOF = {};
  17262. function tokenizer($TEXT, filename, html5_comments, shebang) {
  17263. var S = {
  17264. text : $TEXT,
  17265. filename : filename,
  17266. pos : 0,
  17267. tokpos : 0,
  17268. line : 1,
  17269. tokline : 0,
  17270. col : 0,
  17271. tokcol : 0,
  17272. newline_before : false,
  17273. regex_allowed : false,
  17274. comments_before : []
  17275. };
  17276. function peek() { return S.text.charAt(S.pos); };
  17277. function next(signal_eof, in_string) {
  17278. var ch = S.text.charAt(S.pos++);
  17279. if (signal_eof && !ch)
  17280. throw EX_EOF;
  17281. if ("\r\n\u2028\u2029".indexOf(ch) >= 0) {
  17282. S.newline_before = S.newline_before || !in_string;
  17283. ++S.line;
  17284. S.col = 0;
  17285. if (!in_string && ch == "\r" && peek() == "\n") {
  17286. // treat a \r\n sequence as a single \n
  17287. ++S.pos;
  17288. ch = "\n";
  17289. }
  17290. } else {
  17291. ++S.col;
  17292. }
  17293. return ch;
  17294. };
  17295. function forward(i) {
  17296. while (i-- > 0) next();
  17297. };
  17298. function looking_at(str) {
  17299. return S.text.substr(S.pos, str.length) == str;
  17300. };
  17301. function find(what, signal_eof) {
  17302. var pos = S.text.indexOf(what, S.pos);
  17303. if (signal_eof && pos == -1) throw EX_EOF;
  17304. return pos;
  17305. };
  17306. function start_token() {
  17307. S.tokline = S.line;
  17308. S.tokcol = S.col;
  17309. S.tokpos = S.pos;
  17310. };
  17311. var prev_was_dot = false;
  17312. function token(type, value, is_comment) {
  17313. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  17314. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  17315. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  17316. prev_was_dot = (type == "punc" && value == ".");
  17317. var ret = {
  17318. type : type,
  17319. value : value,
  17320. line : S.tokline,
  17321. col : S.tokcol,
  17322. pos : S.tokpos,
  17323. endline : S.line,
  17324. endcol : S.col,
  17325. endpos : S.pos,
  17326. nlb : S.newline_before,
  17327. file : filename
  17328. };
  17329. if (/^(?:num|string|regexp)$/i.test(type)) {
  17330. ret.raw = $TEXT.substring(ret.pos, ret.endpos);
  17331. }
  17332. if (!is_comment) {
  17333. ret.comments_before = S.comments_before;
  17334. S.comments_before = [];
  17335. // make note of any newlines in the comments that came before
  17336. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  17337. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  17338. }
  17339. }
  17340. S.newline_before = false;
  17341. return new AST_Token(ret);
  17342. };
  17343. function skip_whitespace() {
  17344. var ch;
  17345. while (WHITESPACE_CHARS(ch = peek()) || ch == "\u2028" || ch == "\u2029")
  17346. next();
  17347. };
  17348. function read_while(pred) {
  17349. var ret = "", ch, i = 0;
  17350. while ((ch = peek()) && pred(ch, i++))
  17351. ret += next();
  17352. return ret;
  17353. };
  17354. function parse_error(err) {
  17355. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  17356. };
  17357. function read_num(prefix) {
  17358. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  17359. var num = read_while(function(ch, i){
  17360. var code = ch.charCodeAt(0);
  17361. switch (code) {
  17362. case 120: case 88: // xX
  17363. return has_x ? false : (has_x = true);
  17364. case 101: case 69: // eE
  17365. return has_x ? true : has_e ? false : (has_e = after_e = true);
  17366. case 45: // -
  17367. return after_e || (i == 0 && !prefix);
  17368. case 43: // +
  17369. return after_e;
  17370. case (after_e = false, 46): // .
  17371. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  17372. }
  17373. return is_alphanumeric_char(code);
  17374. });
  17375. if (prefix) num = prefix + num;
  17376. var valid = parse_js_number(num);
  17377. if (!isNaN(valid)) {
  17378. return token("num", valid);
  17379. } else {
  17380. parse_error("Invalid syntax: " + num);
  17381. }
  17382. };
  17383. function read_escaped_char(in_string) {
  17384. var ch = next(true, in_string);
  17385. switch (ch.charCodeAt(0)) {
  17386. case 110 : return "\n";
  17387. case 114 : return "\r";
  17388. case 116 : return "\t";
  17389. case 98 : return "\b";
  17390. case 118 : return "\u000b"; // \v
  17391. case 102 : return "\f";
  17392. case 48 : return "\0";
  17393. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  17394. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  17395. case 10 : return ""; // newline
  17396. case 13 : // \r
  17397. if (peek() == "\n") { // DOS newline
  17398. next(true, in_string);
  17399. return "";
  17400. }
  17401. }
  17402. return ch;
  17403. };
  17404. function hex_bytes(n) {
  17405. var num = 0;
  17406. for (; n > 0; --n) {
  17407. var digit = parseInt(next(true), 16);
  17408. if (isNaN(digit))
  17409. parse_error("Invalid hex-character pattern in string");
  17410. num = (num << 4) | digit;
  17411. }
  17412. return num;
  17413. };
  17414. var read_string = with_eof_error("Unterminated string constant", function(quote_char){
  17415. var quote = next(), ret = "";
  17416. for (;;) {
  17417. var ch = next(true, true);
  17418. if (ch == "\\") {
  17419. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  17420. // https://github.com/mishoo/UglifyJS/issues/178
  17421. var octal_len = 0, first = null;
  17422. ch = read_while(function(ch){
  17423. if (ch >= "0" && ch <= "7") {
  17424. if (!first) {
  17425. first = ch;
  17426. return ++octal_len;
  17427. }
  17428. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  17429. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  17430. }
  17431. return false;
  17432. });
  17433. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  17434. else ch = read_escaped_char(true);
  17435. }
  17436. else if (ch == quote) break;
  17437. ret += ch;
  17438. }
  17439. var tok = token("string", ret);
  17440. tok.quote = quote_char;
  17441. return tok;
  17442. });
  17443. function skip_line_comment(type) {
  17444. var regex_allowed = S.regex_allowed;
  17445. var i = find("\n"), ret;
  17446. if (i == -1) {
  17447. ret = S.text.substr(S.pos);
  17448. S.pos = S.text.length;
  17449. } else {
  17450. ret = S.text.substring(S.pos, i);
  17451. S.pos = i;
  17452. }
  17453. S.col = S.tokcol + (S.pos - S.tokpos);
  17454. S.comments_before.push(token(type, ret, true));
  17455. S.regex_allowed = regex_allowed;
  17456. return next_token();
  17457. };
  17458. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
  17459. var regex_allowed = S.regex_allowed;
  17460. var i = find("*/", true);
  17461. var text = S.text.substring(S.pos, i);
  17462. var a = text.split("\n"), n = a.length;
  17463. // update stream position
  17464. S.pos = i + 2;
  17465. S.line += n - 1;
  17466. if (n > 1) S.col = a[n - 1].length;
  17467. else S.col += a[n - 1].length;
  17468. S.col += 2;
  17469. var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  17470. S.comments_before.push(token("comment2", text, true));
  17471. S.regex_allowed = regex_allowed;
  17472. S.newline_before = nlb;
  17473. return next_token();
  17474. });
  17475. function read_name() {
  17476. var backslash = false, name = "", ch, escaped = false, hex;
  17477. while ((ch = peek()) != null) {
  17478. if (!backslash) {
  17479. if (ch == "\\") escaped = backslash = true, next();
  17480. else if (is_identifier_char(ch)) name += next();
  17481. else break;
  17482. }
  17483. else {
  17484. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  17485. ch = read_escaped_char();
  17486. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  17487. name += ch;
  17488. backslash = false;
  17489. }
  17490. }
  17491. if (KEYWORDS(name) && escaped) {
  17492. hex = name.charCodeAt(0).toString(16).toUpperCase();
  17493. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  17494. }
  17495. return name;
  17496. };
  17497. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
  17498. var prev_backslash = false, ch, in_class = false;
  17499. while ((ch = next(true))) if (prev_backslash) {
  17500. regexp += "\\" + ch;
  17501. prev_backslash = false;
  17502. } else if (ch == "[") {
  17503. in_class = true;
  17504. regexp += ch;
  17505. } else if (ch == "]" && in_class) {
  17506. in_class = false;
  17507. regexp += ch;
  17508. } else if (ch == "/" && !in_class) {
  17509. break;
  17510. } else if (ch == "\\") {
  17511. prev_backslash = true;
  17512. } else {
  17513. regexp += ch;
  17514. }
  17515. var mods = read_name();
  17516. try {
  17517. return token("regexp", new RegExp(regexp, mods));
  17518. } catch(e) {
  17519. parse_error(e.message);
  17520. }
  17521. });
  17522. function read_operator(prefix) {
  17523. function grow(op) {
  17524. if (!peek()) return op;
  17525. var bigger = op + peek();
  17526. if (OPERATORS(bigger)) {
  17527. next();
  17528. return grow(bigger);
  17529. } else {
  17530. return op;
  17531. }
  17532. };
  17533. return token("operator", grow(prefix || next()));
  17534. };
  17535. function handle_slash() {
  17536. next();
  17537. switch (peek()) {
  17538. case "/":
  17539. next();
  17540. return skip_line_comment("comment1");
  17541. case "*":
  17542. next();
  17543. return skip_multiline_comment();
  17544. }
  17545. return S.regex_allowed ? read_regexp("") : read_operator("/");
  17546. };
  17547. function handle_dot() {
  17548. next();
  17549. return is_digit(peek().charCodeAt(0))
  17550. ? read_num(".")
  17551. : token("punc", ".");
  17552. };
  17553. function read_word() {
  17554. var word = read_name();
  17555. if (prev_was_dot) return token("name", word);
  17556. return KEYWORDS_ATOM(word) ? token("atom", word)
  17557. : !KEYWORDS(word) ? token("name", word)
  17558. : OPERATORS(word) ? token("operator", word)
  17559. : token("keyword", word);
  17560. };
  17561. function with_eof_error(eof_error, cont) {
  17562. return function(x) {
  17563. try {
  17564. return cont(x);
  17565. } catch(ex) {
  17566. if (ex === EX_EOF) parse_error(eof_error);
  17567. else throw ex;
  17568. }
  17569. };
  17570. };
  17571. function next_token(force_regexp) {
  17572. if (force_regexp != null)
  17573. return read_regexp(force_regexp);
  17574. skip_whitespace();
  17575. start_token();
  17576. if (html5_comments) {
  17577. if (looking_at("<!--")) {
  17578. forward(4);
  17579. return skip_line_comment("comment3");
  17580. }
  17581. if (looking_at("-->") && S.newline_before) {
  17582. forward(3);
  17583. return skip_line_comment("comment4");
  17584. }
  17585. }
  17586. var ch = peek();
  17587. if (!ch) return token("eof");
  17588. var code = ch.charCodeAt(0);
  17589. switch (code) {
  17590. case 34: case 39: return read_string(ch);
  17591. case 46: return handle_dot();
  17592. case 47: return handle_slash();
  17593. }
  17594. if (is_digit(code)) return read_num();
  17595. if (PUNC_CHARS(ch)) return token("punc", next());
  17596. if (OPERATOR_CHARS(ch)) return read_operator();
  17597. if (code == 92 || is_identifier_start(code)) return read_word();
  17598. if (shebang) {
  17599. if (S.pos == 0 && looking_at("#!")) {
  17600. forward(2);
  17601. return skip_line_comment("comment5");
  17602. }
  17603. }
  17604. parse_error("Unexpected character '" + ch + "'");
  17605. };
  17606. next_token.context = function(nc) {
  17607. if (nc) S = nc;
  17608. return S;
  17609. };
  17610. return next_token;
  17611. };
  17612. /* -----[ Parser (constants) ]----- */
  17613. var UNARY_PREFIX = makePredicate([
  17614. "typeof",
  17615. "void",
  17616. "delete",
  17617. "--",
  17618. "++",
  17619. "!",
  17620. "~",
  17621. "-",
  17622. "+"
  17623. ]);
  17624. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  17625. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  17626. var PRECEDENCE = (function(a, ret){
  17627. for (var i = 0; i < a.length; ++i) {
  17628. var b = a[i];
  17629. for (var j = 0; j < b.length; ++j) {
  17630. ret[b[j]] = i + 1;
  17631. }
  17632. }
  17633. return ret;
  17634. })(
  17635. [
  17636. ["||"],
  17637. ["&&"],
  17638. ["|"],
  17639. ["^"],
  17640. ["&"],
  17641. ["==", "===", "!=", "!=="],
  17642. ["<", ">", "<=", ">=", "in", "instanceof"],
  17643. [">>", "<<", ">>>"],
  17644. ["+", "-"],
  17645. ["*", "/", "%"]
  17646. ],
  17647. {}
  17648. );
  17649. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  17650. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  17651. /* -----[ Parser ]----- */
  17652. function parse($TEXT, options) {
  17653. options = defaults(options, {
  17654. strict : false,
  17655. filename : null,
  17656. toplevel : null,
  17657. expression : false,
  17658. html5_comments : true,
  17659. bare_returns : false,
  17660. shebang : true,
  17661. });
  17662. var S = {
  17663. input : (typeof $TEXT == "string"
  17664. ? tokenizer($TEXT, options.filename,
  17665. options.html5_comments, options.shebang)
  17666. : $TEXT),
  17667. token : null,
  17668. prev : null,
  17669. peeked : null,
  17670. in_function : 0,
  17671. in_directives : true,
  17672. in_loop : 0,
  17673. labels : []
  17674. };
  17675. S.token = next();
  17676. function is(type, value) {
  17677. return is_token(S.token, type, value);
  17678. };
  17679. function peek() { return S.peeked || (S.peeked = S.input()); };
  17680. function next() {
  17681. S.prev = S.token;
  17682. if (S.peeked) {
  17683. S.token = S.peeked;
  17684. S.peeked = null;
  17685. } else {
  17686. S.token = S.input();
  17687. }
  17688. S.in_directives = S.in_directives && (
  17689. S.token.type == "string" || is("punc", ";")
  17690. );
  17691. return S.token;
  17692. };
  17693. function prev() {
  17694. return S.prev;
  17695. };
  17696. function croak(msg, line, col, pos) {
  17697. var ctx = S.input.context();
  17698. js_error(msg,
  17699. ctx.filename,
  17700. line != null ? line : ctx.tokline,
  17701. col != null ? col : ctx.tokcol,
  17702. pos != null ? pos : ctx.tokpos);
  17703. };
  17704. function token_error(token, msg) {
  17705. croak(msg, token.line, token.col);
  17706. };
  17707. function unexpected(token) {
  17708. if (token == null)
  17709. token = S.token;
  17710. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  17711. };
  17712. function expect_token(type, val) {
  17713. if (is(type, val)) {
  17714. return next();
  17715. }
  17716. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  17717. };
  17718. function expect(punc) { return expect_token("punc", punc); };
  17719. function can_insert_semicolon() {
  17720. return !options.strict && (
  17721. S.token.nlb || is("eof") || is("punc", "}")
  17722. );
  17723. };
  17724. function semicolon() {
  17725. if (is("punc", ";")) next();
  17726. else if (!can_insert_semicolon()) unexpected();
  17727. };
  17728. function parenthesised() {
  17729. expect("(");
  17730. var exp = expression(true);
  17731. expect(")");
  17732. return exp;
  17733. };
  17734. function embed_tokens(parser) {
  17735. return function() {
  17736. var start = S.token;
  17737. var expr = parser();
  17738. var end = prev();
  17739. expr.start = start;
  17740. expr.end = end;
  17741. return expr;
  17742. };
  17743. };
  17744. function handle_regexp() {
  17745. if (is("operator", "/") || is("operator", "/=")) {
  17746. S.peeked = null;
  17747. S.token = S.input(S.token.value.substr(1)); // force regexp
  17748. }
  17749. };
  17750. var statement = embed_tokens(function() {
  17751. var tmp;
  17752. handle_regexp();
  17753. switch (S.token.type) {
  17754. case "string":
  17755. var dir = S.in_directives, stat = simple_statement();
  17756. // XXXv2: decide how to fix directives
  17757. if (dir && stat.body instanceof AST_String && !is("punc", ",")) {
  17758. return new AST_Directive({
  17759. start : stat.body.start,
  17760. end : stat.body.end,
  17761. quote : stat.body.quote,
  17762. value : stat.body.value,
  17763. });
  17764. }
  17765. return stat;
  17766. case "num":
  17767. case "regexp":
  17768. case "operator":
  17769. case "atom":
  17770. return simple_statement();
  17771. case "name":
  17772. return is_token(peek(), "punc", ":")
  17773. ? labeled_statement()
  17774. : simple_statement();
  17775. case "punc":
  17776. switch (S.token.value) {
  17777. case "{":
  17778. return new AST_BlockStatement({
  17779. start : S.token,
  17780. body : block_(),
  17781. end : prev()
  17782. });
  17783. case "[":
  17784. case "(":
  17785. return simple_statement();
  17786. case ";":
  17787. next();
  17788. return new AST_EmptyStatement();
  17789. default:
  17790. unexpected();
  17791. }
  17792. case "keyword":
  17793. switch (tmp = S.token.value, next(), tmp) {
  17794. case "break":
  17795. return break_cont(AST_Break);
  17796. case "continue":
  17797. return break_cont(AST_Continue);
  17798. case "debugger":
  17799. semicolon();
  17800. return new AST_Debugger();
  17801. case "do":
  17802. return new AST_Do({
  17803. body : in_loop(statement),
  17804. condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
  17805. });
  17806. case "while":
  17807. return new AST_While({
  17808. condition : parenthesised(),
  17809. body : in_loop(statement)
  17810. });
  17811. case "for":
  17812. return for_();
  17813. case "function":
  17814. return function_(AST_Defun);
  17815. case "if":
  17816. return if_();
  17817. case "return":
  17818. if (S.in_function == 0 && !options.bare_returns)
  17819. croak("'return' outside of function");
  17820. return new AST_Return({
  17821. value: ( is("punc", ";")
  17822. ? (next(), null)
  17823. : can_insert_semicolon()
  17824. ? null
  17825. : (tmp = expression(true), semicolon(), tmp) )
  17826. });
  17827. case "switch":
  17828. return new AST_Switch({
  17829. expression : parenthesised(),
  17830. body : in_loop(switch_body_)
  17831. });
  17832. case "throw":
  17833. if (S.token.nlb)
  17834. croak("Illegal newline after 'throw'");
  17835. return new AST_Throw({
  17836. value: (tmp = expression(true), semicolon(), tmp)
  17837. });
  17838. case "try":
  17839. return try_();
  17840. case "var":
  17841. return tmp = var_(), semicolon(), tmp;
  17842. case "const":
  17843. return tmp = const_(), semicolon(), tmp;
  17844. case "with":
  17845. return new AST_With({
  17846. expression : parenthesised(),
  17847. body : statement()
  17848. });
  17849. default:
  17850. unexpected();
  17851. }
  17852. }
  17853. });
  17854. function labeled_statement() {
  17855. var label = as_symbol(AST_Label);
  17856. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  17857. // ECMA-262, 12.12: An ECMAScript program is considered
  17858. // syntactically incorrect if it contains a
  17859. // LabelledStatement that is enclosed by a
  17860. // LabelledStatement with the same Identifier as label.
  17861. croak("Label " + label.name + " defined twice");
  17862. }
  17863. expect(":");
  17864. S.labels.push(label);
  17865. var stat = statement();
  17866. S.labels.pop();
  17867. if (!(stat instanceof AST_IterationStatement)) {
  17868. // check for `continue` that refers to this label.
  17869. // those should be reported as syntax errors.
  17870. // https://github.com/mishoo/UglifyJS2/issues/287
  17871. label.references.forEach(function(ref){
  17872. if (ref instanceof AST_Continue) {
  17873. ref = ref.label.start;
  17874. croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
  17875. ref.line, ref.col, ref.pos);
  17876. }
  17877. });
  17878. }
  17879. return new AST_LabeledStatement({ body: stat, label: label });
  17880. };
  17881. function simple_statement(tmp) {
  17882. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  17883. };
  17884. function break_cont(type) {
  17885. var label = null, ldef;
  17886. if (!can_insert_semicolon()) {
  17887. label = as_symbol(AST_LabelRef, true);
  17888. }
  17889. if (label != null) {
  17890. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  17891. if (!ldef)
  17892. croak("Undefined label " + label.name);
  17893. label.thedef = ldef;
  17894. }
  17895. else if (S.in_loop == 0)
  17896. croak(type.TYPE + " not inside a loop or switch");
  17897. semicolon();
  17898. var stat = new type({ label: label });
  17899. if (ldef) ldef.references.push(stat);
  17900. return stat;
  17901. };
  17902. function for_() {
  17903. expect("(");
  17904. var init = null;
  17905. if (!is("punc", ";")) {
  17906. init = is("keyword", "var")
  17907. ? (next(), var_(true))
  17908. : expression(true, true);
  17909. if (is("operator", "in")) {
  17910. if (init instanceof AST_Var && init.definitions.length > 1)
  17911. croak("Only one variable declaration allowed in for..in loop");
  17912. next();
  17913. return for_in(init);
  17914. }
  17915. }
  17916. return regular_for(init);
  17917. };
  17918. function regular_for(init) {
  17919. expect(";");
  17920. var test = is("punc", ";") ? null : expression(true);
  17921. expect(";");
  17922. var step = is("punc", ")") ? null : expression(true);
  17923. expect(")");
  17924. return new AST_For({
  17925. init : init,
  17926. condition : test,
  17927. step : step,
  17928. body : in_loop(statement)
  17929. });
  17930. };
  17931. function for_in(init) {
  17932. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  17933. var obj = expression(true);
  17934. expect(")");
  17935. return new AST_ForIn({
  17936. init : init,
  17937. name : lhs,
  17938. object : obj,
  17939. body : in_loop(statement)
  17940. });
  17941. };
  17942. var function_ = function(ctor) {
  17943. var in_statement = ctor === AST_Defun;
  17944. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  17945. if (in_statement && !name)
  17946. unexpected();
  17947. expect("(");
  17948. return new ctor({
  17949. name: name,
  17950. argnames: (function(first, a){
  17951. while (!is("punc", ")")) {
  17952. if (first) first = false; else expect(",");
  17953. a.push(as_symbol(AST_SymbolFunarg));
  17954. }
  17955. next();
  17956. return a;
  17957. })(true, []),
  17958. body: (function(loop, labels){
  17959. ++S.in_function;
  17960. S.in_directives = true;
  17961. S.in_loop = 0;
  17962. S.labels = [];
  17963. var a = block_();
  17964. --S.in_function;
  17965. S.in_loop = loop;
  17966. S.labels = labels;
  17967. return a;
  17968. })(S.in_loop, S.labels)
  17969. });
  17970. };
  17971. function if_() {
  17972. var cond = parenthesised(), body = statement(), belse = null;
  17973. if (is("keyword", "else")) {
  17974. next();
  17975. belse = statement();
  17976. }
  17977. return new AST_If({
  17978. condition : cond,
  17979. body : body,
  17980. alternative : belse
  17981. });
  17982. };
  17983. function block_() {
  17984. expect("{");
  17985. var a = [];
  17986. while (!is("punc", "}")) {
  17987. if (is("eof")) unexpected();
  17988. a.push(statement());
  17989. }
  17990. next();
  17991. return a;
  17992. };
  17993. function switch_body_() {
  17994. expect("{");
  17995. var a = [], cur = null, branch = null, tmp;
  17996. while (!is("punc", "}")) {
  17997. if (is("eof")) unexpected();
  17998. if (is("keyword", "case")) {
  17999. if (branch) branch.end = prev();
  18000. cur = [];
  18001. branch = new AST_Case({
  18002. start : (tmp = S.token, next(), tmp),
  18003. expression : expression(true),
  18004. body : cur
  18005. });
  18006. a.push(branch);
  18007. expect(":");
  18008. }
  18009. else if (is("keyword", "default")) {
  18010. if (branch) branch.end = prev();
  18011. cur = [];
  18012. branch = new AST_Default({
  18013. start : (tmp = S.token, next(), expect(":"), tmp),
  18014. body : cur
  18015. });
  18016. a.push(branch);
  18017. }
  18018. else {
  18019. if (!cur) unexpected();
  18020. cur.push(statement());
  18021. }
  18022. }
  18023. if (branch) branch.end = prev();
  18024. next();
  18025. return a;
  18026. };
  18027. function try_() {
  18028. var body = block_(), bcatch = null, bfinally = null;
  18029. if (is("keyword", "catch")) {
  18030. var start = S.token;
  18031. next();
  18032. expect("(");
  18033. var name = as_symbol(AST_SymbolCatch);
  18034. expect(")");
  18035. bcatch = new AST_Catch({
  18036. start : start,
  18037. argname : name,
  18038. body : block_(),
  18039. end : prev()
  18040. });
  18041. }
  18042. if (is("keyword", "finally")) {
  18043. var start = S.token;
  18044. next();
  18045. bfinally = new AST_Finally({
  18046. start : start,
  18047. body : block_(),
  18048. end : prev()
  18049. });
  18050. }
  18051. if (!bcatch && !bfinally)
  18052. croak("Missing catch/finally blocks");
  18053. return new AST_Try({
  18054. body : body,
  18055. bcatch : bcatch,
  18056. bfinally : bfinally
  18057. });
  18058. };
  18059. function vardefs(no_in, in_const) {
  18060. var a = [];
  18061. for (;;) {
  18062. a.push(new AST_VarDef({
  18063. start : S.token,
  18064. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  18065. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  18066. end : prev()
  18067. }));
  18068. if (!is("punc", ","))
  18069. break;
  18070. next();
  18071. }
  18072. return a;
  18073. };
  18074. var var_ = function(no_in) {
  18075. return new AST_Var({
  18076. start : prev(),
  18077. definitions : vardefs(no_in, false),
  18078. end : prev()
  18079. });
  18080. };
  18081. var const_ = function() {
  18082. return new AST_Const({
  18083. start : prev(),
  18084. definitions : vardefs(false, true),
  18085. end : prev()
  18086. });
  18087. };
  18088. var new_ = function(allow_calls) {
  18089. var start = S.token;
  18090. expect_token("operator", "new");
  18091. var newexp = expr_atom(false), args;
  18092. if (is("punc", "(")) {
  18093. next();
  18094. args = expr_list(")");
  18095. } else {
  18096. args = [];
  18097. }
  18098. return subscripts(new AST_New({
  18099. start : start,
  18100. expression : newexp,
  18101. args : args,
  18102. end : prev()
  18103. }), allow_calls);
  18104. };
  18105. function as_atom_node() {
  18106. var tok = S.token, ret;
  18107. switch (tok.type) {
  18108. case "name":
  18109. case "keyword":
  18110. ret = _make_symbol(AST_SymbolRef);
  18111. break;
  18112. case "num":
  18113. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  18114. break;
  18115. case "string":
  18116. ret = new AST_String({
  18117. start : tok,
  18118. end : tok,
  18119. value : tok.value,
  18120. quote : tok.quote
  18121. });
  18122. break;
  18123. case "regexp":
  18124. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  18125. break;
  18126. case "atom":
  18127. switch (tok.value) {
  18128. case "false":
  18129. ret = new AST_False({ start: tok, end: tok });
  18130. break;
  18131. case "true":
  18132. ret = new AST_True({ start: tok, end: tok });
  18133. break;
  18134. case "null":
  18135. ret = new AST_Null({ start: tok, end: tok });
  18136. break;
  18137. }
  18138. break;
  18139. }
  18140. next();
  18141. return ret;
  18142. };
  18143. var expr_atom = function(allow_calls) {
  18144. if (is("operator", "new")) {
  18145. return new_(allow_calls);
  18146. }
  18147. var start = S.token;
  18148. if (is("punc")) {
  18149. switch (start.value) {
  18150. case "(":
  18151. next();
  18152. var ex = expression(true);
  18153. ex.start = start;
  18154. ex.end = S.token;
  18155. expect(")");
  18156. return subscripts(ex, allow_calls);
  18157. case "[":
  18158. return subscripts(array_(), allow_calls);
  18159. case "{":
  18160. return subscripts(object_(), allow_calls);
  18161. }
  18162. unexpected();
  18163. }
  18164. if (is("keyword", "function")) {
  18165. next();
  18166. var func = function_(AST_Function);
  18167. func.start = start;
  18168. func.end = prev();
  18169. return subscripts(func, allow_calls);
  18170. }
  18171. if (ATOMIC_START_TOKEN[S.token.type]) {
  18172. return subscripts(as_atom_node(), allow_calls);
  18173. }
  18174. unexpected();
  18175. };
  18176. function expr_list(closing, allow_trailing_comma, allow_empty) {
  18177. var first = true, a = [];
  18178. while (!is("punc", closing)) {
  18179. if (first) first = false; else expect(",");
  18180. if (allow_trailing_comma && is("punc", closing)) break;
  18181. if (is("punc", ",") && allow_empty) {
  18182. a.push(new AST_Hole({ start: S.token, end: S.token }));
  18183. } else {
  18184. a.push(expression(false));
  18185. }
  18186. }
  18187. next();
  18188. return a;
  18189. };
  18190. var array_ = embed_tokens(function() {
  18191. expect("[");
  18192. return new AST_Array({
  18193. elements: expr_list("]", !options.strict, true)
  18194. });
  18195. });
  18196. var object_ = embed_tokens(function() {
  18197. expect("{");
  18198. var first = true, a = [];
  18199. while (!is("punc", "}")) {
  18200. if (first) first = false; else expect(",");
  18201. if (!options.strict && is("punc", "}"))
  18202. // allow trailing comma
  18203. break;
  18204. var start = S.token;
  18205. var type = start.type;
  18206. var name = as_property_name();
  18207. if (type == "name" && !is("punc", ":")) {
  18208. if (name == "get") {
  18209. a.push(new AST_ObjectGetter({
  18210. start : start,
  18211. key : as_atom_node(),
  18212. value : function_(AST_Accessor),
  18213. end : prev()
  18214. }));
  18215. continue;
  18216. }
  18217. if (name == "set") {
  18218. a.push(new AST_ObjectSetter({
  18219. start : start,
  18220. key : as_atom_node(),
  18221. value : function_(AST_Accessor),
  18222. end : prev()
  18223. }));
  18224. continue;
  18225. }
  18226. }
  18227. expect(":");
  18228. a.push(new AST_ObjectKeyVal({
  18229. start : start,
  18230. quote : start.quote,
  18231. key : name,
  18232. value : expression(false),
  18233. end : prev()
  18234. }));
  18235. }
  18236. next();
  18237. return new AST_Object({ properties: a });
  18238. });
  18239. function as_property_name() {
  18240. var tmp = S.token;
  18241. next();
  18242. switch (tmp.type) {
  18243. case "num":
  18244. case "string":
  18245. case "name":
  18246. case "operator":
  18247. case "keyword":
  18248. case "atom":
  18249. return tmp.value;
  18250. default:
  18251. unexpected();
  18252. }
  18253. };
  18254. function as_name() {
  18255. var tmp = S.token;
  18256. next();
  18257. switch (tmp.type) {
  18258. case "name":
  18259. case "operator":
  18260. case "keyword":
  18261. case "atom":
  18262. return tmp.value;
  18263. default:
  18264. unexpected();
  18265. }
  18266. };
  18267. function _make_symbol(type) {
  18268. var name = S.token.value;
  18269. return new (name == "this" ? AST_This : type)({
  18270. name : String(name),
  18271. start : S.token,
  18272. end : S.token
  18273. });
  18274. };
  18275. function as_symbol(type, noerror) {
  18276. if (!is("name")) {
  18277. if (!noerror) croak("Name expected");
  18278. return null;
  18279. }
  18280. var sym = _make_symbol(type);
  18281. next();
  18282. return sym;
  18283. };
  18284. var subscripts = function(expr, allow_calls) {
  18285. var start = expr.start;
  18286. if (is("punc", ".")) {
  18287. next();
  18288. return subscripts(new AST_Dot({
  18289. start : start,
  18290. expression : expr,
  18291. property : as_name(),
  18292. end : prev()
  18293. }), allow_calls);
  18294. }
  18295. if (is("punc", "[")) {
  18296. next();
  18297. var prop = expression(true);
  18298. expect("]");
  18299. return subscripts(new AST_Sub({
  18300. start : start,
  18301. expression : expr,
  18302. property : prop,
  18303. end : prev()
  18304. }), allow_calls);
  18305. }
  18306. if (allow_calls && is("punc", "(")) {
  18307. next();
  18308. return subscripts(new AST_Call({
  18309. start : start,
  18310. expression : expr,
  18311. args : expr_list(")"),
  18312. end : prev()
  18313. }), true);
  18314. }
  18315. return expr;
  18316. };
  18317. var maybe_unary = function(allow_calls) {
  18318. var start = S.token;
  18319. if (is("operator") && UNARY_PREFIX(start.value)) {
  18320. next();
  18321. handle_regexp();
  18322. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  18323. ex.start = start;
  18324. ex.end = prev();
  18325. return ex;
  18326. }
  18327. var val = expr_atom(allow_calls);
  18328. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  18329. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  18330. val.start = start;
  18331. val.end = S.token;
  18332. next();
  18333. }
  18334. return val;
  18335. };
  18336. function make_unary(ctor, op, expr) {
  18337. if ((op == "++" || op == "--") && !is_assignable(expr))
  18338. croak("Invalid use of " + op + " operator");
  18339. return new ctor({ operator: op, expression: expr });
  18340. };
  18341. var expr_op = function(left, min_prec, no_in) {
  18342. var op = is("operator") ? S.token.value : null;
  18343. if (op == "in" && no_in) op = null;
  18344. var prec = op != null ? PRECEDENCE[op] : null;
  18345. if (prec != null && prec > min_prec) {
  18346. next();
  18347. var right = expr_op(maybe_unary(true), prec, no_in);
  18348. return expr_op(new AST_Binary({
  18349. start : left.start,
  18350. left : left,
  18351. operator : op,
  18352. right : right,
  18353. end : right.end
  18354. }), min_prec, no_in);
  18355. }
  18356. return left;
  18357. };
  18358. function expr_ops(no_in) {
  18359. return expr_op(maybe_unary(true), 0, no_in);
  18360. };
  18361. var maybe_conditional = function(no_in) {
  18362. var start = S.token;
  18363. var expr = expr_ops(no_in);
  18364. if (is("operator", "?")) {
  18365. next();
  18366. var yes = expression(false);
  18367. expect(":");
  18368. return new AST_Conditional({
  18369. start : start,
  18370. condition : expr,
  18371. consequent : yes,
  18372. alternative : expression(false, no_in),
  18373. end : prev()
  18374. });
  18375. }
  18376. return expr;
  18377. };
  18378. function is_assignable(expr) {
  18379. if (!options.strict) return true;
  18380. if (expr instanceof AST_This) return false;
  18381. return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
  18382. };
  18383. var maybe_assign = function(no_in) {
  18384. var start = S.token;
  18385. var left = maybe_conditional(no_in), val = S.token.value;
  18386. if (is("operator") && ASSIGNMENT(val)) {
  18387. if (is_assignable(left)) {
  18388. next();
  18389. return new AST_Assign({
  18390. start : start,
  18391. left : left,
  18392. operator : val,
  18393. right : maybe_assign(no_in),
  18394. end : prev()
  18395. });
  18396. }
  18397. croak("Invalid assignment");
  18398. }
  18399. return left;
  18400. };
  18401. var expression = function(commas, no_in) {
  18402. var start = S.token;
  18403. var expr = maybe_assign(no_in);
  18404. if (commas && is("punc", ",")) {
  18405. next();
  18406. return new AST_Seq({
  18407. start : start,
  18408. car : expr,
  18409. cdr : expression(true, no_in),
  18410. end : peek()
  18411. });
  18412. }
  18413. return expr;
  18414. };
  18415. function in_loop(cont) {
  18416. ++S.in_loop;
  18417. var ret = cont();
  18418. --S.in_loop;
  18419. return ret;
  18420. };
  18421. if (options.expression) {
  18422. return expression(true);
  18423. }
  18424. return (function(){
  18425. var start = S.token;
  18426. var body = [];
  18427. while (!is("eof"))
  18428. body.push(statement());
  18429. var end = prev();
  18430. var toplevel = options.toplevel;
  18431. if (toplevel) {
  18432. toplevel.body = toplevel.body.concat(body);
  18433. toplevel.end = end;
  18434. } else {
  18435. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  18436. }
  18437. return toplevel;
  18438. })();
  18439. };
  18440. /***********************************************************************
  18441. A JavaScript tokenizer / parser / beautifier / compressor.
  18442. https://github.com/mishoo/UglifyJS2
  18443. -------------------------------- (C) ---------------------------------
  18444. Author: Mihai Bazon
  18445. <mihai.bazon@gmail.com>
  18446. http://mihai.bazon.net/blog
  18447. Distributed under the BSD license:
  18448. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  18449. Redistribution and use in source and binary forms, with or without
  18450. modification, are permitted provided that the following conditions
  18451. are met:
  18452. * Redistributions of source code must retain the above
  18453. copyright notice, this list of conditions and the following
  18454. disclaimer.
  18455. * Redistributions in binary form must reproduce the above
  18456. copyright notice, this list of conditions and the following
  18457. disclaimer in the documentation and/or other materials
  18458. provided with the distribution.
  18459. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  18460. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18461. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18462. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  18463. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  18464. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18465. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18466. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  18467. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  18468. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  18469. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  18470. SUCH DAMAGE.
  18471. ***********************************************************************/
  18472. "use strict";
  18473. // Tree transformer helpers.
  18474. function TreeTransformer(before, after) {
  18475. TreeWalker.call(this);
  18476. this.before = before;
  18477. this.after = after;
  18478. }
  18479. TreeTransformer.prototype = new TreeWalker;
  18480. (function(undefined){
  18481. function _(node, descend) {
  18482. node.DEFMETHOD("transform", function(tw, in_list){
  18483. var x, y;
  18484. tw.push(this);
  18485. if (tw.before) x = tw.before(this, descend, in_list);
  18486. if (x === undefined) {
  18487. if (!tw.after) {
  18488. x = this;
  18489. descend(x, tw);
  18490. } else {
  18491. tw.stack[tw.stack.length - 1] = x = this.clone();
  18492. descend(x, tw);
  18493. y = tw.after(x, in_list);
  18494. if (y !== undefined) x = y;
  18495. }
  18496. }
  18497. tw.pop(this);
  18498. return x;
  18499. });
  18500. };
  18501. function do_list(list, tw) {
  18502. return MAP(list, function(node){
  18503. return node.transform(tw, true);
  18504. });
  18505. };
  18506. _(AST_Node, noop);
  18507. _(AST_LabeledStatement, function(self, tw){
  18508. self.label = self.label.transform(tw);
  18509. self.body = self.body.transform(tw);
  18510. });
  18511. _(AST_SimpleStatement, function(self, tw){
  18512. self.body = self.body.transform(tw);
  18513. });
  18514. _(AST_Block, function(self, tw){
  18515. self.body = do_list(self.body, tw);
  18516. });
  18517. _(AST_DWLoop, function(self, tw){
  18518. self.condition = self.condition.transform(tw);
  18519. self.body = self.body.transform(tw);
  18520. });
  18521. _(AST_For, function(self, tw){
  18522. if (self.init) self.init = self.init.transform(tw);
  18523. if (self.condition) self.condition = self.condition.transform(tw);
  18524. if (self.step) self.step = self.step.transform(tw);
  18525. self.body = self.body.transform(tw);
  18526. });
  18527. _(AST_ForIn, function(self, tw){
  18528. self.init = self.init.transform(tw);
  18529. self.object = self.object.transform(tw);
  18530. self.body = self.body.transform(tw);
  18531. });
  18532. _(AST_With, function(self, tw){
  18533. self.expression = self.expression.transform(tw);
  18534. self.body = self.body.transform(tw);
  18535. });
  18536. _(AST_Exit, function(self, tw){
  18537. if (self.value) self.value = self.value.transform(tw);
  18538. });
  18539. _(AST_LoopControl, function(self, tw){
  18540. if (self.label) self.label = self.label.transform(tw);
  18541. });
  18542. _(AST_If, function(self, tw){
  18543. self.condition = self.condition.transform(tw);
  18544. self.body = self.body.transform(tw);
  18545. if (self.alternative) self.alternative = self.alternative.transform(tw);
  18546. });
  18547. _(AST_Switch, function(self, tw){
  18548. self.expression = self.expression.transform(tw);
  18549. self.body = do_list(self.body, tw);
  18550. });
  18551. _(AST_Case, function(self, tw){
  18552. self.expression = self.expression.transform(tw);
  18553. self.body = do_list(self.body, tw);
  18554. });
  18555. _(AST_Try, function(self, tw){
  18556. self.body = do_list(self.body, tw);
  18557. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  18558. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  18559. });
  18560. _(AST_Catch, function(self, tw){
  18561. self.argname = self.argname.transform(tw);
  18562. self.body = do_list(self.body, tw);
  18563. });
  18564. _(AST_Definitions, function(self, tw){
  18565. self.definitions = do_list(self.definitions, tw);
  18566. });
  18567. _(AST_VarDef, function(self, tw){
  18568. self.name = self.name.transform(tw);
  18569. if (self.value) self.value = self.value.transform(tw);
  18570. });
  18571. _(AST_Lambda, function(self, tw){
  18572. if (self.name) self.name = self.name.transform(tw);
  18573. self.argnames = do_list(self.argnames, tw);
  18574. self.body = do_list(self.body, tw);
  18575. });
  18576. _(AST_Call, function(self, tw){
  18577. self.expression = self.expression.transform(tw);
  18578. self.args = do_list(self.args, tw);
  18579. });
  18580. _(AST_Seq, function(self, tw){
  18581. self.car = self.car.transform(tw);
  18582. self.cdr = self.cdr.transform(tw);
  18583. });
  18584. _(AST_Dot, function(self, tw){
  18585. self.expression = self.expression.transform(tw);
  18586. });
  18587. _(AST_Sub, function(self, tw){
  18588. self.expression = self.expression.transform(tw);
  18589. self.property = self.property.transform(tw);
  18590. });
  18591. _(AST_Unary, function(self, tw){
  18592. self.expression = self.expression.transform(tw);
  18593. });
  18594. _(AST_Binary, function(self, tw){
  18595. self.left = self.left.transform(tw);
  18596. self.right = self.right.transform(tw);
  18597. });
  18598. _(AST_Conditional, function(self, tw){
  18599. self.condition = self.condition.transform(tw);
  18600. self.consequent = self.consequent.transform(tw);
  18601. self.alternative = self.alternative.transform(tw);
  18602. });
  18603. _(AST_Array, function(self, tw){
  18604. self.elements = do_list(self.elements, tw);
  18605. });
  18606. _(AST_Object, function(self, tw){
  18607. self.properties = do_list(self.properties, tw);
  18608. });
  18609. _(AST_ObjectProperty, function(self, tw){
  18610. self.value = self.value.transform(tw);
  18611. });
  18612. })();
  18613. /***********************************************************************
  18614. A JavaScript tokenizer / parser / beautifier / compressor.
  18615. https://github.com/mishoo/UglifyJS2
  18616. -------------------------------- (C) ---------------------------------
  18617. Author: Mihai Bazon
  18618. <mihai.bazon@gmail.com>
  18619. http://mihai.bazon.net/blog
  18620. Distributed under the BSD license:
  18621. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  18622. Redistribution and use in source and binary forms, with or without
  18623. modification, are permitted provided that the following conditions
  18624. are met:
  18625. * Redistributions of source code must retain the above
  18626. copyright notice, this list of conditions and the following
  18627. disclaimer.
  18628. * Redistributions in binary form must reproduce the above
  18629. copyright notice, this list of conditions and the following
  18630. disclaimer in the documentation and/or other materials
  18631. provided with the distribution.
  18632. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  18633. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18634. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18635. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  18636. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  18637. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18638. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18639. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  18640. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  18641. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  18642. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  18643. SUCH DAMAGE.
  18644. ***********************************************************************/
  18645. "use strict";
  18646. function SymbolDef(scope, index, orig) {
  18647. this.name = orig.name;
  18648. this.orig = [ orig ];
  18649. this.scope = scope;
  18650. this.references = [];
  18651. this.global = false;
  18652. this.mangled_name = null;
  18653. this.undeclared = false;
  18654. this.constant = false;
  18655. this.index = index;
  18656. };
  18657. SymbolDef.prototype = {
  18658. unmangleable: function(options) {
  18659. if (!options) options = {};
  18660. return (this.global && !options.toplevel)
  18661. || this.undeclared
  18662. || (!options.eval && (this.scope.uses_eval || this.scope.uses_with))
  18663. || (options.keep_fnames
  18664. && (this.orig[0] instanceof AST_SymbolLambda
  18665. || this.orig[0] instanceof AST_SymbolDefun));
  18666. },
  18667. mangle: function(options) {
  18668. var cache = options.cache && options.cache.props;
  18669. if (this.global && cache && cache.has(this.name)) {
  18670. this.mangled_name = cache.get(this.name);
  18671. }
  18672. else if (!this.mangled_name && !this.unmangleable(options)) {
  18673. var s = this.scope;
  18674. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  18675. s = s.parent_scope;
  18676. this.mangled_name = s.next_mangled(options, this);
  18677. if (this.global && cache) {
  18678. cache.set(this.name, this.mangled_name);
  18679. }
  18680. }
  18681. }
  18682. };
  18683. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  18684. options = defaults(options, {
  18685. screw_ie8: false,
  18686. cache: null
  18687. });
  18688. // pass 1: setup scope chaining and handle definitions
  18689. var self = this;
  18690. var scope = self.parent_scope = null;
  18691. var labels = new Dictionary();
  18692. var defun = null;
  18693. var nesting = 0;
  18694. var tw = new TreeWalker(function(node, descend){
  18695. if (options.screw_ie8 && node instanceof AST_Catch) {
  18696. var save_scope = scope;
  18697. scope = new AST_Scope(node);
  18698. scope.init_scope_vars(nesting);
  18699. scope.parent_scope = save_scope;
  18700. descend();
  18701. scope = save_scope;
  18702. return true;
  18703. }
  18704. if (node instanceof AST_Scope) {
  18705. node.init_scope_vars(nesting);
  18706. var save_scope = node.parent_scope = scope;
  18707. var save_defun = defun;
  18708. var save_labels = labels;
  18709. defun = scope = node;
  18710. labels = new Dictionary();
  18711. ++nesting; descend(); --nesting;
  18712. scope = save_scope;
  18713. defun = save_defun;
  18714. labels = save_labels;
  18715. return true; // don't descend again in TreeWalker
  18716. }
  18717. if (node instanceof AST_LabeledStatement) {
  18718. var l = node.label;
  18719. if (labels.has(l.name)) {
  18720. throw new Error(string_template("Label {name} defined twice", l));
  18721. }
  18722. labels.set(l.name, l);
  18723. descend();
  18724. labels.del(l.name);
  18725. return true; // no descend again
  18726. }
  18727. if (node instanceof AST_With) {
  18728. for (var s = scope; s; s = s.parent_scope)
  18729. s.uses_with = true;
  18730. return;
  18731. }
  18732. if (node instanceof AST_Symbol) {
  18733. node.scope = scope;
  18734. }
  18735. if (node instanceof AST_Label) {
  18736. node.thedef = node;
  18737. node.references = [];
  18738. }
  18739. if (node instanceof AST_SymbolLambda) {
  18740. defun.def_function(node);
  18741. }
  18742. else if (node instanceof AST_SymbolDefun) {
  18743. // Careful here, the scope where this should be defined is
  18744. // the parent scope. The reason is that we enter a new
  18745. // scope when we encounter the AST_Defun node (which is
  18746. // instanceof AST_Scope) but we get to the symbol a bit
  18747. // later.
  18748. (node.scope = defun.parent_scope).def_function(node);
  18749. }
  18750. else if (node instanceof AST_SymbolVar
  18751. || node instanceof AST_SymbolConst) {
  18752. var def = defun.def_variable(node);
  18753. def.constant = node instanceof AST_SymbolConst;
  18754. def.init = tw.parent().value;
  18755. }
  18756. else if (node instanceof AST_SymbolCatch) {
  18757. (options.screw_ie8 ? scope : defun)
  18758. .def_variable(node);
  18759. }
  18760. else if (node instanceof AST_LabelRef) {
  18761. var sym = labels.get(node.name);
  18762. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  18763. name: node.name,
  18764. line: node.start.line,
  18765. col: node.start.col
  18766. }));
  18767. node.thedef = sym;
  18768. }
  18769. });
  18770. self.walk(tw);
  18771. // pass 2: find back references and eval
  18772. var func = null;
  18773. var globals = self.globals = new Dictionary();
  18774. var tw = new TreeWalker(function(node, descend){
  18775. if (node instanceof AST_Lambda) {
  18776. var prev_func = func;
  18777. func = node;
  18778. descend();
  18779. func = prev_func;
  18780. return true;
  18781. }
  18782. if (node instanceof AST_LoopControl && node.label) {
  18783. node.label.thedef.references.push(node);
  18784. return true;
  18785. }
  18786. if (node instanceof AST_SymbolRef) {
  18787. var name = node.name;
  18788. var sym = node.scope.find_variable(name);
  18789. if (!sym) {
  18790. var g;
  18791. if (globals.has(name)) {
  18792. g = globals.get(name);
  18793. } else {
  18794. g = new SymbolDef(self, globals.size(), node);
  18795. g.undeclared = true;
  18796. g.global = true;
  18797. globals.set(name, g);
  18798. }
  18799. node.thedef = g;
  18800. if (name == "eval" && tw.parent() instanceof AST_Call) {
  18801. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
  18802. s.uses_eval = true;
  18803. }
  18804. if (func && name == "arguments") {
  18805. func.uses_arguments = true;
  18806. }
  18807. } else {
  18808. node.thedef = sym;
  18809. }
  18810. node.reference();
  18811. return true;
  18812. }
  18813. });
  18814. self.walk(tw);
  18815. if (options.cache) {
  18816. this.cname = options.cache.cname;
  18817. }
  18818. });
  18819. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  18820. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  18821. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  18822. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  18823. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  18824. this.parent_scope = null; // the parent scope
  18825. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  18826. this.cname = -1; // the current index for mangling functions/variables
  18827. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  18828. });
  18829. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  18830. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  18831. this.uses_arguments = false;
  18832. });
  18833. AST_SymbolRef.DEFMETHOD("reference", function() {
  18834. var def = this.definition();
  18835. def.references.push(this);
  18836. var s = this.scope;
  18837. while (s) {
  18838. push_uniq(s.enclosed, def);
  18839. if (s === def.scope) break;
  18840. s = s.parent_scope;
  18841. }
  18842. this.frame = this.scope.nesting - def.scope.nesting;
  18843. });
  18844. AST_Scope.DEFMETHOD("find_variable", function(name){
  18845. if (name instanceof AST_Symbol) name = name.name;
  18846. return this.variables.get(name)
  18847. || (this.parent_scope && this.parent_scope.find_variable(name));
  18848. });
  18849. AST_Scope.DEFMETHOD("def_function", function(symbol){
  18850. this.functions.set(symbol.name, this.def_variable(symbol));
  18851. });
  18852. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  18853. var def;
  18854. if (!this.variables.has(symbol.name)) {
  18855. def = new SymbolDef(this, this.variables.size(), symbol);
  18856. this.variables.set(symbol.name, def);
  18857. def.global = !this.parent_scope;
  18858. } else {
  18859. def = this.variables.get(symbol.name);
  18860. def.orig.push(symbol);
  18861. }
  18862. return symbol.thedef = def;
  18863. });
  18864. AST_Scope.DEFMETHOD("next_mangled", function(options){
  18865. var ext = this.enclosed;
  18866. out: while (true) {
  18867. var m = base54(++this.cname);
  18868. if (!is_identifier(m)) continue; // skip over "do"
  18869. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  18870. // shadow a name excepted from mangling.
  18871. if (options.except.indexOf(m) >= 0) continue;
  18872. // we must ensure that the mangled name does not shadow a name
  18873. // from some parent scope that is referenced in this or in
  18874. // inner scopes.
  18875. for (var i = ext.length; --i >= 0;) {
  18876. var sym = ext[i];
  18877. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  18878. if (m == name) continue out;
  18879. }
  18880. return m;
  18881. }
  18882. });
  18883. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  18884. // #179, #326
  18885. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  18886. // a function expression's argument cannot shadow the function expression's name
  18887. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  18888. while (true) {
  18889. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  18890. if (!(tricky_def && tricky_def.mangled_name == name))
  18891. return name;
  18892. }
  18893. });
  18894. AST_Scope.DEFMETHOD("references", function(sym){
  18895. if (sym instanceof AST_Symbol) sym = sym.definition();
  18896. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  18897. });
  18898. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  18899. return this.definition().unmangleable(options);
  18900. });
  18901. // property accessors are not mangleable
  18902. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  18903. return true;
  18904. });
  18905. // labels are always mangleable
  18906. AST_Label.DEFMETHOD("unmangleable", function(){
  18907. return false;
  18908. });
  18909. AST_Symbol.DEFMETHOD("unreferenced", function(){
  18910. return this.definition().references.length == 0
  18911. && !(this.scope.uses_eval || this.scope.uses_with);
  18912. });
  18913. AST_Symbol.DEFMETHOD("undeclared", function(){
  18914. return this.definition().undeclared;
  18915. });
  18916. AST_LabelRef.DEFMETHOD("undeclared", function(){
  18917. return false;
  18918. });
  18919. AST_Label.DEFMETHOD("undeclared", function(){
  18920. return false;
  18921. });
  18922. AST_Symbol.DEFMETHOD("definition", function(){
  18923. return this.thedef;
  18924. });
  18925. AST_Symbol.DEFMETHOD("global", function(){
  18926. return this.definition().global;
  18927. });
  18928. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  18929. return defaults(options, {
  18930. except : [],
  18931. eval : false,
  18932. sort : false,
  18933. toplevel : false,
  18934. screw_ie8 : false,
  18935. keep_fnames : false
  18936. });
  18937. });
  18938. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  18939. options = this._default_mangler_options(options);
  18940. // We only need to mangle declaration nodes. Special logic wired
  18941. // into the code generator will display the mangled name if it's
  18942. // present (and for AST_SymbolRef-s it'll use the mangled name of
  18943. // the AST_SymbolDeclaration that it points to).
  18944. var lname = -1;
  18945. var to_mangle = [];
  18946. if (options.cache) {
  18947. this.globals.each(function(symbol){
  18948. if (options.except.indexOf(symbol.name) < 0) {
  18949. to_mangle.push(symbol);
  18950. }
  18951. });
  18952. }
  18953. var tw = new TreeWalker(function(node, descend){
  18954. if (node instanceof AST_LabeledStatement) {
  18955. // lname is incremented when we get to the AST_Label
  18956. var save_nesting = lname;
  18957. descend();
  18958. lname = save_nesting;
  18959. return true; // don't descend again in TreeWalker
  18960. }
  18961. if (node instanceof AST_Scope) {
  18962. var p = tw.parent(), a = [];
  18963. node.variables.each(function(symbol){
  18964. if (options.except.indexOf(symbol.name) < 0) {
  18965. a.push(symbol);
  18966. }
  18967. });
  18968. if (options.sort) a.sort(function(a, b){
  18969. return b.references.length - a.references.length;
  18970. });
  18971. to_mangle.push.apply(to_mangle, a);
  18972. return;
  18973. }
  18974. if (node instanceof AST_Label) {
  18975. var name;
  18976. do name = base54(++lname); while (!is_identifier(name));
  18977. node.mangled_name = name;
  18978. return true;
  18979. }
  18980. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  18981. to_mangle.push(node.definition());
  18982. return;
  18983. }
  18984. });
  18985. this.walk(tw);
  18986. to_mangle.forEach(function(def){ def.mangle(options) });
  18987. if (options.cache) {
  18988. options.cache.cname = this.cname;
  18989. }
  18990. });
  18991. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  18992. options = this._default_mangler_options(options);
  18993. var tw = new TreeWalker(function(node){
  18994. if (node instanceof AST_Constant)
  18995. base54.consider(node.print_to_string());
  18996. else if (node instanceof AST_Return)
  18997. base54.consider("return");
  18998. else if (node instanceof AST_Throw)
  18999. base54.consider("throw");
  19000. else if (node instanceof AST_Continue)
  19001. base54.consider("continue");
  19002. else if (node instanceof AST_Break)
  19003. base54.consider("break");
  19004. else if (node instanceof AST_Debugger)
  19005. base54.consider("debugger");
  19006. else if (node instanceof AST_Directive)
  19007. base54.consider(node.value);
  19008. else if (node instanceof AST_While)
  19009. base54.consider("while");
  19010. else if (node instanceof AST_Do)
  19011. base54.consider("do while");
  19012. else if (node instanceof AST_If) {
  19013. base54.consider("if");
  19014. if (node.alternative) base54.consider("else");
  19015. }
  19016. else if (node instanceof AST_Var)
  19017. base54.consider("var");
  19018. else if (node instanceof AST_Const)
  19019. base54.consider("const");
  19020. else if (node instanceof AST_Lambda)
  19021. base54.consider("function");
  19022. else if (node instanceof AST_For)
  19023. base54.consider("for");
  19024. else if (node instanceof AST_ForIn)
  19025. base54.consider("for in");
  19026. else if (node instanceof AST_Switch)
  19027. base54.consider("switch");
  19028. else if (node instanceof AST_Case)
  19029. base54.consider("case");
  19030. else if (node instanceof AST_Default)
  19031. base54.consider("default");
  19032. else if (node instanceof AST_With)
  19033. base54.consider("with");
  19034. else if (node instanceof AST_ObjectSetter)
  19035. base54.consider("set" + node.key);
  19036. else if (node instanceof AST_ObjectGetter)
  19037. base54.consider("get" + node.key);
  19038. else if (node instanceof AST_ObjectKeyVal)
  19039. base54.consider(node.key);
  19040. else if (node instanceof AST_New)
  19041. base54.consider("new");
  19042. else if (node instanceof AST_This)
  19043. base54.consider("this");
  19044. else if (node instanceof AST_Try)
  19045. base54.consider("try");
  19046. else if (node instanceof AST_Catch)
  19047. base54.consider("catch");
  19048. else if (node instanceof AST_Finally)
  19049. base54.consider("finally");
  19050. else if (node instanceof AST_Symbol && node.unmangleable(options))
  19051. base54.consider(node.name);
  19052. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  19053. base54.consider(node.operator);
  19054. else if (node instanceof AST_Dot)
  19055. base54.consider(node.property);
  19056. });
  19057. this.walk(tw);
  19058. base54.sort();
  19059. });
  19060. var base54 = (function() {
  19061. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  19062. var chars, frequency;
  19063. function reset() {
  19064. frequency = Object.create(null);
  19065. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  19066. chars.forEach(function(ch){ frequency[ch] = 0 });
  19067. }
  19068. base54.consider = function(str){
  19069. for (var i = str.length; --i >= 0;) {
  19070. var code = str.charCodeAt(i);
  19071. if (code in frequency) ++frequency[code];
  19072. }
  19073. };
  19074. base54.sort = function() {
  19075. chars = mergeSort(chars, function(a, b){
  19076. if (is_digit(a) && !is_digit(b)) return 1;
  19077. if (is_digit(b) && !is_digit(a)) return -1;
  19078. return frequency[b] - frequency[a];
  19079. });
  19080. };
  19081. base54.reset = reset;
  19082. reset();
  19083. base54.get = function(){ return chars };
  19084. base54.freq = function(){ return frequency };
  19085. function base54(num) {
  19086. var ret = "", base = 54;
  19087. num++;
  19088. do {
  19089. num--;
  19090. ret += String.fromCharCode(chars[num % base]);
  19091. num = Math.floor(num / base);
  19092. base = 64;
  19093. } while (num > 0);
  19094. return ret;
  19095. };
  19096. return base54;
  19097. })();
  19098. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  19099. options = defaults(options, {
  19100. undeclared : false, // this makes a lot of noise
  19101. unreferenced : true,
  19102. assign_to_global : true,
  19103. func_arguments : true,
  19104. nested_defuns : true,
  19105. eval : true
  19106. });
  19107. var tw = new TreeWalker(function(node){
  19108. if (options.undeclared
  19109. && node instanceof AST_SymbolRef
  19110. && node.undeclared())
  19111. {
  19112. // XXX: this also warns about JS standard names,
  19113. // i.e. Object, Array, parseInt etc. Should add a list of
  19114. // exceptions.
  19115. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  19116. name: node.name,
  19117. file: node.start.file,
  19118. line: node.start.line,
  19119. col: node.start.col
  19120. });
  19121. }
  19122. if (options.assign_to_global)
  19123. {
  19124. var sym = null;
  19125. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  19126. sym = node.left;
  19127. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  19128. sym = node.init;
  19129. if (sym
  19130. && (sym.undeclared()
  19131. || (sym.global() && sym.scope !== sym.definition().scope))) {
  19132. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  19133. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  19134. name: sym.name,
  19135. file: sym.start.file,
  19136. line: sym.start.line,
  19137. col: sym.start.col
  19138. });
  19139. }
  19140. }
  19141. if (options.eval
  19142. && node instanceof AST_SymbolRef
  19143. && node.undeclared()
  19144. && node.name == "eval") {
  19145. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  19146. }
  19147. if (options.unreferenced
  19148. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  19149. && !(node instanceof AST_SymbolCatch)
  19150. && node.unreferenced()) {
  19151. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  19152. type: node instanceof AST_Label ? "Label" : "Symbol",
  19153. name: node.name,
  19154. file: node.start.file,
  19155. line: node.start.line,
  19156. col: node.start.col
  19157. });
  19158. }
  19159. if (options.func_arguments
  19160. && node instanceof AST_Lambda
  19161. && node.uses_arguments) {
  19162. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  19163. name: node.name ? node.name.name : "anonymous",
  19164. file: node.start.file,
  19165. line: node.start.line,
  19166. col: node.start.col
  19167. });
  19168. }
  19169. if (options.nested_defuns
  19170. && node instanceof AST_Defun
  19171. && !(tw.parent() instanceof AST_Scope)) {
  19172. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  19173. name: node.name.name,
  19174. type: tw.parent().TYPE,
  19175. file: node.start.file,
  19176. line: node.start.line,
  19177. col: node.start.col
  19178. });
  19179. }
  19180. });
  19181. this.walk(tw);
  19182. });
  19183. /***********************************************************************
  19184. A JavaScript tokenizer / parser / beautifier / compressor.
  19185. https://github.com/mishoo/UglifyJS2
  19186. -------------------------------- (C) ---------------------------------
  19187. Author: Mihai Bazon
  19188. <mihai.bazon@gmail.com>
  19189. http://mihai.bazon.net/blog
  19190. Distributed under the BSD license:
  19191. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  19192. Redistribution and use in source and binary forms, with or without
  19193. modification, are permitted provided that the following conditions
  19194. are met:
  19195. * Redistributions of source code must retain the above
  19196. copyright notice, this list of conditions and the following
  19197. disclaimer.
  19198. * Redistributions in binary form must reproduce the above
  19199. copyright notice, this list of conditions and the following
  19200. disclaimer in the documentation and/or other materials
  19201. provided with the distribution.
  19202. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  19203. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19204. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19205. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  19206. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  19207. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  19208. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19209. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  19210. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  19211. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  19212. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  19213. SUCH DAMAGE.
  19214. ***********************************************************************/
  19215. "use strict";
  19216. function OutputStream(options) {
  19217. options = defaults(options, {
  19218. indent_start : 0,
  19219. indent_level : 4,
  19220. quote_keys : false,
  19221. space_colon : true,
  19222. ascii_only : false,
  19223. unescape_regexps : false,
  19224. inline_script : false,
  19225. width : 80,
  19226. max_line_len : 32000,
  19227. beautify : false,
  19228. source_map : null,
  19229. bracketize : false,
  19230. semicolons : true,
  19231. comments : false,
  19232. shebang : true,
  19233. preserve_line : false,
  19234. screw_ie8 : false,
  19235. preamble : null,
  19236. quote_style : 0
  19237. }, true);
  19238. var indentation = 0;
  19239. var current_col = 0;
  19240. var current_line = 1;
  19241. var current_pos = 0;
  19242. var OUTPUT = "";
  19243. function to_ascii(str, identifier) {
  19244. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  19245. var code = ch.charCodeAt(0).toString(16);
  19246. if (code.length <= 2 && !identifier) {
  19247. while (code.length < 2) code = "0" + code;
  19248. return "\\x" + code;
  19249. } else {
  19250. while (code.length < 4) code = "0" + code;
  19251. return "\\u" + code;
  19252. }
  19253. });
  19254. };
  19255. function make_string(str, quote) {
  19256. var dq = 0, sq = 0;
  19257. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s){
  19258. switch (s) {
  19259. case "\\": return "\\\\";
  19260. case "\b": return "\\b";
  19261. case "\f": return "\\f";
  19262. case "\n": return "\\n";
  19263. case "\r": return "\\r";
  19264. case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B";
  19265. case "\u2028": return "\\u2028";
  19266. case "\u2029": return "\\u2029";
  19267. case '"': ++dq; return '"';
  19268. case "'": ++sq; return "'";
  19269. case "\0": return "\\x00";
  19270. case "\ufeff": return "\\ufeff";
  19271. }
  19272. return s;
  19273. });
  19274. function quote_single() {
  19275. return "'" + str.replace(/\x27/g, "\\'") + "'";
  19276. }
  19277. function quote_double() {
  19278. return '"' + str.replace(/\x22/g, '\\"') + '"';
  19279. }
  19280. if (options.ascii_only) str = to_ascii(str);
  19281. switch (options.quote_style) {
  19282. case 1:
  19283. return quote_single();
  19284. case 2:
  19285. return quote_double();
  19286. case 3:
  19287. return quote == "'" ? quote_single() : quote_double();
  19288. default:
  19289. return dq > sq ? quote_single() : quote_double();
  19290. }
  19291. };
  19292. function encode_string(str, quote) {
  19293. var ret = make_string(str, quote);
  19294. if (options.inline_script) {
  19295. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  19296. ret = ret.replace(/\x3c!--/g, "\\x3c!--");
  19297. ret = ret.replace(/--\x3e/g, "--\\x3e");
  19298. }
  19299. return ret;
  19300. };
  19301. function make_name(name) {
  19302. name = name.toString();
  19303. if (options.ascii_only)
  19304. name = to_ascii(name, true);
  19305. return name;
  19306. };
  19307. function make_indent(back) {
  19308. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  19309. };
  19310. /* -----[ beautification/minification ]----- */
  19311. var might_need_space = false;
  19312. var might_need_semicolon = false;
  19313. var last = null;
  19314. function last_char() {
  19315. return last.charAt(last.length - 1);
  19316. };
  19317. function maybe_newline() {
  19318. if (options.max_line_len && current_col > options.max_line_len)
  19319. print("\n");
  19320. };
  19321. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  19322. function print(str) {
  19323. str = String(str);
  19324. var ch = str.charAt(0);
  19325. if (might_need_semicolon) {
  19326. might_need_semicolon = false;
  19327. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  19328. if (options.semicolons || requireSemicolonChars(ch)) {
  19329. OUTPUT += ";";
  19330. current_col++;
  19331. current_pos++;
  19332. } else {
  19333. OUTPUT += "\n";
  19334. current_pos++;
  19335. current_line++;
  19336. current_col = 0;
  19337. if (/^\s+$/.test(str)) {
  19338. // reset the semicolon flag, since we didn't print one
  19339. // now and might still have to later
  19340. might_need_semicolon = true;
  19341. }
  19342. }
  19343. if (!options.beautify)
  19344. might_need_space = false;
  19345. }
  19346. }
  19347. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  19348. var target_line = stack[stack.length - 1].start.line;
  19349. while (current_line < target_line) {
  19350. OUTPUT += "\n";
  19351. current_pos++;
  19352. current_line++;
  19353. current_col = 0;
  19354. might_need_space = false;
  19355. }
  19356. }
  19357. if (might_need_space) {
  19358. var prev = last_char();
  19359. if ((is_identifier_char(prev)
  19360. && (is_identifier_char(ch) || ch == "\\"))
  19361. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  19362. {
  19363. OUTPUT += " ";
  19364. current_col++;
  19365. current_pos++;
  19366. }
  19367. might_need_space = false;
  19368. }
  19369. var a = str.split(/\r?\n/), n = a.length - 1;
  19370. current_line += n;
  19371. if (n == 0) {
  19372. current_col += a[n].length;
  19373. } else {
  19374. current_col = a[n].length;
  19375. }
  19376. current_pos += str.length;
  19377. last = str;
  19378. OUTPUT += str;
  19379. };
  19380. var space = options.beautify ? function() {
  19381. print(" ");
  19382. } : function() {
  19383. might_need_space = true;
  19384. };
  19385. var indent = options.beautify ? function(half) {
  19386. if (options.beautify) {
  19387. print(make_indent(half ? 0.5 : 0));
  19388. }
  19389. } : noop;
  19390. var with_indent = options.beautify ? function(col, cont) {
  19391. if (col === true) col = next_indent();
  19392. var save_indentation = indentation;
  19393. indentation = col;
  19394. var ret = cont();
  19395. indentation = save_indentation;
  19396. return ret;
  19397. } : function(col, cont) { return cont() };
  19398. var newline = options.beautify ? function() {
  19399. print("\n");
  19400. } : maybe_newline;
  19401. var semicolon = options.beautify ? function() {
  19402. print(";");
  19403. } : function() {
  19404. might_need_semicolon = true;
  19405. };
  19406. function force_semicolon() {
  19407. might_need_semicolon = false;
  19408. print(";");
  19409. };
  19410. function next_indent() {
  19411. return indentation + options.indent_level;
  19412. };
  19413. function with_block(cont) {
  19414. var ret;
  19415. print("{");
  19416. newline();
  19417. with_indent(next_indent(), function(){
  19418. ret = cont();
  19419. });
  19420. indent();
  19421. print("}");
  19422. return ret;
  19423. };
  19424. function with_parens(cont) {
  19425. print("(");
  19426. //XXX: still nice to have that for argument lists
  19427. //var ret = with_indent(current_col, cont);
  19428. var ret = cont();
  19429. print(")");
  19430. return ret;
  19431. };
  19432. function with_square(cont) {
  19433. print("[");
  19434. //var ret = with_indent(current_col, cont);
  19435. var ret = cont();
  19436. print("]");
  19437. return ret;
  19438. };
  19439. function comma() {
  19440. print(",");
  19441. space();
  19442. };
  19443. function colon() {
  19444. print(":");
  19445. if (options.space_colon) space();
  19446. };
  19447. var add_mapping = options.source_map ? function(token, name) {
  19448. try {
  19449. if (token) options.source_map.add(
  19450. token.file || "?",
  19451. current_line, current_col,
  19452. token.line, token.col,
  19453. (!name && token.type == "name") ? token.value : name
  19454. );
  19455. } catch(ex) {
  19456. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  19457. file: token.file,
  19458. line: token.line,
  19459. col: token.col,
  19460. cline: current_line,
  19461. ccol: current_col,
  19462. name: name || ""
  19463. })
  19464. }
  19465. } : noop;
  19466. function get() {
  19467. return OUTPUT;
  19468. };
  19469. if (options.preamble) {
  19470. print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  19471. }
  19472. var stack = [];
  19473. return {
  19474. get : get,
  19475. toString : get,
  19476. indent : indent,
  19477. indentation : function() { return indentation },
  19478. current_width : function() { return current_col - indentation },
  19479. should_break : function() { return options.width && this.current_width() >= options.width },
  19480. newline : newline,
  19481. print : print,
  19482. space : space,
  19483. comma : comma,
  19484. colon : colon,
  19485. last : function() { return last },
  19486. semicolon : semicolon,
  19487. force_semicolon : force_semicolon,
  19488. to_ascii : to_ascii,
  19489. print_name : function(name) { print(make_name(name)) },
  19490. print_string : function(str, quote) { print(encode_string(str, quote)) },
  19491. next_indent : next_indent,
  19492. with_indent : with_indent,
  19493. with_block : with_block,
  19494. with_parens : with_parens,
  19495. with_square : with_square,
  19496. add_mapping : add_mapping,
  19497. option : function(opt) { return options[opt] },
  19498. line : function() { return current_line },
  19499. col : function() { return current_col },
  19500. pos : function() { return current_pos },
  19501. push_node : function(node) { stack.push(node) },
  19502. pop_node : function() { return stack.pop() },
  19503. stack : function() { return stack },
  19504. parent : function(n) {
  19505. return stack[stack.length - 2 - (n || 0)];
  19506. }
  19507. };
  19508. };
  19509. /* -----[ code generators ]----- */
  19510. (function(){
  19511. /* -----[ utils ]----- */
  19512. function DEFPRINT(nodetype, generator) {
  19513. nodetype.DEFMETHOD("_codegen", generator);
  19514. };
  19515. var use_asm = false;
  19516. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  19517. var self = this, generator = self._codegen, prev_use_asm = use_asm;
  19518. if (self instanceof AST_Directive && self.value == "use asm") {
  19519. use_asm = true;
  19520. }
  19521. function doit() {
  19522. self.add_comments(stream);
  19523. self.add_source_map(stream);
  19524. generator(self, stream);
  19525. }
  19526. stream.push_node(self);
  19527. if (force_parens || self.needs_parens(stream)) {
  19528. stream.with_parens(doit);
  19529. } else {
  19530. doit();
  19531. }
  19532. stream.pop_node();
  19533. if (self instanceof AST_Lambda) {
  19534. use_asm = prev_use_asm;
  19535. }
  19536. });
  19537. AST_Node.DEFMETHOD("print_to_string", function(options){
  19538. var s = OutputStream(options);
  19539. this.print(s);
  19540. return s.get();
  19541. });
  19542. /* -----[ comments ]----- */
  19543. AST_Node.DEFMETHOD("add_comments", function(output){
  19544. var c = output.option("comments"), self = this;
  19545. var start = self.start;
  19546. if (start && !start._comments_dumped) {
  19547. start._comments_dumped = true;
  19548. var comments = start.comments_before || [];
  19549. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  19550. // and https://github.com/mishoo/UglifyJS2/issues/372
  19551. if (self instanceof AST_Exit && self.value) {
  19552. self.value.walk(new TreeWalker(function(node){
  19553. if (node.start && node.start.comments_before) {
  19554. comments = comments.concat(node.start.comments_before);
  19555. node.start.comments_before = [];
  19556. }
  19557. if (node instanceof AST_Function ||
  19558. node instanceof AST_Array ||
  19559. node instanceof AST_Object)
  19560. {
  19561. return true; // don't go inside.
  19562. }
  19563. }));
  19564. }
  19565. if (!c) {
  19566. comments = comments.filter(function(comment) {
  19567. return comment.type == "comment5";
  19568. });
  19569. } else if (c.test) {
  19570. comments = comments.filter(function(comment){
  19571. return c.test(comment.value) || comment.type == "comment5";
  19572. });
  19573. } else if (typeof c == "function") {
  19574. comments = comments.filter(function(comment){
  19575. return c(self, comment) || comment.type == "comment5";
  19576. });
  19577. }
  19578. // Keep single line comments after nlb, after nlb
  19579. if (!output.option("beautify") && comments.length > 0 &&
  19580. /comment[134]/.test(comments[0].type) &&
  19581. output.col() !== 0 && comments[0].nlb)
  19582. {
  19583. output.print("\n");
  19584. }
  19585. comments.forEach(function(c){
  19586. if (/comment[134]/.test(c.type)) {
  19587. output.print("//" + c.value + "\n");
  19588. output.indent();
  19589. }
  19590. else if (c.type == "comment2") {
  19591. output.print("/*" + c.value + "*/");
  19592. if (start.nlb) {
  19593. output.print("\n");
  19594. output.indent();
  19595. } else {
  19596. output.space();
  19597. }
  19598. }
  19599. else if (output.pos() === 0 && c.type == "comment5" && output.option("shebang")) {
  19600. output.print("#!" + c.value + "\n");
  19601. output.indent();
  19602. }
  19603. });
  19604. }
  19605. });
  19606. /* -----[ PARENTHESES ]----- */
  19607. function PARENS(nodetype, func) {
  19608. if (Array.isArray(nodetype)) {
  19609. nodetype.forEach(function(nodetype){
  19610. PARENS(nodetype, func);
  19611. });
  19612. } else {
  19613. nodetype.DEFMETHOD("needs_parens", func);
  19614. }
  19615. };
  19616. PARENS(AST_Node, function(){
  19617. return false;
  19618. });
  19619. // a function expression needs parens around it when it's provably
  19620. // the first token to appear in a statement.
  19621. PARENS(AST_Function, function(output){
  19622. return first_in_statement(output);
  19623. });
  19624. // same goes for an object literal, because otherwise it would be
  19625. // interpreted as a block of code.
  19626. PARENS(AST_Object, function(output){
  19627. return first_in_statement(output);
  19628. });
  19629. PARENS([ AST_Unary, AST_Undefined ], function(output){
  19630. var p = output.parent();
  19631. return p instanceof AST_PropAccess && p.expression === this;
  19632. });
  19633. PARENS(AST_Seq, function(output){
  19634. var p = output.parent();
  19635. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  19636. || p instanceof AST_Unary // !(foo, bar, baz)
  19637. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  19638. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  19639. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  19640. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  19641. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  19642. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  19643. * ==> 20 (side effect, set a := 10 and b := 20) */
  19644. ;
  19645. });
  19646. PARENS(AST_Binary, function(output){
  19647. var p = output.parent();
  19648. // (foo && bar)()
  19649. if (p instanceof AST_Call && p.expression === this)
  19650. return true;
  19651. // typeof (foo && bar)
  19652. if (p instanceof AST_Unary)
  19653. return true;
  19654. // (foo && bar)["prop"], (foo && bar).prop
  19655. if (p instanceof AST_PropAccess && p.expression === this)
  19656. return true;
  19657. // this deals with precedence: 3 * (2 + 1)
  19658. if (p instanceof AST_Binary) {
  19659. var po = p.operator, pp = PRECEDENCE[po];
  19660. var so = this.operator, sp = PRECEDENCE[so];
  19661. if (pp > sp
  19662. || (pp == sp
  19663. && this === p.right)) {
  19664. return true;
  19665. }
  19666. }
  19667. });
  19668. PARENS(AST_PropAccess, function(output){
  19669. var p = output.parent();
  19670. if (p instanceof AST_New && p.expression === this) {
  19671. // i.e. new (foo.bar().baz)
  19672. //
  19673. // if there's one call into this subtree, then we need
  19674. // parens around it too, otherwise the call will be
  19675. // interpreted as passing the arguments to the upper New
  19676. // expression.
  19677. try {
  19678. this.walk(new TreeWalker(function(node){
  19679. if (node instanceof AST_Call) throw p;
  19680. }));
  19681. } catch(ex) {
  19682. if (ex !== p) throw ex;
  19683. return true;
  19684. }
  19685. }
  19686. });
  19687. PARENS(AST_Call, function(output){
  19688. var p = output.parent(), p1;
  19689. if (p instanceof AST_New && p.expression === this)
  19690. return true;
  19691. // workaround for Safari bug.
  19692. // https://bugs.webkit.org/show_bug.cgi?id=123506
  19693. return this.expression instanceof AST_Function
  19694. && p instanceof AST_PropAccess
  19695. && p.expression === this
  19696. && (p1 = output.parent(1)) instanceof AST_Assign
  19697. && p1.left === p;
  19698. });
  19699. PARENS(AST_New, function(output){
  19700. var p = output.parent();
  19701. if (no_constructor_parens(this, output)
  19702. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  19703. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  19704. return true;
  19705. });
  19706. PARENS(AST_Number, function(output){
  19707. var p = output.parent();
  19708. if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
  19709. return true;
  19710. });
  19711. PARENS([ AST_Assign, AST_Conditional ], function (output){
  19712. var p = output.parent();
  19713. // !(a = false) → true
  19714. if (p instanceof AST_Unary)
  19715. return true;
  19716. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  19717. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  19718. return true;
  19719. // (a = func)() —or— new (a = Object)()
  19720. if (p instanceof AST_Call && p.expression === this)
  19721. return true;
  19722. // (a = foo) ? bar : baz
  19723. if (p instanceof AST_Conditional && p.condition === this)
  19724. return true;
  19725. // (a = foo)["prop"] —or— (a = foo).prop
  19726. if (p instanceof AST_PropAccess && p.expression === this)
  19727. return true;
  19728. });
  19729. /* -----[ PRINTERS ]----- */
  19730. DEFPRINT(AST_Directive, function(self, output){
  19731. output.print_string(self.value, self.quote);
  19732. output.semicolon();
  19733. });
  19734. DEFPRINT(AST_Debugger, function(self, output){
  19735. output.print("debugger");
  19736. output.semicolon();
  19737. });
  19738. /* -----[ statements ]----- */
  19739. function display_body(body, is_toplevel, output) {
  19740. var last = body.length - 1;
  19741. body.forEach(function(stmt, i){
  19742. if (!(stmt instanceof AST_EmptyStatement)) {
  19743. output.indent();
  19744. stmt.print(output);
  19745. if (!(i == last && is_toplevel)) {
  19746. output.newline();
  19747. if (is_toplevel) output.newline();
  19748. }
  19749. }
  19750. });
  19751. };
  19752. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  19753. force_statement(this.body, output);
  19754. });
  19755. DEFPRINT(AST_Statement, function(self, output){
  19756. self.body.print(output);
  19757. output.semicolon();
  19758. });
  19759. DEFPRINT(AST_Toplevel, function(self, output){
  19760. display_body(self.body, true, output);
  19761. output.print("");
  19762. });
  19763. DEFPRINT(AST_LabeledStatement, function(self, output){
  19764. self.label.print(output);
  19765. output.colon();
  19766. self.body.print(output);
  19767. });
  19768. DEFPRINT(AST_SimpleStatement, function(self, output){
  19769. self.body.print(output);
  19770. output.semicolon();
  19771. });
  19772. function print_bracketed(body, output) {
  19773. if (body.length > 0) output.with_block(function(){
  19774. display_body(body, false, output);
  19775. });
  19776. else output.print("{}");
  19777. };
  19778. DEFPRINT(AST_BlockStatement, function(self, output){
  19779. print_bracketed(self.body, output);
  19780. });
  19781. DEFPRINT(AST_EmptyStatement, function(self, output){
  19782. output.semicolon();
  19783. });
  19784. DEFPRINT(AST_Do, function(self, output){
  19785. output.print("do");
  19786. output.space();
  19787. self._do_print_body(output);
  19788. output.space();
  19789. output.print("while");
  19790. output.space();
  19791. output.with_parens(function(){
  19792. self.condition.print(output);
  19793. });
  19794. output.semicolon();
  19795. });
  19796. DEFPRINT(AST_While, function(self, output){
  19797. output.print("while");
  19798. output.space();
  19799. output.with_parens(function(){
  19800. self.condition.print(output);
  19801. });
  19802. output.space();
  19803. self._do_print_body(output);
  19804. });
  19805. DEFPRINT(AST_For, function(self, output){
  19806. output.print("for");
  19807. output.space();
  19808. output.with_parens(function(){
  19809. if (self.init && !(self.init instanceof AST_EmptyStatement)) {
  19810. if (self.init instanceof AST_Definitions) {
  19811. self.init.print(output);
  19812. } else {
  19813. parenthesize_for_noin(self.init, output, true);
  19814. }
  19815. output.print(";");
  19816. output.space();
  19817. } else {
  19818. output.print(";");
  19819. }
  19820. if (self.condition) {
  19821. self.condition.print(output);
  19822. output.print(";");
  19823. output.space();
  19824. } else {
  19825. output.print(";");
  19826. }
  19827. if (self.step) {
  19828. self.step.print(output);
  19829. }
  19830. });
  19831. output.space();
  19832. self._do_print_body(output);
  19833. });
  19834. DEFPRINT(AST_ForIn, function(self, output){
  19835. output.print("for");
  19836. output.space();
  19837. output.with_parens(function(){
  19838. self.init.print(output);
  19839. output.space();
  19840. output.print("in");
  19841. output.space();
  19842. self.object.print(output);
  19843. });
  19844. output.space();
  19845. self._do_print_body(output);
  19846. });
  19847. DEFPRINT(AST_With, function(self, output){
  19848. output.print("with");
  19849. output.space();
  19850. output.with_parens(function(){
  19851. self.expression.print(output);
  19852. });
  19853. output.space();
  19854. self._do_print_body(output);
  19855. });
  19856. /* -----[ functions ]----- */
  19857. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  19858. var self = this;
  19859. if (!nokeyword) {
  19860. output.print("function");
  19861. }
  19862. if (self.name) {
  19863. output.space();
  19864. self.name.print(output);
  19865. }
  19866. output.with_parens(function(){
  19867. self.argnames.forEach(function(arg, i){
  19868. if (i) output.comma();
  19869. arg.print(output);
  19870. });
  19871. });
  19872. output.space();
  19873. print_bracketed(self.body, output);
  19874. });
  19875. DEFPRINT(AST_Lambda, function(self, output){
  19876. self._do_print(output);
  19877. });
  19878. /* -----[ exits ]----- */
  19879. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  19880. output.print(kind);
  19881. if (this.value) {
  19882. output.space();
  19883. this.value.print(output);
  19884. }
  19885. output.semicolon();
  19886. });
  19887. DEFPRINT(AST_Return, function(self, output){
  19888. self._do_print(output, "return");
  19889. });
  19890. DEFPRINT(AST_Throw, function(self, output){
  19891. self._do_print(output, "throw");
  19892. });
  19893. /* -----[ loop control ]----- */
  19894. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  19895. output.print(kind);
  19896. if (this.label) {
  19897. output.space();
  19898. this.label.print(output);
  19899. }
  19900. output.semicolon();
  19901. });
  19902. DEFPRINT(AST_Break, function(self, output){
  19903. self._do_print(output, "break");
  19904. });
  19905. DEFPRINT(AST_Continue, function(self, output){
  19906. self._do_print(output, "continue");
  19907. });
  19908. /* -----[ if ]----- */
  19909. function make_then(self, output) {
  19910. if (output.option("bracketize")) {
  19911. make_block(self.body, output);
  19912. return;
  19913. }
  19914. // The squeezer replaces "block"-s that contain only a single
  19915. // statement with the statement itself; technically, the AST
  19916. // is correct, but this can create problems when we output an
  19917. // IF having an ELSE clause where the THEN clause ends in an
  19918. // IF *without* an ELSE block (then the outer ELSE would refer
  19919. // to the inner IF). This function checks for this case and
  19920. // adds the block brackets if needed.
  19921. if (!self.body)
  19922. return output.force_semicolon();
  19923. if (self.body instanceof AST_Do
  19924. && !output.option("screw_ie8")) {
  19925. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  19926. // croaks with "syntax error" on code like this: if (foo)
  19927. // do ... while(cond); else ... we need block brackets
  19928. // around do/while
  19929. make_block(self.body, output);
  19930. return;
  19931. }
  19932. var b = self.body;
  19933. while (true) {
  19934. if (b instanceof AST_If) {
  19935. if (!b.alternative) {
  19936. make_block(self.body, output);
  19937. return;
  19938. }
  19939. b = b.alternative;
  19940. }
  19941. else if (b instanceof AST_StatementWithBody) {
  19942. b = b.body;
  19943. }
  19944. else break;
  19945. }
  19946. force_statement(self.body, output);
  19947. };
  19948. DEFPRINT(AST_If, function(self, output){
  19949. output.print("if");
  19950. output.space();
  19951. output.with_parens(function(){
  19952. self.condition.print(output);
  19953. });
  19954. output.space();
  19955. if (self.alternative) {
  19956. make_then(self, output);
  19957. output.space();
  19958. output.print("else");
  19959. output.space();
  19960. force_statement(self.alternative, output);
  19961. } else {
  19962. self._do_print_body(output);
  19963. }
  19964. });
  19965. /* -----[ switch ]----- */
  19966. DEFPRINT(AST_Switch, function(self, output){
  19967. output.print("switch");
  19968. output.space();
  19969. output.with_parens(function(){
  19970. self.expression.print(output);
  19971. });
  19972. output.space();
  19973. if (self.body.length > 0) output.with_block(function(){
  19974. self.body.forEach(function(stmt, i){
  19975. if (i) output.newline();
  19976. output.indent(true);
  19977. stmt.print(output);
  19978. });
  19979. });
  19980. else output.print("{}");
  19981. });
  19982. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  19983. if (this.body.length > 0) {
  19984. output.newline();
  19985. this.body.forEach(function(stmt){
  19986. output.indent();
  19987. stmt.print(output);
  19988. output.newline();
  19989. });
  19990. }
  19991. });
  19992. DEFPRINT(AST_Default, function(self, output){
  19993. output.print("default:");
  19994. self._do_print_body(output);
  19995. });
  19996. DEFPRINT(AST_Case, function(self, output){
  19997. output.print("case");
  19998. output.space();
  19999. self.expression.print(output);
  20000. output.print(":");
  20001. self._do_print_body(output);
  20002. });
  20003. /* -----[ exceptions ]----- */
  20004. DEFPRINT(AST_Try, function(self, output){
  20005. output.print("try");
  20006. output.space();
  20007. print_bracketed(self.body, output);
  20008. if (self.bcatch) {
  20009. output.space();
  20010. self.bcatch.print(output);
  20011. }
  20012. if (self.bfinally) {
  20013. output.space();
  20014. self.bfinally.print(output);
  20015. }
  20016. });
  20017. DEFPRINT(AST_Catch, function(self, output){
  20018. output.print("catch");
  20019. output.space();
  20020. output.with_parens(function(){
  20021. self.argname.print(output);
  20022. });
  20023. output.space();
  20024. print_bracketed(self.body, output);
  20025. });
  20026. DEFPRINT(AST_Finally, function(self, output){
  20027. output.print("finally");
  20028. output.space();
  20029. print_bracketed(self.body, output);
  20030. });
  20031. /* -----[ var/const ]----- */
  20032. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  20033. output.print(kind);
  20034. output.space();
  20035. this.definitions.forEach(function(def, i){
  20036. if (i) output.comma();
  20037. def.print(output);
  20038. });
  20039. var p = output.parent();
  20040. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  20041. var avoid_semicolon = in_for && p.init === this;
  20042. if (!avoid_semicolon)
  20043. output.semicolon();
  20044. });
  20045. DEFPRINT(AST_Var, function(self, output){
  20046. self._do_print(output, "var");
  20047. });
  20048. DEFPRINT(AST_Const, function(self, output){
  20049. self._do_print(output, "const");
  20050. });
  20051. function parenthesize_for_noin(node, output, noin) {
  20052. if (!noin) node.print(output);
  20053. else try {
  20054. // need to take some precautions here:
  20055. // https://github.com/mishoo/UglifyJS2/issues/60
  20056. node.walk(new TreeWalker(function(node){
  20057. if (node instanceof AST_Binary && node.operator == "in")
  20058. throw output;
  20059. }));
  20060. node.print(output);
  20061. } catch(ex) {
  20062. if (ex !== output) throw ex;
  20063. node.print(output, true);
  20064. }
  20065. };
  20066. DEFPRINT(AST_VarDef, function(self, output){
  20067. self.name.print(output);
  20068. if (self.value) {
  20069. output.space();
  20070. output.print("=");
  20071. output.space();
  20072. var p = output.parent(1);
  20073. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  20074. parenthesize_for_noin(self.value, output, noin);
  20075. }
  20076. });
  20077. /* -----[ other expressions ]----- */
  20078. DEFPRINT(AST_Call, function(self, output){
  20079. self.expression.print(output);
  20080. if (self instanceof AST_New && no_constructor_parens(self, output))
  20081. return;
  20082. output.with_parens(function(){
  20083. self.args.forEach(function(expr, i){
  20084. if (i) output.comma();
  20085. expr.print(output);
  20086. });
  20087. });
  20088. });
  20089. DEFPRINT(AST_New, function(self, output){
  20090. output.print("new");
  20091. output.space();
  20092. AST_Call.prototype._codegen(self, output);
  20093. });
  20094. AST_Seq.DEFMETHOD("_do_print", function(output){
  20095. this.car.print(output);
  20096. if (this.cdr) {
  20097. output.comma();
  20098. if (output.should_break()) {
  20099. output.newline();
  20100. output.indent();
  20101. }
  20102. this.cdr.print(output);
  20103. }
  20104. });
  20105. DEFPRINT(AST_Seq, function(self, output){
  20106. self._do_print(output);
  20107. // var p = output.parent();
  20108. // if (p instanceof AST_Statement) {
  20109. // output.with_indent(output.next_indent(), function(){
  20110. // self._do_print(output);
  20111. // });
  20112. // } else {
  20113. // self._do_print(output);
  20114. // }
  20115. });
  20116. DEFPRINT(AST_Dot, function(self, output){
  20117. var expr = self.expression;
  20118. expr.print(output);
  20119. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  20120. if (!/[xa-f.]/i.test(output.last())) {
  20121. output.print(".");
  20122. }
  20123. }
  20124. output.print(".");
  20125. // the name after dot would be mapped about here.
  20126. output.add_mapping(self.end);
  20127. output.print_name(self.property);
  20128. });
  20129. DEFPRINT(AST_Sub, function(self, output){
  20130. self.expression.print(output);
  20131. output.print("[");
  20132. self.property.print(output);
  20133. output.print("]");
  20134. });
  20135. DEFPRINT(AST_UnaryPrefix, function(self, output){
  20136. var op = self.operator;
  20137. output.print(op);
  20138. if (/^[a-z]/i.test(op)
  20139. || (/[+-]$/.test(op)
  20140. && self.expression instanceof AST_UnaryPrefix
  20141. && /^[+-]/.test(self.expression.operator))) {
  20142. output.space();
  20143. }
  20144. self.expression.print(output);
  20145. });
  20146. DEFPRINT(AST_UnaryPostfix, function(self, output){
  20147. self.expression.print(output);
  20148. output.print(self.operator);
  20149. });
  20150. DEFPRINT(AST_Binary, function(self, output){
  20151. var op = self.operator;
  20152. self.left.print(output);
  20153. if (op[0] == ">" /* ">>" ">>>" ">" ">=" */
  20154. && self.left instanceof AST_UnaryPostfix
  20155. && self.left.operator == "--") {
  20156. // space is mandatory to avoid outputting -->
  20157. output.print(" ");
  20158. } else {
  20159. // the space is optional depending on "beautify"
  20160. output.space();
  20161. }
  20162. output.print(op);
  20163. if ((op == "<" || op == "<<")
  20164. && self.right instanceof AST_UnaryPrefix
  20165. && self.right.operator == "!"
  20166. && self.right.expression instanceof AST_UnaryPrefix
  20167. && self.right.expression.operator == "--") {
  20168. // space is mandatory to avoid outputting <!--
  20169. output.print(" ");
  20170. } else {
  20171. // the space is optional depending on "beautify"
  20172. output.space();
  20173. }
  20174. self.right.print(output);
  20175. });
  20176. DEFPRINT(AST_Conditional, function(self, output){
  20177. self.condition.print(output);
  20178. output.space();
  20179. output.print("?");
  20180. output.space();
  20181. self.consequent.print(output);
  20182. output.space();
  20183. output.colon();
  20184. self.alternative.print(output);
  20185. });
  20186. /* -----[ literals ]----- */
  20187. DEFPRINT(AST_Array, function(self, output){
  20188. output.with_square(function(){
  20189. var a = self.elements, len = a.length;
  20190. if (len > 0) output.space();
  20191. a.forEach(function(exp, i){
  20192. if (i) output.comma();
  20193. exp.print(output);
  20194. // If the final element is a hole, we need to make sure it
  20195. // doesn't look like a trailing comma, by inserting an actual
  20196. // trailing comma.
  20197. if (i === len - 1 && exp instanceof AST_Hole)
  20198. output.comma();
  20199. });
  20200. if (len > 0) output.space();
  20201. });
  20202. });
  20203. DEFPRINT(AST_Object, function(self, output){
  20204. if (self.properties.length > 0) output.with_block(function(){
  20205. self.properties.forEach(function(prop, i){
  20206. if (i) {
  20207. output.print(",");
  20208. output.newline();
  20209. }
  20210. output.indent();
  20211. prop.print(output);
  20212. });
  20213. output.newline();
  20214. });
  20215. else output.print("{}");
  20216. });
  20217. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  20218. var key = self.key;
  20219. var quote = self.quote;
  20220. if (output.option("quote_keys")) {
  20221. output.print_string(key + "");
  20222. } else if ((typeof key == "number"
  20223. || !output.option("beautify")
  20224. && +key + "" == key)
  20225. && parseFloat(key) >= 0) {
  20226. output.print(make_num(key));
  20227. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  20228. output.print_name(key);
  20229. } else {
  20230. output.print_string(key, quote);
  20231. }
  20232. output.colon();
  20233. self.value.print(output);
  20234. });
  20235. DEFPRINT(AST_ObjectSetter, function(self, output){
  20236. output.print("set");
  20237. output.space();
  20238. self.key.print(output);
  20239. self.value._do_print(output, true);
  20240. });
  20241. DEFPRINT(AST_ObjectGetter, function(self, output){
  20242. output.print("get");
  20243. output.space();
  20244. self.key.print(output);
  20245. self.value._do_print(output, true);
  20246. });
  20247. DEFPRINT(AST_Symbol, function(self, output){
  20248. var def = self.definition();
  20249. output.print_name(def ? def.mangled_name || def.name : self.name);
  20250. });
  20251. DEFPRINT(AST_Undefined, function(self, output){
  20252. output.print("void 0");
  20253. });
  20254. DEFPRINT(AST_Hole, noop);
  20255. DEFPRINT(AST_Infinity, function(self, output){
  20256. output.print("Infinity");
  20257. });
  20258. DEFPRINT(AST_NaN, function(self, output){
  20259. output.print("NaN");
  20260. });
  20261. DEFPRINT(AST_This, function(self, output){
  20262. output.print("this");
  20263. });
  20264. DEFPRINT(AST_Constant, function(self, output){
  20265. output.print(self.getValue());
  20266. });
  20267. DEFPRINT(AST_String, function(self, output){
  20268. output.print_string(self.getValue(), self.quote);
  20269. });
  20270. DEFPRINT(AST_Number, function(self, output){
  20271. if (use_asm && self.start.raw != null) {
  20272. output.print(self.start.raw);
  20273. } else {
  20274. output.print(make_num(self.getValue()));
  20275. }
  20276. });
  20277. function regexp_safe_literal(code) {
  20278. return [
  20279. 0x5c , // \
  20280. 0x2f , // /
  20281. 0x2e , // .
  20282. 0x2b , // +
  20283. 0x2a , // *
  20284. 0x3f , // ?
  20285. 0x28 , // (
  20286. 0x29 , // )
  20287. 0x5b , // [
  20288. 0x5d , // ]
  20289. 0x7b , // {
  20290. 0x7d , // }
  20291. 0x24 , // $
  20292. 0x5e , // ^
  20293. 0x3a , // :
  20294. 0x7c , // |
  20295. 0x21 , // !
  20296. 0x0a , // \n
  20297. 0x0d , // \r
  20298. 0x00 , // \0
  20299. 0xfeff , // Unicode BOM
  20300. 0x2028 , // unicode "line separator"
  20301. 0x2029 , // unicode "paragraph separator"
  20302. ].indexOf(code) < 0;
  20303. };
  20304. DEFPRINT(AST_RegExp, function(self, output){
  20305. var str = self.getValue().toString();
  20306. if (output.option("ascii_only")) {
  20307. str = output.to_ascii(str);
  20308. } else if (output.option("unescape_regexps")) {
  20309. str = str.split("\\\\").map(function(str){
  20310. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  20311. var code = parseInt(s.substr(2), 16);
  20312. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  20313. });
  20314. }).join("\\\\");
  20315. }
  20316. output.print(str);
  20317. var p = output.parent();
  20318. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  20319. output.print(" ");
  20320. });
  20321. function force_statement(stat, output) {
  20322. if (output.option("bracketize")) {
  20323. if (!stat || stat instanceof AST_EmptyStatement)
  20324. output.print("{}");
  20325. else if (stat instanceof AST_BlockStatement)
  20326. stat.print(output);
  20327. else output.with_block(function(){
  20328. output.indent();
  20329. stat.print(output);
  20330. output.newline();
  20331. });
  20332. } else {
  20333. if (!stat || stat instanceof AST_EmptyStatement)
  20334. output.force_semicolon();
  20335. else
  20336. stat.print(output);
  20337. }
  20338. };
  20339. // return true if the node at the top of the stack (that means the
  20340. // innermost node in the current output) is lexically the first in
  20341. // a statement.
  20342. function first_in_statement(output) {
  20343. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  20344. while (i > 0) {
  20345. if (p instanceof AST_Statement && p.body === node)
  20346. return true;
  20347. if ((p instanceof AST_Seq && p.car === node ) ||
  20348. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  20349. (p instanceof AST_Dot && p.expression === node ) ||
  20350. (p instanceof AST_Sub && p.expression === node ) ||
  20351. (p instanceof AST_Conditional && p.condition === node ) ||
  20352. (p instanceof AST_Binary && p.left === node ) ||
  20353. (p instanceof AST_UnaryPostfix && p.expression === node ))
  20354. {
  20355. node = p;
  20356. p = a[--i];
  20357. } else {
  20358. return false;
  20359. }
  20360. }
  20361. };
  20362. // self should be AST_New. decide if we want to show parens or not.
  20363. function no_constructor_parens(self, output) {
  20364. return self.args.length == 0 && !output.option("beautify");
  20365. };
  20366. function best_of(a) {
  20367. var best = a[0], len = best.length;
  20368. for (var i = 1; i < a.length; ++i) {
  20369. if (a[i].length < len) {
  20370. best = a[i];
  20371. len = best.length;
  20372. }
  20373. }
  20374. return best;
  20375. };
  20376. function make_num(num) {
  20377. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  20378. if (Math.floor(num) === num) {
  20379. if (num >= 0) {
  20380. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  20381. "0" + num.toString(8)); // same.
  20382. } else {
  20383. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  20384. "-0" + (-num).toString(8)); // same.
  20385. }
  20386. if ((m = /^(.*?)(0+)$/.exec(num))) {
  20387. a.push(m[1] + "e" + m[2].length);
  20388. }
  20389. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  20390. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  20391. str.substr(str.indexOf(".")));
  20392. }
  20393. return best_of(a);
  20394. };
  20395. function make_block(stmt, output) {
  20396. if (stmt instanceof AST_BlockStatement) {
  20397. stmt.print(output);
  20398. return;
  20399. }
  20400. output.with_block(function(){
  20401. output.indent();
  20402. stmt.print(output);
  20403. output.newline();
  20404. });
  20405. };
  20406. /* -----[ source map generators ]----- */
  20407. function DEFMAP(nodetype, generator) {
  20408. nodetype.DEFMETHOD("add_source_map", function(stream){
  20409. generator(this, stream);
  20410. });
  20411. };
  20412. // We could easily add info for ALL nodes, but it seems to me that
  20413. // would be quite wasteful, hence this noop in the base class.
  20414. DEFMAP(AST_Node, noop);
  20415. function basic_sourcemap_gen(self, output) {
  20416. output.add_mapping(self.start);
  20417. };
  20418. // XXX: I'm not exactly sure if we need it for all of these nodes,
  20419. // or if we should add even more.
  20420. DEFMAP(AST_Directive, basic_sourcemap_gen);
  20421. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  20422. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  20423. DEFMAP(AST_Jump, basic_sourcemap_gen);
  20424. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  20425. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  20426. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  20427. DEFMAP(AST_Switch, basic_sourcemap_gen);
  20428. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  20429. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  20430. DEFMAP(AST_Toplevel, noop);
  20431. DEFMAP(AST_New, basic_sourcemap_gen);
  20432. DEFMAP(AST_Try, basic_sourcemap_gen);
  20433. DEFMAP(AST_Catch, basic_sourcemap_gen);
  20434. DEFMAP(AST_Finally, basic_sourcemap_gen);
  20435. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  20436. DEFMAP(AST_Constant, basic_sourcemap_gen);
  20437. DEFMAP(AST_ObjectSetter, function(self, output){
  20438. output.add_mapping(self.start, self.key.name);
  20439. });
  20440. DEFMAP(AST_ObjectGetter, function(self, output){
  20441. output.add_mapping(self.start, self.key.name);
  20442. });
  20443. DEFMAP(AST_ObjectProperty, function(self, output){
  20444. output.add_mapping(self.start, self.key);
  20445. });
  20446. })();
  20447. /***********************************************************************
  20448. A JavaScript tokenizer / parser / beautifier / compressor.
  20449. https://github.com/mishoo/UglifyJS2
  20450. -------------------------------- (C) ---------------------------------
  20451. Author: Mihai Bazon
  20452. <mihai.bazon@gmail.com>
  20453. http://mihai.bazon.net/blog
  20454. Distributed under the BSD license:
  20455. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  20456. Redistribution and use in source and binary forms, with or without
  20457. modification, are permitted provided that the following conditions
  20458. are met:
  20459. * Redistributions of source code must retain the above
  20460. copyright notice, this list of conditions and the following
  20461. disclaimer.
  20462. * Redistributions in binary form must reproduce the above
  20463. copyright notice, this list of conditions and the following
  20464. disclaimer in the documentation and/or other materials
  20465. provided with the distribution.
  20466. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  20467. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20468. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20469. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  20470. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  20471. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20472. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  20473. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20474. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  20475. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  20476. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  20477. SUCH DAMAGE.
  20478. ***********************************************************************/
  20479. "use strict";
  20480. function Compressor(options, false_by_default) {
  20481. if (!(this instanceof Compressor))
  20482. return new Compressor(options, false_by_default);
  20483. TreeTransformer.call(this, this.before, this.after);
  20484. this.options = defaults(options, {
  20485. sequences : !false_by_default,
  20486. properties : !false_by_default,
  20487. dead_code : !false_by_default,
  20488. drop_debugger : !false_by_default,
  20489. unsafe : false,
  20490. unsafe_comps : false,
  20491. conditionals : !false_by_default,
  20492. comparisons : !false_by_default,
  20493. evaluate : !false_by_default,
  20494. booleans : !false_by_default,
  20495. loops : !false_by_default,
  20496. unused : !false_by_default,
  20497. hoist_funs : !false_by_default,
  20498. keep_fargs : true,
  20499. keep_fnames : false,
  20500. hoist_vars : false,
  20501. if_return : !false_by_default,
  20502. join_vars : !false_by_default,
  20503. cascade : !false_by_default,
  20504. side_effects : !false_by_default,
  20505. pure_getters : false,
  20506. pure_funcs : null,
  20507. negate_iife : !false_by_default,
  20508. screw_ie8 : false,
  20509. drop_console : false,
  20510. angular : false,
  20511. warnings : true,
  20512. global_defs : {}
  20513. }, true);
  20514. };
  20515. Compressor.prototype = new TreeTransformer;
  20516. merge(Compressor.prototype, {
  20517. option: function(key) { return this.options[key] },
  20518. warn: function() {
  20519. if (this.options.warnings)
  20520. AST_Node.warn.apply(AST_Node, arguments);
  20521. },
  20522. before: function(node, descend, in_list) {
  20523. if (node._squeezed) return node;
  20524. var was_scope = false;
  20525. if (node instanceof AST_Scope) {
  20526. node = node.hoist_declarations(this);
  20527. was_scope = true;
  20528. }
  20529. descend(node, this);
  20530. node = node.optimize(this);
  20531. if (was_scope && node instanceof AST_Scope) {
  20532. node.drop_unused(this);
  20533. descend(node, this);
  20534. }
  20535. node._squeezed = true;
  20536. return node;
  20537. }
  20538. });
  20539. (function(){
  20540. function OPT(node, optimizer) {
  20541. node.DEFMETHOD("optimize", function(compressor){
  20542. var self = this;
  20543. if (self._optimized) return self;
  20544. if (compressor.has_directive("use asm")) return self;
  20545. var opt = optimizer(self, compressor);
  20546. opt._optimized = true;
  20547. if (opt === self) return opt;
  20548. return opt.transform(compressor);
  20549. });
  20550. };
  20551. OPT(AST_Node, function(self, compressor){
  20552. return self;
  20553. });
  20554. AST_Node.DEFMETHOD("equivalent_to", function(node){
  20555. // XXX: this is a rather expensive way to test two node's equivalence:
  20556. return this.print_to_string() == node.print_to_string();
  20557. });
  20558. function make_node(ctor, orig, props) {
  20559. if (!props) props = {};
  20560. if (orig) {
  20561. if (!props.start) props.start = orig.start;
  20562. if (!props.end) props.end = orig.end;
  20563. }
  20564. return new ctor(props);
  20565. };
  20566. function make_node_from_constant(compressor, val, orig) {
  20567. // XXX: WIP.
  20568. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  20569. // if (node instanceof AST_SymbolRef) {
  20570. // var scope = compressor.find_parent(AST_Scope);
  20571. // var def = scope.find_variable(node);
  20572. // node.thedef = def;
  20573. // return node;
  20574. // }
  20575. // })).transform(compressor);
  20576. if (val instanceof AST_Node) return val.transform(compressor);
  20577. switch (typeof val) {
  20578. case "string":
  20579. return make_node(AST_String, orig, {
  20580. value: val
  20581. }).optimize(compressor);
  20582. case "number":
  20583. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  20584. value: val
  20585. }).optimize(compressor);
  20586. case "boolean":
  20587. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  20588. case "undefined":
  20589. return make_node(AST_Undefined, orig).optimize(compressor);
  20590. default:
  20591. if (val === null) {
  20592. return make_node(AST_Null, orig, { value: null }).optimize(compressor);
  20593. }
  20594. if (val instanceof RegExp) {
  20595. return make_node(AST_RegExp, orig, { value: val }).optimize(compressor);
  20596. }
  20597. throw new Error(string_template("Can't handle constant of type: {type}", {
  20598. type: typeof val
  20599. }));
  20600. }
  20601. };
  20602. function as_statement_array(thing) {
  20603. if (thing === null) return [];
  20604. if (thing instanceof AST_BlockStatement) return thing.body;
  20605. if (thing instanceof AST_EmptyStatement) return [];
  20606. if (thing instanceof AST_Statement) return [ thing ];
  20607. throw new Error("Can't convert thing to statement array");
  20608. };
  20609. function is_empty(thing) {
  20610. if (thing === null) return true;
  20611. if (thing instanceof AST_EmptyStatement) return true;
  20612. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  20613. return false;
  20614. };
  20615. function loop_body(x) {
  20616. if (x instanceof AST_Switch) return x;
  20617. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  20618. return (x.body instanceof AST_BlockStatement ? x.body : x);
  20619. }
  20620. return x;
  20621. };
  20622. function tighten_body(statements, compressor) {
  20623. var CHANGED, max_iter = 10;
  20624. do {
  20625. CHANGED = false;
  20626. if (compressor.option("angular")) {
  20627. statements = process_for_angular(statements);
  20628. }
  20629. statements = eliminate_spurious_blocks(statements);
  20630. if (compressor.option("dead_code")) {
  20631. statements = eliminate_dead_code(statements, compressor);
  20632. }
  20633. if (compressor.option("if_return")) {
  20634. statements = handle_if_return(statements, compressor);
  20635. }
  20636. if (compressor.option("sequences")) {
  20637. statements = sequencesize(statements, compressor);
  20638. }
  20639. if (compressor.option("join_vars")) {
  20640. statements = join_consecutive_vars(statements, compressor);
  20641. }
  20642. } while (CHANGED && max_iter-- > 0);
  20643. if (compressor.option("negate_iife")) {
  20644. negate_iifes(statements, compressor);
  20645. }
  20646. return statements;
  20647. function process_for_angular(statements) {
  20648. function has_inject(comment) {
  20649. return /@ngInject/.test(comment.value);
  20650. }
  20651. function make_arguments_names_list(func) {
  20652. return func.argnames.map(function(sym){
  20653. return make_node(AST_String, sym, { value: sym.name });
  20654. });
  20655. }
  20656. function make_array(orig, elements) {
  20657. return make_node(AST_Array, orig, { elements: elements });
  20658. }
  20659. function make_injector(func, name) {
  20660. return make_node(AST_SimpleStatement, func, {
  20661. body: make_node(AST_Assign, func, {
  20662. operator: "=",
  20663. left: make_node(AST_Dot, name, {
  20664. expression: make_node(AST_SymbolRef, name, name),
  20665. property: "$inject"
  20666. }),
  20667. right: make_array(func, make_arguments_names_list(func))
  20668. })
  20669. });
  20670. }
  20671. function check_expression(body) {
  20672. if (body && body.args) {
  20673. // if this is a function call check all of arguments passed
  20674. body.args.forEach(function(argument, index, array) {
  20675. var comments = argument.start.comments_before;
  20676. // if the argument is function preceded by @ngInject
  20677. if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) {
  20678. // replace the function with an array of names of its parameters and function at the end
  20679. array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument));
  20680. }
  20681. });
  20682. // if this is chained call check previous one recursively
  20683. if (body.expression && body.expression.expression) {
  20684. check_expression(body.expression.expression);
  20685. }
  20686. }
  20687. }
  20688. return statements.reduce(function(a, stat){
  20689. a.push(stat);
  20690. if (stat.body && stat.body.args) {
  20691. check_expression(stat.body);
  20692. } else {
  20693. var token = stat.start;
  20694. var comments = token.comments_before;
  20695. if (comments && comments.length > 0) {
  20696. var last = comments.pop();
  20697. if (has_inject(last)) {
  20698. // case 1: defun
  20699. if (stat instanceof AST_Defun) {
  20700. a.push(make_injector(stat, stat.name));
  20701. }
  20702. else if (stat instanceof AST_Definitions) {
  20703. stat.definitions.forEach(function(def) {
  20704. if (def.value && def.value instanceof AST_Lambda) {
  20705. a.push(make_injector(def.value, def.name));
  20706. }
  20707. });
  20708. }
  20709. else {
  20710. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  20711. }
  20712. }
  20713. }
  20714. }
  20715. return a;
  20716. }, []);
  20717. }
  20718. function eliminate_spurious_blocks(statements) {
  20719. var seen_dirs = [];
  20720. return statements.reduce(function(a, stat){
  20721. if (stat instanceof AST_BlockStatement) {
  20722. CHANGED = true;
  20723. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  20724. } else if (stat instanceof AST_EmptyStatement) {
  20725. CHANGED = true;
  20726. } else if (stat instanceof AST_Directive) {
  20727. if (seen_dirs.indexOf(stat.value) < 0) {
  20728. a.push(stat);
  20729. seen_dirs.push(stat.value);
  20730. } else {
  20731. CHANGED = true;
  20732. }
  20733. } else {
  20734. a.push(stat);
  20735. }
  20736. return a;
  20737. }, []);
  20738. };
  20739. function handle_if_return(statements, compressor) {
  20740. var self = compressor.self();
  20741. var in_lambda = self instanceof AST_Lambda;
  20742. var ret = [];
  20743. loop: for (var i = statements.length; --i >= 0;) {
  20744. var stat = statements[i];
  20745. switch (true) {
  20746. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  20747. CHANGED = true;
  20748. // note, ret.length is probably always zero
  20749. // because we drop unreachable code before this
  20750. // step. nevertheless, it's good to check.
  20751. continue loop;
  20752. case stat instanceof AST_If:
  20753. if (stat.body instanceof AST_Return) {
  20754. //---
  20755. // pretty silly case, but:
  20756. // if (foo()) return; return; ==> foo(); return;
  20757. if (((in_lambda && ret.length == 0)
  20758. || (ret[0] instanceof AST_Return && !ret[0].value))
  20759. && !stat.body.value && !stat.alternative) {
  20760. CHANGED = true;
  20761. var cond = make_node(AST_SimpleStatement, stat.condition, {
  20762. body: stat.condition
  20763. });
  20764. ret.unshift(cond);
  20765. continue loop;
  20766. }
  20767. //---
  20768. // if (foo()) return x; return y; ==> return foo() ? x : y;
  20769. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  20770. CHANGED = true;
  20771. stat = stat.clone();
  20772. stat.alternative = ret[0];
  20773. ret[0] = stat.transform(compressor);
  20774. continue loop;
  20775. }
  20776. //---
  20777. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  20778. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  20779. CHANGED = true;
  20780. stat = stat.clone();
  20781. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  20782. value: make_node(AST_Undefined, stat)
  20783. });
  20784. ret[0] = stat.transform(compressor);
  20785. continue loop;
  20786. }
  20787. //---
  20788. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  20789. if (!stat.body.value && in_lambda) {
  20790. CHANGED = true;
  20791. stat = stat.clone();
  20792. stat.condition = stat.condition.negate(compressor);
  20793. stat.body = make_node(AST_BlockStatement, stat, {
  20794. body: as_statement_array(stat.alternative).concat(ret)
  20795. });
  20796. stat.alternative = null;
  20797. ret = [ stat.transform(compressor) ];
  20798. continue loop;
  20799. }
  20800. //---
  20801. // XXX: what was the intention of this case?
  20802. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  20803. // however, with sequences on this helps producing slightly better output for
  20804. // the example code.
  20805. if (compressor.option("sequences")
  20806. && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  20807. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  20808. CHANGED = true;
  20809. ret.push(make_node(AST_Return, ret[0], {
  20810. value: make_node(AST_Undefined, ret[0])
  20811. }).transform(compressor));
  20812. ret = as_statement_array(stat.alternative).concat(ret);
  20813. ret.unshift(stat);
  20814. continue loop;
  20815. }
  20816. }
  20817. var ab = aborts(stat.body);
  20818. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  20819. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  20820. || (ab instanceof AST_Continue && self === loop_body(lct))
  20821. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  20822. if (ab.label) {
  20823. remove(ab.label.thedef.references, ab);
  20824. }
  20825. CHANGED = true;
  20826. var body = as_statement_array(stat.body).slice(0, -1);
  20827. stat = stat.clone();
  20828. stat.condition = stat.condition.negate(compressor);
  20829. stat.body = make_node(AST_BlockStatement, stat, {
  20830. body: as_statement_array(stat.alternative).concat(ret)
  20831. });
  20832. stat.alternative = make_node(AST_BlockStatement, stat, {
  20833. body: body
  20834. });
  20835. ret = [ stat.transform(compressor) ];
  20836. continue loop;
  20837. }
  20838. var ab = aborts(stat.alternative);
  20839. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  20840. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  20841. || (ab instanceof AST_Continue && self === loop_body(lct))
  20842. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  20843. if (ab.label) {
  20844. remove(ab.label.thedef.references, ab);
  20845. }
  20846. CHANGED = true;
  20847. stat = stat.clone();
  20848. stat.body = make_node(AST_BlockStatement, stat.body, {
  20849. body: as_statement_array(stat.body).concat(ret)
  20850. });
  20851. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  20852. body: as_statement_array(stat.alternative).slice(0, -1)
  20853. });
  20854. ret = [ stat.transform(compressor) ];
  20855. continue loop;
  20856. }
  20857. ret.unshift(stat);
  20858. break;
  20859. default:
  20860. ret.unshift(stat);
  20861. break;
  20862. }
  20863. }
  20864. return ret;
  20865. };
  20866. function eliminate_dead_code(statements, compressor) {
  20867. var has_quit = false;
  20868. var orig = statements.length;
  20869. var self = compressor.self();
  20870. statements = statements.reduce(function(a, stat){
  20871. if (has_quit) {
  20872. extract_declarations_from_unreachable_code(compressor, stat, a);
  20873. } else {
  20874. if (stat instanceof AST_LoopControl) {
  20875. var lct = compressor.loopcontrol_target(stat.label);
  20876. if ((stat instanceof AST_Break
  20877. && lct instanceof AST_BlockStatement
  20878. && loop_body(lct) === self) || (stat instanceof AST_Continue
  20879. && loop_body(lct) === self)) {
  20880. if (stat.label) {
  20881. remove(stat.label.thedef.references, stat);
  20882. }
  20883. } else {
  20884. a.push(stat);
  20885. }
  20886. } else {
  20887. a.push(stat);
  20888. }
  20889. if (aborts(stat)) has_quit = true;
  20890. }
  20891. return a;
  20892. }, []);
  20893. CHANGED = statements.length != orig;
  20894. return statements;
  20895. };
  20896. function sequencesize(statements, compressor) {
  20897. if (statements.length < 2) return statements;
  20898. var seq = [], ret = [];
  20899. function push_seq() {
  20900. seq = AST_Seq.from_array(seq);
  20901. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  20902. body: seq
  20903. }));
  20904. seq = [];
  20905. };
  20906. statements.forEach(function(stat){
  20907. if (stat instanceof AST_SimpleStatement && seq.length < 2000) seq.push(stat.body);
  20908. else push_seq(), ret.push(stat);
  20909. });
  20910. push_seq();
  20911. ret = sequencesize_2(ret, compressor);
  20912. CHANGED = ret.length != statements.length;
  20913. return ret;
  20914. };
  20915. function sequencesize_2(statements, compressor) {
  20916. function cons_seq(right) {
  20917. ret.pop();
  20918. var left = prev.body;
  20919. if (left instanceof AST_Seq) {
  20920. left.add(right);
  20921. } else {
  20922. left = AST_Seq.cons(left, right);
  20923. }
  20924. return left.transform(compressor);
  20925. };
  20926. var ret = [], prev = null;
  20927. statements.forEach(function(stat){
  20928. if (prev) {
  20929. if (stat instanceof AST_For) {
  20930. var opera = {};
  20931. try {
  20932. prev.body.walk(new TreeWalker(function(node){
  20933. if (node instanceof AST_Binary && node.operator == "in")
  20934. throw opera;
  20935. }));
  20936. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  20937. stat.init = cons_seq(stat.init);
  20938. }
  20939. else if (!stat.init) {
  20940. stat.init = prev.body;
  20941. ret.pop();
  20942. }
  20943. } catch(ex) {
  20944. if (ex !== opera) throw ex;
  20945. }
  20946. }
  20947. else if (stat instanceof AST_If) {
  20948. stat.condition = cons_seq(stat.condition);
  20949. }
  20950. else if (stat instanceof AST_With) {
  20951. stat.expression = cons_seq(stat.expression);
  20952. }
  20953. else if (stat instanceof AST_Exit && stat.value) {
  20954. stat.value = cons_seq(stat.value);
  20955. }
  20956. else if (stat instanceof AST_Exit) {
  20957. stat.value = cons_seq(make_node(AST_Undefined, stat));
  20958. }
  20959. else if (stat instanceof AST_Switch) {
  20960. stat.expression = cons_seq(stat.expression);
  20961. }
  20962. }
  20963. ret.push(stat);
  20964. prev = stat instanceof AST_SimpleStatement ? stat : null;
  20965. });
  20966. return ret;
  20967. };
  20968. function join_consecutive_vars(statements, compressor) {
  20969. var prev = null;
  20970. return statements.reduce(function(a, stat){
  20971. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  20972. prev.definitions = prev.definitions.concat(stat.definitions);
  20973. CHANGED = true;
  20974. }
  20975. else if (stat instanceof AST_For
  20976. && prev instanceof AST_Definitions
  20977. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  20978. CHANGED = true;
  20979. a.pop();
  20980. if (stat.init) {
  20981. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  20982. } else {
  20983. stat.init = prev;
  20984. }
  20985. a.push(stat);
  20986. prev = stat;
  20987. }
  20988. else {
  20989. prev = stat;
  20990. a.push(stat);
  20991. }
  20992. return a;
  20993. }, []);
  20994. };
  20995. function negate_iifes(statements, compressor) {
  20996. statements.forEach(function(stat){
  20997. if (stat instanceof AST_SimpleStatement) {
  20998. stat.body = (function transform(thing) {
  20999. return thing.transform(new TreeTransformer(function(node){
  21000. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  21001. return make_node(AST_UnaryPrefix, node, {
  21002. operator: "!",
  21003. expression: node
  21004. });
  21005. }
  21006. else if (node instanceof AST_Call) {
  21007. node.expression = transform(node.expression);
  21008. }
  21009. else if (node instanceof AST_Seq) {
  21010. node.car = transform(node.car);
  21011. }
  21012. else if (node instanceof AST_Conditional) {
  21013. var expr = transform(node.condition);
  21014. if (expr !== node.condition) {
  21015. // it has been negated, reverse
  21016. node.condition = expr;
  21017. var tmp = node.consequent;
  21018. node.consequent = node.alternative;
  21019. node.alternative = tmp;
  21020. }
  21021. }
  21022. return node;
  21023. }));
  21024. })(stat.body);
  21025. }
  21026. });
  21027. };
  21028. };
  21029. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  21030. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  21031. stat.walk(new TreeWalker(function(node){
  21032. if (node instanceof AST_Definitions) {
  21033. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  21034. node.remove_initializers();
  21035. target.push(node);
  21036. return true;
  21037. }
  21038. if (node instanceof AST_Defun) {
  21039. target.push(node);
  21040. return true;
  21041. }
  21042. if (node instanceof AST_Scope) {
  21043. return true;
  21044. }
  21045. }));
  21046. };
  21047. /* -----[ boolean/negation helpers ]----- */
  21048. // methods to determine whether an expression has a boolean result type
  21049. (function (def){
  21050. var unary_bool = [ "!", "delete" ];
  21051. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  21052. def(AST_Node, function(){ return false });
  21053. def(AST_UnaryPrefix, function(){
  21054. return member(this.operator, unary_bool);
  21055. });
  21056. def(AST_Binary, function(){
  21057. return member(this.operator, binary_bool) ||
  21058. ( (this.operator == "&&" || this.operator == "||") &&
  21059. this.left.is_boolean() && this.right.is_boolean() );
  21060. });
  21061. def(AST_Conditional, function(){
  21062. return this.consequent.is_boolean() && this.alternative.is_boolean();
  21063. });
  21064. def(AST_Assign, function(){
  21065. return this.operator == "=" && this.right.is_boolean();
  21066. });
  21067. def(AST_Seq, function(){
  21068. return this.cdr.is_boolean();
  21069. });
  21070. def(AST_True, function(){ return true });
  21071. def(AST_False, function(){ return true });
  21072. })(function(node, func){
  21073. node.DEFMETHOD("is_boolean", func);
  21074. });
  21075. // methods to determine if an expression has a string result type
  21076. (function (def){
  21077. def(AST_Node, function(){ return false });
  21078. def(AST_String, function(){ return true });
  21079. def(AST_UnaryPrefix, function(){
  21080. return this.operator == "typeof";
  21081. });
  21082. def(AST_Binary, function(compressor){
  21083. return this.operator == "+" &&
  21084. (this.left.is_string(compressor) || this.right.is_string(compressor));
  21085. });
  21086. def(AST_Assign, function(compressor){
  21087. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  21088. });
  21089. def(AST_Seq, function(compressor){
  21090. return this.cdr.is_string(compressor);
  21091. });
  21092. def(AST_Conditional, function(compressor){
  21093. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  21094. });
  21095. def(AST_Call, function(compressor){
  21096. return compressor.option("unsafe")
  21097. && this.expression instanceof AST_SymbolRef
  21098. && this.expression.name == "String"
  21099. && this.expression.undeclared();
  21100. });
  21101. })(function(node, func){
  21102. node.DEFMETHOD("is_string", func);
  21103. });
  21104. function best_of(ast1, ast2) {
  21105. return ast1.print_to_string().length >
  21106. ast2.print_to_string().length
  21107. ? ast2 : ast1;
  21108. };
  21109. // methods to evaluate a constant expression
  21110. (function (def){
  21111. // The evaluate method returns an array with one or two
  21112. // elements. If the node has been successfully reduced to a
  21113. // constant, then the second element tells us the value;
  21114. // otherwise the second element is missing. The first element
  21115. // of the array is always an AST_Node descendant; if
  21116. // evaluation was successful it's a node that represents the
  21117. // constant; otherwise it's the original or a replacement node.
  21118. AST_Node.DEFMETHOD("evaluate", function(compressor){
  21119. if (!compressor.option("evaluate")) return [ this ];
  21120. try {
  21121. var val = this._eval(compressor);
  21122. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  21123. } catch(ex) {
  21124. if (ex !== def) throw ex;
  21125. return [ this ];
  21126. }
  21127. });
  21128. def(AST_Statement, function(){
  21129. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  21130. });
  21131. def(AST_Function, function(){
  21132. // XXX: AST_Function inherits from AST_Scope, which itself
  21133. // inherits from AST_Statement; however, an AST_Function
  21134. // isn't really a statement. This could byte in other
  21135. // places too. :-( Wish JS had multiple inheritance.
  21136. throw def;
  21137. });
  21138. function ev(node, compressor) {
  21139. if (!compressor) throw new Error("Compressor must be passed");
  21140. return node._eval(compressor);
  21141. };
  21142. def(AST_Node, function(){
  21143. throw def; // not constant
  21144. });
  21145. def(AST_Constant, function(){
  21146. return this.getValue();
  21147. });
  21148. def(AST_UnaryPrefix, function(compressor){
  21149. var e = this.expression;
  21150. switch (this.operator) {
  21151. case "!": return !ev(e, compressor);
  21152. case "typeof":
  21153. // Function would be evaluated to an array and so typeof would
  21154. // incorrectly return 'object'. Hence making is a special case.
  21155. if (e instanceof AST_Function) return typeof function(){};
  21156. e = ev(e, compressor);
  21157. // typeof <RegExp> returns "object" or "function" on different platforms
  21158. // so cannot evaluate reliably
  21159. if (e instanceof RegExp) throw def;
  21160. return typeof e;
  21161. case "void": return void ev(e, compressor);
  21162. case "~": return ~ev(e, compressor);
  21163. case "-":
  21164. e = ev(e, compressor);
  21165. if (e === 0) throw def;
  21166. return -e;
  21167. case "+": return +ev(e, compressor);
  21168. }
  21169. throw def;
  21170. });
  21171. def(AST_Binary, function(c){
  21172. var left = this.left, right = this.right;
  21173. switch (this.operator) {
  21174. case "&&" : return ev(left, c) && ev(right, c);
  21175. case "||" : return ev(left, c) || ev(right, c);
  21176. case "|" : return ev(left, c) | ev(right, c);
  21177. case "&" : return ev(left, c) & ev(right, c);
  21178. case "^" : return ev(left, c) ^ ev(right, c);
  21179. case "+" : return ev(left, c) + ev(right, c);
  21180. case "*" : return ev(left, c) * ev(right, c);
  21181. case "/" : return ev(left, c) / ev(right, c);
  21182. case "%" : return ev(left, c) % ev(right, c);
  21183. case "-" : return ev(left, c) - ev(right, c);
  21184. case "<<" : return ev(left, c) << ev(right, c);
  21185. case ">>" : return ev(left, c) >> ev(right, c);
  21186. case ">>>" : return ev(left, c) >>> ev(right, c);
  21187. case "==" : return ev(left, c) == ev(right, c);
  21188. case "===" : return ev(left, c) === ev(right, c);
  21189. case "!=" : return ev(left, c) != ev(right, c);
  21190. case "!==" : return ev(left, c) !== ev(right, c);
  21191. case "<" : return ev(left, c) < ev(right, c);
  21192. case "<=" : return ev(left, c) <= ev(right, c);
  21193. case ">" : return ev(left, c) > ev(right, c);
  21194. case ">=" : return ev(left, c) >= ev(right, c);
  21195. case "in" : return ev(left, c) in ev(right, c);
  21196. case "instanceof" : return ev(left, c) instanceof ev(right, c);
  21197. }
  21198. throw def;
  21199. });
  21200. def(AST_Conditional, function(compressor){
  21201. return ev(this.condition, compressor)
  21202. ? ev(this.consequent, compressor)
  21203. : ev(this.alternative, compressor);
  21204. });
  21205. def(AST_SymbolRef, function(compressor){
  21206. var d = this.definition();
  21207. if (d && d.constant && d.init) return ev(d.init, compressor);
  21208. throw def;
  21209. });
  21210. def(AST_Dot, function(compressor){
  21211. if (compressor.option("unsafe") && this.property == "length") {
  21212. var str = ev(this.expression, compressor);
  21213. if (typeof str == "string")
  21214. return str.length;
  21215. }
  21216. throw def;
  21217. });
  21218. })(function(node, func){
  21219. node.DEFMETHOD("_eval", func);
  21220. });
  21221. // method to negate an expression
  21222. (function(def){
  21223. function basic_negation(exp) {
  21224. return make_node(AST_UnaryPrefix, exp, {
  21225. operator: "!",
  21226. expression: exp
  21227. });
  21228. };
  21229. def(AST_Node, function(){
  21230. return basic_negation(this);
  21231. });
  21232. def(AST_Statement, function(){
  21233. throw new Error("Cannot negate a statement");
  21234. });
  21235. def(AST_Function, function(){
  21236. return basic_negation(this);
  21237. });
  21238. def(AST_UnaryPrefix, function(){
  21239. if (this.operator == "!")
  21240. return this.expression;
  21241. return basic_negation(this);
  21242. });
  21243. def(AST_Seq, function(compressor){
  21244. var self = this.clone();
  21245. self.cdr = self.cdr.negate(compressor);
  21246. return self;
  21247. });
  21248. def(AST_Conditional, function(compressor){
  21249. var self = this.clone();
  21250. self.consequent = self.consequent.negate(compressor);
  21251. self.alternative = self.alternative.negate(compressor);
  21252. return best_of(basic_negation(this), self);
  21253. });
  21254. def(AST_Binary, function(compressor){
  21255. var self = this.clone(), op = this.operator;
  21256. if (compressor.option("unsafe_comps")) {
  21257. switch (op) {
  21258. case "<=" : self.operator = ">" ; return self;
  21259. case "<" : self.operator = ">=" ; return self;
  21260. case ">=" : self.operator = "<" ; return self;
  21261. case ">" : self.operator = "<=" ; return self;
  21262. }
  21263. }
  21264. switch (op) {
  21265. case "==" : self.operator = "!="; return self;
  21266. case "!=" : self.operator = "=="; return self;
  21267. case "===": self.operator = "!=="; return self;
  21268. case "!==": self.operator = "==="; return self;
  21269. case "&&":
  21270. self.operator = "||";
  21271. self.left = self.left.negate(compressor);
  21272. self.right = self.right.negate(compressor);
  21273. return best_of(basic_negation(this), self);
  21274. case "||":
  21275. self.operator = "&&";
  21276. self.left = self.left.negate(compressor);
  21277. self.right = self.right.negate(compressor);
  21278. return best_of(basic_negation(this), self);
  21279. }
  21280. return basic_negation(this);
  21281. });
  21282. })(function(node, func){
  21283. node.DEFMETHOD("negate", function(compressor){
  21284. return func.call(this, compressor);
  21285. });
  21286. });
  21287. // determine if expression has side effects
  21288. (function(def){
  21289. def(AST_Node, function(compressor){ return true });
  21290. def(AST_EmptyStatement, function(compressor){ return false });
  21291. def(AST_Constant, function(compressor){ return false });
  21292. def(AST_This, function(compressor){ return false });
  21293. def(AST_Call, function(compressor){
  21294. var pure = compressor.option("pure_funcs");
  21295. if (!pure) return true;
  21296. if (typeof pure == "function") return pure(this);
  21297. return pure.indexOf(this.expression.print_to_string()) < 0;
  21298. });
  21299. def(AST_Block, function(compressor){
  21300. for (var i = this.body.length; --i >= 0;) {
  21301. if (this.body[i].has_side_effects(compressor))
  21302. return true;
  21303. }
  21304. return false;
  21305. });
  21306. def(AST_SimpleStatement, function(compressor){
  21307. return this.body.has_side_effects(compressor);
  21308. });
  21309. def(AST_Defun, function(compressor){ return true });
  21310. def(AST_Function, function(compressor){ return false });
  21311. def(AST_Binary, function(compressor){
  21312. return this.left.has_side_effects(compressor)
  21313. || this.right.has_side_effects(compressor);
  21314. });
  21315. def(AST_Assign, function(compressor){ return true });
  21316. def(AST_Conditional, function(compressor){
  21317. return this.condition.has_side_effects(compressor)
  21318. || this.consequent.has_side_effects(compressor)
  21319. || this.alternative.has_side_effects(compressor);
  21320. });
  21321. def(AST_Unary, function(compressor){
  21322. return this.operator == "delete"
  21323. || this.operator == "++"
  21324. || this.operator == "--"
  21325. || this.expression.has_side_effects(compressor);
  21326. });
  21327. def(AST_SymbolRef, function(compressor){
  21328. return this.global() && this.undeclared();
  21329. });
  21330. def(AST_Object, function(compressor){
  21331. for (var i = this.properties.length; --i >= 0;)
  21332. if (this.properties[i].has_side_effects(compressor))
  21333. return true;
  21334. return false;
  21335. });
  21336. def(AST_ObjectProperty, function(compressor){
  21337. return this.value.has_side_effects(compressor);
  21338. });
  21339. def(AST_Array, function(compressor){
  21340. for (var i = this.elements.length; --i >= 0;)
  21341. if (this.elements[i].has_side_effects(compressor))
  21342. return true;
  21343. return false;
  21344. });
  21345. def(AST_Dot, function(compressor){
  21346. if (!compressor.option("pure_getters")) return true;
  21347. return this.expression.has_side_effects(compressor);
  21348. });
  21349. def(AST_Sub, function(compressor){
  21350. if (!compressor.option("pure_getters")) return true;
  21351. return this.expression.has_side_effects(compressor)
  21352. || this.property.has_side_effects(compressor);
  21353. });
  21354. def(AST_PropAccess, function(compressor){
  21355. return !compressor.option("pure_getters");
  21356. });
  21357. def(AST_Seq, function(compressor){
  21358. return this.car.has_side_effects(compressor)
  21359. || this.cdr.has_side_effects(compressor);
  21360. });
  21361. })(function(node, func){
  21362. node.DEFMETHOD("has_side_effects", func);
  21363. });
  21364. // tell me if a statement aborts
  21365. function aborts(thing) {
  21366. return thing && thing.aborts();
  21367. };
  21368. (function(def){
  21369. def(AST_Statement, function(){ return null });
  21370. def(AST_Jump, function(){ return this });
  21371. function block_aborts(){
  21372. var n = this.body.length;
  21373. return n > 0 && aborts(this.body[n - 1]);
  21374. };
  21375. def(AST_BlockStatement, block_aborts);
  21376. def(AST_SwitchBranch, block_aborts);
  21377. def(AST_If, function(){
  21378. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  21379. });
  21380. })(function(node, func){
  21381. node.DEFMETHOD("aborts", func);
  21382. });
  21383. /* -----[ optimizers ]----- */
  21384. OPT(AST_Directive, function(self, compressor){
  21385. if (compressor.has_directive(self.value) === "up") {
  21386. return make_node(AST_EmptyStatement, self);
  21387. }
  21388. return self;
  21389. });
  21390. OPT(AST_Debugger, function(self, compressor){
  21391. if (compressor.option("drop_debugger"))
  21392. return make_node(AST_EmptyStatement, self);
  21393. return self;
  21394. });
  21395. OPT(AST_LabeledStatement, function(self, compressor){
  21396. if (self.body instanceof AST_Break
  21397. && compressor.loopcontrol_target(self.body.label) === self.body) {
  21398. return make_node(AST_EmptyStatement, self);
  21399. }
  21400. return self.label.references.length == 0 ? self.body : self;
  21401. });
  21402. OPT(AST_Block, function(self, compressor){
  21403. self.body = tighten_body(self.body, compressor);
  21404. return self;
  21405. });
  21406. OPT(AST_BlockStatement, function(self, compressor){
  21407. self.body = tighten_body(self.body, compressor);
  21408. switch (self.body.length) {
  21409. case 1: return self.body[0];
  21410. case 0: return make_node(AST_EmptyStatement, self);
  21411. }
  21412. return self;
  21413. });
  21414. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  21415. var self = this;
  21416. if (compressor.has_directive("use asm")) return self;
  21417. if (compressor.option("unused")
  21418. && !(self instanceof AST_Toplevel)
  21419. && !self.uses_eval
  21420. ) {
  21421. var in_use = [];
  21422. var initializations = new Dictionary();
  21423. // pass 1: find out which symbols are directly used in
  21424. // this scope (not in nested scopes).
  21425. var scope = this;
  21426. var tw = new TreeWalker(function(node, descend){
  21427. if (node !== self) {
  21428. if (node instanceof AST_Defun) {
  21429. initializations.add(node.name.name, node);
  21430. return true; // don't go in nested scopes
  21431. }
  21432. if (node instanceof AST_Definitions && scope === self) {
  21433. node.definitions.forEach(function(def){
  21434. if (def.value) {
  21435. initializations.add(def.name.name, def.value);
  21436. if (def.value.has_side_effects(compressor)) {
  21437. def.value.walk(tw);
  21438. }
  21439. }
  21440. });
  21441. return true;
  21442. }
  21443. if (node instanceof AST_SymbolRef) {
  21444. push_uniq(in_use, node.definition());
  21445. return true;
  21446. }
  21447. if (node instanceof AST_Scope) {
  21448. var save_scope = scope;
  21449. scope = node;
  21450. descend();
  21451. scope = save_scope;
  21452. return true;
  21453. }
  21454. }
  21455. });
  21456. self.walk(tw);
  21457. // pass 2: for every used symbol we need to walk its
  21458. // initialization code to figure out if it uses other
  21459. // symbols (that may not be in_use).
  21460. for (var i = 0; i < in_use.length; ++i) {
  21461. in_use[i].orig.forEach(function(decl){
  21462. // undeclared globals will be instanceof AST_SymbolRef
  21463. var init = initializations.get(decl.name);
  21464. if (init) init.forEach(function(init){
  21465. var tw = new TreeWalker(function(node){
  21466. if (node instanceof AST_SymbolRef) {
  21467. push_uniq(in_use, node.definition());
  21468. }
  21469. });
  21470. init.walk(tw);
  21471. });
  21472. });
  21473. }
  21474. // pass 3: we should drop declarations not in_use
  21475. var tt = new TreeTransformer(
  21476. function before(node, descend, in_list) {
  21477. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  21478. if (!compressor.option("keep_fargs")) {
  21479. for (var a = node.argnames, i = a.length; --i >= 0;) {
  21480. var sym = a[i];
  21481. if (sym.unreferenced()) {
  21482. a.pop();
  21483. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  21484. name : sym.name,
  21485. file : sym.start.file,
  21486. line : sym.start.line,
  21487. col : sym.start.col
  21488. });
  21489. }
  21490. else break;
  21491. }
  21492. }
  21493. }
  21494. if (node instanceof AST_Defun && node !== self) {
  21495. if (!member(node.name.definition(), in_use)) {
  21496. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  21497. name : node.name.name,
  21498. file : node.name.start.file,
  21499. line : node.name.start.line,
  21500. col : node.name.start.col
  21501. });
  21502. return make_node(AST_EmptyStatement, node);
  21503. }
  21504. return node;
  21505. }
  21506. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  21507. var def = node.definitions.filter(function(def){
  21508. if (member(def.name.definition(), in_use)) return true;
  21509. var w = {
  21510. name : def.name.name,
  21511. file : def.name.start.file,
  21512. line : def.name.start.line,
  21513. col : def.name.start.col
  21514. };
  21515. if (def.value && def.value.has_side_effects(compressor)) {
  21516. def._unused_side_effects = true;
  21517. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  21518. return true;
  21519. }
  21520. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  21521. return false;
  21522. });
  21523. // place uninitialized names at the start
  21524. def = mergeSort(def, function(a, b){
  21525. if (!a.value && b.value) return -1;
  21526. if (!b.value && a.value) return 1;
  21527. return 0;
  21528. });
  21529. // for unused names whose initialization has
  21530. // side effects, we can cascade the init. code
  21531. // into the next one, or next statement.
  21532. var side_effects = [];
  21533. for (var i = 0; i < def.length;) {
  21534. var x = def[i];
  21535. if (x._unused_side_effects) {
  21536. side_effects.push(x.value);
  21537. def.splice(i, 1);
  21538. } else {
  21539. if (side_effects.length > 0) {
  21540. side_effects.push(x.value);
  21541. x.value = AST_Seq.from_array(side_effects);
  21542. side_effects = [];
  21543. }
  21544. ++i;
  21545. }
  21546. }
  21547. if (side_effects.length > 0) {
  21548. side_effects = make_node(AST_BlockStatement, node, {
  21549. body: [ make_node(AST_SimpleStatement, node, {
  21550. body: AST_Seq.from_array(side_effects)
  21551. }) ]
  21552. });
  21553. } else {
  21554. side_effects = null;
  21555. }
  21556. if (def.length == 0 && !side_effects) {
  21557. return make_node(AST_EmptyStatement, node);
  21558. }
  21559. if (def.length == 0) {
  21560. return in_list ? MAP.splice(side_effects.body) : side_effects;
  21561. }
  21562. node.definitions = def;
  21563. if (side_effects) {
  21564. side_effects.body.unshift(node);
  21565. return in_list ? MAP.splice(side_effects.body) : side_effects;
  21566. }
  21567. return node;
  21568. }
  21569. if (node instanceof AST_For) {
  21570. descend(node, this);
  21571. if (node.init instanceof AST_BlockStatement) {
  21572. // certain combination of unused name + side effect leads to:
  21573. // https://github.com/mishoo/UglifyJS2/issues/44
  21574. // that's an invalid AST.
  21575. // We fix it at this stage by moving the `var` outside the `for`.
  21576. var body = node.init.body.slice(0, -1);
  21577. node.init = node.init.body.slice(-1)[0].body;
  21578. body.push(node);
  21579. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  21580. body: body
  21581. });
  21582. }
  21583. }
  21584. if (node instanceof AST_Scope && node !== self)
  21585. return node;
  21586. }
  21587. );
  21588. self.transform(tt);
  21589. }
  21590. });
  21591. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  21592. var self = this;
  21593. if (compressor.has_directive("use asm")) return self;
  21594. var hoist_funs = compressor.option("hoist_funs");
  21595. var hoist_vars = compressor.option("hoist_vars");
  21596. if (hoist_funs || hoist_vars) {
  21597. var dirs = [];
  21598. var hoisted = [];
  21599. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  21600. // let's count var_decl first, we seem to waste a lot of
  21601. // space if we hoist `var` when there's only one.
  21602. self.walk(new TreeWalker(function(node){
  21603. if (node instanceof AST_Scope && node !== self)
  21604. return true;
  21605. if (node instanceof AST_Var) {
  21606. ++var_decl;
  21607. return true;
  21608. }
  21609. }));
  21610. hoist_vars = hoist_vars && var_decl > 1;
  21611. var tt = new TreeTransformer(
  21612. function before(node) {
  21613. if (node !== self) {
  21614. if (node instanceof AST_Directive) {
  21615. dirs.push(node);
  21616. return make_node(AST_EmptyStatement, node);
  21617. }
  21618. if (node instanceof AST_Defun && hoist_funs) {
  21619. hoisted.push(node);
  21620. return make_node(AST_EmptyStatement, node);
  21621. }
  21622. if (node instanceof AST_Var && hoist_vars) {
  21623. node.definitions.forEach(function(def){
  21624. vars.set(def.name.name, def);
  21625. ++vars_found;
  21626. });
  21627. var seq = node.to_assignments();
  21628. var p = tt.parent();
  21629. if (p instanceof AST_ForIn && p.init === node) {
  21630. if (seq == null) return node.definitions[0].name;
  21631. return seq;
  21632. }
  21633. if (p instanceof AST_For && p.init === node) {
  21634. return seq;
  21635. }
  21636. if (!seq) return make_node(AST_EmptyStatement, node);
  21637. return make_node(AST_SimpleStatement, node, {
  21638. body: seq
  21639. });
  21640. }
  21641. if (node instanceof AST_Scope)
  21642. return node; // to avoid descending in nested scopes
  21643. }
  21644. }
  21645. );
  21646. self = self.transform(tt);
  21647. if (vars_found > 0) {
  21648. // collect only vars which don't show up in self's arguments list
  21649. var defs = [];
  21650. vars.each(function(def, name){
  21651. if (self instanceof AST_Lambda
  21652. && find_if(function(x){ return x.name == def.name.name },
  21653. self.argnames)) {
  21654. vars.del(name);
  21655. } else {
  21656. def = def.clone();
  21657. def.value = null;
  21658. defs.push(def);
  21659. vars.set(name, def);
  21660. }
  21661. });
  21662. if (defs.length > 0) {
  21663. // try to merge in assignments
  21664. for (var i = 0; i < self.body.length;) {
  21665. if (self.body[i] instanceof AST_SimpleStatement) {
  21666. var expr = self.body[i].body, sym, assign;
  21667. if (expr instanceof AST_Assign
  21668. && expr.operator == "="
  21669. && (sym = expr.left) instanceof AST_Symbol
  21670. && vars.has(sym.name))
  21671. {
  21672. var def = vars.get(sym.name);
  21673. if (def.value) break;
  21674. def.value = expr.right;
  21675. remove(defs, def);
  21676. defs.push(def);
  21677. self.body.splice(i, 1);
  21678. continue;
  21679. }
  21680. if (expr instanceof AST_Seq
  21681. && (assign = expr.car) instanceof AST_Assign
  21682. && assign.operator == "="
  21683. && (sym = assign.left) instanceof AST_Symbol
  21684. && vars.has(sym.name))
  21685. {
  21686. var def = vars.get(sym.name);
  21687. if (def.value) break;
  21688. def.value = assign.right;
  21689. remove(defs, def);
  21690. defs.push(def);
  21691. self.body[i].body = expr.cdr;
  21692. continue;
  21693. }
  21694. }
  21695. if (self.body[i] instanceof AST_EmptyStatement) {
  21696. self.body.splice(i, 1);
  21697. continue;
  21698. }
  21699. if (self.body[i] instanceof AST_BlockStatement) {
  21700. var tmp = [ i, 1 ].concat(self.body[i].body);
  21701. self.body.splice.apply(self.body, tmp);
  21702. continue;
  21703. }
  21704. break;
  21705. }
  21706. defs = make_node(AST_Var, self, {
  21707. definitions: defs
  21708. });
  21709. hoisted.push(defs);
  21710. };
  21711. }
  21712. self.body = dirs.concat(hoisted, self.body);
  21713. }
  21714. return self;
  21715. });
  21716. OPT(AST_SimpleStatement, function(self, compressor){
  21717. if (compressor.option("side_effects")) {
  21718. if (!self.body.has_side_effects(compressor)) {
  21719. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  21720. return make_node(AST_EmptyStatement, self);
  21721. }
  21722. }
  21723. return self;
  21724. });
  21725. OPT(AST_DWLoop, function(self, compressor){
  21726. var cond = self.condition.evaluate(compressor);
  21727. self.condition = cond[0];
  21728. if (!compressor.option("loops")) return self;
  21729. if (cond.length > 1) {
  21730. if (cond[1]) {
  21731. return make_node(AST_For, self, {
  21732. body: self.body
  21733. });
  21734. } else if (self instanceof AST_While) {
  21735. if (compressor.option("dead_code")) {
  21736. var a = [];
  21737. extract_declarations_from_unreachable_code(compressor, self.body, a);
  21738. return make_node(AST_BlockStatement, self, { body: a });
  21739. }
  21740. }
  21741. }
  21742. return self;
  21743. });
  21744. function if_break_in_loop(self, compressor) {
  21745. function drop_it(rest) {
  21746. rest = as_statement_array(rest);
  21747. if (self.body instanceof AST_BlockStatement) {
  21748. self.body = self.body.clone();
  21749. self.body.body = rest.concat(self.body.body.slice(1));
  21750. self.body = self.body.transform(compressor);
  21751. } else {
  21752. self.body = make_node(AST_BlockStatement, self.body, {
  21753. body: rest
  21754. }).transform(compressor);
  21755. }
  21756. if_break_in_loop(self, compressor);
  21757. }
  21758. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  21759. if (first instanceof AST_If) {
  21760. if (first.body instanceof AST_Break
  21761. && compressor.loopcontrol_target(first.body.label) === self) {
  21762. if (self.condition) {
  21763. self.condition = make_node(AST_Binary, self.condition, {
  21764. left: self.condition,
  21765. operator: "&&",
  21766. right: first.condition.negate(compressor),
  21767. });
  21768. } else {
  21769. self.condition = first.condition.negate(compressor);
  21770. }
  21771. drop_it(first.alternative);
  21772. }
  21773. else if (first.alternative instanceof AST_Break
  21774. && compressor.loopcontrol_target(first.alternative.label) === self) {
  21775. if (self.condition) {
  21776. self.condition = make_node(AST_Binary, self.condition, {
  21777. left: self.condition,
  21778. operator: "&&",
  21779. right: first.condition,
  21780. });
  21781. } else {
  21782. self.condition = first.condition;
  21783. }
  21784. drop_it(first.body);
  21785. }
  21786. }
  21787. };
  21788. OPT(AST_While, function(self, compressor) {
  21789. if (!compressor.option("loops")) return self;
  21790. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  21791. if (self instanceof AST_While) {
  21792. if_break_in_loop(self, compressor);
  21793. self = make_node(AST_For, self, self).transform(compressor);
  21794. }
  21795. return self;
  21796. });
  21797. OPT(AST_For, function(self, compressor){
  21798. var cond = self.condition;
  21799. if (cond) {
  21800. cond = cond.evaluate(compressor);
  21801. self.condition = cond[0];
  21802. }
  21803. if (!compressor.option("loops")) return self;
  21804. if (cond) {
  21805. if (cond.length > 1 && !cond[1]) {
  21806. if (compressor.option("dead_code")) {
  21807. var a = [];
  21808. if (self.init instanceof AST_Statement) {
  21809. a.push(self.init);
  21810. }
  21811. else if (self.init) {
  21812. a.push(make_node(AST_SimpleStatement, self.init, {
  21813. body: self.init
  21814. }));
  21815. }
  21816. extract_declarations_from_unreachable_code(compressor, self.body, a);
  21817. return make_node(AST_BlockStatement, self, { body: a });
  21818. }
  21819. }
  21820. }
  21821. if_break_in_loop(self, compressor);
  21822. return self;
  21823. });
  21824. OPT(AST_If, function(self, compressor){
  21825. if (!compressor.option("conditionals")) return self;
  21826. // if condition can be statically determined, warn and drop
  21827. // one of the blocks. note, statically determined implies
  21828. // “has no side effects”; also it doesn't work for cases like
  21829. // `x && true`, though it probably should.
  21830. var cond = self.condition.evaluate(compressor);
  21831. self.condition = cond[0];
  21832. if (cond.length > 1) {
  21833. if (cond[1]) {
  21834. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  21835. if (compressor.option("dead_code")) {
  21836. var a = [];
  21837. if (self.alternative) {
  21838. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  21839. }
  21840. a.push(self.body);
  21841. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  21842. }
  21843. } else {
  21844. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  21845. if (compressor.option("dead_code")) {
  21846. var a = [];
  21847. extract_declarations_from_unreachable_code(compressor, self.body, a);
  21848. if (self.alternative) a.push(self.alternative);
  21849. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  21850. }
  21851. }
  21852. }
  21853. if (is_empty(self.alternative)) self.alternative = null;
  21854. var negated = self.condition.negate(compressor);
  21855. var negated_is_best = best_of(self.condition, negated) === negated;
  21856. if (self.alternative && negated_is_best) {
  21857. negated_is_best = false; // because we already do the switch here.
  21858. self.condition = negated;
  21859. var tmp = self.body;
  21860. self.body = self.alternative || make_node(AST_EmptyStatement);
  21861. self.alternative = tmp;
  21862. }
  21863. if (is_empty(self.body) && is_empty(self.alternative)) {
  21864. return make_node(AST_SimpleStatement, self.condition, {
  21865. body: self.condition
  21866. }).transform(compressor);
  21867. }
  21868. if (self.body instanceof AST_SimpleStatement
  21869. && self.alternative instanceof AST_SimpleStatement) {
  21870. return make_node(AST_SimpleStatement, self, {
  21871. body: make_node(AST_Conditional, self, {
  21872. condition : self.condition,
  21873. consequent : self.body.body,
  21874. alternative : self.alternative.body
  21875. })
  21876. }).transform(compressor);
  21877. }
  21878. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  21879. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  21880. body: make_node(AST_Binary, self, {
  21881. operator : "||",
  21882. left : negated,
  21883. right : self.body.body
  21884. })
  21885. }).transform(compressor);
  21886. return make_node(AST_SimpleStatement, self, {
  21887. body: make_node(AST_Binary, self, {
  21888. operator : "&&",
  21889. left : self.condition,
  21890. right : self.body.body
  21891. })
  21892. }).transform(compressor);
  21893. }
  21894. if (self.body instanceof AST_EmptyStatement
  21895. && self.alternative
  21896. && self.alternative instanceof AST_SimpleStatement) {
  21897. return make_node(AST_SimpleStatement, self, {
  21898. body: make_node(AST_Binary, self, {
  21899. operator : "||",
  21900. left : self.condition,
  21901. right : self.alternative.body
  21902. })
  21903. }).transform(compressor);
  21904. }
  21905. if (self.body instanceof AST_Exit
  21906. && self.alternative instanceof AST_Exit
  21907. && self.body.TYPE == self.alternative.TYPE) {
  21908. return make_node(self.body.CTOR, self, {
  21909. value: make_node(AST_Conditional, self, {
  21910. condition : self.condition,
  21911. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  21912. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  21913. })
  21914. }).transform(compressor);
  21915. }
  21916. if (self.body instanceof AST_If
  21917. && !self.body.alternative
  21918. && !self.alternative) {
  21919. self.condition = make_node(AST_Binary, self.condition, {
  21920. operator: "&&",
  21921. left: self.condition,
  21922. right: self.body.condition
  21923. }).transform(compressor);
  21924. self.body = self.body.body;
  21925. }
  21926. if (aborts(self.body)) {
  21927. if (self.alternative) {
  21928. var alt = self.alternative;
  21929. self.alternative = null;
  21930. return make_node(AST_BlockStatement, self, {
  21931. body: [ self, alt ]
  21932. }).transform(compressor);
  21933. }
  21934. }
  21935. if (aborts(self.alternative)) {
  21936. var body = self.body;
  21937. self.body = self.alternative;
  21938. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  21939. self.alternative = null;
  21940. return make_node(AST_BlockStatement, self, {
  21941. body: [ self, body ]
  21942. }).transform(compressor);
  21943. }
  21944. return self;
  21945. });
  21946. OPT(AST_Switch, function(self, compressor){
  21947. if (self.body.length == 0 && compressor.option("conditionals")) {
  21948. return make_node(AST_SimpleStatement, self, {
  21949. body: self.expression
  21950. }).transform(compressor);
  21951. }
  21952. for(;;) {
  21953. var last_branch = self.body[self.body.length - 1];
  21954. if (last_branch) {
  21955. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  21956. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  21957. last_branch.body.pop();
  21958. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  21959. self.body.pop();
  21960. continue;
  21961. }
  21962. }
  21963. break;
  21964. }
  21965. var exp = self.expression.evaluate(compressor);
  21966. out: if (exp.length == 2) try {
  21967. // constant expression
  21968. self.expression = exp[0];
  21969. if (!compressor.option("dead_code")) break out;
  21970. var value = exp[1];
  21971. var in_if = false;
  21972. var in_block = false;
  21973. var started = false;
  21974. var stopped = false;
  21975. var ruined = false;
  21976. var tt = new TreeTransformer(function(node, descend, in_list){
  21977. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  21978. // no need to descend these node types
  21979. return node;
  21980. }
  21981. else if (node instanceof AST_Switch && node === self) {
  21982. node = node.clone();
  21983. descend(node, this);
  21984. return ruined ? node : make_node(AST_BlockStatement, node, {
  21985. body: node.body.reduce(function(a, branch){
  21986. return a.concat(branch.body);
  21987. }, [])
  21988. }).transform(compressor);
  21989. }
  21990. else if (node instanceof AST_If || node instanceof AST_Try) {
  21991. var save = in_if;
  21992. in_if = !in_block;
  21993. descend(node, this);
  21994. in_if = save;
  21995. return node;
  21996. }
  21997. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  21998. var save = in_block;
  21999. in_block = true;
  22000. descend(node, this);
  22001. in_block = save;
  22002. return node;
  22003. }
  22004. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  22005. if (in_if) {
  22006. ruined = true;
  22007. return node;
  22008. }
  22009. if (in_block) return node;
  22010. stopped = true;
  22011. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  22012. }
  22013. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  22014. if (stopped) return MAP.skip;
  22015. if (node instanceof AST_Case) {
  22016. var exp = node.expression.evaluate(compressor);
  22017. if (exp.length < 2) {
  22018. // got a case with non-constant expression, baling out
  22019. throw self;
  22020. }
  22021. if (exp[1] === value || started) {
  22022. started = true;
  22023. if (aborts(node)) stopped = true;
  22024. descend(node, this);
  22025. return node;
  22026. }
  22027. return MAP.skip;
  22028. }
  22029. descend(node, this);
  22030. return node;
  22031. }
  22032. });
  22033. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  22034. self = self.transform(tt);
  22035. } catch(ex) {
  22036. if (ex !== self) throw ex;
  22037. }
  22038. return self;
  22039. });
  22040. OPT(AST_Case, function(self, compressor){
  22041. self.body = tighten_body(self.body, compressor);
  22042. return self;
  22043. });
  22044. OPT(AST_Try, function(self, compressor){
  22045. self.body = tighten_body(self.body, compressor);
  22046. return self;
  22047. });
  22048. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  22049. this.definitions.forEach(function(def){ def.value = null });
  22050. });
  22051. AST_Definitions.DEFMETHOD("to_assignments", function(){
  22052. var assignments = this.definitions.reduce(function(a, def){
  22053. if (def.value) {
  22054. var name = make_node(AST_SymbolRef, def.name, def.name);
  22055. a.push(make_node(AST_Assign, def, {
  22056. operator : "=",
  22057. left : name,
  22058. right : def.value
  22059. }));
  22060. }
  22061. return a;
  22062. }, []);
  22063. if (assignments.length == 0) return null;
  22064. return AST_Seq.from_array(assignments);
  22065. });
  22066. OPT(AST_Definitions, function(self, compressor){
  22067. if (self.definitions.length == 0)
  22068. return make_node(AST_EmptyStatement, self);
  22069. return self;
  22070. });
  22071. OPT(AST_Function, function(self, compressor){
  22072. self = AST_Lambda.prototype.optimize.call(self, compressor);
  22073. if (compressor.option("unused") && !compressor.option("keep_fnames")) {
  22074. if (self.name && self.name.unreferenced()) {
  22075. self.name = null;
  22076. }
  22077. }
  22078. return self;
  22079. });
  22080. OPT(AST_Call, function(self, compressor){
  22081. if (compressor.option("unsafe")) {
  22082. var exp = self.expression;
  22083. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  22084. switch (exp.name) {
  22085. case "Array":
  22086. if (self.args.length != 1) {
  22087. return make_node(AST_Array, self, {
  22088. elements: self.args
  22089. }).transform(compressor);
  22090. }
  22091. break;
  22092. case "Object":
  22093. if (self.args.length == 0) {
  22094. return make_node(AST_Object, self, {
  22095. properties: []
  22096. });
  22097. }
  22098. break;
  22099. case "String":
  22100. if (self.args.length == 0) return make_node(AST_String, self, {
  22101. value: ""
  22102. });
  22103. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  22104. left: self.args[0],
  22105. operator: "+",
  22106. right: make_node(AST_String, self, { value: "" })
  22107. }).transform(compressor);
  22108. break;
  22109. case "Number":
  22110. if (self.args.length == 0) return make_node(AST_Number, self, {
  22111. value: 0
  22112. });
  22113. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  22114. expression: self.args[0],
  22115. operator: "+"
  22116. }).transform(compressor);
  22117. case "Boolean":
  22118. if (self.args.length == 0) return make_node(AST_False, self);
  22119. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  22120. expression: make_node(AST_UnaryPrefix, null, {
  22121. expression: self.args[0],
  22122. operator: "!"
  22123. }),
  22124. operator: "!"
  22125. }).transform(compressor);
  22126. break;
  22127. case "Function":
  22128. // new Function() => function(){}
  22129. if (self.args.length == 0) return make_node(AST_Function, self, {
  22130. argnames: [],
  22131. body: []
  22132. });
  22133. if (all(self.args, function(x){ return x instanceof AST_String })) {
  22134. // quite a corner-case, but we can handle it:
  22135. // https://github.com/mishoo/UglifyJS2/issues/203
  22136. // if the code argument is a constant, then we can minify it.
  22137. try {
  22138. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  22139. return arg.value;
  22140. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  22141. var ast = parse(code);
  22142. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  22143. var comp = new Compressor(compressor.options);
  22144. ast = ast.transform(comp);
  22145. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  22146. ast.mangle_names();
  22147. var fun;
  22148. try {
  22149. ast.walk(new TreeWalker(function(node){
  22150. if (node instanceof AST_Lambda) {
  22151. fun = node;
  22152. throw ast;
  22153. }
  22154. }));
  22155. } catch(ex) {
  22156. if (ex !== ast) throw ex;
  22157. };
  22158. if (!fun) return self;
  22159. var args = fun.argnames.map(function(arg, i){
  22160. return make_node(AST_String, self.args[i], {
  22161. value: arg.print_to_string()
  22162. });
  22163. });
  22164. var code = OutputStream();
  22165. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  22166. code = code.toString().replace(/^\{|\}$/g, "");
  22167. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  22168. value: code
  22169. }));
  22170. self.args = args;
  22171. return self;
  22172. } catch(ex) {
  22173. if (ex instanceof JS_Parse_Error) {
  22174. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  22175. compressor.warn(ex.toString());
  22176. } else {
  22177. console.log(ex);
  22178. throw ex;
  22179. }
  22180. }
  22181. }
  22182. break;
  22183. }
  22184. }
  22185. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  22186. return make_node(AST_Binary, self, {
  22187. left: make_node(AST_String, self, { value: "" }),
  22188. operator: "+",
  22189. right: exp.expression
  22190. }).transform(compressor);
  22191. }
  22192. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  22193. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  22194. if (separator == null) break EXIT; // not a constant
  22195. var elements = exp.expression.elements.reduce(function(a, el){
  22196. el = el.evaluate(compressor);
  22197. if (a.length == 0 || el.length == 1) {
  22198. a.push(el);
  22199. } else {
  22200. var last = a[a.length - 1];
  22201. if (last.length == 2) {
  22202. // it's a constant
  22203. var val = "" + last[1] + separator + el[1];
  22204. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  22205. } else {
  22206. a.push(el);
  22207. }
  22208. }
  22209. return a;
  22210. }, []);
  22211. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  22212. if (elements.length == 1) return elements[0][0];
  22213. if (separator == "") {
  22214. var first;
  22215. if (elements[0][0] instanceof AST_String
  22216. || elements[1][0] instanceof AST_String) {
  22217. first = elements.shift()[0];
  22218. } else {
  22219. first = make_node(AST_String, self, { value: "" });
  22220. }
  22221. return elements.reduce(function(prev, el){
  22222. return make_node(AST_Binary, el[0], {
  22223. operator : "+",
  22224. left : prev,
  22225. right : el[0],
  22226. });
  22227. }, first).transform(compressor);
  22228. }
  22229. // need this awkward cloning to not affect original element
  22230. // best_of will decide which one to get through.
  22231. var node = self.clone();
  22232. node.expression = node.expression.clone();
  22233. node.expression.expression = node.expression.expression.clone();
  22234. node.expression.expression.elements = elements.map(function(el){
  22235. return el[0];
  22236. });
  22237. return best_of(self, node);
  22238. }
  22239. }
  22240. if (compressor.option("side_effects")) {
  22241. if (self.expression instanceof AST_Function
  22242. && self.args.length == 0
  22243. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  22244. return make_node(AST_Undefined, self).transform(compressor);
  22245. }
  22246. }
  22247. if (compressor.option("drop_console")) {
  22248. if (self.expression instanceof AST_PropAccess) {
  22249. var name = self.expression.expression;
  22250. while (name.expression) {
  22251. name = name.expression;
  22252. }
  22253. if (name instanceof AST_SymbolRef
  22254. && name.name == "console"
  22255. && name.undeclared()) {
  22256. return make_node(AST_Undefined, self).transform(compressor);
  22257. }
  22258. }
  22259. }
  22260. return self.evaluate(compressor)[0];
  22261. });
  22262. OPT(AST_New, function(self, compressor){
  22263. if (compressor.option("unsafe")) {
  22264. var exp = self.expression;
  22265. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  22266. switch (exp.name) {
  22267. case "Object":
  22268. case "RegExp":
  22269. case "Function":
  22270. case "Error":
  22271. case "Array":
  22272. return make_node(AST_Call, self, self).transform(compressor);
  22273. }
  22274. }
  22275. }
  22276. return self;
  22277. });
  22278. OPT(AST_Seq, function(self, compressor){
  22279. if (!compressor.option("side_effects"))
  22280. return self;
  22281. if (!self.car.has_side_effects(compressor)) {
  22282. // we shouldn't compress (1,func)(something) to
  22283. // func(something) because that changes the meaning of
  22284. // the func (becomes lexical instead of global).
  22285. var p = compressor.parent();
  22286. if (!(p instanceof AST_Call && p.expression === self)) {
  22287. return self.cdr;
  22288. }
  22289. }
  22290. if (compressor.option("cascade")) {
  22291. if (self.car instanceof AST_Assign
  22292. && !self.car.left.has_side_effects(compressor)) {
  22293. if (self.car.left.equivalent_to(self.cdr)) {
  22294. return self.car;
  22295. }
  22296. if (self.cdr instanceof AST_Call
  22297. && self.cdr.expression.equivalent_to(self.car.left)) {
  22298. self.cdr.expression = self.car;
  22299. return self.cdr;
  22300. }
  22301. }
  22302. if (!self.car.has_side_effects(compressor)
  22303. && !self.cdr.has_side_effects(compressor)
  22304. && self.car.equivalent_to(self.cdr)) {
  22305. return self.car;
  22306. }
  22307. }
  22308. if (self.cdr instanceof AST_UnaryPrefix
  22309. && self.cdr.operator == "void"
  22310. && !self.cdr.expression.has_side_effects(compressor)) {
  22311. self.cdr.expression = self.car;
  22312. return self.cdr;
  22313. }
  22314. if (self.cdr instanceof AST_Undefined) {
  22315. return make_node(AST_UnaryPrefix, self, {
  22316. operator : "void",
  22317. expression : self.car
  22318. });
  22319. }
  22320. return self;
  22321. });
  22322. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  22323. if (compressor.option("sequences")) {
  22324. if (this.expression instanceof AST_Seq) {
  22325. var seq = this.expression;
  22326. var x = seq.to_array();
  22327. this.expression = x.pop();
  22328. x.push(this);
  22329. seq = AST_Seq.from_array(x).transform(compressor);
  22330. return seq;
  22331. }
  22332. }
  22333. return this;
  22334. });
  22335. OPT(AST_UnaryPostfix, function(self, compressor){
  22336. return self.lift_sequences(compressor);
  22337. });
  22338. OPT(AST_UnaryPrefix, function(self, compressor){
  22339. self = self.lift_sequences(compressor);
  22340. var e = self.expression;
  22341. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  22342. switch (self.operator) {
  22343. case "!":
  22344. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  22345. // !!foo ==> foo, if we're in boolean context
  22346. return e.expression;
  22347. }
  22348. break;
  22349. case "typeof":
  22350. // typeof always returns a non-empty string, thus it's
  22351. // always true in booleans
  22352. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  22353. return make_node(AST_True, self);
  22354. }
  22355. if (e instanceof AST_Binary && self.operator == "!") {
  22356. self = best_of(self, e.negate(compressor));
  22357. }
  22358. }
  22359. return self.evaluate(compressor)[0];
  22360. });
  22361. function has_side_effects_or_prop_access(node, compressor) {
  22362. var save_pure_getters = compressor.option("pure_getters");
  22363. compressor.options.pure_getters = false;
  22364. var ret = node.has_side_effects(compressor);
  22365. compressor.options.pure_getters = save_pure_getters;
  22366. return ret;
  22367. }
  22368. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  22369. if (compressor.option("sequences")) {
  22370. if (this.left instanceof AST_Seq) {
  22371. var seq = this.left;
  22372. var x = seq.to_array();
  22373. this.left = x.pop();
  22374. x.push(this);
  22375. seq = AST_Seq.from_array(x).transform(compressor);
  22376. return seq;
  22377. }
  22378. if (this.right instanceof AST_Seq
  22379. && this instanceof AST_Assign
  22380. && !has_side_effects_or_prop_access(this.left, compressor)) {
  22381. var seq = this.right;
  22382. var x = seq.to_array();
  22383. this.right = x.pop();
  22384. x.push(this);
  22385. seq = AST_Seq.from_array(x).transform(compressor);
  22386. return seq;
  22387. }
  22388. }
  22389. return this;
  22390. });
  22391. var commutativeOperators = makePredicate("== === != !== * & | ^");
  22392. OPT(AST_Binary, function(self, compressor){
  22393. function reverse(op, force) {
  22394. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  22395. if (op) self.operator = op;
  22396. var tmp = self.left;
  22397. self.left = self.right;
  22398. self.right = tmp;
  22399. }
  22400. }
  22401. if (commutativeOperators(self.operator)) {
  22402. if (self.right instanceof AST_Constant
  22403. && !(self.left instanceof AST_Constant)) {
  22404. // if right is a constant, whatever side effects the
  22405. // left side might have could not influence the
  22406. // result. hence, force switch.
  22407. if (!(self.left instanceof AST_Binary
  22408. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  22409. reverse(null, true);
  22410. }
  22411. }
  22412. if (/^[!=]==?$/.test(self.operator)) {
  22413. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  22414. if (self.right.consequent instanceof AST_SymbolRef
  22415. && self.right.consequent.definition() === self.left.definition()) {
  22416. if (/^==/.test(self.operator)) return self.right.condition;
  22417. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  22418. }
  22419. if (self.right.alternative instanceof AST_SymbolRef
  22420. && self.right.alternative.definition() === self.left.definition()) {
  22421. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  22422. if (/^!=/.test(self.operator)) return self.right.condition;
  22423. }
  22424. }
  22425. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  22426. if (self.left.consequent instanceof AST_SymbolRef
  22427. && self.left.consequent.definition() === self.right.definition()) {
  22428. if (/^==/.test(self.operator)) return self.left.condition;
  22429. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  22430. }
  22431. if (self.left.alternative instanceof AST_SymbolRef
  22432. && self.left.alternative.definition() === self.right.definition()) {
  22433. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  22434. if (/^!=/.test(self.operator)) return self.left.condition;
  22435. }
  22436. }
  22437. }
  22438. }
  22439. self = self.lift_sequences(compressor);
  22440. if (compressor.option("comparisons")) switch (self.operator) {
  22441. case "===":
  22442. case "!==":
  22443. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  22444. (self.left.is_boolean() && self.right.is_boolean())) {
  22445. self.operator = self.operator.substr(0, 2);
  22446. }
  22447. // XXX: intentionally falling down to the next case
  22448. case "==":
  22449. case "!=":
  22450. if (self.left instanceof AST_String
  22451. && self.left.value == "undefined"
  22452. && self.right instanceof AST_UnaryPrefix
  22453. && self.right.operator == "typeof"
  22454. && compressor.option("unsafe")) {
  22455. if (!(self.right.expression instanceof AST_SymbolRef)
  22456. || !self.right.expression.undeclared()) {
  22457. self.right = self.right.expression;
  22458. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  22459. if (self.operator.length == 2) self.operator += "=";
  22460. }
  22461. }
  22462. break;
  22463. }
  22464. if (compressor.option("conditionals")) {
  22465. if (self.operator == "&&") {
  22466. var ll = self.left.evaluate(compressor);
  22467. if (ll.length > 1) {
  22468. if (ll[1]) {
  22469. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  22470. var rr = self.right.evaluate(compressor);
  22471. return rr[0];
  22472. } else {
  22473. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  22474. return ll[0];
  22475. }
  22476. }
  22477. }
  22478. else if (self.operator == "||") {
  22479. var ll = self.left.evaluate(compressor);
  22480. if (ll.length > 1) {
  22481. if (ll[1]) {
  22482. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  22483. return ll[0];
  22484. } else {
  22485. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  22486. var rr = self.right.evaluate(compressor);
  22487. return rr[0];
  22488. }
  22489. }
  22490. }
  22491. }
  22492. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  22493. case "&&":
  22494. var ll = self.left.evaluate(compressor);
  22495. var rr = self.right.evaluate(compressor);
  22496. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  22497. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  22498. if (self.left.has_side_effects(compressor)) {
  22499. return make_node(AST_Seq, self, {
  22500. car: self.left,
  22501. cdr: make_node(AST_False)
  22502. }).optimize(compressor);
  22503. }
  22504. return make_node(AST_False, self);
  22505. }
  22506. if (ll.length > 1 && ll[1]) {
  22507. return rr[0];
  22508. }
  22509. if (rr.length > 1 && rr[1]) {
  22510. return ll[0];
  22511. }
  22512. break;
  22513. case "||":
  22514. var ll = self.left.evaluate(compressor);
  22515. var rr = self.right.evaluate(compressor);
  22516. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  22517. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  22518. if (self.left.has_side_effects(compressor)) {
  22519. return make_node(AST_Seq, self, {
  22520. car: self.left,
  22521. cdr: make_node(AST_True)
  22522. }).optimize(compressor);
  22523. }
  22524. return make_node(AST_True, self);
  22525. }
  22526. if (ll.length > 1 && !ll[1]) {
  22527. return rr[0];
  22528. }
  22529. if (rr.length > 1 && !rr[1]) {
  22530. return ll[0];
  22531. }
  22532. break;
  22533. case "+":
  22534. var ll = self.left.evaluate(compressor);
  22535. var rr = self.right.evaluate(compressor);
  22536. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  22537. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  22538. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  22539. return make_node(AST_True, self);
  22540. }
  22541. break;
  22542. }
  22543. if (compressor.option("comparisons") && self.is_boolean()) {
  22544. if (!(compressor.parent() instanceof AST_Binary)
  22545. || compressor.parent() instanceof AST_Assign) {
  22546. var negated = make_node(AST_UnaryPrefix, self, {
  22547. operator: "!",
  22548. expression: self.negate(compressor)
  22549. });
  22550. self = best_of(self, negated);
  22551. }
  22552. switch (self.operator) {
  22553. case "<": reverse(">"); break;
  22554. case "<=": reverse(">="); break;
  22555. }
  22556. }
  22557. if (self.operator == "+" && self.right instanceof AST_String
  22558. && self.right.getValue() === "" && self.left instanceof AST_Binary
  22559. && self.left.operator == "+" && self.left.is_string(compressor)) {
  22560. return self.left;
  22561. }
  22562. if (compressor.option("evaluate")) {
  22563. if (self.operator == "+") {
  22564. if (self.left instanceof AST_Constant
  22565. && self.right instanceof AST_Binary
  22566. && self.right.operator == "+"
  22567. && self.right.left instanceof AST_Constant
  22568. && self.right.is_string(compressor)) {
  22569. self = make_node(AST_Binary, self, {
  22570. operator: "+",
  22571. left: make_node(AST_String, null, {
  22572. value: "" + self.left.getValue() + self.right.left.getValue(),
  22573. start: self.left.start,
  22574. end: self.right.left.end
  22575. }),
  22576. right: self.right.right
  22577. });
  22578. }
  22579. if (self.right instanceof AST_Constant
  22580. && self.left instanceof AST_Binary
  22581. && self.left.operator == "+"
  22582. && self.left.right instanceof AST_Constant
  22583. && self.left.is_string(compressor)) {
  22584. self = make_node(AST_Binary, self, {
  22585. operator: "+",
  22586. left: self.left.left,
  22587. right: make_node(AST_String, null, {
  22588. value: "" + self.left.right.getValue() + self.right.getValue(),
  22589. start: self.left.right.start,
  22590. end: self.right.end
  22591. })
  22592. });
  22593. }
  22594. if (self.left instanceof AST_Binary
  22595. && self.left.operator == "+"
  22596. && self.left.is_string(compressor)
  22597. && self.left.right instanceof AST_Constant
  22598. && self.right instanceof AST_Binary
  22599. && self.right.operator == "+"
  22600. && self.right.left instanceof AST_Constant
  22601. && self.right.is_string(compressor)) {
  22602. self = make_node(AST_Binary, self, {
  22603. operator: "+",
  22604. left: make_node(AST_Binary, self.left, {
  22605. operator: "+",
  22606. left: self.left.left,
  22607. right: make_node(AST_String, null, {
  22608. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  22609. start: self.left.right.start,
  22610. end: self.right.left.end
  22611. })
  22612. }),
  22613. right: self.right.right
  22614. });
  22615. }
  22616. }
  22617. }
  22618. // x && (y && z) ==> x && y && z
  22619. // x || (y || z) ==> x || y || z
  22620. if (self.right instanceof AST_Binary
  22621. && self.right.operator == self.operator
  22622. && (self.operator == "&&" || self.operator == "||"))
  22623. {
  22624. self.left = make_node(AST_Binary, self.left, {
  22625. operator : self.operator,
  22626. left : self.left,
  22627. right : self.right.left
  22628. });
  22629. self.right = self.right.right;
  22630. return self.transform(compressor);
  22631. }
  22632. return self.evaluate(compressor)[0];
  22633. });
  22634. OPT(AST_SymbolRef, function(self, compressor){
  22635. function isLHS(symbol, parent) {
  22636. return (
  22637. parent instanceof AST_Binary &&
  22638. parent.operator === '=' &&
  22639. parent.left === symbol
  22640. );
  22641. }
  22642. if (self.undeclared() && !isLHS(self, compressor.parent())) {
  22643. var defines = compressor.option("global_defs");
  22644. if (defines && defines.hasOwnProperty(self.name)) {
  22645. return make_node_from_constant(compressor, defines[self.name], self);
  22646. }
  22647. switch (self.name) {
  22648. case "undefined":
  22649. return make_node(AST_Undefined, self);
  22650. case "NaN":
  22651. return make_node(AST_NaN, self).transform(compressor);
  22652. case "Infinity":
  22653. return make_node(AST_Infinity, self).transform(compressor);
  22654. }
  22655. }
  22656. return self;
  22657. });
  22658. OPT(AST_Infinity, function (self, compressor) {
  22659. return make_node(AST_Binary, self, {
  22660. operator : '/',
  22661. left : make_node(AST_Number, self, {value: 1}),
  22662. right : make_node(AST_Number, self, {value: 0})
  22663. });
  22664. });
  22665. OPT(AST_Undefined, function(self, compressor){
  22666. if (compressor.option("unsafe")) {
  22667. var scope = compressor.find_parent(AST_Scope);
  22668. var undef = scope.find_variable("undefined");
  22669. if (undef) {
  22670. var ref = make_node(AST_SymbolRef, self, {
  22671. name : "undefined",
  22672. scope : scope,
  22673. thedef : undef
  22674. });
  22675. ref.reference();
  22676. return ref;
  22677. }
  22678. }
  22679. return self;
  22680. });
  22681. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  22682. OPT(AST_Assign, function(self, compressor){
  22683. self = self.lift_sequences(compressor);
  22684. if (self.operator == "="
  22685. && self.left instanceof AST_SymbolRef
  22686. && self.right instanceof AST_Binary
  22687. && self.right.left instanceof AST_SymbolRef
  22688. && self.right.left.name == self.left.name
  22689. && member(self.right.operator, ASSIGN_OPS)) {
  22690. self.operator = self.right.operator + "=";
  22691. self.right = self.right.right;
  22692. }
  22693. return self;
  22694. });
  22695. OPT(AST_Conditional, function(self, compressor){
  22696. if (!compressor.option("conditionals")) return self;
  22697. if (self.condition instanceof AST_Seq) {
  22698. var car = self.condition.car;
  22699. self.condition = self.condition.cdr;
  22700. return AST_Seq.cons(car, self);
  22701. }
  22702. var cond = self.condition.evaluate(compressor);
  22703. if (cond.length > 1) {
  22704. if (cond[1]) {
  22705. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  22706. return self.consequent;
  22707. } else {
  22708. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  22709. return self.alternative;
  22710. }
  22711. }
  22712. var negated = cond[0].negate(compressor);
  22713. if (best_of(cond[0], negated) === negated) {
  22714. self = make_node(AST_Conditional, self, {
  22715. condition: negated,
  22716. consequent: self.alternative,
  22717. alternative: self.consequent
  22718. });
  22719. }
  22720. var consequent = self.consequent;
  22721. var alternative = self.alternative;
  22722. if (consequent instanceof AST_Assign
  22723. && alternative instanceof AST_Assign
  22724. && consequent.operator == alternative.operator
  22725. && consequent.left.equivalent_to(alternative.left)
  22726. && !consequent.left.has_side_effects(compressor)
  22727. ) {
  22728. /*
  22729. * Stuff like this:
  22730. * if (foo) exp = something; else exp = something_else;
  22731. * ==>
  22732. * exp = foo ? something : something_else;
  22733. */
  22734. return make_node(AST_Assign, self, {
  22735. operator: consequent.operator,
  22736. left: consequent.left,
  22737. right: make_node(AST_Conditional, self, {
  22738. condition: self.condition,
  22739. consequent: consequent.right,
  22740. alternative: alternative.right
  22741. })
  22742. });
  22743. }
  22744. if (consequent instanceof AST_Call
  22745. && alternative.TYPE === consequent.TYPE
  22746. && consequent.args.length == alternative.args.length
  22747. && !consequent.expression.has_side_effects(compressor)
  22748. && consequent.expression.equivalent_to(alternative.expression)) {
  22749. if (consequent.args.length == 0) {
  22750. return make_node(AST_Seq, self, {
  22751. car: self.condition,
  22752. cdr: consequent
  22753. });
  22754. }
  22755. if (consequent.args.length == 1) {
  22756. consequent.args[0] = make_node(AST_Conditional, self, {
  22757. condition: self.condition,
  22758. consequent: consequent.args[0],
  22759. alternative: alternative.args[0]
  22760. });
  22761. return consequent;
  22762. }
  22763. }
  22764. // x?y?z:a:a --> x&&y?z:a
  22765. if (consequent instanceof AST_Conditional
  22766. && consequent.alternative.equivalent_to(alternative)) {
  22767. return make_node(AST_Conditional, self, {
  22768. condition: make_node(AST_Binary, self, {
  22769. left: self.condition,
  22770. operator: "&&",
  22771. right: consequent.condition
  22772. }),
  22773. consequent: consequent.consequent,
  22774. alternative: alternative
  22775. });
  22776. }
  22777. // x=y?1:1 --> x=1
  22778. if (consequent instanceof AST_Constant
  22779. && alternative instanceof AST_Constant
  22780. && consequent.equivalent_to(alternative)) {
  22781. if (self.condition.has_side_effects(compressor)) {
  22782. return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent.value, self)]);
  22783. } else {
  22784. return make_node_from_constant(compressor, consequent.value, self);
  22785. }
  22786. }
  22787. // x=y?true:false --> x=!!y
  22788. if (consequent instanceof AST_True
  22789. && alternative instanceof AST_False) {
  22790. self.condition = self.condition.negate(compressor);
  22791. return make_node(AST_UnaryPrefix, self.condition, {
  22792. operator: "!",
  22793. expression: self.condition
  22794. });
  22795. }
  22796. // x=y?false:true --> x=!y
  22797. if (consequent instanceof AST_False
  22798. && alternative instanceof AST_True) {
  22799. return self.condition.negate(compressor)
  22800. }
  22801. return self;
  22802. });
  22803. OPT(AST_Boolean, function(self, compressor){
  22804. if (compressor.option("booleans")) {
  22805. var p = compressor.parent();
  22806. if (p instanceof AST_Binary && (p.operator == "=="
  22807. || p.operator == "!=")) {
  22808. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  22809. operator : p.operator,
  22810. value : self.value,
  22811. file : p.start.file,
  22812. line : p.start.line,
  22813. col : p.start.col,
  22814. });
  22815. return make_node(AST_Number, self, {
  22816. value: +self.value
  22817. });
  22818. }
  22819. return make_node(AST_UnaryPrefix, self, {
  22820. operator: "!",
  22821. expression: make_node(AST_Number, self, {
  22822. value: 1 - self.value
  22823. })
  22824. });
  22825. }
  22826. return self;
  22827. });
  22828. OPT(AST_Sub, function(self, compressor){
  22829. var prop = self.property;
  22830. if (prop instanceof AST_String && compressor.option("properties")) {
  22831. prop = prop.getValue();
  22832. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  22833. return make_node(AST_Dot, self, {
  22834. expression : self.expression,
  22835. property : prop
  22836. }).optimize(compressor);
  22837. }
  22838. var v = parseFloat(prop);
  22839. if (!isNaN(v) && v.toString() == prop) {
  22840. self.property = make_node(AST_Number, self.property, {
  22841. value: v
  22842. });
  22843. }
  22844. }
  22845. return self;
  22846. });
  22847. OPT(AST_Dot, function(self, compressor){
  22848. var prop = self.property;
  22849. if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) {
  22850. return make_node(AST_Sub, self, {
  22851. expression : self.expression,
  22852. property : make_node(AST_String, self, {
  22853. value: prop
  22854. })
  22855. }).optimize(compressor);
  22856. }
  22857. return self.evaluate(compressor)[0];
  22858. });
  22859. function literals_in_boolean_context(self, compressor) {
  22860. if (compressor.option("booleans") && compressor.in_boolean_context() && !self.has_side_effects(compressor)) {
  22861. return make_node(AST_True, self);
  22862. }
  22863. return self;
  22864. };
  22865. OPT(AST_Array, literals_in_boolean_context);
  22866. OPT(AST_Object, literals_in_boolean_context);
  22867. OPT(AST_RegExp, literals_in_boolean_context);
  22868. OPT(AST_Return, function(self, compressor){
  22869. if (self.value instanceof AST_Undefined) {
  22870. self.value = null;
  22871. }
  22872. return self;
  22873. });
  22874. })();
  22875. /***********************************************************************
  22876. A JavaScript tokenizer / parser / beautifier / compressor.
  22877. https://github.com/mishoo/UglifyJS2
  22878. -------------------------------- (C) ---------------------------------
  22879. Author: Mihai Bazon
  22880. <mihai.bazon@gmail.com>
  22881. http://mihai.bazon.net/blog
  22882. Distributed under the BSD license:
  22883. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  22884. Redistribution and use in source and binary forms, with or without
  22885. modification, are permitted provided that the following conditions
  22886. are met:
  22887. * Redistributions of source code must retain the above
  22888. copyright notice, this list of conditions and the following
  22889. disclaimer.
  22890. * Redistributions in binary form must reproduce the above
  22891. copyright notice, this list of conditions and the following
  22892. disclaimer in the documentation and/or other materials
  22893. provided with the distribution.
  22894. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  22895. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22896. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22897. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  22898. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  22899. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22900. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22901. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22902. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  22903. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  22904. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22905. SUCH DAMAGE.
  22906. ***********************************************************************/
  22907. "use strict";
  22908. // a small wrapper around fitzgen's source-map library
  22909. function SourceMap(options) {
  22910. options = defaults(options, {
  22911. file : null,
  22912. root : null,
  22913. orig : null,
  22914. orig_line_diff : 0,
  22915. dest_line_diff : 0,
  22916. });
  22917. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  22918. var generator;
  22919. if (orig_map) {
  22920. generator = MOZ_SourceMap.SourceMapGenerator.fromSourceMap(orig_map);
  22921. } else {
  22922. generator = new MOZ_SourceMap.SourceMapGenerator({
  22923. file : options.file,
  22924. sourceRoot : options.root
  22925. });
  22926. }
  22927. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  22928. if (orig_map) {
  22929. var info = orig_map.originalPositionFor({
  22930. line: orig_line,
  22931. column: orig_col
  22932. });
  22933. if (info.source === null) {
  22934. return;
  22935. }
  22936. source = info.source;
  22937. orig_line = info.line;
  22938. orig_col = info.column;
  22939. name = info.name || name;
  22940. }
  22941. generator.addMapping({
  22942. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  22943. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  22944. source : source,
  22945. name : name
  22946. });
  22947. }
  22948. return {
  22949. add : add,
  22950. get : function() { return generator },
  22951. toString : function() { return JSON.stringify(generator.toJSON()); }
  22952. };
  22953. };
  22954. /***********************************************************************
  22955. A JavaScript tokenizer / parser / beautifier / compressor.
  22956. https://github.com/mishoo/UglifyJS2
  22957. -------------------------------- (C) ---------------------------------
  22958. Author: Mihai Bazon
  22959. <mihai.bazon@gmail.com>
  22960. http://mihai.bazon.net/blog
  22961. Distributed under the BSD license:
  22962. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  22963. Redistribution and use in source and binary forms, with or without
  22964. modification, are permitted provided that the following conditions
  22965. are met:
  22966. * Redistributions of source code must retain the above
  22967. copyright notice, this list of conditions and the following
  22968. disclaimer.
  22969. * Redistributions in binary form must reproduce the above
  22970. copyright notice, this list of conditions and the following
  22971. disclaimer in the documentation and/or other materials
  22972. provided with the distribution.
  22973. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  22974. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22975. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22976. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  22977. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  22978. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22979. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22980. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22981. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  22982. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  22983. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22984. SUCH DAMAGE.
  22985. ***********************************************************************/
  22986. "use strict";
  22987. (function(){
  22988. var MOZ_TO_ME = {
  22989. ExpressionStatement: function(M) {
  22990. var expr = M.expression;
  22991. if (expr.type === "Literal" && typeof expr.value === "string") {
  22992. return new AST_Directive({
  22993. start: my_start_token(M),
  22994. end: my_end_token(M),
  22995. value: expr.value
  22996. });
  22997. }
  22998. return new AST_SimpleStatement({
  22999. start: my_start_token(M),
  23000. end: my_end_token(M),
  23001. body: from_moz(expr)
  23002. });
  23003. },
  23004. TryStatement: function(M) {
  23005. var handlers = M.handlers || [M.handler];
  23006. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  23007. throw new Error("Multiple catch clauses are not supported.");
  23008. }
  23009. return new AST_Try({
  23010. start : my_start_token(M),
  23011. end : my_end_token(M),
  23012. body : from_moz(M.block).body,
  23013. bcatch : from_moz(handlers[0]),
  23014. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  23015. });
  23016. },
  23017. Property: function(M) {
  23018. var key = M.key;
  23019. var name = key.type == "Identifier" ? key.name : key.value;
  23020. var args = {
  23021. start : my_start_token(key),
  23022. end : my_end_token(M.value),
  23023. key : name,
  23024. value : from_moz(M.value)
  23025. };
  23026. switch (M.kind) {
  23027. case "init":
  23028. return new AST_ObjectKeyVal(args);
  23029. case "set":
  23030. args.value.name = from_moz(key);
  23031. return new AST_ObjectSetter(args);
  23032. case "get":
  23033. args.value.name = from_moz(key);
  23034. return new AST_ObjectGetter(args);
  23035. }
  23036. },
  23037. ObjectExpression: function(M) {
  23038. return new AST_Object({
  23039. start : my_start_token(M),
  23040. end : my_end_token(M),
  23041. properties : M.properties.map(function(prop){
  23042. prop.type = "Property";
  23043. return from_moz(prop)
  23044. })
  23045. });
  23046. },
  23047. SequenceExpression: function(M) {
  23048. return AST_Seq.from_array(M.expressions.map(from_moz));
  23049. },
  23050. MemberExpression: function(M) {
  23051. return new (M.computed ? AST_Sub : AST_Dot)({
  23052. start : my_start_token(M),
  23053. end : my_end_token(M),
  23054. property : M.computed ? from_moz(M.property) : M.property.name,
  23055. expression : from_moz(M.object)
  23056. });
  23057. },
  23058. SwitchCase: function(M) {
  23059. return new (M.test ? AST_Case : AST_Default)({
  23060. start : my_start_token(M),
  23061. end : my_end_token(M),
  23062. expression : from_moz(M.test),
  23063. body : M.consequent.map(from_moz)
  23064. });
  23065. },
  23066. VariableDeclaration: function(M) {
  23067. return new (M.kind === "const" ? AST_Const : AST_Var)({
  23068. start : my_start_token(M),
  23069. end : my_end_token(M),
  23070. definitions : M.declarations.map(from_moz)
  23071. });
  23072. },
  23073. Literal: function(M) {
  23074. var val = M.value, args = {
  23075. start : my_start_token(M),
  23076. end : my_end_token(M)
  23077. };
  23078. if (val === null) return new AST_Null(args);
  23079. switch (typeof val) {
  23080. case "string":
  23081. args.value = val;
  23082. return new AST_String(args);
  23083. case "number":
  23084. args.value = val;
  23085. return new AST_Number(args);
  23086. case "boolean":
  23087. return new (val ? AST_True : AST_False)(args);
  23088. default:
  23089. var rx = M.regex;
  23090. if (rx && rx.pattern) {
  23091. // RegExpLiteral as per ESTree AST spec
  23092. args.value = new RegExp(rx.pattern, rx.flags).toString();
  23093. } else {
  23094. // support legacy RegExp
  23095. args.value = M.regex && M.raw ? M.raw : val;
  23096. }
  23097. return new AST_RegExp(args);
  23098. }
  23099. },
  23100. Identifier: function(M) {
  23101. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  23102. return new ( p.type == "LabeledStatement" ? AST_Label
  23103. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  23104. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  23105. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  23106. : p.type == "CatchClause" ? AST_SymbolCatch
  23107. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  23108. : AST_SymbolRef)({
  23109. start : my_start_token(M),
  23110. end : my_end_token(M),
  23111. name : M.name
  23112. });
  23113. }
  23114. };
  23115. MOZ_TO_ME.UpdateExpression =
  23116. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  23117. var prefix = "prefix" in M ? M.prefix
  23118. : M.type == "UnaryExpression" ? true : false;
  23119. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  23120. start : my_start_token(M),
  23121. end : my_end_token(M),
  23122. operator : M.operator,
  23123. expression : from_moz(M.argument)
  23124. });
  23125. };
  23126. map("Program", AST_Toplevel, "body@body");
  23127. map("EmptyStatement", AST_EmptyStatement);
  23128. map("BlockStatement", AST_BlockStatement, "body@body");
  23129. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  23130. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  23131. map("BreakStatement", AST_Break, "label>label");
  23132. map("ContinueStatement", AST_Continue, "label>label");
  23133. map("WithStatement", AST_With, "object>expression, body>body");
  23134. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  23135. map("ReturnStatement", AST_Return, "argument>value");
  23136. map("ThrowStatement", AST_Throw, "argument>value");
  23137. map("WhileStatement", AST_While, "test>condition, body>body");
  23138. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  23139. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  23140. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  23141. map("DebuggerStatement", AST_Debugger);
  23142. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  23143. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  23144. map("CatchClause", AST_Catch, "param>argname, body%body");
  23145. map("ThisExpression", AST_This);
  23146. map("ArrayExpression", AST_Array, "elements@elements");
  23147. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  23148. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  23149. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  23150. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  23151. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  23152. map("NewExpression", AST_New, "callee>expression, arguments@args");
  23153. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  23154. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  23155. return {
  23156. type: "ExpressionStatement",
  23157. expression: {
  23158. type: "Literal",
  23159. value: M.value
  23160. }
  23161. };
  23162. });
  23163. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  23164. return {
  23165. type: "ExpressionStatement",
  23166. expression: to_moz(M.body)
  23167. };
  23168. });
  23169. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  23170. return {
  23171. type: "SwitchCase",
  23172. test: to_moz(M.expression),
  23173. consequent: M.body.map(to_moz)
  23174. };
  23175. });
  23176. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  23177. return {
  23178. type: "TryStatement",
  23179. block: to_moz_block(M),
  23180. handler: to_moz(M.bcatch),
  23181. guardedHandlers: [],
  23182. finalizer: to_moz(M.bfinally)
  23183. };
  23184. });
  23185. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  23186. return {
  23187. type: "CatchClause",
  23188. param: to_moz(M.argname),
  23189. guard: null,
  23190. body: to_moz_block(M)
  23191. };
  23192. });
  23193. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  23194. return {
  23195. type: "VariableDeclaration",
  23196. kind: M instanceof AST_Const ? "const" : "var",
  23197. declarations: M.definitions.map(to_moz)
  23198. };
  23199. });
  23200. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  23201. return {
  23202. type: "SequenceExpression",
  23203. expressions: M.to_array().map(to_moz)
  23204. };
  23205. });
  23206. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  23207. var isComputed = M instanceof AST_Sub;
  23208. return {
  23209. type: "MemberExpression",
  23210. object: to_moz(M.expression),
  23211. computed: isComputed,
  23212. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  23213. };
  23214. });
  23215. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  23216. return {
  23217. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  23218. operator: M.operator,
  23219. prefix: M instanceof AST_UnaryPrefix,
  23220. argument: to_moz(M.expression)
  23221. };
  23222. });
  23223. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  23224. return {
  23225. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  23226. left: to_moz(M.left),
  23227. operator: M.operator,
  23228. right: to_moz(M.right)
  23229. };
  23230. });
  23231. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  23232. return {
  23233. type: "ObjectExpression",
  23234. properties: M.properties.map(to_moz)
  23235. };
  23236. });
  23237. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  23238. var key = (
  23239. is_identifier(M.key)
  23240. ? {type: "Identifier", name: M.key}
  23241. : {type: "Literal", value: M.key}
  23242. );
  23243. var kind;
  23244. if (M instanceof AST_ObjectKeyVal) {
  23245. kind = "init";
  23246. } else
  23247. if (M instanceof AST_ObjectGetter) {
  23248. kind = "get";
  23249. } else
  23250. if (M instanceof AST_ObjectSetter) {
  23251. kind = "set";
  23252. }
  23253. return {
  23254. type: "Property",
  23255. kind: kind,
  23256. key: key,
  23257. value: to_moz(M.value)
  23258. };
  23259. });
  23260. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  23261. var def = M.definition();
  23262. return {
  23263. type: "Identifier",
  23264. name: def ? def.mangled_name || def.name : M.name
  23265. };
  23266. });
  23267. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  23268. var value = M.value;
  23269. return {
  23270. type: "Literal",
  23271. value: value,
  23272. raw: value.toString(),
  23273. regex: {
  23274. pattern: value.source,
  23275. flags: value.toString().match(/[gimuy]*$/)[0]
  23276. }
  23277. };
  23278. });
  23279. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  23280. var value = M.value;
  23281. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  23282. return {
  23283. type: "UnaryExpression",
  23284. operator: "-",
  23285. prefix: true,
  23286. argument: {
  23287. type: "Literal",
  23288. value: -value,
  23289. raw: M.start.raw
  23290. }
  23291. };
  23292. }
  23293. return {
  23294. type: "Literal",
  23295. value: value,
  23296. raw: M.start.raw
  23297. };
  23298. });
  23299. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  23300. return {
  23301. type: "Identifier",
  23302. name: String(M.value)
  23303. };
  23304. });
  23305. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  23306. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  23307. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  23308. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  23309. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  23310. /* -----[ tools ]----- */
  23311. function raw_token(moznode) {
  23312. if (moznode.type == "Literal") {
  23313. return moznode.raw != null ? moznode.raw : moznode.value + "";
  23314. }
  23315. }
  23316. function my_start_token(moznode) {
  23317. var loc = moznode.loc, start = loc && loc.start;
  23318. var range = moznode.range;
  23319. return new AST_Token({
  23320. file : loc && loc.source,
  23321. line : start && start.line,
  23322. col : start && start.column,
  23323. pos : range ? range[0] : moznode.start,
  23324. endline : start && start.line,
  23325. endcol : start && start.column,
  23326. endpos : range ? range[0] : moznode.start,
  23327. raw : raw_token(moznode),
  23328. });
  23329. };
  23330. function my_end_token(moznode) {
  23331. var loc = moznode.loc, end = loc && loc.end;
  23332. var range = moznode.range;
  23333. return new AST_Token({
  23334. file : loc && loc.source,
  23335. line : end && end.line,
  23336. col : end && end.column,
  23337. pos : range ? range[1] : moznode.end,
  23338. endline : end && end.line,
  23339. endcol : end && end.column,
  23340. endpos : range ? range[1] : moznode.end,
  23341. raw : raw_token(moznode),
  23342. });
  23343. };
  23344. function map(moztype, mytype, propmap) {
  23345. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  23346. moz_to_me += "return new U2." + mytype.name + "({\n" +
  23347. "start: my_start_token(M),\n" +
  23348. "end: my_end_token(M)";
  23349. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  23350. me_to_moz += "return {\n" +
  23351. "type: " + JSON.stringify(moztype);
  23352. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  23353. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  23354. if (!m) throw new Error("Can't understand property map: " + prop);
  23355. var moz = m[1], how = m[2], my = m[3];
  23356. moz_to_me += ",\n" + my + ": ";
  23357. me_to_moz += ",\n" + moz + ": ";
  23358. switch (how) {
  23359. case "@":
  23360. moz_to_me += "M." + moz + ".map(from_moz)";
  23361. me_to_moz += "M." + my + ".map(to_moz)";
  23362. break;
  23363. case ">":
  23364. moz_to_me += "from_moz(M." + moz + ")";
  23365. me_to_moz += "to_moz(M." + my + ")";
  23366. break;
  23367. case "=":
  23368. moz_to_me += "M." + moz;
  23369. me_to_moz += "M." + my;
  23370. break;
  23371. case "%":
  23372. moz_to_me += "from_moz(M." + moz + ").body";
  23373. me_to_moz += "to_moz_block(M)";
  23374. break;
  23375. default:
  23376. throw new Error("Can't understand operator in propmap: " + prop);
  23377. }
  23378. });
  23379. moz_to_me += "\n})\n}";
  23380. me_to_moz += "\n}\n}";
  23381. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  23382. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  23383. //console.log(moz_to_me);
  23384. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  23385. exports, my_start_token, my_end_token, from_moz
  23386. );
  23387. me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")(
  23388. to_moz, to_moz_block
  23389. );
  23390. MOZ_TO_ME[moztype] = moz_to_me;
  23391. def_to_moz(mytype, me_to_moz);
  23392. };
  23393. var FROM_MOZ_STACK = null;
  23394. function from_moz(node) {
  23395. FROM_MOZ_STACK.push(node);
  23396. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  23397. FROM_MOZ_STACK.pop();
  23398. return ret;
  23399. };
  23400. AST_Node.from_mozilla_ast = function(node){
  23401. var save_stack = FROM_MOZ_STACK;
  23402. FROM_MOZ_STACK = [];
  23403. var ast = from_moz(node);
  23404. FROM_MOZ_STACK = save_stack;
  23405. return ast;
  23406. };
  23407. function set_moz_loc(mynode, moznode, myparent) {
  23408. var start = mynode.start;
  23409. var end = mynode.end;
  23410. if (start.pos != null && end.endpos != null) {
  23411. moznode.range = [start.pos, end.endpos];
  23412. }
  23413. if (start.line) {
  23414. moznode.loc = {
  23415. start: {line: start.line, column: start.col},
  23416. end: end.endline ? {line: end.endline, column: end.endcol} : null
  23417. };
  23418. if (start.file) {
  23419. moznode.loc.source = start.file;
  23420. }
  23421. }
  23422. return moznode;
  23423. };
  23424. function def_to_moz(mytype, handler) {
  23425. mytype.DEFMETHOD("to_mozilla_ast", function() {
  23426. return set_moz_loc(this, handler(this));
  23427. });
  23428. };
  23429. function to_moz(node) {
  23430. return node != null ? node.to_mozilla_ast() : null;
  23431. };
  23432. function to_moz_block(node) {
  23433. return {
  23434. type: "BlockStatement",
  23435. body: node.body.map(to_moz)
  23436. };
  23437. };
  23438. })();
  23439. /***********************************************************************
  23440. A JavaScript tokenizer / parser / beautifier / compressor.
  23441. https://github.com/mishoo/UglifyJS2
  23442. -------------------------------- (C) ---------------------------------
  23443. Author: Mihai Bazon
  23444. <mihai.bazon@gmail.com>
  23445. http://mihai.bazon.net/blog
  23446. Distributed under the BSD license:
  23447. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  23448. Redistribution and use in source and binary forms, with or without
  23449. modification, are permitted provided that the following conditions
  23450. are met:
  23451. * Redistributions of source code must retain the above
  23452. copyright notice, this list of conditions and the following
  23453. disclaimer.
  23454. * Redistributions in binary form must reproduce the above
  23455. copyright notice, this list of conditions and the following
  23456. disclaimer in the documentation and/or other materials
  23457. provided with the distribution.
  23458. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  23459. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23460. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23461. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  23462. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  23463. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  23464. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  23465. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23466. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  23467. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  23468. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23469. SUCH DAMAGE.
  23470. ***********************************************************************/
  23471. "use strict";
  23472. function find_builtins() {
  23473. var a = [];
  23474. [ Object, Array, Function, Number,
  23475. String, Boolean, Error, Math,
  23476. Date, RegExp
  23477. ].forEach(function(ctor){
  23478. Object.getOwnPropertyNames(ctor).map(add);
  23479. if (ctor.prototype) {
  23480. Object.getOwnPropertyNames(ctor.prototype).map(add);
  23481. }
  23482. });
  23483. function add(name) {
  23484. push_uniq(a, name);
  23485. }
  23486. return a;
  23487. }
  23488. function mangle_properties(ast, options) {
  23489. options = defaults(options, {
  23490. reserved : null,
  23491. cache : null,
  23492. only_cache : false,
  23493. regex : null
  23494. });
  23495. var reserved = options.reserved;
  23496. if (reserved == null)
  23497. reserved = find_builtins();
  23498. var cache = options.cache;
  23499. if (cache == null) {
  23500. cache = {
  23501. cname: -1,
  23502. props: new Dictionary()
  23503. };
  23504. }
  23505. var regex = options.regex;
  23506. var names_to_mangle = [];
  23507. var unmangleable = [];
  23508. // step 1: find candidates to mangle
  23509. ast.walk(new TreeWalker(function(node){
  23510. if (node instanceof AST_ObjectKeyVal) {
  23511. add(node.key);
  23512. }
  23513. else if (node instanceof AST_ObjectProperty) {
  23514. // setter or getter, since KeyVal is handled above
  23515. add(node.key.name);
  23516. }
  23517. else if (node instanceof AST_Dot) {
  23518. if (this.parent() instanceof AST_Assign) {
  23519. add(node.property);
  23520. }
  23521. }
  23522. else if (node instanceof AST_Sub) {
  23523. if (this.parent() instanceof AST_Assign) {
  23524. addStrings(node.property);
  23525. }
  23526. }
  23527. }));
  23528. // step 2: transform the tree, renaming properties
  23529. return ast.transform(new TreeTransformer(function(node){
  23530. if (node instanceof AST_ObjectKeyVal) {
  23531. node.key = mangle(node.key);
  23532. }
  23533. else if (node instanceof AST_ObjectProperty) {
  23534. // setter or getter
  23535. node.key.name = mangle(node.key.name);
  23536. }
  23537. else if (node instanceof AST_Dot) {
  23538. node.property = mangle(node.property);
  23539. }
  23540. else if (node instanceof AST_Sub) {
  23541. node.property = mangleStrings(node.property);
  23542. }
  23543. // else if (node instanceof AST_String) {
  23544. // if (should_mangle(node.value)) {
  23545. // AST_Node.warn(
  23546. // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", {
  23547. // file : node.start.file,
  23548. // line : node.start.line,
  23549. // col : node.start.col,
  23550. // prop : node.value
  23551. // }
  23552. // );
  23553. // }
  23554. // }
  23555. }));
  23556. // only function declarations after this line
  23557. function can_mangle(name) {
  23558. if (unmangleable.indexOf(name) >= 0) return false;
  23559. if (reserved.indexOf(name) >= 0) return false;
  23560. if (options.only_cache) {
  23561. return cache.props.has(name);
  23562. }
  23563. if (/^[0-9.]+$/.test(name)) return false;
  23564. return true;
  23565. }
  23566. function should_mangle(name) {
  23567. if (regex && !regex.test(name)) return false;
  23568. if (reserved.indexOf(name) >= 0) return false;
  23569. return cache.props.has(name)
  23570. || names_to_mangle.indexOf(name) >= 0;
  23571. }
  23572. function add(name) {
  23573. if (can_mangle(name))
  23574. push_uniq(names_to_mangle, name);
  23575. if (!should_mangle(name)) {
  23576. push_uniq(unmangleable, name);
  23577. }
  23578. }
  23579. function mangle(name) {
  23580. if (!should_mangle(name)) {
  23581. return name;
  23582. }
  23583. var mangled = cache.props.get(name);
  23584. if (!mangled) {
  23585. do {
  23586. mangled = base54(++cache.cname);
  23587. } while (!can_mangle(mangled));
  23588. cache.props.set(name, mangled);
  23589. }
  23590. return mangled;
  23591. }
  23592. function addStrings(node) {
  23593. var out = {};
  23594. try {
  23595. (function walk(node){
  23596. node.walk(new TreeWalker(function(node){
  23597. if (node instanceof AST_Seq) {
  23598. walk(node.cdr);
  23599. return true;
  23600. }
  23601. if (node instanceof AST_String) {
  23602. add(node.value);
  23603. return true;
  23604. }
  23605. if (node instanceof AST_Conditional) {
  23606. walk(node.consequent);
  23607. walk(node.alternative);
  23608. return true;
  23609. }
  23610. throw out;
  23611. }));
  23612. })(node);
  23613. } catch(ex) {
  23614. if (ex !== out) throw ex;
  23615. }
  23616. }
  23617. function mangleStrings(node) {
  23618. return node.transform(new TreeTransformer(function(node){
  23619. if (node instanceof AST_Seq) {
  23620. node.cdr = mangleStrings(node.cdr);
  23621. }
  23622. else if (node instanceof AST_String) {
  23623. node.value = mangle(node.value);
  23624. }
  23625. else if (node instanceof AST_Conditional) {
  23626. node.consequent = mangleStrings(node.consequent);
  23627. node.alternative = mangleStrings(node.alternative);
  23628. }
  23629. return node;
  23630. }));
  23631. }
  23632. }
  23633. AST_Node.warn_function = function(txt) { logger.error("uglifyjs2 WARN: " + txt); };
  23634. exports.minify = function(files, options, name) {
  23635. options = defaults(options, {
  23636. spidermonkey : false,
  23637. outSourceMap : null,
  23638. sourceRoot : null,
  23639. inSourceMap : null,
  23640. fromString : false,
  23641. warnings : false,
  23642. mangle : {},
  23643. output : null,
  23644. compress : {}
  23645. });
  23646. base54.reset();
  23647. // 1. parse
  23648. var toplevel = null,
  23649. sourcesContent = {};
  23650. if (options.spidermonkey) {
  23651. toplevel = AST_Node.from_mozilla_ast(files);
  23652. } else {
  23653. if (typeof files == "string")
  23654. files = [ files ];
  23655. files.forEach(function(file, i){
  23656. var code = options.fromString
  23657. ? file
  23658. : rjsFile.readFile(file, "utf8");
  23659. sourcesContent[file] = code;
  23660. toplevel = parse(code, {
  23661. filename: options.fromString ? name : file,
  23662. toplevel: toplevel
  23663. });
  23664. });
  23665. }
  23666. if (options.wrap) {
  23667. toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll);
  23668. }
  23669. // 2. compress
  23670. if (options.compress) {
  23671. var compress = { warnings: options.warnings };
  23672. merge(compress, options.compress);
  23673. toplevel.figure_out_scope();
  23674. var sq = Compressor(compress);
  23675. toplevel = toplevel.transform(sq);
  23676. }
  23677. // 3. mangle
  23678. if (options.mangle) {
  23679. toplevel.figure_out_scope(options.mangle);
  23680. toplevel.compute_char_frequency(options.mangle);
  23681. toplevel.mangle_names(options.mangle);
  23682. }
  23683. // 4. output
  23684. var inMap = options.inSourceMap;
  23685. var output = {};
  23686. if (typeof options.inSourceMap == "string") {
  23687. inMap = rjsFile.readFile(options.inSourceMap, "utf8");
  23688. }
  23689. if (options.outSourceMap) {
  23690. output.source_map = SourceMap({
  23691. file: options.outSourceMap,
  23692. orig: inMap,
  23693. root: options.sourceRoot
  23694. });
  23695. if (options.sourceMapIncludeSources) {
  23696. for (var file in sourcesContent) {
  23697. if (sourcesContent.hasOwnProperty(file)) {
  23698. output.source_map.get().setSourceContent(file, sourcesContent[file]);
  23699. }
  23700. }
  23701. }
  23702. }
  23703. if (options.output) {
  23704. merge(output, options.output);
  23705. }
  23706. var stream = OutputStream(output);
  23707. toplevel.print(stream);
  23708. if (options.outSourceMap && "string" === typeof options.outSourceMap) {
  23709. stream += "\n//# sourceMappingURL=" + options.outSourceMap;
  23710. }
  23711. var source_map = output.source_map;
  23712. if (source_map) {
  23713. source_map = source_map + "";
  23714. }
  23715. return {
  23716. code : stream + "",
  23717. map : source_map
  23718. };
  23719. };
  23720. // exports.describe_ast = function() {
  23721. // function doitem(ctor) {
  23722. // var sub = {};
  23723. // ctor.SUBCLASSES.forEach(function(ctor){
  23724. // sub[ctor.TYPE] = doitem(ctor);
  23725. // });
  23726. // var ret = {};
  23727. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  23728. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  23729. // return ret;
  23730. // }
  23731. // return doitem(AST_Node).sub;
  23732. // }
  23733. exports.describe_ast = function() {
  23734. var out = OutputStream({ beautify: true });
  23735. function doitem(ctor) {
  23736. out.print("AST_" + ctor.TYPE);
  23737. var props = ctor.SELF_PROPS.filter(function(prop){
  23738. return !/^\$/.test(prop);
  23739. });
  23740. if (props.length > 0) {
  23741. out.space();
  23742. out.with_parens(function(){
  23743. props.forEach(function(prop, i){
  23744. if (i) out.space();
  23745. out.print(prop);
  23746. });
  23747. });
  23748. }
  23749. if (ctor.documentation) {
  23750. out.space();
  23751. out.print_string(ctor.documentation);
  23752. }
  23753. if (ctor.SUBCLASSES.length > 0) {
  23754. out.space();
  23755. out.with_block(function(){
  23756. ctor.SUBCLASSES.forEach(function(ctor, i){
  23757. out.indent();
  23758. doitem(ctor);
  23759. out.newline();
  23760. });
  23761. });
  23762. }
  23763. };
  23764. doitem(AST_Node);
  23765. return out + "";
  23766. };
  23767. });
  23768. /**
  23769. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  23770. * Available via the MIT or new BSD license.
  23771. * see: http://github.com/jrburke/requirejs for details
  23772. */
  23773. /*jslint plusplus: true */
  23774. /*global define: false */
  23775. define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
  23776. 'use strict';
  23777. function arrayToString(ary) {
  23778. var output = '[';
  23779. if (ary) {
  23780. ary.forEach(function (item, i) {
  23781. output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
  23782. });
  23783. }
  23784. output += ']';
  23785. return output;
  23786. }
  23787. //This string is saved off because JSLint complains
  23788. //about obj.arguments use, as 'reserved word'
  23789. var argPropName = 'arguments',
  23790. //Default object to use for "scope" checking for UMD identifiers.
  23791. emptyScope = {},
  23792. mixin = lang.mixin,
  23793. hasProp = lang.hasProp;
  23794. //From an esprima example for traversing its ast.
  23795. function traverse(object, visitor) {
  23796. var key, child;
  23797. if (!object) {
  23798. return;
  23799. }
  23800. if (visitor.call(null, object) === false) {
  23801. return false;
  23802. }
  23803. for (key in object) {
  23804. if (object.hasOwnProperty(key)) {
  23805. child = object[key];
  23806. if (typeof child === 'object' && child !== null) {
  23807. if (traverse(child, visitor) === false) {
  23808. return false;
  23809. }
  23810. }
  23811. }
  23812. }
  23813. }
  23814. //Like traverse, but visitor returning false just
  23815. //stops that subtree analysis, not the rest of tree
  23816. //visiting.
  23817. function traverseBroad(object, visitor) {
  23818. var key, child;
  23819. if (!object) {
  23820. return;
  23821. }
  23822. if (visitor.call(null, object) === false) {
  23823. return false;
  23824. }
  23825. for (key in object) {
  23826. if (object.hasOwnProperty(key)) {
  23827. child = object[key];
  23828. if (typeof child === 'object' && child !== null) {
  23829. traverseBroad(child, visitor);
  23830. }
  23831. }
  23832. }
  23833. }
  23834. /**
  23835. * Pulls out dependencies from an array literal with just string members.
  23836. * If string literals, will just return those string values in an array,
  23837. * skipping other items in the array.
  23838. *
  23839. * @param {Node} node an AST node.
  23840. *
  23841. * @returns {Array} an array of strings.
  23842. * If null is returned, then it means the input node was not a valid
  23843. * dependency.
  23844. */
  23845. function getValidDeps(node) {
  23846. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  23847. return;
  23848. }
  23849. var deps = [];
  23850. node.elements.some(function (elem) {
  23851. if (elem.type === 'Literal') {
  23852. deps.push(elem.value);
  23853. }
  23854. });
  23855. return deps.length ? deps : undefined;
  23856. }
  23857. // Detects regular or arrow function expressions as the desired expression
  23858. // type.
  23859. function isFnExpression(node) {
  23860. return (node && (node.type === 'FunctionExpression' ||
  23861. node.type === 'ArrowFunctionExpression'));
  23862. }
  23863. /**
  23864. * Main parse function. Returns a string of any valid require or
  23865. * define/require.def calls as part of one JavaScript source string.
  23866. * @param {String} moduleName the module name that represents this file.
  23867. * It is used to create a default define if there is not one already for the
  23868. * file. This allows properly tracing dependencies for builds. Otherwise, if
  23869. * the file just has a require() call, the file dependencies will not be
  23870. * properly reflected: the file will come before its dependencies.
  23871. * @param {String} moduleName
  23872. * @param {String} fileName
  23873. * @param {String} fileContents
  23874. * @param {Object} options optional options. insertNeedsDefine: true will
  23875. * add calls to require.needsDefine() if appropriate.
  23876. * @returns {String} JS source string or null, if no require or
  23877. * define/require.def calls are found.
  23878. */
  23879. function parse(moduleName, fileName, fileContents, options) {
  23880. options = options || {};
  23881. //Set up source input
  23882. var i, moduleCall, depString,
  23883. moduleDeps = [],
  23884. result = '',
  23885. moduleList = [],
  23886. needsDefine = true,
  23887. astRoot = esprima.parse(fileContents);
  23888. parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  23889. if (!deps) {
  23890. deps = [];
  23891. }
  23892. if (callName === 'define' && (!name || name === moduleName)) {
  23893. needsDefine = false;
  23894. }
  23895. if (!name) {
  23896. //If there is no module name, the dependencies are for
  23897. //this file/default module name.
  23898. moduleDeps = moduleDeps.concat(deps);
  23899. } else {
  23900. moduleList.push({
  23901. name: name,
  23902. deps: deps
  23903. });
  23904. }
  23905. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  23906. return factoryIdentifier;
  23907. }
  23908. //If define was found, no need to dive deeper, unless
  23909. //the config explicitly wants to dig deeper.
  23910. return !!options.findNestedDependencies;
  23911. }, options);
  23912. if (options.insertNeedsDefine && needsDefine) {
  23913. result += 'require.needsDefine("' + moduleName + '");';
  23914. }
  23915. if (moduleDeps.length || moduleList.length) {
  23916. for (i = 0; i < moduleList.length; i++) {
  23917. moduleCall = moduleList[i];
  23918. if (result) {
  23919. result += '\n';
  23920. }
  23921. //If this is the main module for this file, combine any
  23922. //"anonymous" dependencies (could come from a nested require
  23923. //call) with this module.
  23924. if (moduleCall.name === moduleName) {
  23925. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  23926. moduleDeps = [];
  23927. }
  23928. depString = arrayToString(moduleCall.deps);
  23929. result += 'define("' + moduleCall.name + '",' +
  23930. depString + ');';
  23931. }
  23932. if (moduleDeps.length) {
  23933. if (result) {
  23934. result += '\n';
  23935. }
  23936. depString = arrayToString(moduleDeps);
  23937. result += 'define("' + moduleName + '",' + depString + ');';
  23938. }
  23939. }
  23940. return result || null;
  23941. }
  23942. parse.traverse = traverse;
  23943. parse.traverseBroad = traverseBroad;
  23944. parse.isFnExpression = isFnExpression;
  23945. /**
  23946. * Handles parsing a file recursively for require calls.
  23947. * @param {Array} parentNode the AST node to start with.
  23948. * @param {Function} onMatch function to call on a parse match.
  23949. * @param {Object} [options] This is normally the build config options if
  23950. * it is passed.
  23951. * @param {Object} [fnExpScope] holds list of function expresssion
  23952. * argument identifiers, set up internally, not passed in
  23953. */
  23954. parse.recurse = function (object, onMatch, options, fnExpScope) {
  23955. //Like traverse, but skips if branches that would not be processed
  23956. //after has application that results in tests of true or false boolean
  23957. //literal values.
  23958. var key, child, result, i, params, param, tempObject,
  23959. hasHas = options && options.has;
  23960. fnExpScope = fnExpScope || emptyScope;
  23961. if (!object) {
  23962. return;
  23963. }
  23964. //If has replacement has resulted in if(true){} or if(false){}, take
  23965. //the appropriate branch and skip the other one.
  23966. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  23967. object.test.type === 'Literal') {
  23968. if (object.test.value) {
  23969. //Take the if branch
  23970. this.recurse(object.consequent, onMatch, options, fnExpScope);
  23971. } else {
  23972. //Take the else branch
  23973. this.recurse(object.alternate, onMatch, options, fnExpScope);
  23974. }
  23975. } else {
  23976. result = this.parseNode(object, onMatch, fnExpScope);
  23977. if (result === false) {
  23978. return;
  23979. } else if (typeof result === 'string') {
  23980. return result;
  23981. }
  23982. //Build up a "scope" object that informs nested recurse calls if
  23983. //the define call references an identifier that is likely a UMD
  23984. //wrapped function expression argument.
  23985. //Catch (function(a) {... wrappers
  23986. if (object.type === 'ExpressionStatement' && object.expression &&
  23987. object.expression.type === 'CallExpression' && object.expression.callee &&
  23988. isFnExpression(object.expression.callee)) {
  23989. tempObject = object.expression.callee;
  23990. }
  23991. // Catch !function(a) {... wrappers
  23992. if (object.type === 'UnaryExpression' && object.argument &&
  23993. object.argument.type === 'CallExpression' && object.argument.callee &&
  23994. isFnExpression(object.argument.callee)) {
  23995. tempObject = object.argument.callee;
  23996. }
  23997. if (tempObject && tempObject.params && tempObject.params.length) {
  23998. params = tempObject.params;
  23999. fnExpScope = mixin({}, fnExpScope, true);
  24000. for (i = 0; i < params.length; i++) {
  24001. param = params[i];
  24002. if (param.type === 'Identifier') {
  24003. fnExpScope[param.name] = true;
  24004. }
  24005. }
  24006. }
  24007. for (key in object) {
  24008. if (object.hasOwnProperty(key)) {
  24009. child = object[key];
  24010. if (typeof child === 'object' && child !== null) {
  24011. result = this.recurse(child, onMatch, options, fnExpScope);
  24012. if (typeof result === 'string') {
  24013. break;
  24014. }
  24015. }
  24016. }
  24017. }
  24018. //Check for an identifier for a factory function identifier being
  24019. //passed in as a function expression, indicating a UMD-type of
  24020. //wrapping.
  24021. if (typeof result === 'string') {
  24022. if (hasProp(fnExpScope, result)) {
  24023. //result still in scope, keep jumping out indicating the
  24024. //identifier still in use.
  24025. return result;
  24026. }
  24027. return;
  24028. }
  24029. }
  24030. };
  24031. /**
  24032. * Determines if the file defines the require/define module API.
  24033. * Specifically, it looks for the `define.amd = ` expression.
  24034. * @param {String} fileName
  24035. * @param {String} fileContents
  24036. * @returns {Boolean}
  24037. */
  24038. parse.definesRequire = function (fileName, fileContents) {
  24039. var foundDefine = false,
  24040. foundDefineAmd = false;
  24041. traverse(esprima.parse(fileContents), function (node) {
  24042. // Look for a top level declaration of a define, like
  24043. // var requirejs, require, define, off Program body.
  24044. if (node.type === 'Program' && node.body && node.body.length) {
  24045. foundDefine = node.body.some(function(bodyNode) {
  24046. // var define
  24047. if (bodyNode.type === 'VariableDeclaration') {
  24048. var decls = bodyNode.declarations;
  24049. if (decls) {
  24050. var hasVarDefine = decls.some(function(declNode) {
  24051. return (declNode.type === 'VariableDeclarator' &&
  24052. declNode.id &&
  24053. declNode.id.type === 'Identifier' &&
  24054. declNode.id.name === 'define');
  24055. });
  24056. if (hasVarDefine) {
  24057. return true;
  24058. }
  24059. }
  24060. }
  24061. // function define() {}
  24062. if (bodyNode.type === 'FunctionDeclaration' &&
  24063. bodyNode.id &&
  24064. bodyNode.id.type === 'Identifier' &&
  24065. bodyNode.id.name === 'define') {
  24066. return true;
  24067. }
  24068. });
  24069. }
  24070. // Need define variable found first, before detecting define.amd.
  24071. if (foundDefine && parse.hasDefineAmd(node)) {
  24072. foundDefineAmd = true;
  24073. //Stop traversal
  24074. return false;
  24075. }
  24076. });
  24077. return foundDefine && foundDefineAmd;
  24078. };
  24079. /**
  24080. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  24081. * define(function(require, exports, module){}) wrapper. These dependencies
  24082. * will be added to a modified define() call that lists the dependencies
  24083. * on the outside of the function.
  24084. * @param {String} fileName
  24085. * @param {String|Object} fileContents: a string of contents, or an already
  24086. * parsed AST tree.
  24087. * @returns {Array} an array of module names that are dependencies. Always
  24088. * returns an array, but could be of length zero.
  24089. */
  24090. parse.getAnonDeps = function (fileName, fileContents) {
  24091. var astRoot = typeof fileContents === 'string' ?
  24092. esprima.parse(fileContents) : fileContents,
  24093. defFunc = this.findAnonDefineFactory(astRoot);
  24094. return parse.getAnonDepsFromNode(defFunc);
  24095. };
  24096. /**
  24097. * Finds require("") calls inside a CommonJS anonymous module wrapped
  24098. * in a define function, given an AST node for the definition function.
  24099. * @param {Node} node the AST node for the definition function.
  24100. * @returns {Array} and array of dependency names. Can be of zero length.
  24101. */
  24102. parse.getAnonDepsFromNode = function (node) {
  24103. var deps = [],
  24104. funcArgLength;
  24105. if (node) {
  24106. this.findRequireDepNames(node, deps);
  24107. //If no deps, still add the standard CommonJS require, exports,
  24108. //module, in that order, to the deps, but only if specified as
  24109. //function args. In particular, if exports is used, it is favored
  24110. //over the return value of the function, so only add it if asked.
  24111. funcArgLength = node.params && node.params.length;
  24112. if (funcArgLength) {
  24113. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  24114. ["require"]).concat(deps);
  24115. }
  24116. }
  24117. return deps;
  24118. };
  24119. parse.isDefineNodeWithArgs = function (node) {
  24120. return node && node.type === 'CallExpression' &&
  24121. node.callee && node.callee.type === 'Identifier' &&
  24122. node.callee.name === 'define' && node[argPropName];
  24123. };
  24124. /**
  24125. * Finds the function in define(function (require, exports, module){});
  24126. * @param {Array} node
  24127. * @returns {Boolean}
  24128. */
  24129. parse.findAnonDefineFactory = function (node) {
  24130. var match;
  24131. traverse(node, function (node) {
  24132. var arg0, arg1;
  24133. if (parse.isDefineNodeWithArgs(node)) {
  24134. //Just the factory function passed to define
  24135. arg0 = node[argPropName][0];
  24136. if (isFnExpression(arg0)) {
  24137. match = arg0;
  24138. return false;
  24139. }
  24140. //A string literal module ID followed by the factory function.
  24141. arg1 = node[argPropName][1];
  24142. if (arg0.type === 'Literal' && isFnExpression(arg1)) {
  24143. match = arg1;
  24144. return false;
  24145. }
  24146. }
  24147. });
  24148. return match;
  24149. };
  24150. /**
  24151. * Finds any config that is passed to requirejs. That includes calls to
  24152. * require/requirejs.config(), as well as require({}, ...) and
  24153. * requirejs({}, ...)
  24154. * @param {String} fileContents
  24155. *
  24156. * @returns {Object} a config details object with the following properties:
  24157. * - config: {Object} the config object found. Can be undefined if no
  24158. * config found.
  24159. * - range: {Array} the start index and end index in the contents where
  24160. * the config was found. Can be undefined if no config found.
  24161. * Can throw an error if the config in the file cannot be evaluated in
  24162. * a build context to valid JavaScript.
  24163. */
  24164. parse.findConfig = function (fileContents) {
  24165. /*jslint evil: true */
  24166. var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
  24167. quoteRegExp = /(:\s|\[\s*)(['"])/,
  24168. astRoot = esprima.parse(fileContents, {
  24169. loc: true
  24170. });
  24171. traverse(astRoot, function (node) {
  24172. var arg,
  24173. requireType = parse.hasRequire(node);
  24174. if (requireType && (requireType === 'require' ||
  24175. requireType === 'requirejs' ||
  24176. requireType === 'requireConfig' ||
  24177. requireType === 'requirejsConfig')) {
  24178. arg = node[argPropName] && node[argPropName][0];
  24179. if (arg && arg.type === 'ObjectExpression') {
  24180. stringData = parse.nodeToString(fileContents, arg);
  24181. jsConfig = stringData.value;
  24182. foundRange = stringData.range;
  24183. return false;
  24184. }
  24185. } else {
  24186. arg = parse.getRequireObjectLiteral(node);
  24187. if (arg) {
  24188. stringData = parse.nodeToString(fileContents, arg);
  24189. jsConfig = stringData.value;
  24190. foundRange = stringData.range;
  24191. return false;
  24192. }
  24193. }
  24194. });
  24195. if (jsConfig) {
  24196. // Eval the config
  24197. quoteMatch = quoteRegExp.exec(jsConfig);
  24198. quote = (quoteMatch && quoteMatch[2]) || '"';
  24199. foundConfig = eval('(' + jsConfig + ')');
  24200. }
  24201. return {
  24202. config: foundConfig,
  24203. range: foundRange,
  24204. quote: quote
  24205. };
  24206. };
  24207. /** Returns the node for the object literal assigned to require/requirejs,
  24208. * for holding a declarative config.
  24209. */
  24210. parse.getRequireObjectLiteral = function (node) {
  24211. if (node.id && node.id.type === 'Identifier' &&
  24212. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  24213. node.init && node.init.type === 'ObjectExpression') {
  24214. return node.init;
  24215. }
  24216. };
  24217. /**
  24218. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  24219. * Does *not* do .config calls though. See pragma.namespace for the complete
  24220. * set of namespace transforms. This function is used because require calls
  24221. * inside a define() call should not be renamed, so a simple regexp is not
  24222. * good enough.
  24223. * @param {String} fileContents the contents to transform.
  24224. * @param {String} ns the namespace, *not* including trailing dot.
  24225. * @return {String} the fileContents with the namespace applied
  24226. */
  24227. parse.renameNamespace = function (fileContents, ns) {
  24228. var lines,
  24229. locs = [],
  24230. astRoot = esprima.parse(fileContents, {
  24231. loc: true
  24232. });
  24233. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  24234. locs.push(node.loc);
  24235. //Do not recurse into define functions, they should be using
  24236. //local defines.
  24237. return callName !== 'define';
  24238. }, {});
  24239. if (locs.length) {
  24240. lines = fileContents.split('\n');
  24241. //Go backwards through the found locs, adding in the namespace name
  24242. //in front.
  24243. locs.reverse();
  24244. locs.forEach(function (loc) {
  24245. var startIndex = loc.start.column,
  24246. //start.line is 1-based, not 0 based.
  24247. lineIndex = loc.start.line - 1,
  24248. line = lines[lineIndex];
  24249. lines[lineIndex] = line.substring(0, startIndex) +
  24250. ns + '.' +
  24251. line.substring(startIndex,
  24252. line.length);
  24253. });
  24254. fileContents = lines.join('\n');
  24255. }
  24256. return fileContents;
  24257. };
  24258. /**
  24259. * Finds all dependencies specified in dependency arrays and inside
  24260. * simplified commonjs wrappers.
  24261. * @param {String} fileName
  24262. * @param {String} fileContents
  24263. *
  24264. * @returns {Array} an array of dependency strings. The dependencies
  24265. * have not been normalized, they may be relative IDs.
  24266. */
  24267. parse.findDependencies = function (fileName, fileContents, options) {
  24268. var dependencies = [],
  24269. astRoot = esprima.parse(fileContents);
  24270. parse.recurse(astRoot, function (callName, config, name, deps) {
  24271. if (deps) {
  24272. dependencies = dependencies.concat(deps);
  24273. }
  24274. }, options);
  24275. return dependencies;
  24276. };
  24277. /**
  24278. * Finds only CJS dependencies, ones that are the form
  24279. * require('stringLiteral')
  24280. */
  24281. parse.findCjsDependencies = function (fileName, fileContents) {
  24282. var dependencies = [];
  24283. traverse(esprima.parse(fileContents), function (node) {
  24284. var arg;
  24285. if (node && node.type === 'CallExpression' && node.callee &&
  24286. node.callee.type === 'Identifier' &&
  24287. node.callee.name === 'require' && node[argPropName] &&
  24288. node[argPropName].length === 1) {
  24289. arg = node[argPropName][0];
  24290. if (arg.type === 'Literal') {
  24291. dependencies.push(arg.value);
  24292. }
  24293. }
  24294. });
  24295. return dependencies;
  24296. };
  24297. //function define() {}
  24298. parse.hasDefDefine = function (node) {
  24299. return node.type === 'FunctionDeclaration' && node.id &&
  24300. node.id.type === 'Identifier' && node.id.name === 'define';
  24301. };
  24302. //define.amd = ...
  24303. parse.hasDefineAmd = function (node) {
  24304. return node && node.type === 'AssignmentExpression' &&
  24305. node.left && node.left.type === 'MemberExpression' &&
  24306. node.left.object && node.left.object.name === 'define' &&
  24307. node.left.property && node.left.property.name === 'amd';
  24308. };
  24309. //define.amd reference, as in: if (define.amd)
  24310. parse.refsDefineAmd = function (node) {
  24311. return node && node.type === 'MemberExpression' &&
  24312. node.object && node.object.name === 'define' &&
  24313. node.object.type === 'Identifier' &&
  24314. node.property && node.property.name === 'amd' &&
  24315. node.property.type === 'Identifier';
  24316. };
  24317. //require(), requirejs(), require.config() and requirejs.config()
  24318. parse.hasRequire = function (node) {
  24319. var callName,
  24320. c = node && node.callee;
  24321. if (node && node.type === 'CallExpression' && c) {
  24322. if (c.type === 'Identifier' &&
  24323. (c.name === 'require' ||
  24324. c.name === 'requirejs')) {
  24325. //A require/requirejs({}, ...) call
  24326. callName = c.name;
  24327. } else if (c.type === 'MemberExpression' &&
  24328. c.object &&
  24329. c.object.type === 'Identifier' &&
  24330. (c.object.name === 'require' ||
  24331. c.object.name === 'requirejs') &&
  24332. c.property && c.property.name === 'config') {
  24333. // require/requirejs.config({}) call
  24334. callName = c.object.name + 'Config';
  24335. }
  24336. }
  24337. return callName;
  24338. };
  24339. //define()
  24340. parse.hasDefine = function (node) {
  24341. return node && node.type === 'CallExpression' && node.callee &&
  24342. node.callee.type === 'Identifier' &&
  24343. node.callee.name === 'define';
  24344. };
  24345. /**
  24346. * If there is a named define in the file, returns the name. Does not
  24347. * scan for mulitple names, just the first one.
  24348. */
  24349. parse.getNamedDefine = function (fileContents) {
  24350. var name;
  24351. traverse(esprima.parse(fileContents), function (node) {
  24352. if (node && node.type === 'CallExpression' && node.callee &&
  24353. node.callee.type === 'Identifier' &&
  24354. node.callee.name === 'define' &&
  24355. node[argPropName] && node[argPropName][0] &&
  24356. node[argPropName][0].type === 'Literal') {
  24357. name = node[argPropName][0].value;
  24358. return false;
  24359. }
  24360. });
  24361. return name;
  24362. };
  24363. /**
  24364. * Determines if define(), require({}|[]) or requirejs was called in the
  24365. * file. Also finds out if define() is declared and if define.amd is called.
  24366. */
  24367. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  24368. var uses;
  24369. traverse(esprima.parse(fileContents), function (node) {
  24370. var type, callName, arg;
  24371. if (parse.hasDefDefine(node)) {
  24372. //function define() {}
  24373. type = 'declaresDefine';
  24374. } else if (parse.hasDefineAmd(node)) {
  24375. type = 'defineAmd';
  24376. } else {
  24377. callName = parse.hasRequire(node);
  24378. if (callName) {
  24379. arg = node[argPropName] && node[argPropName][0];
  24380. if (arg && (arg.type === 'ObjectExpression' ||
  24381. arg.type === 'ArrayExpression')) {
  24382. type = callName;
  24383. }
  24384. } else if (parse.hasDefine(node)) {
  24385. type = 'define';
  24386. }
  24387. }
  24388. if (type) {
  24389. if (!uses) {
  24390. uses = {};
  24391. }
  24392. uses[type] = true;
  24393. }
  24394. });
  24395. return uses;
  24396. };
  24397. /**
  24398. * Determines if require(''), exports.x =, module.exports =,
  24399. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  24400. * also checks for Node variants.
  24401. */
  24402. parse.usesCommonJs = function (fileName, fileContents) {
  24403. var uses = null,
  24404. assignsExports = false;
  24405. traverse(esprima.parse(fileContents), function (node) {
  24406. var type,
  24407. exp = node.expression || node.init;
  24408. if (node.type === 'Identifier' &&
  24409. (node.name === '__dirname' || node.name === '__filename')) {
  24410. type = node.name.substring(2);
  24411. } else if (node.type === 'VariableDeclarator' && node.id &&
  24412. node.id.type === 'Identifier' &&
  24413. node.id.name === 'exports') {
  24414. //Hmm, a variable assignment for exports, so does not use cjs
  24415. //exports.
  24416. type = 'varExports';
  24417. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  24418. exp.left.type === 'MemberExpression' && exp.left.object) {
  24419. if (exp.left.object.name === 'module' && exp.left.property &&
  24420. exp.left.property.name === 'exports') {
  24421. type = 'moduleExports';
  24422. } else if (exp.left.object.name === 'exports' &&
  24423. exp.left.property) {
  24424. type = 'exports';
  24425. }
  24426. } else if (node && node.type === 'CallExpression' && node.callee &&
  24427. node.callee.type === 'Identifier' &&
  24428. node.callee.name === 'require' && node[argPropName] &&
  24429. node[argPropName].length === 1 &&
  24430. node[argPropName][0].type === 'Literal') {
  24431. type = 'require';
  24432. }
  24433. if (type) {
  24434. if (type === 'varExports') {
  24435. assignsExports = true;
  24436. } else if (type !== 'exports' || !assignsExports) {
  24437. if (!uses) {
  24438. uses = {};
  24439. }
  24440. uses[type] = true;
  24441. }
  24442. }
  24443. });
  24444. return uses;
  24445. };
  24446. parse.findRequireDepNames = function (node, deps) {
  24447. traverse(node, function (node) {
  24448. var arg;
  24449. if (node && node.type === 'CallExpression' && node.callee &&
  24450. node.callee.type === 'Identifier' &&
  24451. node.callee.name === 'require' &&
  24452. node[argPropName] && node[argPropName].length === 1) {
  24453. arg = node[argPropName][0];
  24454. if (arg.type === 'Literal') {
  24455. deps.push(arg.value);
  24456. }
  24457. }
  24458. });
  24459. };
  24460. /**
  24461. * Determines if a specific node is a valid require or define/require.def
  24462. * call.
  24463. * @param {Array} node
  24464. * @param {Function} onMatch a function to call when a match is found.
  24465. * It is passed the match name, and the config, name, deps possible args.
  24466. * The config, name and deps args are not normalized.
  24467. * @param {Object} fnExpScope an object whose keys are all function
  24468. * expression identifiers that should be in scope. Useful for UMD wrapper
  24469. * detection to avoid parsing more into the wrapped UMD code.
  24470. *
  24471. * @returns {String} a JS source string with the valid require/define call.
  24472. * Otherwise null.
  24473. */
  24474. parse.parseNode = function (node, onMatch, fnExpScope) {
  24475. var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
  24476. args = node && node[argPropName],
  24477. callName = parse.hasRequire(node),
  24478. isUmd = false;
  24479. if (callName === 'require' || callName === 'requirejs') {
  24480. //A plain require/requirejs call
  24481. arg = node[argPropName] && node[argPropName][0];
  24482. if (arg && arg.type !== 'ArrayExpression') {
  24483. if (arg.type === 'ObjectExpression') {
  24484. //A config call, try the second arg.
  24485. arg = node[argPropName][1];
  24486. }
  24487. }
  24488. deps = getValidDeps(arg);
  24489. if (!deps) {
  24490. return;
  24491. }
  24492. return onMatch("require", null, null, deps, node);
  24493. } else if (parse.hasDefine(node) && args && args.length) {
  24494. name = args[0];
  24495. deps = args[1];
  24496. factory = args[2];
  24497. if (name.type === 'ArrayExpression') {
  24498. //No name, adjust args
  24499. factory = deps;
  24500. deps = name;
  24501. name = null;
  24502. } else if (isFnExpression(name)) {
  24503. //Just the factory, no name or deps
  24504. factory = name;
  24505. name = deps = null;
  24506. } else if (name.type === 'Identifier' && args.length === 1 &&
  24507. hasProp(fnExpScope, name.name)) {
  24508. //define(e) where e is a UMD identifier for the factory
  24509. //function.
  24510. isUmd = true;
  24511. factory = name;
  24512. name = null;
  24513. } else if (name.type !== 'Literal') {
  24514. //An object literal, just null out
  24515. name = deps = factory = null;
  24516. }
  24517. if (name && name.type === 'Literal' && deps) {
  24518. if (isFnExpression(deps)) {
  24519. //deps is the factory
  24520. factory = deps;
  24521. deps = null;
  24522. } else if (deps.type === 'ObjectExpression') {
  24523. //deps is object literal, null out
  24524. deps = factory = null;
  24525. } else if (deps.type === 'Identifier') {
  24526. if (args.length === 2) {
  24527. //define('id', factory)
  24528. deps = factory = null;
  24529. } else if (args.length === 3 && isFnExpression(factory)) {
  24530. //define('id', depsIdentifier, factory)
  24531. //Since identifier, cannot know the deps, but do not
  24532. //error out, assume they are taken care of outside of
  24533. //static parsing.
  24534. deps = null;
  24535. }
  24536. }
  24537. }
  24538. if (deps && deps.type === 'ArrayExpression') {
  24539. deps = getValidDeps(deps);
  24540. } else if (isFnExpression(factory)) {
  24541. //If no deps and a factory function, could be a commonjs sugar
  24542. //wrapper, scan the function for dependencies.
  24543. cjsDeps = parse.getAnonDepsFromNode(factory);
  24544. if (cjsDeps.length) {
  24545. deps = cjsDeps;
  24546. }
  24547. } else if (deps || (factory && !isUmd)) {
  24548. //Does not match the shape of an AMD call.
  24549. return;
  24550. }
  24551. //Just save off the name as a string instead of an AST object.
  24552. if (name && name.type === 'Literal') {
  24553. name = name.value;
  24554. }
  24555. return onMatch("define", null, name, deps, node,
  24556. (factory && factory.type === 'Identifier' ? factory.name : undefined),
  24557. fnExpScope);
  24558. } else if (node.type === 'CallExpression' && node.callee &&
  24559. isFnExpression(node.callee) &&
  24560. node.callee.body && node.callee.body.body &&
  24561. node.callee.body.body.length === 1 &&
  24562. node.callee.body.body[0].type === 'IfStatement') {
  24563. bodyNode = node.callee.body.body[0];
  24564. //Look for a define(Identifier) case, but only if inside an
  24565. //if that has a define.amd test
  24566. if (bodyNode.consequent && bodyNode.consequent.body) {
  24567. exp = bodyNode.consequent.body[0];
  24568. if (exp.type === 'ExpressionStatement' && exp.expression &&
  24569. parse.hasDefine(exp.expression) &&
  24570. exp.expression.arguments &&
  24571. exp.expression.arguments.length === 1 &&
  24572. exp.expression.arguments[0].type === 'Identifier') {
  24573. //Calls define(Identifier) as first statement in body.
  24574. //Confirm the if test references define.amd
  24575. traverse(bodyNode.test, function (node) {
  24576. if (parse.refsDefineAmd(node)) {
  24577. refsDefine = true;
  24578. return false;
  24579. }
  24580. });
  24581. if (refsDefine) {
  24582. return onMatch("define", null, null, null, exp.expression,
  24583. exp.expression.arguments[0].name, fnExpScope);
  24584. }
  24585. }
  24586. }
  24587. }
  24588. };
  24589. /**
  24590. * Converts an AST node into a JS source string by extracting
  24591. * the node's location from the given contents string. Assumes
  24592. * esprima.parse() with loc was done.
  24593. * @param {String} contents
  24594. * @param {Object} node
  24595. * @returns {String} a JS source string.
  24596. */
  24597. parse.nodeToString = function (contents, node) {
  24598. var extracted,
  24599. loc = node.loc,
  24600. lines = contents.split('\n'),
  24601. firstLine = loc.start.line > 1 ?
  24602. lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
  24603. '',
  24604. preamble = firstLine +
  24605. lines[loc.start.line - 1].substring(0, loc.start.column);
  24606. if (loc.start.line === loc.end.line) {
  24607. extracted = lines[loc.start.line - 1].substring(loc.start.column,
  24608. loc.end.column);
  24609. } else {
  24610. extracted = lines[loc.start.line - 1].substring(loc.start.column) +
  24611. '\n' +
  24612. lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
  24613. '\n' +
  24614. lines[loc.end.line - 1].substring(0, loc.end.column);
  24615. }
  24616. return {
  24617. value: extracted,
  24618. range: [
  24619. preamble.length,
  24620. preamble.length + extracted.length
  24621. ]
  24622. };
  24623. };
  24624. /**
  24625. * Extracts license comments from JS text.
  24626. * @param {String} fileName
  24627. * @param {String} contents
  24628. * @returns {String} a string of license comments.
  24629. */
  24630. parse.getLicenseComments = function (fileName, contents) {
  24631. var commentNode, refNode, subNode, value, i, j,
  24632. //xpconnect's Reflect does not support comment or range, but
  24633. //prefer continued operation vs strict parity of operation,
  24634. //as license comments can be expressed in other ways, like
  24635. //via wrap args, or linked via sourcemaps.
  24636. ast = esprima.parse(contents, {
  24637. comment: true,
  24638. range: true
  24639. }),
  24640. result = '',
  24641. existsMap = {},
  24642. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  24643. if (ast.comments) {
  24644. for (i = 0; i < ast.comments.length; i++) {
  24645. commentNode = ast.comments[i];
  24646. if (commentNode.type === 'Line') {
  24647. value = '//' + commentNode.value + lineEnd;
  24648. refNode = commentNode;
  24649. if (i + 1 >= ast.comments.length) {
  24650. value += lineEnd;
  24651. } else {
  24652. //Look for immediately adjacent single line comments
  24653. //since it could from a multiple line comment made out
  24654. //of single line comments. Like this comment.
  24655. for (j = i + 1; j < ast.comments.length; j++) {
  24656. subNode = ast.comments[j];
  24657. if (subNode.type === 'Line' &&
  24658. subNode.range[0] === refNode.range[1] + 1) {
  24659. //Adjacent single line comment. Collect it.
  24660. value += '//' + subNode.value + lineEnd;
  24661. refNode = subNode;
  24662. } else {
  24663. //No more single line comment blocks. Break out
  24664. //and continue outer looping.
  24665. break;
  24666. }
  24667. }
  24668. value += lineEnd;
  24669. i = j - 1;
  24670. }
  24671. } else {
  24672. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  24673. }
  24674. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  24675. (commentNode.type === 'Block' &&
  24676. value.indexOf('/*!') === 0) ||
  24677. value.indexOf('opyright') !== -1 ||
  24678. value.indexOf('(c)') !== -1)) {
  24679. result += value;
  24680. existsMap[value] = true;
  24681. }
  24682. }
  24683. }
  24684. return result;
  24685. };
  24686. return parse;
  24687. });
  24688. /**
  24689. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  24690. * Available via the MIT or new BSD license.
  24691. * see: http://github.com/jrburke/requirejs for details
  24692. */
  24693. /*global define */
  24694. define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
  24695. function (esprima, parse, logger, lang) {
  24696. 'use strict';
  24697. var transform,
  24698. baseIndentRegExp = /^([ \t]+)/,
  24699. indentRegExp = /\{[\r\n]+([ \t]+)/,
  24700. keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
  24701. bulkIndentRegExps = {
  24702. '\n': /\n/g,
  24703. '\r\n': /\r\n/g
  24704. };
  24705. function applyIndent(str, indent, lineReturn) {
  24706. var regExp = bulkIndentRegExps[lineReturn];
  24707. return str.replace(regExp, '$&' + indent);
  24708. }
  24709. transform = {
  24710. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  24711. options = options || {};
  24712. var astRoot, contentLines, modLine,
  24713. foundAnon,
  24714. scanCount = 0,
  24715. scanReset = false,
  24716. defineInfos = [],
  24717. applySourceUrl = function (contents) {
  24718. if (options.useSourceUrl) {
  24719. contents = 'eval("' + lang.jsEscape(contents) +
  24720. '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  24721. path +
  24722. '");\n';
  24723. }
  24724. return contents;
  24725. };
  24726. try {
  24727. astRoot = esprima.parse(contents, {
  24728. loc: true
  24729. });
  24730. } catch (e) {
  24731. logger.trace('toTransport skipping ' + path + ': ' +
  24732. e.toString());
  24733. return contents;
  24734. }
  24735. //Find the define calls and their position in the files.
  24736. parse.traverse(astRoot, function (node) {
  24737. var args, firstArg, firstArgLoc, factoryNode,
  24738. needsId, depAction, foundId, init,
  24739. sourceUrlData, range,
  24740. namespaceExists = false;
  24741. // If a bundle script with a define declaration, do not
  24742. // parse any further at this level. Likely a built layer
  24743. // by some other tool.
  24744. if (node.type === 'VariableDeclarator' &&
  24745. node.id && node.id.name === 'define' &&
  24746. node.id.type === 'Identifier') {
  24747. init = node.init;
  24748. if (init && init.callee &&
  24749. init.callee.type === 'CallExpression' &&
  24750. init.callee.callee &&
  24751. init.callee.callee.type === 'Identifier' &&
  24752. init.callee.callee.name === 'require' &&
  24753. init.callee.arguments && init.callee.arguments.length === 1 &&
  24754. init.callee.arguments[0].type === 'Literal' &&
  24755. init.callee.arguments[0].value &&
  24756. init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
  24757. // the var define = require('amdefine')(module) case,
  24758. // keep going in that case.
  24759. } else {
  24760. return false;
  24761. }
  24762. }
  24763. namespaceExists = namespace &&
  24764. node.type === 'CallExpression' &&
  24765. node.callee && node.callee.object &&
  24766. node.callee.object.type === 'Identifier' &&
  24767. node.callee.object.name === namespace &&
  24768. node.callee.property.type === 'Identifier' &&
  24769. node.callee.property.name === 'define';
  24770. if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
  24771. //The arguments are where its at.
  24772. args = node.arguments;
  24773. if (!args || !args.length) {
  24774. return;
  24775. }
  24776. firstArg = args[0];
  24777. firstArgLoc = firstArg.loc;
  24778. if (args.length === 1) {
  24779. if (firstArg.type === 'Identifier') {
  24780. //The define(factory) case, but
  24781. //only allow it if one Identifier arg,
  24782. //to limit impact of false positives.
  24783. needsId = true;
  24784. depAction = 'empty';
  24785. } else if (parse.isFnExpression(firstArg)) {
  24786. //define(function(){})
  24787. factoryNode = firstArg;
  24788. needsId = true;
  24789. depAction = 'scan';
  24790. } else if (firstArg.type === 'ObjectExpression') {
  24791. //define({});
  24792. needsId = true;
  24793. depAction = 'skip';
  24794. } else if (firstArg.type === 'Literal' &&
  24795. typeof firstArg.value === 'number') {
  24796. //define('12345');
  24797. needsId = true;
  24798. depAction = 'skip';
  24799. } else if (firstArg.type === 'UnaryExpression' &&
  24800. firstArg.operator === '-' &&
  24801. firstArg.argument &&
  24802. firstArg.argument.type === 'Literal' &&
  24803. typeof firstArg.argument.value === 'number') {
  24804. //define('-12345');
  24805. needsId = true;
  24806. depAction = 'skip';
  24807. } else if (firstArg.type === 'MemberExpression' &&
  24808. firstArg.object &&
  24809. firstArg.property &&
  24810. firstArg.property.type === 'Identifier') {
  24811. //define(this.key);
  24812. needsId = true;
  24813. depAction = 'empty';
  24814. }
  24815. } else if (firstArg.type === 'ArrayExpression') {
  24816. //define([], ...);
  24817. needsId = true;
  24818. depAction = 'skip';
  24819. } else if (firstArg.type === 'Literal' &&
  24820. typeof firstArg.value === 'string') {
  24821. //define('string', ....)
  24822. //Already has an ID.
  24823. needsId = false;
  24824. if (args.length === 2 &&
  24825. parse.isFnExpression(args[1])) {
  24826. //Needs dependency scanning.
  24827. factoryNode = args[1];
  24828. depAction = 'scan';
  24829. } else {
  24830. depAction = 'skip';
  24831. }
  24832. } else {
  24833. //Unknown define entity, keep looking, even
  24834. //in the subtree for this node.
  24835. return;
  24836. }
  24837. range = {
  24838. foundId: foundId,
  24839. needsId: needsId,
  24840. depAction: depAction,
  24841. namespaceExists: namespaceExists,
  24842. node: node,
  24843. defineLoc: node.loc,
  24844. firstArgLoc: firstArgLoc,
  24845. factoryNode: factoryNode,
  24846. sourceUrlData: sourceUrlData
  24847. };
  24848. //Only transform ones that do not have IDs. If it has an
  24849. //ID but no dependency array, assume it is something like
  24850. //a phonegap implementation, that has its own internal
  24851. //define that cannot handle dependency array constructs,
  24852. //and if it is a named module, then it means it has been
  24853. //set for transport form.
  24854. if (range.needsId) {
  24855. if (foundAnon) {
  24856. logger.trace(path + ' has more than one anonymous ' +
  24857. 'define. May be a built file from another ' +
  24858. 'build system like, Ender. Skipping normalization.');
  24859. defineInfos = [];
  24860. return false;
  24861. } else {
  24862. foundAnon = range;
  24863. defineInfos.push(range);
  24864. }
  24865. } else if (depAction === 'scan') {
  24866. scanCount += 1;
  24867. if (scanCount > 1) {
  24868. //Just go back to an array that just has the
  24869. //anon one, since this is an already optimized
  24870. //file like the phonegap one.
  24871. if (!scanReset) {
  24872. defineInfos = foundAnon ? [foundAnon] : [];
  24873. scanReset = true;
  24874. }
  24875. } else {
  24876. defineInfos.push(range);
  24877. }
  24878. }
  24879. }
  24880. });
  24881. if (!defineInfos.length) {
  24882. return applySourceUrl(contents);
  24883. }
  24884. //Reverse the matches, need to start from the bottom of
  24885. //the file to modify it, so that the ranges are still true
  24886. //further up.
  24887. defineInfos.reverse();
  24888. contentLines = contents.split('\n');
  24889. modLine = function (loc, contentInsertion) {
  24890. var startIndex = loc.start.column,
  24891. //start.line is 1-based, not 0 based.
  24892. lineIndex = loc.start.line - 1,
  24893. line = contentLines[lineIndex];
  24894. contentLines[lineIndex] = line.substring(0, startIndex) +
  24895. contentInsertion +
  24896. line.substring(startIndex,
  24897. line.length);
  24898. };
  24899. defineInfos.forEach(function (info) {
  24900. var deps,
  24901. contentInsertion = '',
  24902. depString = '';
  24903. //Do the modifications "backwards", in other words, start with the
  24904. //one that is farthest down and work up, so that the ranges in the
  24905. //defineInfos still apply. So that means deps, id, then namespace.
  24906. if (info.needsId && moduleName) {
  24907. contentInsertion += "'" + moduleName + "',";
  24908. }
  24909. if (info.depAction === 'scan') {
  24910. deps = parse.getAnonDepsFromNode(info.factoryNode);
  24911. if (deps.length) {
  24912. depString = '[' + deps.map(function (dep) {
  24913. return "'" + dep + "'";
  24914. }) + ']';
  24915. } else {
  24916. depString = '[]';
  24917. }
  24918. depString += ',';
  24919. if (info.factoryNode) {
  24920. //Already have a named module, need to insert the
  24921. //dependencies after the name.
  24922. modLine(info.factoryNode.loc, depString);
  24923. } else {
  24924. contentInsertion += depString;
  24925. }
  24926. }
  24927. if (contentInsertion) {
  24928. modLine(info.firstArgLoc, contentInsertion);
  24929. }
  24930. //Do namespace last so that ui does not mess upthe parenRange
  24931. //used above.
  24932. if (namespace && !info.namespaceExists) {
  24933. modLine(info.defineLoc, namespace + '.');
  24934. }
  24935. //Notify any listener for the found info
  24936. if (onFound) {
  24937. onFound(info);
  24938. }
  24939. });
  24940. contents = contentLines.join('\n');
  24941. return applySourceUrl(contents);
  24942. },
  24943. /**
  24944. * Modify the contents of a require.config/requirejs.config call. This
  24945. * call will LOSE any existing comments that are in the config string.
  24946. *
  24947. * @param {String} fileContents String that may contain a config call
  24948. * @param {Function} onConfig Function called when the first config
  24949. * call is found. It will be passed an Object which is the current
  24950. * config, and the onConfig function should return an Object to use
  24951. * as the config.
  24952. * @return {String} the fileContents with the config changes applied.
  24953. */
  24954. modifyConfig: function (fileContents, onConfig) {
  24955. var details = parse.findConfig(fileContents),
  24956. config = details.config;
  24957. if (config) {
  24958. config = onConfig(config);
  24959. if (config) {
  24960. return transform.serializeConfig(config,
  24961. fileContents,
  24962. details.range[0],
  24963. details.range[1],
  24964. {
  24965. quote: details.quote
  24966. });
  24967. }
  24968. }
  24969. return fileContents;
  24970. },
  24971. serializeConfig: function (config, fileContents, start, end, options) {
  24972. //Calculate base level of indent
  24973. var indent, match, configString, outDentRegExp,
  24974. baseIndent = '',
  24975. startString = fileContents.substring(0, start),
  24976. existingConfigString = fileContents.substring(start, end),
  24977. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  24978. lastReturnIndex = startString.lastIndexOf('\n');
  24979. //Get the basic amount of indent for the require config call.
  24980. if (lastReturnIndex === -1) {
  24981. lastReturnIndex = 0;
  24982. }
  24983. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  24984. if (match && match[1]) {
  24985. baseIndent = match[1];
  24986. }
  24987. //Calculate internal indentation for config
  24988. match = indentRegExp.exec(existingConfigString);
  24989. if (match && match[1]) {
  24990. indent = match[1];
  24991. }
  24992. if (!indent || indent.length < baseIndent) {
  24993. indent = ' ';
  24994. } else {
  24995. indent = indent.substring(baseIndent.length);
  24996. }
  24997. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  24998. configString = transform.objectToString(config, {
  24999. indent: indent,
  25000. lineReturn: lineReturn,
  25001. outDentRegExp: outDentRegExp,
  25002. quote: options && options.quote
  25003. });
  25004. //Add in the base indenting level.
  25005. configString = applyIndent(configString, baseIndent, lineReturn);
  25006. return startString + configString + fileContents.substring(end);
  25007. },
  25008. /**
  25009. * Tries converting a JS object to a string. This will likely suck, and
  25010. * is tailored to the type of config expected in a loader config call.
  25011. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  25012. * no weird recursively referenced stuff.
  25013. * @param {Object} obj the object to convert
  25014. * @param {Object} options options object with the following values:
  25015. * {String} indent the indentation to use for each level
  25016. * {String} lineReturn the type of line return to use
  25017. * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  25018. * {String} quote the quote type to use, ' or ". Optional. Default is "
  25019. * @param {String} totalIndent the total indent to print for this level
  25020. * @return {String} a string representation of the object.
  25021. */
  25022. objectToString: function (obj, options, totalIndent) {
  25023. var startBrace, endBrace, nextIndent,
  25024. first = true,
  25025. value = '',
  25026. lineReturn = options.lineReturn,
  25027. indent = options.indent,
  25028. outDentRegExp = options.outDentRegExp,
  25029. quote = options.quote || '"';
  25030. totalIndent = totalIndent || '';
  25031. nextIndent = totalIndent + indent;
  25032. if (obj === null) {
  25033. value = 'null';
  25034. } else if (obj === undefined) {
  25035. value = 'undefined';
  25036. } else if (typeof obj === 'number' || typeof obj === 'boolean') {
  25037. value = obj;
  25038. } else if (typeof obj === 'string') {
  25039. //Use double quotes in case the config may also work as JSON.
  25040. value = quote + lang.jsEscape(obj) + quote;
  25041. } else if (lang.isArray(obj)) {
  25042. lang.each(obj, function (item, i) {
  25043. value += (i !== 0 ? ',' + lineReturn : '' ) +
  25044. nextIndent +
  25045. transform.objectToString(item,
  25046. options,
  25047. nextIndent);
  25048. });
  25049. startBrace = '[';
  25050. endBrace = ']';
  25051. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  25052. //The outdent regexp just helps pretty up the conversion
  25053. //just in node. Rhino strips comments and does a different
  25054. //indent scheme for Function toString, so not really helpful
  25055. //there.
  25056. value = obj.toString().replace(outDentRegExp, '$1');
  25057. } else {
  25058. //An object
  25059. lang.eachProp(obj, function (v, prop) {
  25060. value += (first ? '': ',' + lineReturn) +
  25061. nextIndent +
  25062. (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
  25063. ': ' +
  25064. transform.objectToString(v,
  25065. options,
  25066. nextIndent);
  25067. first = false;
  25068. });
  25069. startBrace = '{';
  25070. endBrace = '}';
  25071. }
  25072. if (startBrace) {
  25073. value = startBrace +
  25074. lineReturn +
  25075. value +
  25076. lineReturn + totalIndent +
  25077. endBrace;
  25078. }
  25079. return value;
  25080. }
  25081. };
  25082. return transform;
  25083. });
  25084. /**
  25085. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25086. * Available via the MIT or new BSD license.
  25087. * see: http://github.com/jrburke/requirejs for details
  25088. */
  25089. /*jslint regexp: true, plusplus: true */
  25090. /*global define: false */
  25091. define('pragma', ['parse', 'logger'], function (parse, logger) {
  25092. 'use strict';
  25093. function Temp() {}
  25094. function create(obj, mixin) {
  25095. Temp.prototype = obj;
  25096. var temp = new Temp(), prop;
  25097. //Avoid any extra memory hanging around
  25098. Temp.prototype = null;
  25099. if (mixin) {
  25100. for (prop in mixin) {
  25101. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  25102. temp[prop] = mixin[prop];
  25103. }
  25104. }
  25105. }
  25106. return temp; // Object
  25107. }
  25108. var pragma = {
  25109. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  25110. useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g,
  25111. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  25112. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  25113. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  25114. apiDefRegExp: /var requirejs,\s*require,\s*define;/,
  25115. defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  25116. defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  25117. defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  25118. defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  25119. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  25120. defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  25121. defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/,
  25122. defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/,
  25123. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  25124. removeStrict: function (contents, config) {
  25125. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1');
  25126. },
  25127. namespace: function (fileContents, ns, onLifecycleName) {
  25128. if (ns) {
  25129. //Namespace require/define calls
  25130. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  25131. fileContents = parse.renameNamespace(fileContents, ns);
  25132. //Namespace define ternary use:
  25133. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  25134. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  25135. //Namespace define jquery use:
  25136. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  25137. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  25138. //Namespace has.js define use:
  25139. fileContents = fileContents.replace(pragma.defineHasRegExp,
  25140. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  25141. //Namespace async.js define use:
  25142. fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp,
  25143. "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd");
  25144. //Namespace define checks.
  25145. //Do these ones last, since they are a subset of the more specific
  25146. //checks above.
  25147. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  25148. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  25149. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  25150. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  25151. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  25152. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  25153. fileContents = fileContents.replace(pragma.defineExistsRegExp,
  25154. "typeof " + ns + ".define !== 'undefined'");
  25155. //Check for require.js with the require/define definitions
  25156. if (pragma.apiDefRegExp.test(fileContents) &&
  25157. fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
  25158. //Wrap the file contents in a typeof check, and a function
  25159. //to contain the API globals.
  25160. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
  25161. "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
  25162. fileContents +
  25163. "\n" +
  25164. ns + ".requirejs = requirejs;" +
  25165. ns + ".require = require;" +
  25166. ns + ".define = define;\n" +
  25167. "}\n}());";
  25168. }
  25169. //Finally, if the file wants a special wrapper because it ties
  25170. //in to the requirejs internals in a way that would not fit
  25171. //the above matches, do that. Look for /*requirejs namespace: true*/
  25172. if (pragma.nsWrapRegExp.test(fileContents)) {
  25173. //Remove the pragma.
  25174. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  25175. //Alter the contents.
  25176. fileContents = '(function () {\n' +
  25177. 'var require = ' + ns + '.require,' +
  25178. 'requirejs = ' + ns + '.requirejs,' +
  25179. 'define = ' + ns + '.define;\n' +
  25180. fileContents +
  25181. '\n}());';
  25182. }
  25183. }
  25184. return fileContents;
  25185. },
  25186. /**
  25187. * processes the fileContents for some //>> conditional statements
  25188. */
  25189. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  25190. /*jslint evil: true */
  25191. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  25192. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  25193. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  25194. i, dep, moduleName, collectorMod,
  25195. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  25196. //Legacy arg defined to help in dojo conversion script. Remove later
  25197. //when dojo no longer needs conversion:
  25198. kwArgs = pragmas;
  25199. //Mix in a specific lifecycle scoped object, to allow targeting
  25200. //some pragmas/has tests to only when files are saved, or at different
  25201. //lifecycle events. Do not bother with kwArgs in this section, since
  25202. //the old dojo kwArgs were for all points in the build lifecycle.
  25203. if (onLifecycleName) {
  25204. lifecyclePragmas = config['pragmas' + onLifecycleName];
  25205. lifecycleHas = config['has' + onLifecycleName];
  25206. if (lifecyclePragmas) {
  25207. pragmas = create(pragmas || {}, lifecyclePragmas);
  25208. }
  25209. if (lifecycleHas) {
  25210. hasConfig = create(hasConfig || {}, lifecycleHas);
  25211. }
  25212. }
  25213. //Replace has references if desired
  25214. if (hasConfig) {
  25215. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  25216. if (hasConfig.hasOwnProperty(test)) {
  25217. return !!hasConfig[test];
  25218. }
  25219. return match;
  25220. });
  25221. }
  25222. if (!config.skipPragmas) {
  25223. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  25224. //Found a conditional. Get the conditional line.
  25225. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  25226. if (lineEndIndex === -1) {
  25227. lineEndIndex = fileContents.length - 1;
  25228. }
  25229. //Increment startIndex past the line so the next conditional search can be done.
  25230. startIndex = lineEndIndex + 1;
  25231. //Break apart the conditional.
  25232. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  25233. matches = conditionLine.match(pragma.conditionalRegExp);
  25234. if (matches) {
  25235. type = matches[1];
  25236. marker = matches[2];
  25237. condition = matches[3];
  25238. isTrue = false;
  25239. //See if the condition is true.
  25240. try {
  25241. isTrue = !!eval("(" + condition + ")");
  25242. } catch (e) {
  25243. throw "Error in file: " +
  25244. fileName +
  25245. ". Conditional comment: " +
  25246. conditionLine +
  25247. " failed with this error: " + e;
  25248. }
  25249. //Find the endpoint marker.
  25250. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  25251. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  25252. if (endMatches) {
  25253. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  25254. //Find the next line return based on the match position.
  25255. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  25256. if (lineEndIndex === -1) {
  25257. lineEndIndex = fileContents.length - 1;
  25258. }
  25259. //Should we include the segment?
  25260. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  25261. //Remove the conditional comments, and optionally remove the content inside
  25262. //the conditional comments.
  25263. startLength = startIndex - foundIndex;
  25264. fileContents = fileContents.substring(0, foundIndex) +
  25265. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  25266. fileContents.substring(lineEndIndex + 1, fileContents.length);
  25267. //Move startIndex to foundIndex, since that is the new position in the file
  25268. //where we need to look for more conditionals in the next while loop pass.
  25269. startIndex = foundIndex;
  25270. } else {
  25271. throw "Error in file: " +
  25272. fileName +
  25273. ". Cannot find end marker for conditional comment: " +
  25274. conditionLine;
  25275. }
  25276. }
  25277. }
  25278. }
  25279. //If need to find all plugin resources to optimize, do that now,
  25280. //before namespacing, since the namespacing will change the API
  25281. //names.
  25282. //If there is a plugin collector, scan the file for plugin resources.
  25283. if (config.optimizeAllPluginResources && pluginCollector) {
  25284. try {
  25285. deps = parse.findDependencies(fileName, fileContents);
  25286. if (deps.length) {
  25287. for (i = 0; i < deps.length; i++) {
  25288. dep = deps[i];
  25289. if (dep.indexOf('!') !== -1) {
  25290. moduleName = dep.split('!')[0];
  25291. collectorMod = pluginCollector[moduleName];
  25292. if (!collectorMod) {
  25293. collectorMod = pluginCollector[moduleName] = [];
  25294. }
  25295. collectorMod.push(dep);
  25296. }
  25297. }
  25298. }
  25299. } catch (eDep) {
  25300. logger.error('Parse error looking for plugin resources in ' +
  25301. fileName + ', skipping.');
  25302. }
  25303. }
  25304. //Strip amdefine use for node-shared modules.
  25305. if (!config.keepAmdefine) {
  25306. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  25307. }
  25308. //Do namespacing
  25309. if (onLifecycleName === 'OnSave' && config.namespace) {
  25310. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  25311. }
  25312. return pragma.removeStrict(fileContents, config);
  25313. }
  25314. };
  25315. return pragma;
  25316. });
  25317. if(env === 'browser') {
  25318. /**
  25319. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25320. * Available via the MIT or new BSD license.
  25321. * see: http://github.com/jrburke/requirejs for details
  25322. */
  25323. /*jslint strict: false */
  25324. /*global define: false */
  25325. define('browser/optimize', {});
  25326. }
  25327. if(env === 'node') {
  25328. /**
  25329. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25330. * Available via the MIT or new BSD license.
  25331. * see: http://github.com/jrburke/requirejs for details
  25332. */
  25333. /*jslint strict: false */
  25334. /*global define: false */
  25335. define('node/optimize', {});
  25336. }
  25337. if(env === 'rhino') {
  25338. /**
  25339. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25340. * Available via the MIT or new BSD license.
  25341. * see: http://github.com/jrburke/requirejs for details
  25342. */
  25343. /*jslint sloppy: true, plusplus: true */
  25344. /*global define, java, Packages, com */
  25345. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  25346. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  25347. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  25348. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  25349. if (!Array.prototype.reduce) {
  25350. Array.prototype.reduce = function (fn /*, initialValue */) {
  25351. var i = 0,
  25352. length = this.length,
  25353. accumulator;
  25354. if (arguments.length >= 2) {
  25355. accumulator = arguments[1];
  25356. } else {
  25357. if (length) {
  25358. while (!(i in this)) {
  25359. i++;
  25360. }
  25361. accumulator = this[i++];
  25362. }
  25363. }
  25364. for (; i < length; i++) {
  25365. if (i in this) {
  25366. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  25367. }
  25368. }
  25369. return accumulator;
  25370. };
  25371. }
  25372. var JSSourceFilefromCode, optimize,
  25373. mapRegExp = /"file":"[^"]+"/;
  25374. //Bind to Closure compiler, but if it is not available, do not sweat it.
  25375. try {
  25376. // Try older closure compiler that worked on Java 6
  25377. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  25378. } catch (e) {
  25379. try {
  25380. // Try for newer closure compiler that needs Java 7+
  25381. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  25382. } catch (e) {
  25383. try {
  25384. // Try Nashorn style
  25385. var stringClass = Java.type("java.lang.String").class;
  25386. JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]);
  25387. } catch (e) {}
  25388. }
  25389. }
  25390. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  25391. function closurefromCode(filename, content) {
  25392. return JSSourceFilefromCode.invoke(null, [filename, content]);
  25393. }
  25394. function getFileWriter(fileName, encoding) {
  25395. var outFile = new java.io.File(fileName), outWriter, parentDir;
  25396. parentDir = outFile.getAbsoluteFile().getParentFile();
  25397. if (!parentDir.exists()) {
  25398. if (!parentDir.mkdirs()) {
  25399. throw "Could not create directory: " + parentDir.getAbsolutePath();
  25400. }
  25401. }
  25402. if (encoding) {
  25403. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  25404. } else {
  25405. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  25406. }
  25407. return new java.io.BufferedWriter(outWriter);
  25408. }
  25409. optimize = {
  25410. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  25411. config = config || {};
  25412. var result, mappings, optimized, compressed, baseName, writer,
  25413. outBaseName, outFileNameMap, outFileNameMapContent,
  25414. srcOutFileName, concatNameMap,
  25415. jscomp = Packages.com.google.javascript.jscomp,
  25416. flags = Packages.com.google.common.flags,
  25417. //Set up source input
  25418. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  25419. sourceListArray = new java.util.ArrayList(),
  25420. externList = new java.util.ArrayList(),
  25421. options, option, FLAG_compilation_level, compiler, externExportsPath,
  25422. Compiler = Packages.com.google.javascript.jscomp.Compiler,
  25423. CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
  25424. logger.trace("Minifying file: " + fileName);
  25425. baseName = (new java.io.File(fileName)).getName();
  25426. //Set up options
  25427. options = new jscomp.CompilerOptions();
  25428. for (option in config.CompilerOptions) {
  25429. // options are false by default and jslint wanted an if statement in this for loop
  25430. if (config.CompilerOptions[option]) {
  25431. options[option] = config.CompilerOptions[option];
  25432. }
  25433. }
  25434. options.prettyPrint = keepLines || options.prettyPrint;
  25435. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  25436. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  25437. if (config.generateSourceMaps) {
  25438. mappings = new java.util.ArrayList();
  25439. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
  25440. options.setSourceMapLocationMappings(mappings);
  25441. options.setSourceMapOutputPath(fileName + ".map");
  25442. }
  25443. //If we need to pass an externs file to Closure so that it does not create aliases
  25444. //for certain symbols, do so here.
  25445. externList.addAll(CommandLineRunner.getDefaultExterns());
  25446. if (config.externExportsPath) {
  25447. externExportsPath = config.externExportsPath;
  25448. externList.add(jscomp.SourceFile.fromFile(externExportsPath));
  25449. }
  25450. //Trigger the compiler
  25451. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  25452. compiler = new Compiler();
  25453. //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
  25454. //accepting the getDefaultExterns return value (a List) also wants the sources as a List
  25455. sourceListArray.add(jsSourceFile);
  25456. result = compiler.compile(externList, sourceListArray, options);
  25457. if (result.success) {
  25458. optimized = String(compiler.toSource());
  25459. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  25460. outBaseName = (new java.io.File(outFileName)).getName();
  25461. srcOutFileName = outFileName + ".src.js";
  25462. outFileNameMap = outFileName + ".map";
  25463. //If previous .map file exists, move it to the ".src.js"
  25464. //location. Need to update the sourceMappingURL part in the
  25465. //src.js file too.
  25466. if (file.exists(outFileNameMap)) {
  25467. concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
  25468. file.saveFile(concatNameMap, file.readFile(outFileNameMap));
  25469. file.saveFile(srcOutFileName,
  25470. fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
  25471. '/# sourceMappingURL=$1.src.js.map'));
  25472. } else {
  25473. file.saveUtf8File(srcOutFileName, fileContents);
  25474. }
  25475. writer = getFileWriter(outFileNameMap, "utf-8");
  25476. result.sourceMap.appendTo(writer, outFileName);
  25477. writer.close();
  25478. //Not sure how better to do this, but right now the .map file
  25479. //leaks the full OS path in the "file" property. Manually
  25480. //modify it to not do that.
  25481. file.saveFile(outFileNameMap,
  25482. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  25483. fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
  25484. } else {
  25485. fileContents = optimized;
  25486. }
  25487. return fileContents;
  25488. } else {
  25489. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  25490. }
  25491. return fileContents;
  25492. }
  25493. };
  25494. return optimize;
  25495. });
  25496. }
  25497. if(env === 'xpconnect') {
  25498. define('xpconnect/optimize', {});
  25499. }
  25500. /**
  25501. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25502. * Available via the MIT or new BSD license.
  25503. * see: http://github.com/jrburke/requirejs for details
  25504. */
  25505. /*jslint plusplus: true, nomen: true, regexp: true */
  25506. /*global define: false */
  25507. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  25508. 'pragma', 'uglifyjs/index', 'uglifyjs2',
  25509. 'source-map'],
  25510. function (lang, logger, envOptimize, file, parse,
  25511. pragma, uglify, uglify2,
  25512. sourceMap) {
  25513. 'use strict';
  25514. var optimize,
  25515. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  25516. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  25517. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
  25518. protocolRegExp = /^\w+:/,
  25519. SourceMapGenerator = sourceMap.SourceMapGenerator,
  25520. SourceMapConsumer =sourceMap.SourceMapConsumer;
  25521. /**
  25522. * If an URL from a CSS url value contains start/end quotes, remove them.
  25523. * This is not done in the regexp, since my regexp fu is not that strong,
  25524. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  25525. * @param {String} url
  25526. */
  25527. function cleanCssUrlQuotes(url) {
  25528. //Make sure we are not ending in whitespace.
  25529. //Not very confident of the css regexps above that there will not be ending
  25530. //whitespace.
  25531. url = url.replace(/\s+$/, "");
  25532. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  25533. url = url.substring(1, url.length - 1);
  25534. }
  25535. return url;
  25536. }
  25537. function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
  25538. return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  25539. var firstChar, hasProtocol, parts, i,
  25540. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  25541. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  25542. //Only do the work for relative URLs. Skip things that start with / or #, or have
  25543. //a protocol.
  25544. firstChar = fixedUrlMatch.charAt(0);
  25545. hasProtocol = protocolRegExp.test(fixedUrlMatch);
  25546. if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {
  25547. //It is a relative URL, tack on the cssPrefix and path prefix
  25548. urlMatch = cssPrefix + path + fixedUrlMatch;
  25549. } else if (!hasProtocol) {
  25550. logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
  25551. }
  25552. //Collapse .. and .
  25553. parts = urlMatch.split("/");
  25554. for (i = parts.length - 1; i > 0; i--) {
  25555. if (parts[i] === ".") {
  25556. parts.splice(i, 1);
  25557. } else if (parts[i] === "..") {
  25558. if (i !== 0 && parts[i - 1] !== "..") {
  25559. parts.splice(i - 1, 2);
  25560. i -= 1;
  25561. }
  25562. }
  25563. }
  25564. return "url(" + parts.join("/") + ")";
  25565. });
  25566. }
  25567. /**
  25568. * Inlines nested stylesheets that have @import calls in them.
  25569. * @param {String} fileName the file name
  25570. * @param {String} fileContents the file contents
  25571. * @param {String} cssImportIgnore comma delimited string of files to ignore
  25572. * @param {String} cssPrefix string to be prefixed before relative URLs
  25573. * @param {Object} included an object used to track the files already imported
  25574. */
  25575. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
  25576. //Find the last slash in the name.
  25577. fileName = fileName.replace(lang.backSlashRegExp, "/");
  25578. var endIndex = fileName.lastIndexOf("/"),
  25579. //Make a file path based on the last slash.
  25580. //If no slash, so must be just a file name. Use empty string then.
  25581. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  25582. //store a list of merged files
  25583. importList = [],
  25584. skippedList = [];
  25585. //First make a pass by removing any commented out @import calls.
  25586. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  25587. //Make sure we have a delimited ignore list to make matching faster
  25588. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  25589. cssImportIgnore += ",";
  25590. }
  25591. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  25592. //Only process media type "all" or empty media type rules.
  25593. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  25594. skippedList.push(fileName);
  25595. return fullMatch;
  25596. }
  25597. importFileName = cleanCssUrlQuotes(importFileName);
  25598. //Ignore the file import if it is part of an ignore list.
  25599. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  25600. return fullMatch;
  25601. }
  25602. //Make sure we have a unix path for the rest of the operation.
  25603. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  25604. try {
  25605. //if a relative path, then tack on the filePath.
  25606. //If it is not a relative path, then the readFile below will fail,
  25607. //and we will just skip that import.
  25608. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  25609. importContents = file.readFile(fullImportFileName),
  25610. importEndIndex, importPath, flat;
  25611. //Skip the file if it has already been included.
  25612. if (included[fullImportFileName]) {
  25613. return '';
  25614. }
  25615. included[fullImportFileName] = true;
  25616. //Make sure to flatten any nested imports.
  25617. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  25618. importContents = flat.fileContents;
  25619. if (flat.importList.length) {
  25620. importList.push.apply(importList, flat.importList);
  25621. }
  25622. if (flat.skippedList.length) {
  25623. skippedList.push.apply(skippedList, flat.skippedList);
  25624. }
  25625. //Make the full import path
  25626. importEndIndex = importFileName.lastIndexOf("/");
  25627. //Make a file path based on the last slash.
  25628. //If no slash, so must be just a file name. Use empty string then.
  25629. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  25630. //fix url() on relative import (#5)
  25631. importPath = importPath.replace(/^\.\//, '');
  25632. //Modify URL paths to match the path represented by this file.
  25633. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
  25634. importList.push(fullImportFileName);
  25635. return importContents;
  25636. } catch (e) {
  25637. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  25638. return fullMatch;
  25639. }
  25640. });
  25641. if (cssPrefix && topLevel) {
  25642. //Modify URL paths to match the path represented by this file.
  25643. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
  25644. }
  25645. return {
  25646. importList : importList,
  25647. skippedList: skippedList,
  25648. fileContents : fileContents
  25649. };
  25650. }
  25651. optimize = {
  25652. /**
  25653. * Optimizes a file that contains JavaScript content. Optionally collects
  25654. * plugin resources mentioned in a file, and then passes the content
  25655. * through an minifier if one is specified via config.optimize.
  25656. *
  25657. * @param {String} fileName the name of the file to optimize
  25658. * @param {String} fileContents the contents to optimize. If this is
  25659. * a null value, then fileName will be used to read the fileContents.
  25660. * @param {String} outFileName the name of the file to use for the
  25661. * saved optimized content.
  25662. * @param {Object} config the build config object.
  25663. * @param {Array} [pluginCollector] storage for any plugin resources
  25664. * found.
  25665. */
  25666. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  25667. if (!fileContents) {
  25668. fileContents = file.readFile(fileName);
  25669. }
  25670. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  25671. file.saveUtf8File(outFileName, fileContents);
  25672. },
  25673. /**
  25674. * Optimizes a file that contains JavaScript content. Optionally collects
  25675. * plugin resources mentioned in a file, and then passes the content
  25676. * through an minifier if one is specified via config.optimize.
  25677. *
  25678. * @param {String} fileName the name of the file that matches the
  25679. * fileContents.
  25680. * @param {String} fileContents the string of JS to optimize.
  25681. * @param {Object} [config] the build config object.
  25682. * @param {Array} [pluginCollector] storage for any plugin resources
  25683. * found.
  25684. */
  25685. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  25686. var optFunc, optConfig,
  25687. parts = (String(config.optimize)).split('.'),
  25688. optimizerName = parts[0],
  25689. keepLines = parts[1] === 'keepLines',
  25690. licenseContents = '';
  25691. config = config || {};
  25692. //Apply pragmas/namespace renaming
  25693. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  25694. //Optimize the JS files if asked.
  25695. if (optimizerName && optimizerName !== 'none') {
  25696. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  25697. if (!optFunc) {
  25698. throw new Error('optimizer with name of "' +
  25699. optimizerName +
  25700. '" not found for this environment');
  25701. }
  25702. optConfig = config[optimizerName] || {};
  25703. if (config.generateSourceMaps) {
  25704. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  25705. optConfig._buildSourceMap = config._buildSourceMap;
  25706. }
  25707. try {
  25708. if (config.preserveLicenseComments) {
  25709. //Pull out any license comments for prepending after optimization.
  25710. try {
  25711. licenseContents = parse.getLicenseComments(fileName, fileContents);
  25712. } catch (e) {
  25713. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  25714. }
  25715. }
  25716. fileContents = licenseContents + optFunc(fileName,
  25717. fileContents,
  25718. outFileName,
  25719. keepLines,
  25720. optConfig);
  25721. if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
  25722. config._buildSourceMap = optConfig._buildSourceMap;
  25723. }
  25724. } catch (e) {
  25725. if (config.throwWhen && config.throwWhen.optimize) {
  25726. throw e;
  25727. } else {
  25728. logger.error(e);
  25729. }
  25730. }
  25731. } else {
  25732. if (config._buildSourceMap) {
  25733. config._buildSourceMap = null;
  25734. }
  25735. }
  25736. return fileContents;
  25737. },
  25738. /**
  25739. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  25740. * optionally removes line returns.
  25741. * @param {String} fileName the path to the CSS file to optimize
  25742. * @param {String} outFileName the path to save the optimized file.
  25743. * @param {Object} config the config object with the optimizeCss and
  25744. * cssImportIgnore options.
  25745. */
  25746. cssFile: function (fileName, outFileName, config) {
  25747. //Read in the file. Make sure we have a JS string.
  25748. var originalFileContents = file.readFile(fileName),
  25749. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
  25750. //Do not use the flattened CSS if there was one that was skipped.
  25751. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  25752. startIndex, endIndex, buildText, comment;
  25753. if (flat.skippedList.length) {
  25754. logger.warn('Cannot inline @imports for ' + fileName +
  25755. ',\nthe following files had media queries in them:\n' +
  25756. flat.skippedList.join('\n'));
  25757. }
  25758. //Do comment removal.
  25759. try {
  25760. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  25761. startIndex = 0;
  25762. //Get rid of comments.
  25763. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  25764. endIndex = fileContents.indexOf("*/", startIndex + 2);
  25765. if (endIndex === -1) {
  25766. throw "Improper comment in CSS file: " + fileName;
  25767. }
  25768. comment = fileContents.substring(startIndex, endIndex);
  25769. if (config.preserveLicenseComments &&
  25770. (comment.indexOf('license') !== -1 ||
  25771. comment.indexOf('opyright') !== -1 ||
  25772. comment.indexOf('(c)') !== -1)) {
  25773. //Keep the comment, just increment the startIndex
  25774. startIndex = endIndex;
  25775. } else {
  25776. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  25777. startIndex = 0;
  25778. }
  25779. }
  25780. }
  25781. //Get rid of newlines.
  25782. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  25783. fileContents = fileContents.replace(/[\r\n]/g, " ");
  25784. fileContents = fileContents.replace(/\s+/g, " ");
  25785. fileContents = fileContents.replace(/\{\s/g, "{");
  25786. fileContents = fileContents.replace(/\s\}/g, "}");
  25787. } else {
  25788. //Remove multiple empty lines.
  25789. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  25790. fileContents = fileContents.replace(/(\n)+/g, "\n");
  25791. }
  25792. //Remove unnecessary whitespace
  25793. if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
  25794. //Remove leading and trailing whitespace from lines
  25795. fileContents = fileContents.replace(/^[ \t]+/gm, "");
  25796. fileContents = fileContents.replace(/[ \t]+$/gm, "");
  25797. //Remove whitespace after semicolon, colon, curly brackets and commas
  25798. fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
  25799. //Remove whitespace before opening curly brackets
  25800. fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
  25801. //Truncate double whitespace
  25802. fileContents = fileContents.replace(/([ \t])+/g, "$1");
  25803. //Remove empty lines
  25804. fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
  25805. }
  25806. } catch (e) {
  25807. fileContents = originalFileContents;
  25808. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  25809. }
  25810. file.saveUtf8File(outFileName, fileContents);
  25811. //text output to stdout and/or written to build.txt file
  25812. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  25813. flat.importList.push(fileName);
  25814. buildText += flat.importList.map(function(path){
  25815. return path.replace(config.dir, "");
  25816. }).join("\n");
  25817. return {
  25818. importList: flat.importList,
  25819. buildText: buildText +"\n"
  25820. };
  25821. },
  25822. /**
  25823. * Optimizes CSS files, inlining @import calls, stripping comments, and
  25824. * optionally removes line returns.
  25825. * @param {String} startDir the path to the top level directory
  25826. * @param {Object} config the config object with the optimizeCss and
  25827. * cssImportIgnore options.
  25828. */
  25829. css: function (startDir, config) {
  25830. var buildText = "",
  25831. importList = [],
  25832. shouldRemove = config.dir && config.removeCombined,
  25833. i, fileName, result, fileList;
  25834. if (config.optimizeCss.indexOf("standard") !== -1) {
  25835. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  25836. if (fileList) {
  25837. for (i = 0; i < fileList.length; i++) {
  25838. fileName = fileList[i];
  25839. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  25840. result = optimize.cssFile(fileName, fileName, config);
  25841. buildText += result.buildText;
  25842. if (shouldRemove) {
  25843. result.importList.pop();
  25844. importList = importList.concat(result.importList);
  25845. }
  25846. }
  25847. }
  25848. if (shouldRemove) {
  25849. importList.forEach(function (path) {
  25850. if (file.exists(path)) {
  25851. file.deleteFile(path);
  25852. }
  25853. });
  25854. }
  25855. }
  25856. return buildText;
  25857. },
  25858. optimizers: {
  25859. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  25860. var parser = uglify.parser,
  25861. processor = uglify.uglify,
  25862. ast, errMessage, errMatch;
  25863. config = config || {};
  25864. logger.trace("Uglifying file: " + fileName);
  25865. try {
  25866. ast = parser.parse(fileContents, config.strict_semicolons);
  25867. if (config.no_mangle !== true) {
  25868. ast = processor.ast_mangle(ast, config);
  25869. }
  25870. ast = processor.ast_squeeze(ast, config);
  25871. fileContents = processor.gen_code(ast, config);
  25872. if (config.max_line_length) {
  25873. fileContents = processor.split_lines(fileContents, config.max_line_length);
  25874. }
  25875. //Add trailing semicolon to match uglifyjs command line version
  25876. fileContents += ';';
  25877. } catch (e) {
  25878. errMessage = e.toString();
  25879. errMatch = /\nError(\r)?\n/.exec(errMessage);
  25880. if (errMatch) {
  25881. errMessage = errMessage.substring(0, errMatch.index);
  25882. }
  25883. throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
  25884. }
  25885. return fileContents;
  25886. },
  25887. uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
  25888. var result, existingMap, resultMap, finalMap, sourceIndex,
  25889. uconfig = {},
  25890. existingMapPath = outFileName + '.map',
  25891. baseName = fileName && fileName.split('/').pop();
  25892. config = config || {};
  25893. lang.mixin(uconfig, config, true);
  25894. uconfig.fromString = true;
  25895. if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
  25896. uconfig.outSourceMap = baseName + '.map';
  25897. if (config._buildSourceMap) {
  25898. existingMap = JSON.parse(config._buildSourceMap);
  25899. uconfig.inSourceMap = existingMap;
  25900. } else if (file.exists(existingMapPath)) {
  25901. uconfig.inSourceMap = existingMapPath;
  25902. existingMap = JSON.parse(file.readFile(existingMapPath));
  25903. }
  25904. }
  25905. logger.trace("Uglify2 file: " + fileName);
  25906. try {
  25907. //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
  25908. result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');
  25909. if (uconfig.outSourceMap && result.map) {
  25910. resultMap = result.map;
  25911. if (!existingMap && !config._buildSourceMap) {
  25912. file.saveFile(outFileName + '.src.js', fileContents);
  25913. }
  25914. fileContents = result.code;
  25915. if (config._buildSourceMap) {
  25916. config._buildSourceMap = resultMap;
  25917. } else {
  25918. file.saveFile(outFileName + '.map', resultMap);
  25919. }
  25920. } else {
  25921. fileContents = result.code;
  25922. }
  25923. } catch (e) {
  25924. throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
  25925. }
  25926. return fileContents;
  25927. }
  25928. }
  25929. };
  25930. return optimize;
  25931. });
  25932. /**
  25933. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25934. * Available via the MIT or new BSD license.
  25935. * see: http://github.com/jrburke/requirejs for details
  25936. */
  25937. /*
  25938. * This file patches require.js to communicate with the build system.
  25939. */
  25940. //Using sloppy since this uses eval for some code like plugins,
  25941. //which may not be strict mode compliant. So if use strict is used
  25942. //below they will have strict rules applied and may cause an error.
  25943. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  25944. /*global require, define: true */
  25945. //NOT asking for require as a dependency since the goal is to modify the
  25946. //global require below
  25947. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  25948. file,
  25949. pragma,
  25950. parse,
  25951. lang,
  25952. logger,
  25953. commonJs,
  25954. prim
  25955. ) {
  25956. var allowRun = true,
  25957. hasProp = lang.hasProp,
  25958. falseProp = lang.falseProp,
  25959. getOwn = lang.getOwn,
  25960. // Used to strip out use strict from toString()'d functions for the
  25961. // shim config since they will explicitly want to not be bound by strict,
  25962. // but some envs, explicitly xpcshell, adds a use strict.
  25963. useStrictRegExp = /['"]use strict['"];/g;
  25964. //Turn off throwing on resolution conflict, that was just an older prim
  25965. //idea about finding errors early, but does not comply with how promises
  25966. //should operate.
  25967. prim.hideResolutionConflict = true;
  25968. //This method should be called when the patches to require should take hold.
  25969. return function () {
  25970. if (!allowRun) {
  25971. return;
  25972. }
  25973. allowRun = false;
  25974. var layer,
  25975. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  25976. oldNewContext = require.s.newContext,
  25977. oldDef,
  25978. //create local undefined values for module and exports,
  25979. //so that when files are evaled in this function they do not
  25980. //see the node values used for r.js
  25981. exports,
  25982. module;
  25983. /**
  25984. * Reset "global" build caches that are kept around between
  25985. * build layer builds. Useful to do when there are multiple
  25986. * top level requirejs.optimize() calls.
  25987. */
  25988. require._cacheReset = function () {
  25989. //Stored raw text caches, used by browser use.
  25990. require._cachedRawText = {};
  25991. //Stored cached file contents for reuse in other layers.
  25992. require._cachedFileContents = {};
  25993. //Store which cached files contain a require definition.
  25994. require._cachedDefinesRequireUrls = {};
  25995. };
  25996. require._cacheReset();
  25997. /**
  25998. * Makes sure the URL is something that can be supported by the
  25999. * optimization tool.
  26000. * @param {String} url
  26001. * @returns {Boolean}
  26002. */
  26003. require._isSupportedBuildUrl = function (url) {
  26004. //Ignore URLs with protocols, hosts or question marks, means either network
  26005. //access is needed to fetch it or it is too dynamic. Note that
  26006. //on Windows, full paths are used for some urls, which include
  26007. //the drive, like c:/something, so need to test for something other
  26008. //than just a colon.
  26009. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  26010. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  26011. return true;
  26012. } else {
  26013. if (!layer.ignoredUrls[url]) {
  26014. if (url.indexOf('empty:') === -1) {
  26015. logger.info('Cannot optimize network URL, skipping: ' + url);
  26016. }
  26017. layer.ignoredUrls[url] = true;
  26018. }
  26019. return false;
  26020. }
  26021. };
  26022. function normalizeUrlWithBase(context, moduleName, url) {
  26023. //Adjust the URL if it was not transformed to use baseUrl.
  26024. if (require.jsExtRegExp.test(moduleName)) {
  26025. url = (context.config.dir || context.config.dirBaseUrl) + url;
  26026. }
  26027. return url;
  26028. }
  26029. //Overrides the new context call to add existing tracking features.
  26030. require.s.newContext = function (name) {
  26031. var context = oldNewContext(name),
  26032. oldEnable = context.enable,
  26033. moduleProto = context.Module.prototype,
  26034. oldInit = moduleProto.init,
  26035. oldCallPlugin = moduleProto.callPlugin;
  26036. //Only do this for the context used for building.
  26037. if (name === '_') {
  26038. //For build contexts, do everything sync
  26039. context.nextTick = function (fn) {
  26040. fn();
  26041. };
  26042. context.needFullExec = {};
  26043. context.fullExec = {};
  26044. context.plugins = {};
  26045. context.buildShimExports = {};
  26046. //Override the shim exports function generator to just
  26047. //spit out strings that can be used in the stringified
  26048. //build output.
  26049. context.makeShimExports = function (value) {
  26050. var fn;
  26051. if (context.config.wrapShim) {
  26052. fn = function () {
  26053. var str = 'return ';
  26054. // If specifies an export that is just a global
  26055. // name, no dot for a `this.` and such, then also
  26056. // attach to the global, for `var a = {}` files
  26057. // where the function closure would hide that from
  26058. // the global object.
  26059. if (value.exports && value.exports.indexOf('.') === -1) {
  26060. str += 'root.' + value.exports + ' = ';
  26061. }
  26062. if (value.init) {
  26063. str += '(' + value.init.toString()
  26064. .replace(useStrictRegExp, '') + '.apply(this, arguments))';
  26065. }
  26066. if (value.init && value.exports) {
  26067. str += ' || ';
  26068. }
  26069. if (value.exports) {
  26070. str += value.exports;
  26071. }
  26072. str += ';';
  26073. return str;
  26074. };
  26075. } else {
  26076. fn = function () {
  26077. return '(function (global) {\n' +
  26078. ' return function () {\n' +
  26079. ' var ret, fn;\n' +
  26080. (value.init ?
  26081. (' fn = ' + value.init.toString()
  26082. .replace(useStrictRegExp, '') + ';\n' +
  26083. ' ret = fn.apply(global, arguments);\n') : '') +
  26084. (value.exports ?
  26085. ' return ret || global.' + value.exports + ';\n' :
  26086. ' return ret;\n') +
  26087. ' };\n' +
  26088. '}(this))';
  26089. };
  26090. }
  26091. return fn;
  26092. };
  26093. context.enable = function (depMap, parent) {
  26094. var id = depMap.id,
  26095. parentId = parent && parent.map.id,
  26096. needFullExec = context.needFullExec,
  26097. fullExec = context.fullExec,
  26098. mod = getOwn(context.registry, id);
  26099. if (mod && !mod.defined) {
  26100. if (parentId && getOwn(needFullExec, parentId)) {
  26101. needFullExec[id] = depMap;
  26102. }
  26103. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  26104. (parentId && getOwn(needFullExec, parentId) &&
  26105. falseProp(fullExec, id))) {
  26106. context.require.undef(id);
  26107. }
  26108. return oldEnable.apply(context, arguments);
  26109. };
  26110. //Override load so that the file paths can be collected.
  26111. context.load = function (moduleName, url) {
  26112. /*jslint evil: true */
  26113. var contents, pluginBuilderMatch, builderName,
  26114. shim, shimExports;
  26115. //Do not mark the url as fetched if it is
  26116. //not an empty: URL, used by the optimizer.
  26117. //In that case we need to be sure to call
  26118. //load() for each module that is mapped to
  26119. //empty: so that dependencies are satisfied
  26120. //correctly.
  26121. if (url.indexOf('empty:') === 0) {
  26122. delete context.urlFetched[url];
  26123. }
  26124. //Only handle urls that can be inlined, so that means avoiding some
  26125. //URLs like ones that require network access or may be too dynamic,
  26126. //like JSONP
  26127. if (require._isSupportedBuildUrl(url)) {
  26128. //Adjust the URL if it was not transformed to use baseUrl.
  26129. url = normalizeUrlWithBase(context, moduleName, url);
  26130. //Save the module name to path and path to module name mappings.
  26131. layer.buildPathMap[moduleName] = url;
  26132. layer.buildFileToModule[url] = moduleName;
  26133. if (hasProp(context.plugins, moduleName)) {
  26134. //plugins need to have their source evaled as-is.
  26135. context.needFullExec[moduleName] = true;
  26136. }
  26137. prim().start(function () {
  26138. if (hasProp(require._cachedFileContents, url) &&
  26139. (falseProp(context.needFullExec, moduleName) ||
  26140. getOwn(context.fullExec, moduleName))) {
  26141. contents = require._cachedFileContents[url];
  26142. //If it defines require, mark it so it can be hoisted.
  26143. //Done here and in the else below, before the
  26144. //else block removes code from the contents.
  26145. //Related to #263
  26146. if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  26147. layer.existingRequireUrl = url;
  26148. }
  26149. } else {
  26150. //Load the file contents, process for conditionals, then
  26151. //evaluate it.
  26152. return require._cacheReadAsync(url).then(function (text) {
  26153. contents = text;
  26154. if (context.config.cjsTranslate &&
  26155. (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
  26156. contents = commonJs.convert(url, contents);
  26157. }
  26158. //If there is a read filter, run it now.
  26159. if (context.config.onBuildRead) {
  26160. contents = context.config.onBuildRead(moduleName, url, contents);
  26161. }
  26162. contents = pragma.process(url, contents, context.config, 'OnExecute');
  26163. //Find out if the file contains a require() definition. Need to know
  26164. //this so we can inject plugins right after it, but before they are needed,
  26165. //and to make sure this file is first, so that define calls work.
  26166. try {
  26167. if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
  26168. layer.existingRequireUrl = url;
  26169. require._cachedDefinesRequireUrls[url] = true;
  26170. }
  26171. } catch (e1) {
  26172. throw new Error('Parse error using esprima ' +
  26173. 'for file: ' + url + '\n' + e1);
  26174. }
  26175. }).then(function () {
  26176. if (hasProp(context.plugins, moduleName)) {
  26177. //This is a loader plugin, check to see if it has a build extension,
  26178. //otherwise the plugin will act as the plugin builder too.
  26179. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  26180. if (pluginBuilderMatch) {
  26181. //Load the plugin builder for the plugin contents.
  26182. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  26183. context.makeModuleMap(moduleName),
  26184. null,
  26185. true).id;
  26186. return require._cacheReadAsync(context.nameToUrl(builderName));
  26187. }
  26188. }
  26189. return contents;
  26190. }).then(function (text) {
  26191. contents = text;
  26192. //Parse out the require and define calls.
  26193. //Do this even for plugins in case they have their own
  26194. //dependencies that may be separate to how the pluginBuilder works.
  26195. try {
  26196. if (falseProp(context.needFullExec, moduleName)) {
  26197. contents = parse(moduleName, url, contents, {
  26198. insertNeedsDefine: true,
  26199. has: context.config.has,
  26200. findNestedDependencies: context.config.findNestedDependencies
  26201. });
  26202. }
  26203. } catch (e2) {
  26204. throw new Error('Parse error using esprima ' +
  26205. 'for file: ' + url + '\n' + e2);
  26206. }
  26207. require._cachedFileContents[url] = contents;
  26208. });
  26209. }
  26210. }).then(function () {
  26211. if (contents) {
  26212. eval(contents);
  26213. }
  26214. try {
  26215. //If have a string shim config, and this is
  26216. //a fully executed module, try to see if
  26217. //it created a variable in this eval scope
  26218. if (getOwn(context.needFullExec, moduleName)) {
  26219. shim = getOwn(context.config.shim, moduleName);
  26220. if (shim && shim.exports) {
  26221. shimExports = eval(shim.exports);
  26222. if (typeof shimExports !== 'undefined') {
  26223. context.buildShimExports[moduleName] = shimExports;
  26224. }
  26225. }
  26226. }
  26227. //Need to close out completion of this module
  26228. //so that listeners will get notified that it is available.
  26229. context.completeLoad(moduleName);
  26230. } catch (e) {
  26231. //Track which module could not complete loading.
  26232. if (!e.moduleTree) {
  26233. e.moduleTree = [];
  26234. }
  26235. e.moduleTree.push(moduleName);
  26236. throw e;
  26237. }
  26238. }).then(null, function (eOuter) {
  26239. if (!eOuter.fileName) {
  26240. eOuter.fileName = url;
  26241. }
  26242. throw eOuter;
  26243. }).end();
  26244. } else {
  26245. //With unsupported URLs still need to call completeLoad to
  26246. //finish loading.
  26247. context.completeLoad(moduleName);
  26248. }
  26249. };
  26250. //Marks module has having a name, and optionally executes the
  26251. //callback, but only if it meets certain criteria.
  26252. context.execCb = function (name, cb, args, exports) {
  26253. var buildShimExports = getOwn(layer.context.buildShimExports, name);
  26254. if (buildShimExports) {
  26255. return buildShimExports;
  26256. } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
  26257. return cb.apply(exports, args);
  26258. }
  26259. return undefined;
  26260. };
  26261. moduleProto.init = function (depMaps) {
  26262. if (context.needFullExec[this.map.id]) {
  26263. lang.each(depMaps, lang.bind(this, function (depMap) {
  26264. if (typeof depMap === 'string') {
  26265. depMap = context.makeModuleMap(depMap,
  26266. (this.map.isDefine ? this.map : this.map.parentMap));
  26267. }
  26268. if (!context.fullExec[depMap.id]) {
  26269. context.require.undef(depMap.id);
  26270. }
  26271. }));
  26272. }
  26273. return oldInit.apply(this, arguments);
  26274. };
  26275. moduleProto.callPlugin = function () {
  26276. var map = this.map,
  26277. pluginMap = context.makeModuleMap(map.prefix),
  26278. pluginId = pluginMap.id,
  26279. pluginMod = getOwn(context.registry, pluginId);
  26280. context.plugins[pluginId] = true;
  26281. context.needFullExec[pluginId] = map;
  26282. //If the module is not waiting to finish being defined,
  26283. //undef it and start over, to get full execution.
  26284. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  26285. context.require.undef(pluginMap.id);
  26286. }
  26287. return oldCallPlugin.apply(this, arguments);
  26288. };
  26289. }
  26290. return context;
  26291. };
  26292. //Clear up the existing context so that the newContext modifications
  26293. //above will be active.
  26294. delete require.s.contexts._;
  26295. /** Reset state for each build layer pass. */
  26296. require._buildReset = function () {
  26297. var oldContext = require.s.contexts._;
  26298. //Clear up the existing context.
  26299. delete require.s.contexts._;
  26300. //Set up new context, so the layer object can hold onto it.
  26301. require({});
  26302. layer = require._layer = {
  26303. buildPathMap: {},
  26304. buildFileToModule: {},
  26305. buildFilePaths: [],
  26306. pathAdded: {},
  26307. modulesWithNames: {},
  26308. needsDefine: {},
  26309. existingRequireUrl: "",
  26310. ignoredUrls: {},
  26311. context: require.s.contexts._
  26312. };
  26313. //Return the previous context in case it is needed, like for
  26314. //the basic config object.
  26315. return oldContext;
  26316. };
  26317. require._buildReset();
  26318. //Override define() to catch modules that just define an object, so that
  26319. //a dummy define call is not put in the build file for them. They do
  26320. //not end up getting defined via context.execCb, so we need to catch them
  26321. //at the define call.
  26322. oldDef = define;
  26323. //This function signature does not have to be exact, just match what we
  26324. //are looking for.
  26325. define = function (name) {
  26326. if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
  26327. layer.modulesWithNames[name] = true;
  26328. }
  26329. return oldDef.apply(require, arguments);
  26330. };
  26331. define.amd = oldDef.amd;
  26332. //Add some utilities for plugins
  26333. require._readFile = file.readFile;
  26334. require._fileExists = function (path) {
  26335. return file.exists(path);
  26336. };
  26337. //Called when execManager runs for a dependency. Used to figure out
  26338. //what order of execution.
  26339. require.onResourceLoad = function (context, map) {
  26340. var id = map.id,
  26341. url;
  26342. // Fix up any maps that need to be normalized as part of the fullExec
  26343. // plumbing for plugins to participate in the build.
  26344. if (context.plugins && lang.hasProp(context.plugins, id)) {
  26345. lang.eachProp(context.needFullExec, function(value, prop) {
  26346. // For plugin entries themselves, they do not have a map
  26347. // value in needFullExec, just a "true" entry.
  26348. if (value !== true && value.prefix === id && value.unnormalized) {
  26349. var map = context.makeModuleMap(value.originalName, value.parentMap);
  26350. context.needFullExec[map.id] = map;
  26351. }
  26352. });
  26353. }
  26354. //If build needed a full execution, indicate it
  26355. //has been done now. But only do it if the context is tracking
  26356. //that. Only valid for the context used in a build, not for
  26357. //other contexts being run, like for useLib, plain requirejs
  26358. //use in node/rhino.
  26359. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  26360. context.fullExec[id] = map;
  26361. }
  26362. //A plugin.
  26363. if (map.prefix) {
  26364. if (falseProp(layer.pathAdded, id)) {
  26365. layer.buildFilePaths.push(id);
  26366. //For plugins the real path is not knowable, use the name
  26367. //for both module to file and file to module mappings.
  26368. layer.buildPathMap[id] = id;
  26369. layer.buildFileToModule[id] = id;
  26370. layer.modulesWithNames[id] = true;
  26371. layer.pathAdded[id] = true;
  26372. }
  26373. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  26374. //If the url has not been added to the layer yet, and it
  26375. //is from an actual file that was loaded, add it now.
  26376. url = normalizeUrlWithBase(context, id, map.url);
  26377. if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
  26378. //Remember the list of dependencies for this layer.
  26379. layer.buildFilePaths.push(url);
  26380. layer.pathAdded[url] = true;
  26381. }
  26382. }
  26383. };
  26384. //Called by output of the parse() function, when a file does not
  26385. //explicitly call define, probably just require, but the parse()
  26386. //function normalizes on define() for dependency mapping and file
  26387. //ordering works correctly.
  26388. require.needsDefine = function (moduleName) {
  26389. layer.needsDefine[moduleName] = true;
  26390. };
  26391. };
  26392. });
  26393. /**
  26394. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  26395. * Available via the MIT or new BSD license.
  26396. * see: http://github.com/jrburke/requirejs for details
  26397. */
  26398. /*jslint */
  26399. /*global define: false, console: false */
  26400. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  26401. 'use strict';
  26402. var commonJs = {
  26403. //Set to false if you do not want this file to log. Useful in environments
  26404. //like node where you want the work to happen without noise.
  26405. useLog: true,
  26406. convertDir: function (commonJsPath, savePath) {
  26407. var fileList, i,
  26408. jsFileRegExp = /\.js$/,
  26409. fileName, convertedFileName, fileContents;
  26410. //Get list of files to convert.
  26411. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  26412. //Normalize on front slashes and make sure the paths do not end in a slash.
  26413. commonJsPath = commonJsPath.replace(/\\/g, "/");
  26414. savePath = savePath.replace(/\\/g, "/");
  26415. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  26416. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  26417. }
  26418. if (savePath.charAt(savePath.length - 1) === "/") {
  26419. savePath = savePath.substring(0, savePath.length - 1);
  26420. }
  26421. //Cycle through all the JS files and convert them.
  26422. if (!fileList || !fileList.length) {
  26423. if (commonJs.useLog) {
  26424. if (commonJsPath === "convert") {
  26425. //A request just to convert one file.
  26426. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  26427. } else {
  26428. console.log("No files to convert in directory: " + commonJsPath);
  26429. }
  26430. }
  26431. } else {
  26432. for (i = 0; i < fileList.length; i++) {
  26433. fileName = fileList[i];
  26434. convertedFileName = fileName.replace(commonJsPath, savePath);
  26435. //Handle JS files.
  26436. if (jsFileRegExp.test(fileName)) {
  26437. fileContents = file.readFile(fileName);
  26438. fileContents = commonJs.convert(fileName, fileContents);
  26439. file.saveUtf8File(convertedFileName, fileContents);
  26440. } else {
  26441. //Just copy the file over.
  26442. file.copyFile(fileName, convertedFileName, true);
  26443. }
  26444. }
  26445. }
  26446. },
  26447. /**
  26448. * Does the actual file conversion.
  26449. *
  26450. * @param {String} fileName the name of the file.
  26451. *
  26452. * @param {String} fileContents the contents of a file :)
  26453. *
  26454. * @returns {String} the converted contents
  26455. */
  26456. convert: function (fileName, fileContents) {
  26457. //Strip out comments.
  26458. try {
  26459. var preamble = '',
  26460. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  26461. //First see if the module is not already RequireJS-formatted.
  26462. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  26463. return fileContents;
  26464. }
  26465. if (commonJsProps.dirname || commonJsProps.filename) {
  26466. preamble = 'var __filename = module.uri || "", ' +
  26467. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  26468. }
  26469. //Construct the wrapper boilerplate.
  26470. fileContents = 'define(function (require, exports, module) {' +
  26471. preamble +
  26472. fileContents +
  26473. '\n});\n';
  26474. } catch (e) {
  26475. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  26476. return fileContents;
  26477. }
  26478. return fileContents;
  26479. }
  26480. };
  26481. return commonJs;
  26482. });
  26483. /**
  26484. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  26485. * Available via the MIT or new BSD license.
  26486. * see: http://github.com/jrburke/requirejs for details
  26487. */
  26488. /*jslint plusplus: true, nomen: true, regexp: true */
  26489. /*global define, requirejs, java, process, console */
  26490. define('build', function (require) {
  26491. 'use strict';
  26492. var build,
  26493. lang = require('lang'),
  26494. prim = require('prim'),
  26495. logger = require('logger'),
  26496. file = require('env!env/file'),
  26497. parse = require('parse'),
  26498. optimize = require('optimize'),
  26499. pragma = require('pragma'),
  26500. transform = require('transform'),
  26501. requirePatch = require('requirePatch'),
  26502. env = require('env'),
  26503. commonJs = require('commonJs'),
  26504. SourceMapGenerator = require('source-map').SourceMapGenerator,
  26505. hasProp = lang.hasProp,
  26506. getOwn = lang.getOwn,
  26507. falseProp = lang.falseProp,
  26508. endsWithSemiColonRegExp = /;\s*$/,
  26509. endsWithSlashRegExp = /[\/\\]$/,
  26510. resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/,
  26511. deepCopyProps = {
  26512. layer: true
  26513. };
  26514. //Deep copy a config object, but do not copy over the "layer" property,
  26515. //as it can be a deeply nested structure with a full requirejs context.
  26516. function copyConfig(obj) {
  26517. return lang.deeplikeCopy(obj, deepCopyProps);
  26518. }
  26519. prim.nextTick = function (fn) {
  26520. fn();
  26521. };
  26522. //Now map require to the outermost requirejs, now that we have
  26523. //local dependencies for this module. The rest of the require use is
  26524. //manipulating the requirejs loader.
  26525. require = requirejs;
  26526. //Caching function for performance. Attached to
  26527. //require so it can be reused in requirePatch.js. _cachedRawText
  26528. //set up by requirePatch.js
  26529. require._cacheReadAsync = function (path, encoding) {
  26530. var d;
  26531. if (lang.hasProp(require._cachedRawText, path)) {
  26532. d = prim();
  26533. d.resolve(require._cachedRawText[path]);
  26534. return d.promise;
  26535. } else {
  26536. return file.readFileAsync(path, encoding).then(function (text) {
  26537. require._cachedRawText[path] = text;
  26538. return text;
  26539. });
  26540. }
  26541. };
  26542. function makeBuildBaseConfig() {
  26543. return {
  26544. appDir: "",
  26545. pragmas: {},
  26546. paths: {},
  26547. optimize: "uglify",
  26548. optimizeCss: "standard.keepLines.keepWhitespace",
  26549. inlineText: true,
  26550. isBuild: true,
  26551. optimizeAllPluginResources: false,
  26552. findNestedDependencies: false,
  26553. preserveLicenseComments: true,
  26554. //By default, all files/directories are copied, unless
  26555. //they match this regexp, by default just excludes .folders
  26556. dirExclusionRegExp: file.dirExclusionRegExp,
  26557. _buildPathToModuleIndex: {}
  26558. };
  26559. }
  26560. /**
  26561. * Some JS may not be valid if concatenated with other JS, in particular
  26562. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  26563. * those cases.
  26564. */
  26565. function addSemiColon(text, config) {
  26566. if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
  26567. return text;
  26568. } else {
  26569. return text + ";";
  26570. }
  26571. }
  26572. function endsWithSlash(dirName) {
  26573. if (dirName.charAt(dirName.length - 1) !== "/") {
  26574. dirName += "/";
  26575. }
  26576. return dirName;
  26577. }
  26578. //Method used by plugin writeFile calls, defined up here to avoid
  26579. //jslint warning about "making a function in a loop".
  26580. function makeWriteFile(namespace, layer) {
  26581. function writeFile(name, contents) {
  26582. logger.trace('Saving plugin-optimized file: ' + name);
  26583. file.saveUtf8File(name, contents);
  26584. }
  26585. writeFile.asModule = function (moduleName, fileName, contents) {
  26586. writeFile(fileName,
  26587. build.toTransport(namespace, moduleName, fileName, contents, layer));
  26588. };
  26589. return writeFile;
  26590. }
  26591. /**
  26592. * Main API entry point into the build. The args argument can either be
  26593. * an array of arguments (like the onese passed on a command-line),
  26594. * or it can be a JavaScript object that has the format of a build profile
  26595. * file.
  26596. *
  26597. * If it is an object, then in addition to the normal properties allowed in
  26598. * a build profile file, the object should contain one other property:
  26599. *
  26600. * The object could also contain a "buildFile" property, which is a string
  26601. * that is the file path to a build profile that contains the rest
  26602. * of the build profile directives.
  26603. *
  26604. * This function does not return a status, it should throw an error if
  26605. * there is a problem completing the build.
  26606. */
  26607. build = function (args) {
  26608. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  26609. i, j, errorMod,
  26610. stackRegExp = /( {4}at[^\n]+)\n/,
  26611. standardIndent = ' ';
  26612. return prim().start(function () {
  26613. if (!args || lang.isArray(args)) {
  26614. if (!args || args.length < 1) {
  26615. logger.error("build.js buildProfile.js\n" +
  26616. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  26617. return undefined;
  26618. }
  26619. //Next args can include a build file path as well as other build args.
  26620. //build file path comes first. If it does not contain an = then it is
  26621. //a build file path. Otherwise, just all build args.
  26622. if (args[0].indexOf("=") === -1) {
  26623. buildFile = args[0];
  26624. args.splice(0, 1);
  26625. }
  26626. //Remaining args are options to the build
  26627. cmdConfig = build.convertArrayToObject(args);
  26628. cmdConfig.buildFile = buildFile;
  26629. } else {
  26630. cmdConfig = args;
  26631. }
  26632. return build._run(cmdConfig);
  26633. }).then(null, function (e) {
  26634. var err;
  26635. errorMsg = e.toString();
  26636. errorTree = e.moduleTree;
  26637. stackMatch = stackRegExp.exec(errorMsg);
  26638. if (stackMatch) {
  26639. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  26640. }
  26641. //If a module tree that shows what module triggered the error,
  26642. //print it out.
  26643. if (errorTree && errorTree.length > 0) {
  26644. errorMsg += '\nIn module tree:\n';
  26645. for (i = errorTree.length - 1; i > -1; i--) {
  26646. errorMod = errorTree[i];
  26647. if (errorMod) {
  26648. for (j = errorTree.length - i; j > -1; j--) {
  26649. errorMsg += standardIndent;
  26650. }
  26651. errorMsg += errorMod + '\n';
  26652. }
  26653. }
  26654. logger.error(errorMsg);
  26655. }
  26656. errorStack = e.stack;
  26657. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  26658. errorMsg += '\n' + errorStack;
  26659. } else {
  26660. if (!stackMatch && errorStack) {
  26661. //Just trim out the first "at" in the stack.
  26662. stackMatch = stackRegExp.exec(errorStack);
  26663. if (stackMatch) {
  26664. errorMsg += '\n' + stackMatch[0] || '';
  26665. }
  26666. }
  26667. }
  26668. err = new Error(errorMsg);
  26669. err.originalError = e;
  26670. throw err;
  26671. });
  26672. };
  26673. build._run = function (cmdConfig) {
  26674. var buildPaths, fileName, fileNames,
  26675. paths, i,
  26676. baseConfig, config,
  26677. modules, srcPath, buildContext,
  26678. destPath, moduleMap, parentModuleMap, context,
  26679. resources, resource, plugin, fileContents,
  26680. pluginProcessed = {},
  26681. buildFileContents = "",
  26682. pluginCollector = {};
  26683. return prim().start(function () {
  26684. var prop;
  26685. //Can now run the patches to require.js to allow it to be used for
  26686. //build generation. Do it here instead of at the top of the module
  26687. //because we want normal require behavior to load the build tool
  26688. //then want to switch to build mode.
  26689. requirePatch();
  26690. config = build.createConfig(cmdConfig);
  26691. paths = config.paths;
  26692. //Remove the previous build dir, in case it contains source transforms,
  26693. //like the ones done with onBuildRead and onBuildWrite.
  26694. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  26695. file.deleteFile(config.dir);
  26696. }
  26697. if (!config.out && !config.cssIn) {
  26698. //This is not just a one-off file build but a full build profile, with
  26699. //lots of files to process.
  26700. //First copy all the baseUrl content
  26701. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  26702. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  26703. buildPaths = {};
  26704. if (config.appDir) {
  26705. //All the paths should be inside the appDir, so just adjust
  26706. //the paths to use the dirBaseUrl
  26707. for (prop in paths) {
  26708. if (hasProp(paths, prop)) {
  26709. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  26710. }
  26711. }
  26712. } else {
  26713. //If no appDir, then make sure to copy the other paths to this directory.
  26714. for (prop in paths) {
  26715. if (hasProp(paths, prop)) {
  26716. //Set up build path for each path prefix, but only do so
  26717. //if the path falls out of the current baseUrl
  26718. if (paths[prop].indexOf(config.baseUrl) === 0) {
  26719. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  26720. } else {
  26721. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop;
  26722. //Make sure source path is fully formed with baseUrl,
  26723. //if it is a relative URL.
  26724. srcPath = paths[prop];
  26725. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  26726. srcPath = config.baseUrl + srcPath;
  26727. }
  26728. destPath = config.dirBaseUrl + buildPaths[prop];
  26729. //Skip empty: paths
  26730. if (srcPath !== 'empty:') {
  26731. //If the srcPath is a directory, copy the whole directory.
  26732. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  26733. //Copy files to build area. Copy all files (the /\w/ regexp)
  26734. file.copyDir(srcPath, destPath, /\w/, true);
  26735. } else {
  26736. //Try a .js extension
  26737. srcPath += '.js';
  26738. destPath += '.js';
  26739. file.copyFile(srcPath, destPath);
  26740. }
  26741. }
  26742. }
  26743. }
  26744. }
  26745. }
  26746. }
  26747. //Figure out source file location for each module layer. Do this by seeding require
  26748. //with source area configuration. This is needed so that later the module layers
  26749. //can be manually copied over to the source area, since the build may be
  26750. //require multiple times and the above copyDir call only copies newer files.
  26751. require({
  26752. baseUrl: config.baseUrl,
  26753. paths: paths,
  26754. packagePaths: config.packagePaths,
  26755. packages: config.packages
  26756. });
  26757. buildContext = require.s.contexts._;
  26758. modules = config.modules;
  26759. if (modules) {
  26760. modules.forEach(function (module) {
  26761. if (module.name) {
  26762. module._sourcePath = buildContext.nameToUrl(module.name);
  26763. //If the module does not exist, and this is not a "new" module layer,
  26764. //as indicated by a true "create" property on the module, and
  26765. //it is not a plugin-loaded resource, and there is no
  26766. //'rawText' containing the module's source then throw an error.
  26767. if (!file.exists(module._sourcePath) && !module.create &&
  26768. module.name.indexOf('!') === -1 &&
  26769. (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  26770. throw new Error("ERROR: module path does not exist: " +
  26771. module._sourcePath + " for module named: " + module.name +
  26772. ". Path is relative to: " + file.absPath('.'));
  26773. }
  26774. }
  26775. });
  26776. }
  26777. if (config.out) {
  26778. //Just set up the _buildPath for the module layer.
  26779. require(config);
  26780. if (!config.cssIn) {
  26781. config.modules[0]._buildPath = typeof config.out === 'function' ?
  26782. 'FUNCTION' : config.out;
  26783. }
  26784. } else if (!config.cssIn) {
  26785. //Now set up the config for require to use the build area, and calculate the
  26786. //build file locations. Pass along any config info too.
  26787. baseConfig = {
  26788. baseUrl: config.dirBaseUrl,
  26789. paths: buildPaths
  26790. };
  26791. lang.mixin(baseConfig, config);
  26792. require(baseConfig);
  26793. if (modules) {
  26794. modules.forEach(function (module) {
  26795. if (module.name) {
  26796. module._buildPath = buildContext.nameToUrl(module.name, null);
  26797. //If buildPath and sourcePath are the same, throw since this
  26798. //would result in modifying source. This condition can happen
  26799. //with some more tricky paths: config and appDir/baseUrl
  26800. //setting, which is a sign of incorrect config.
  26801. if (module._buildPath === module._sourcePath &&
  26802. !config.allowSourceOverwrites) {
  26803. throw new Error('Module ID \'' + module.name +
  26804. '\' has a source path that is same as output path: ' +
  26805. module._sourcePath +
  26806. '. Stopping, config is malformed.');
  26807. }
  26808. if (!module.create) {
  26809. file.copyFile(module._sourcePath, module._buildPath);
  26810. }
  26811. }
  26812. });
  26813. }
  26814. }
  26815. //Run CSS optimizations before doing JS module tracing, to allow
  26816. //things like text loader plugins loading CSS to get the optimized
  26817. //CSS.
  26818. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  26819. buildFileContents += optimize.css(config.dir, config);
  26820. }
  26821. }).then(function() {
  26822. baseConfig = copyConfig(require.s.contexts._.config);
  26823. }).then(function () {
  26824. var actions = [];
  26825. if (modules) {
  26826. actions = modules.map(function (module, i) {
  26827. return function () {
  26828. //Save off buildPath to module index in a hash for quicker
  26829. //lookup later.
  26830. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
  26831. //Call require to calculate dependencies.
  26832. return build.traceDependencies(module, config, baseConfig)
  26833. .then(function (layer) {
  26834. module.layer = layer;
  26835. });
  26836. };
  26837. });
  26838. return prim.serial(actions);
  26839. }
  26840. }).then(function () {
  26841. var actions;
  26842. if (modules) {
  26843. //Now build up shadow layers for anything that should be excluded.
  26844. //Do this after tracing dependencies for each module, in case one
  26845. //of those modules end up being one of the excluded values.
  26846. actions = modules.map(function (module) {
  26847. return function () {
  26848. if (module.exclude) {
  26849. module.excludeLayers = [];
  26850. return prim.serial(module.exclude.map(function (exclude, i) {
  26851. return function () {
  26852. //See if it is already in the list of modules.
  26853. //If not trace dependencies for it.
  26854. var found = build.findBuildModule(exclude, modules);
  26855. if (found) {
  26856. module.excludeLayers[i] = found;
  26857. } else {
  26858. return build.traceDependencies({name: exclude}, config, baseConfig)
  26859. .then(function (layer) {
  26860. module.excludeLayers[i] = { layer: layer };
  26861. });
  26862. }
  26863. };
  26864. }));
  26865. }
  26866. };
  26867. });
  26868. return prim.serial(actions);
  26869. }
  26870. }).then(function () {
  26871. if (modules) {
  26872. return prim.serial(modules.map(function (module) {
  26873. return function () {
  26874. if (module.exclude) {
  26875. //module.exclude is an array of module names. For each one,
  26876. //get the nested dependencies for it via a matching entry
  26877. //in the module.excludeLayers array.
  26878. module.exclude.forEach(function (excludeModule, i) {
  26879. var excludeLayer = module.excludeLayers[i].layer,
  26880. map = excludeLayer.buildFileToModule;
  26881. excludeLayer.buildFilePaths.forEach(function(filePath){
  26882. build.removeModulePath(map[filePath], filePath, module.layer);
  26883. });
  26884. });
  26885. }
  26886. if (module.excludeShallow) {
  26887. //module.excludeShallow is an array of module names.
  26888. //shallow exclusions are just that module itself, and not
  26889. //its nested dependencies.
  26890. module.excludeShallow.forEach(function (excludeShallowModule) {
  26891. var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
  26892. if (path) {
  26893. build.removeModulePath(excludeShallowModule, path, module.layer);
  26894. }
  26895. });
  26896. }
  26897. //Flatten them and collect the build output for each module.
  26898. return build.flattenModule(module, module.layer, config).then(function (builtModule) {
  26899. var finalText, baseName;
  26900. //Save it to a temp file for now, in case there are other layers that
  26901. //contain optimized content that should not be included in later
  26902. //layer optimizations. See issue #56.
  26903. if (module._buildPath === 'FUNCTION') {
  26904. module._buildText = builtModule.text;
  26905. module._buildSourceMap = builtModule.sourceMap;
  26906. } else {
  26907. finalText = builtModule.text;
  26908. if (builtModule.sourceMap) {
  26909. baseName = module._buildPath.split('/');
  26910. baseName = baseName.pop();
  26911. finalText += '\n//# sourceMappingURL=' + baseName + '.map';
  26912. file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
  26913. }
  26914. file.saveUtf8File(module._buildPath + '-temp', finalText);
  26915. }
  26916. buildFileContents += builtModule.buildText;
  26917. });
  26918. };
  26919. }));
  26920. }
  26921. }).then(function () {
  26922. var moduleName, outOrigSourceMap;
  26923. if (modules) {
  26924. //Now move the build layers to their final position.
  26925. modules.forEach(function (module) {
  26926. var finalPath = module._buildPath;
  26927. if (finalPath !== 'FUNCTION') {
  26928. if (file.exists(finalPath)) {
  26929. file.deleteFile(finalPath);
  26930. }
  26931. file.renameFile(finalPath + '-temp', finalPath);
  26932. //And finally, if removeCombined is specified, remove
  26933. //any of the files that were used in this layer.
  26934. //Be sure not to remove other build layers.
  26935. if (config.removeCombined && !config.out) {
  26936. module.layer.buildFilePaths.forEach(function (path) {
  26937. var isLayer = modules.some(function (mod) {
  26938. return mod._buildPath === path;
  26939. }),
  26940. relPath = build.makeRelativeFilePath(config.dir, path);
  26941. if (file.exists(path) &&
  26942. // not a build layer target
  26943. !isLayer &&
  26944. // not outside the build directory
  26945. relPath.indexOf('..') !== 0) {
  26946. file.deleteFile(path);
  26947. }
  26948. });
  26949. }
  26950. }
  26951. //Signal layer is done
  26952. if (config.onModuleBundleComplete) {
  26953. config.onModuleBundleComplete(module.onCompleteData);
  26954. }
  26955. });
  26956. }
  26957. //If removeCombined in play, remove any empty directories that
  26958. //may now exist because of its use
  26959. if (config.removeCombined && !config.out && config.dir) {
  26960. file.deleteEmptyDirs(config.dir);
  26961. }
  26962. //Do other optimizations.
  26963. if (config.out && !config.cssIn) {
  26964. //Just need to worry about one JS file.
  26965. fileName = config.modules[0]._buildPath;
  26966. if (fileName === 'FUNCTION') {
  26967. outOrigSourceMap = config.modules[0]._buildSourceMap;
  26968. config._buildSourceMap = outOrigSourceMap;
  26969. config.modules[0]._buildText = optimize.js((config.modules[0].name ||
  26970. config.modules[0].include[0] ||
  26971. fileName) + '.build.js',
  26972. config.modules[0]._buildText,
  26973. null,
  26974. config);
  26975. if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
  26976. config.modules[0]._buildSourceMap = config._buildSourceMap;
  26977. config._buildSourceMap = null;
  26978. }
  26979. } else {
  26980. optimize.jsFile(fileName, null, fileName, config);
  26981. }
  26982. } else if (!config.cssIn) {
  26983. //Normal optimizations across modules.
  26984. //JS optimizations.
  26985. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  26986. fileNames.forEach(function (fileName) {
  26987. var cfg, override, moduleIndex;
  26988. //Generate the module name from the config.dir root.
  26989. moduleName = fileName.replace(config.dir, '');
  26990. //Get rid of the extension
  26991. moduleName = moduleName.substring(0, moduleName.length - 3);
  26992. //If there is an override for a specific layer build module,
  26993. //and this file is that module, mix in the override for use
  26994. //by optimize.jsFile.
  26995. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  26996. //Normalize, since getOwn could have returned undefined
  26997. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  26998. //Try to avoid extra work if the other files do not need to
  26999. //be read. Build layers should be processed at the very
  27000. //least for optimization.
  27001. if (moduleIndex > -1 || !config.skipDirOptimize ||
  27002. config.normalizeDirDefines === "all" ||
  27003. config.cjsTranslate) {
  27004. //Convert the file to transport format, but without a name
  27005. //inserted (by passing null for moduleName) since the files are
  27006. //standalone, one module per file.
  27007. fileContents = file.readFile(fileName);
  27008. //For builds, if wanting cjs translation, do it now, so that
  27009. //the individual modules can be loaded cross domain via
  27010. //plain script tags.
  27011. if (config.cjsTranslate &&
  27012. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  27013. fileContents = commonJs.convert(fileName, fileContents);
  27014. }
  27015. if (moduleIndex === -1) {
  27016. if (config.onBuildRead) {
  27017. fileContents = config.onBuildRead(moduleName,
  27018. fileName,
  27019. fileContents);
  27020. }
  27021. //Only do transport normalization if this is not a build
  27022. //layer (since it was already normalized) and if
  27023. //normalizeDirDefines indicated all should be done.
  27024. if (config.normalizeDirDefines === "all") {
  27025. fileContents = build.toTransport(config.namespace,
  27026. null,
  27027. fileName,
  27028. fileContents);
  27029. }
  27030. if (config.onBuildWrite) {
  27031. fileContents = config.onBuildWrite(moduleName,
  27032. fileName,
  27033. fileContents);
  27034. }
  27035. }
  27036. override = moduleIndex > -1 ?
  27037. config.modules[moduleIndex].override : null;
  27038. if (override) {
  27039. cfg = build.createOverrideConfig(config, override);
  27040. } else {
  27041. cfg = config;
  27042. }
  27043. if (moduleIndex > -1 || !config.skipDirOptimize) {
  27044. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  27045. }
  27046. }
  27047. });
  27048. //Normalize all the plugin resources.
  27049. context = require.s.contexts._;
  27050. for (moduleName in pluginCollector) {
  27051. if (hasProp(pluginCollector, moduleName)) {
  27052. parentModuleMap = context.makeModuleMap(moduleName);
  27053. resources = pluginCollector[moduleName];
  27054. for (i = 0; i < resources.length; i++) {
  27055. resource = resources[i];
  27056. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  27057. if (falseProp(context.plugins, moduleMap.prefix)) {
  27058. //Set the value in context.plugins so it
  27059. //will be evaluated as a full plugin.
  27060. context.plugins[moduleMap.prefix] = true;
  27061. //Do not bother if the plugin is not available.
  27062. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  27063. continue;
  27064. }
  27065. //Rely on the require in the build environment
  27066. //to be synchronous
  27067. context.require([moduleMap.prefix]);
  27068. //Now that the plugin is loaded, redo the moduleMap
  27069. //since the plugin will need to normalize part of the path.
  27070. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  27071. }
  27072. //Only bother with plugin resources that can be handled
  27073. //processed by the plugin, via support of the writeFile
  27074. //method.
  27075. if (falseProp(pluginProcessed, moduleMap.id)) {
  27076. //Only do the work if the plugin was really loaded.
  27077. //Using an internal access because the file may
  27078. //not really be loaded.
  27079. plugin = getOwn(context.defined, moduleMap.prefix);
  27080. if (plugin && plugin.writeFile) {
  27081. plugin.writeFile(
  27082. moduleMap.prefix,
  27083. moduleMap.name,
  27084. require,
  27085. makeWriteFile(
  27086. config.namespace
  27087. ),
  27088. context.config
  27089. );
  27090. }
  27091. pluginProcessed[moduleMap.id] = true;
  27092. }
  27093. }
  27094. }
  27095. }
  27096. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  27097. //All module layers are done, write out the build.txt file.
  27098. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  27099. }
  27100. //If just have one CSS file to optimize, do that here.
  27101. if (config.cssIn) {
  27102. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  27103. }
  27104. if (typeof config.out === 'function') {
  27105. config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
  27106. }
  27107. //Print out what was built into which layers.
  27108. if (buildFileContents) {
  27109. logger.info(buildFileContents);
  27110. return buildFileContents;
  27111. }
  27112. return '';
  27113. });
  27114. };
  27115. /**
  27116. * Converts command line args like "paths.foo=../some/path"
  27117. * result.paths = { foo: '../some/path' } where prop = paths,
  27118. * name = paths.foo and value = ../some/path, so it assumes the
  27119. * name=value splitting has already happened.
  27120. */
  27121. function stringDotToObj(result, name, value) {
  27122. var parts = name.split('.');
  27123. parts.forEach(function (prop, i) {
  27124. if (i === parts.length - 1) {
  27125. result[prop] = value;
  27126. } else {
  27127. if (falseProp(result, prop)) {
  27128. result[prop] = {};
  27129. }
  27130. result = result[prop];
  27131. }
  27132. });
  27133. }
  27134. build.objProps = {
  27135. paths: true,
  27136. wrap: true,
  27137. pragmas: true,
  27138. pragmasOnSave: true,
  27139. has: true,
  27140. hasOnSave: true,
  27141. uglify: true,
  27142. uglify2: true,
  27143. closure: true,
  27144. map: true,
  27145. throwWhen: true
  27146. };
  27147. build.hasDotPropMatch = function (prop) {
  27148. var dotProp,
  27149. index = prop.indexOf('.');
  27150. if (index !== -1) {
  27151. dotProp = prop.substring(0, index);
  27152. return hasProp(build.objProps, dotProp);
  27153. }
  27154. return false;
  27155. };
  27156. /**
  27157. * Converts an array that has String members of "name=value"
  27158. * into an object, where the properties on the object are the names in the array.
  27159. * Also converts the strings "true" and "false" to booleans for the values.
  27160. * member name/value pairs, and converts some comma-separated lists into
  27161. * arrays.
  27162. * @param {Array} ary
  27163. */
  27164. build.convertArrayToObject = function (ary) {
  27165. var result = {}, i, separatorIndex, prop, value,
  27166. needArray = {
  27167. "include": true,
  27168. "exclude": true,
  27169. "excludeShallow": true,
  27170. "insertRequire": true,
  27171. "stubModules": true,
  27172. "deps": true,
  27173. "mainConfigFile": true
  27174. };
  27175. for (i = 0; i < ary.length; i++) {
  27176. separatorIndex = ary[i].indexOf("=");
  27177. if (separatorIndex === -1) {
  27178. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  27179. }
  27180. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  27181. if (value === "true") {
  27182. value = true;
  27183. } else if (value === "false") {
  27184. value = false;
  27185. }
  27186. prop = ary[i].substring(0, separatorIndex);
  27187. //Convert to array if necessary
  27188. if (getOwn(needArray, prop)) {
  27189. value = value.split(",");
  27190. }
  27191. if (build.hasDotPropMatch(prop)) {
  27192. stringDotToObj(result, prop, value);
  27193. } else {
  27194. result[prop] = value;
  27195. }
  27196. }
  27197. return result; //Object
  27198. };
  27199. build.makeAbsPath = function (path, absFilePath) {
  27200. if (!absFilePath) {
  27201. return path;
  27202. }
  27203. //Add abspath if necessary. If path starts with a slash or has a colon,
  27204. //then already is an abolute path.
  27205. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  27206. path = absFilePath +
  27207. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  27208. path;
  27209. path = file.normalize(path);
  27210. }
  27211. return path.replace(lang.backSlashRegExp, '/');
  27212. };
  27213. build.makeAbsObject = function (props, obj, absFilePath) {
  27214. var i, prop;
  27215. if (obj) {
  27216. for (i = 0; i < props.length; i++) {
  27217. prop = props[i];
  27218. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  27219. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  27220. }
  27221. }
  27222. }
  27223. };
  27224. /**
  27225. * For any path in a possible config, make it absolute relative
  27226. * to the absFilePath passed in.
  27227. */
  27228. build.makeAbsConfig = function (config, absFilePath) {
  27229. var props, prop, i;
  27230. props = ["appDir", "dir", "baseUrl"];
  27231. for (i = 0; i < props.length; i++) {
  27232. prop = props[i];
  27233. if (getOwn(config, prop)) {
  27234. //Add abspath if necessary, make sure these paths end in
  27235. //slashes
  27236. if (prop === "baseUrl") {
  27237. config.originalBaseUrl = config.baseUrl;
  27238. if (config.appDir) {
  27239. //If baseUrl with an appDir, the baseUrl is relative to
  27240. //the appDir, *not* the absFilePath. appDir and dir are
  27241. //made absolute before baseUrl, so this will work.
  27242. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  27243. } else {
  27244. //The dir output baseUrl is same as regular baseUrl, both
  27245. //relative to the absFilePath.
  27246. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  27247. }
  27248. } else {
  27249. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  27250. }
  27251. config[prop] = endsWithSlash(config[prop]);
  27252. }
  27253. }
  27254. build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]),
  27255. config, absFilePath);
  27256. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  27257. build.makeAbsObject(["externExportsPath"], config.closure, absFilePath);
  27258. };
  27259. /**
  27260. * Creates a relative path to targetPath from refPath.
  27261. * Only deals with file paths, not folders. If folders,
  27262. * make sure paths end in a trailing '/'.
  27263. */
  27264. build.makeRelativeFilePath = function (refPath, targetPath) {
  27265. var i, dotLength, finalParts, length, targetParts, targetName,
  27266. refParts = refPath.split('/'),
  27267. hasEndSlash = endsWithSlashRegExp.test(targetPath),
  27268. dotParts = [];
  27269. targetPath = file.normalize(targetPath);
  27270. if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
  27271. targetPath += '/';
  27272. }
  27273. targetParts = targetPath.split('/');
  27274. //Pull off file name
  27275. targetName = targetParts.pop();
  27276. //Also pop off the ref file name to make the matches against
  27277. //targetParts equivalent.
  27278. refParts.pop();
  27279. length = refParts.length;
  27280. for (i = 0; i < length; i += 1) {
  27281. if (refParts[i] !== targetParts[i]) {
  27282. break;
  27283. }
  27284. }
  27285. //Now i is the index in which they diverge.
  27286. finalParts = targetParts.slice(i);
  27287. dotLength = length - i;
  27288. for (i = 0; i > -1 && i < dotLength; i += 1) {
  27289. dotParts.push('..');
  27290. }
  27291. return dotParts.join('/') + (dotParts.length ? '/' : '') +
  27292. finalParts.join('/') + (finalParts.length ? '/' : '') +
  27293. targetName;
  27294. };
  27295. build.nestedMix = {
  27296. paths: true,
  27297. has: true,
  27298. hasOnSave: true,
  27299. pragmas: true,
  27300. pragmasOnSave: true
  27301. };
  27302. /**
  27303. * Mixes additional source config into target config, and merges some
  27304. * nested config, like paths, correctly.
  27305. */
  27306. function mixConfig(target, source, skipArrays) {
  27307. var prop, value, isArray, targetValue;
  27308. for (prop in source) {
  27309. if (hasProp(source, prop)) {
  27310. //If the value of the property is a plain object, then
  27311. //allow a one-level-deep mixing of it.
  27312. value = source[prop];
  27313. isArray = lang.isArray(value);
  27314. if (typeof value === 'object' && value &&
  27315. !isArray && !lang.isFunction(value) &&
  27316. !lang.isRegExp(value)) {
  27317. // TODO: need to generalize this work, maybe also reuse
  27318. // the work done in requirejs configure, perhaps move to
  27319. // just a deep copy/merge overall. However, given the
  27320. // amount of observable change, wait for a dot release.
  27321. // This change is in relation to #645
  27322. if (prop === 'map') {
  27323. if (!target.map) {
  27324. target.map = {};
  27325. }
  27326. lang.deepMix(target.map, source.map);
  27327. } else {
  27328. target[prop] = lang.mixin({}, target[prop], value, true);
  27329. }
  27330. } else if (isArray) {
  27331. if (!skipArrays) {
  27332. // Some config, like packages, are arrays. For those,
  27333. // just merge the results.
  27334. targetValue = target[prop];
  27335. if (lang.isArray(targetValue)) {
  27336. target[prop] = targetValue.concat(value);
  27337. } else {
  27338. target[prop] = value;
  27339. }
  27340. }
  27341. } else {
  27342. target[prop] = value;
  27343. }
  27344. }
  27345. }
  27346. //Set up log level since it can affect if errors are thrown
  27347. //or caught and passed to errbacks while doing config setup.
  27348. if (lang.hasProp(target, 'logLevel')) {
  27349. logger.logLevel(target.logLevel);
  27350. }
  27351. }
  27352. /**
  27353. * Converts a wrap.startFile or endFile to be start/end as a string.
  27354. * the startFile/endFile values can be arrays.
  27355. */
  27356. function flattenWrapFile(wrap, keyName, absFilePath) {
  27357. var keyFileName = keyName + 'File';
  27358. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  27359. wrap[keyName] = '';
  27360. if (typeof wrap[keyFileName] === 'string') {
  27361. wrap[keyFileName] = [wrap[keyFileName]];
  27362. }
  27363. wrap[keyFileName].forEach(function (fileName) {
  27364. wrap[keyName] += (wrap[keyName] ? '\n' : '') +
  27365. file.readFile(build.makeAbsPath(fileName, absFilePath));
  27366. });
  27367. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  27368. //Allow missing one, just set to empty string.
  27369. wrap[keyName] = '';
  27370. } else if (typeof wrap[keyName] !== 'string') {
  27371. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  27372. }
  27373. }
  27374. function normalizeWrapConfig(config, absFilePath) {
  27375. //Get any wrap text.
  27376. try {
  27377. if (config.wrap) {
  27378. if (config.wrap === true) {
  27379. //Use default values.
  27380. config.wrap = {
  27381. start: '(function () {',
  27382. end: '}());'
  27383. };
  27384. } else {
  27385. flattenWrapFile(config.wrap, 'start', absFilePath);
  27386. flattenWrapFile(config.wrap, 'end', absFilePath);
  27387. }
  27388. }
  27389. } catch (wrapError) {
  27390. throw new Error('Malformed wrap config: ' + wrapError.toString());
  27391. }
  27392. }
  27393. /**
  27394. * Creates a config object for an optimization build.
  27395. * It will also read the build profile if it is available, to create
  27396. * the configuration.
  27397. *
  27398. * @param {Object} cfg config options that take priority
  27399. * over defaults and ones in the build file. These options could
  27400. * be from a command line, for instance.
  27401. *
  27402. * @param {Object} the created config object.
  27403. */
  27404. build.createConfig = function (cfg) {
  27405. /*jslint evil: true */
  27406. var buildFileContents, buildFileConfig, mainConfig,
  27407. mainConfigFile, mainConfigPath, buildFile, absFilePath,
  27408. config = {},
  27409. buildBaseConfig = makeBuildBaseConfig();
  27410. //Make sure all paths are relative to current directory.
  27411. absFilePath = file.absPath('.');
  27412. build.makeAbsConfig(cfg, absFilePath);
  27413. build.makeAbsConfig(buildBaseConfig, absFilePath);
  27414. lang.mixin(config, buildBaseConfig);
  27415. lang.mixin(config, cfg, true);
  27416. //Set up log level early since it can affect if errors are thrown
  27417. //or caught and passed to errbacks, even while constructing config.
  27418. if (lang.hasProp(config, 'logLevel')) {
  27419. logger.logLevel(config.logLevel);
  27420. }
  27421. if (config.buildFile) {
  27422. //A build file exists, load it to get more config.
  27423. buildFile = file.absPath(config.buildFile);
  27424. //Find the build file, and make sure it exists, if this is a build
  27425. //that has a build profile, and not just command line args with an in=path
  27426. if (!file.exists(buildFile)) {
  27427. throw new Error("ERROR: build file does not exist: " + buildFile);
  27428. }
  27429. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  27430. //Load build file options.
  27431. buildFileContents = file.readFile(buildFile);
  27432. try {
  27433. //Be a bit lenient in the file ending in a ; or ending with
  27434. //a //# sourceMappingUrl comment, mostly for compiled languages
  27435. //that create a config, like typescript.
  27436. buildFileContents = buildFileContents
  27437. .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '')
  27438. .trim()
  27439. .replace(/;$/, '');
  27440. buildFileConfig = eval("(" + buildFileContents + ")");
  27441. build.makeAbsConfig(buildFileConfig, absFilePath);
  27442. //Mix in the config now so that items in mainConfigFile can
  27443. //be resolved relative to them if necessary, like if appDir
  27444. //is set here, but the baseUrl is in mainConfigFile. Will
  27445. //re-mix in the same build config later after mainConfigFile
  27446. //is processed, since build config should take priority.
  27447. mixConfig(config, buildFileConfig);
  27448. } catch (e) {
  27449. throw new Error("Build file " + buildFile + " is malformed: " + e);
  27450. }
  27451. }
  27452. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  27453. if (mainConfigFile) {
  27454. if (typeof mainConfigFile === 'string') {
  27455. mainConfigFile = [mainConfigFile];
  27456. }
  27457. mainConfigFile.forEach(function (configFile) {
  27458. configFile = build.makeAbsPath(configFile, absFilePath);
  27459. if (!file.exists(configFile)) {
  27460. throw new Error(configFile + ' does not exist.');
  27461. }
  27462. try {
  27463. mainConfig = parse.findConfig(file.readFile(configFile)).config;
  27464. } catch (configError) {
  27465. throw new Error('The config in mainConfigFile ' +
  27466. configFile +
  27467. ' cannot be used because it cannot be evaluated' +
  27468. ' correctly while running in the optimizer. Try only' +
  27469. ' using a config that is also valid JSON, or do not use' +
  27470. ' mainConfigFile and instead copy the config values needed' +
  27471. ' into a build file or command line arguments given to the optimizer.\n' +
  27472. 'Source error from parsing: ' + configFile + ': ' + configError);
  27473. }
  27474. if (mainConfig) {
  27475. mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
  27476. //Add in some existing config, like appDir, since they can be
  27477. //used inside the configFile -- paths and baseUrl are
  27478. //relative to them.
  27479. if (config.appDir && !mainConfig.appDir) {
  27480. mainConfig.appDir = config.appDir;
  27481. }
  27482. //If no baseUrl, then use the directory holding the main config.
  27483. if (!mainConfig.baseUrl) {
  27484. mainConfig.baseUrl = mainConfigPath;
  27485. }
  27486. build.makeAbsConfig(mainConfig, mainConfigPath);
  27487. mixConfig(config, mainConfig);
  27488. }
  27489. });
  27490. }
  27491. //Mix in build file config, but only after mainConfig has been mixed in.
  27492. //Since this is a re-application, skip array merging.
  27493. if (buildFileConfig) {
  27494. mixConfig(config, buildFileConfig, true);
  27495. }
  27496. //Re-apply the override config values. Command line
  27497. //args should take precedence over build file values.
  27498. //Since this is a re-application, skip array merging.
  27499. mixConfig(config, cfg, true);
  27500. //Fix paths to full paths so that they can be adjusted consistently
  27501. //lately to be in the output area.
  27502. lang.eachProp(config.paths, function (value, prop) {
  27503. if (lang.isArray(value)) {
  27504. throw new Error('paths fallback not supported in optimizer. ' +
  27505. 'Please provide a build config path override ' +
  27506. 'for ' + prop);
  27507. }
  27508. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  27509. });
  27510. //Set final output dir
  27511. if (hasProp(config, "baseUrl")) {
  27512. if (config.appDir) {
  27513. if (!config.originalBaseUrl) {
  27514. throw new Error('Please set a baseUrl in the build config');
  27515. }
  27516. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  27517. } else {
  27518. config.dirBaseUrl = config.dir || config.baseUrl;
  27519. }
  27520. //Make sure dirBaseUrl ends in a slash, since it is
  27521. //concatenated with other strings.
  27522. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  27523. }
  27524. //If out=stdout, write output to STDOUT instead of a file.
  27525. if (config.out && config.out === 'stdout') {
  27526. config.out = function (content) {
  27527. var e = env.get();
  27528. if (e === 'rhino') {
  27529. var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');
  27530. out.println(content);
  27531. } else if (e === 'node') {
  27532. process.stdout.setEncoding('utf8');
  27533. process.stdout.write(content);
  27534. } else {
  27535. console.log(content);
  27536. }
  27537. };
  27538. }
  27539. //Check for errors in config
  27540. if (config.main) {
  27541. throw new Error('"main" passed as an option, but the ' +
  27542. 'supported option is called "name".');
  27543. }
  27544. if (config.out && !config.name && !config.modules && !config.include &&
  27545. !config.cssIn) {
  27546. throw new Error('Missing either a "name", "include" or "modules" ' +
  27547. 'option');
  27548. }
  27549. if (config.cssIn) {
  27550. if (config.dir || config.appDir) {
  27551. throw new Error('cssIn is only for the output of single file ' +
  27552. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  27553. }
  27554. if (!config.out) {
  27555. throw new Error('"out" option missing.');
  27556. }
  27557. }
  27558. if (!config.cssIn && !config.baseUrl) {
  27559. //Just use the current directory as the baseUrl
  27560. config.baseUrl = './';
  27561. }
  27562. if (!config.out && !config.dir) {
  27563. throw new Error('Missing either an "out" or "dir" config value. ' +
  27564. 'If using "appDir" for a full project optimization, ' +
  27565. 'use "dir". If you want to optimize to one file, ' +
  27566. 'use "out".');
  27567. }
  27568. if (config.appDir && config.out) {
  27569. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  27570. 'instead. appDir is used to copy whole projects, ' +
  27571. 'where "out" with "baseUrl" is used to just ' +
  27572. 'optimize to one file.');
  27573. }
  27574. if (config.out && config.dir) {
  27575. throw new Error('The "out" and "dir" options are incompatible.' +
  27576. ' Use "out" if you are targeting a single file' +
  27577. ' for optimization, and "dir" if you want the appDir' +
  27578. ' or baseUrl directories optimized.');
  27579. }
  27580. if (config.dir) {
  27581. // Make sure the output dir is not set to a parent of the
  27582. // source dir or the same dir, as it will result in source
  27583. // code deletion.
  27584. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
  27585. config.dir === config.appDir ||
  27586. (config.baseUrl && build.makeRelativeFilePath(config.dir,
  27587. config.baseUrl).indexOf('..') !== 0) ||
  27588. (config.appDir &&
  27589. build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
  27590. throw new Error('"dir" is set to a parent or same directory as' +
  27591. ' "appDir" or "baseUrl". This can result in' +
  27592. ' the deletion of source code. Stopping. If' +
  27593. ' you want to allow possible overwriting of' +
  27594. ' source code, set "allowSourceOverwrites"' +
  27595. ' to true in the build config, but do so at' +
  27596. ' your own risk. In that case, you may want' +
  27597. ' to also set "keepBuildDir" to true.');
  27598. }
  27599. }
  27600. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  27601. throw new Error('insertRequire should be a list of module IDs' +
  27602. ' to insert in to a require([]) call.');
  27603. }
  27604. if (config.generateSourceMaps) {
  27605. if (config.preserveLicenseComments && config.optimize !== 'none') {
  27606. throw new Error('Cannot use preserveLicenseComments and ' +
  27607. 'generateSourceMaps together. Either explcitly set ' +
  27608. 'preserveLicenseComments to false (default is true) or ' +
  27609. 'turn off generateSourceMaps. If you want source maps with ' +
  27610. 'license comments, see: ' +
  27611. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  27612. } else if (config.optimize !== 'none' &&
  27613. config.optimize !== 'closure' &&
  27614. config.optimize !== 'uglify2') {
  27615. //Allow optimize: none to pass, since it is useful when toggling
  27616. //minification on and off to debug something, and it implicitly
  27617. //works, since it does not need a source map.
  27618. throw new Error('optimize: "' + config.optimize +
  27619. '" does not support generateSourceMaps.');
  27620. }
  27621. }
  27622. if ((config.name || config.include) && !config.modules) {
  27623. //Just need to build one file, but may be part of a whole appDir/
  27624. //baseUrl copy, but specified on the command line, so cannot do
  27625. //the modules array setup. So create a modules section in that
  27626. //case.
  27627. config.modules = [
  27628. {
  27629. name: config.name,
  27630. out: config.out,
  27631. create: config.create,
  27632. include: config.include,
  27633. exclude: config.exclude,
  27634. excludeShallow: config.excludeShallow,
  27635. insertRequire: config.insertRequire,
  27636. stubModules: config.stubModules
  27637. }
  27638. ];
  27639. delete config.stubModules;
  27640. } else if (config.modules && config.out) {
  27641. throw new Error('If the "modules" option is used, then there ' +
  27642. 'should be a "dir" option set and "out" should ' +
  27643. 'not be used since "out" is only for single file ' +
  27644. 'optimization output.');
  27645. } else if (config.modules && config.name) {
  27646. throw new Error('"name" and "modules" options are incompatible. ' +
  27647. 'Either use "name" if doing a single file ' +
  27648. 'optimization, or "modules" if you want to target ' +
  27649. 'more than one file for optimization.');
  27650. }
  27651. if (config.out && !config.cssIn) {
  27652. //Just one file to optimize.
  27653. //Does not have a build file, so set up some defaults.
  27654. //Optimizing CSS should not be allowed, unless explicitly
  27655. //asked for on command line. In that case the only task is
  27656. //to optimize a CSS file.
  27657. if (!cfg.optimizeCss) {
  27658. config.optimizeCss = "none";
  27659. }
  27660. }
  27661. //Normalize cssPrefix
  27662. if (config.cssPrefix) {
  27663. //Make sure cssPrefix ends in a slash
  27664. config.cssPrefix = endsWithSlash(config.cssPrefix);
  27665. } else {
  27666. config.cssPrefix = '';
  27667. }
  27668. //Cycle through modules and normalize
  27669. if (config.modules && config.modules.length) {
  27670. config.modules.forEach(function (mod) {
  27671. if (lang.isArray(mod) || typeof mod === 'string' || !mod) {
  27672. throw new Error('modules config item is malformed: it should' +
  27673. ' be an object with a \'name\' property.');
  27674. }
  27675. //Combine any local stubModules with global values.
  27676. if (config.stubModules) {
  27677. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  27678. }
  27679. //Create a hash lookup for the stubModules config to make lookup
  27680. //cheaper later.
  27681. if (mod.stubModules) {
  27682. mod.stubModules._byName = {};
  27683. mod.stubModules.forEach(function (id) {
  27684. mod.stubModules._byName[id] = true;
  27685. });
  27686. }
  27687. // Legacy command support, which allowed a single string ID
  27688. // for include.
  27689. if (typeof mod.include === 'string') {
  27690. mod.include = [mod.include];
  27691. }
  27692. //Allow wrap config in overrides, but normalize it.
  27693. if (mod.override) {
  27694. normalizeWrapConfig(mod.override, absFilePath);
  27695. }
  27696. });
  27697. }
  27698. normalizeWrapConfig(config, absFilePath);
  27699. //Do final input verification
  27700. if (config.context) {
  27701. throw new Error('The build argument "context" is not supported' +
  27702. ' in a build. It should only be used in web' +
  27703. ' pages.');
  27704. }
  27705. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  27706. //set to "skip" otherwise set to "all".
  27707. if (!hasProp(config, 'normalizeDirDefines')) {
  27708. if (config.optimize === 'none' || config.skipDirOptimize) {
  27709. config.normalizeDirDefines = 'skip';
  27710. } else {
  27711. config.normalizeDirDefines = 'all';
  27712. }
  27713. }
  27714. //Set file.fileExclusionRegExp if desired
  27715. if (hasProp(config, 'fileExclusionRegExp')) {
  27716. if (typeof config.fileExclusionRegExp === "string") {
  27717. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  27718. } else {
  27719. file.exclusionRegExp = config.fileExclusionRegExp;
  27720. }
  27721. } else if (hasProp(config, 'dirExclusionRegExp')) {
  27722. //Set file.dirExclusionRegExp if desired, this is the old
  27723. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  27724. //compatibility
  27725. file.exclusionRegExp = config.dirExclusionRegExp;
  27726. }
  27727. //Track the deps, but in a different key, so that they are not loaded
  27728. //as part of config seeding before all config is in play (#648). Was
  27729. //going to merge this in with "include", but include is added after
  27730. //the "name" target. To preserve what r.js has done previously, make
  27731. //sure "deps" comes before the "name".
  27732. if (config.deps) {
  27733. config._depsInclude = config.deps;
  27734. }
  27735. //Remove things that may cause problems in the build.
  27736. //deps already merged above
  27737. delete config.deps;
  27738. delete config.jQuery;
  27739. delete config.enforceDefine;
  27740. delete config.urlArgs;
  27741. return config;
  27742. };
  27743. /**
  27744. * finds the module being built/optimized with the given moduleName,
  27745. * or returns null.
  27746. * @param {String} moduleName
  27747. * @param {Array} modules
  27748. * @returns {Object} the module object from the build profile, or null.
  27749. */
  27750. build.findBuildModule = function (moduleName, modules) {
  27751. var i, module;
  27752. for (i = 0; i < modules.length; i++) {
  27753. module = modules[i];
  27754. if (module.name === moduleName) {
  27755. return module;
  27756. }
  27757. }
  27758. return null;
  27759. };
  27760. /**
  27761. * Removes a module name and path from a layer, if it is supposed to be
  27762. * excluded from the layer.
  27763. * @param {String} moduleName the name of the module
  27764. * @param {String} path the file path for the module
  27765. * @param {Object} layer the layer to remove the module/path from
  27766. */
  27767. build.removeModulePath = function (module, path, layer) {
  27768. var index = layer.buildFilePaths.indexOf(path);
  27769. if (index !== -1) {
  27770. layer.buildFilePaths.splice(index, 1);
  27771. }
  27772. };
  27773. /**
  27774. * Uses the module build config object to trace the dependencies for the
  27775. * given module.
  27776. *
  27777. * @param {Object} module the module object from the build config info.
  27778. * @param {Object} config the build config object.
  27779. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
  27780. *
  27781. * @returns {Object} layer information about what paths and modules should
  27782. * be in the flattened module.
  27783. */
  27784. build.traceDependencies = function (module, config, baseLoaderConfig) {
  27785. var include, override, layer, context, oldContext,
  27786. rawTextByIds,
  27787. syncChecks = {
  27788. rhino: true,
  27789. node: true,
  27790. xpconnect: true
  27791. },
  27792. deferred = prim();
  27793. //Reset some state set up in requirePatch.js, and clean up require's
  27794. //current context.
  27795. oldContext = require._buildReset();
  27796. //Grab the reset layer and context after the reset, but keep the
  27797. //old config to reuse in the new context.
  27798. layer = require._layer;
  27799. context = layer.context;
  27800. //Put back basic config, use a fresh object for it.
  27801. if (baseLoaderConfig) {
  27802. require(copyConfig(baseLoaderConfig));
  27803. }
  27804. logger.trace("\nTracing dependencies for: " + (module.name ||
  27805. (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
  27806. include = config._depsInclude || [];
  27807. include = include.concat(module.name && !module.create ? [module.name] : []);
  27808. if (module.include) {
  27809. include = include.concat(module.include);
  27810. }
  27811. //If there are overrides to basic config, set that up now.;
  27812. if (module.override) {
  27813. if (baseLoaderConfig) {
  27814. override = build.createOverrideConfig(baseLoaderConfig, module.override);
  27815. } else {
  27816. override = copyConfig(module.override);
  27817. }
  27818. require(override);
  27819. }
  27820. //Now, populate the rawText cache with any values explicitly passed in
  27821. //via config.
  27822. rawTextByIds = require.s.contexts._.config.rawText;
  27823. if (rawTextByIds) {
  27824. lang.eachProp(rawTextByIds, function (contents, id) {
  27825. var url = require.toUrl(id) + '.js';
  27826. require._cachedRawText[url] = contents;
  27827. });
  27828. }
  27829. //Configure the callbacks to be called.
  27830. deferred.reject.__requireJsBuild = true;
  27831. //Use a wrapping function so can check for errors.
  27832. function includeFinished(value) {
  27833. //If a sync build environment, check for errors here, instead of
  27834. //in the then callback below, since some errors, like two IDs pointed
  27835. //to same URL but only one anon ID will leave the loader in an
  27836. //unresolved state since a setTimeout cannot be used to check for
  27837. //timeout.
  27838. var hasError = false;
  27839. if (syncChecks[env.get()]) {
  27840. try {
  27841. build.checkForErrors(context, layer);
  27842. } catch (e) {
  27843. hasError = true;
  27844. deferred.reject(e);
  27845. }
  27846. }
  27847. if (!hasError) {
  27848. deferred.resolve(value);
  27849. }
  27850. }
  27851. includeFinished.__requireJsBuild = true;
  27852. //Figure out module layer dependencies by calling require to do the work.
  27853. require(include, includeFinished, deferred.reject);
  27854. // If a sync env, then with the "two IDs to same anon module path"
  27855. // issue, the require never completes, need to check for errors
  27856. // here.
  27857. if (syncChecks[env.get()]) {
  27858. build.checkForErrors(context, layer);
  27859. }
  27860. return deferred.promise.then(function () {
  27861. //Reset config
  27862. if (module.override && baseLoaderConfig) {
  27863. require(copyConfig(baseLoaderConfig));
  27864. }
  27865. build.checkForErrors(context, layer);
  27866. return layer;
  27867. });
  27868. };
  27869. build.checkForErrors = function (context, layer) {
  27870. //Check to see if it all loaded. If not, then throw, and give
  27871. //a message on what is left.
  27872. var id, prop, mod, idParts, pluginId, pluginResources,
  27873. errMessage = '',
  27874. failedPluginMap = {},
  27875. failedPluginIds = [],
  27876. errIds = [],
  27877. errUrlMap = {},
  27878. errUrlConflicts = {},
  27879. hasErrUrl = false,
  27880. hasUndefined = false,
  27881. defined = context.defined,
  27882. registry = context.registry;
  27883. function populateErrUrlMap(id, errUrl, skipNew) {
  27884. // Loader plugins do not have an errUrl, so skip them.
  27885. if (!errUrl) {
  27886. return;
  27887. }
  27888. if (!skipNew) {
  27889. errIds.push(id);
  27890. }
  27891. if (errUrlMap[errUrl]) {
  27892. hasErrUrl = true;
  27893. //This error module has the same URL as another
  27894. //error module, could be misconfiguration.
  27895. if (!errUrlConflicts[errUrl]) {
  27896. errUrlConflicts[errUrl] = [];
  27897. //Store the original module that had the same URL.
  27898. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  27899. }
  27900. errUrlConflicts[errUrl].push(id);
  27901. } else if (!skipNew) {
  27902. errUrlMap[errUrl] = id;
  27903. }
  27904. }
  27905. for (id in registry) {
  27906. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  27907. hasUndefined = true;
  27908. mod = getOwn(registry, id);
  27909. idParts = id.split('!');
  27910. pluginId = idParts[0];
  27911. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  27912. populateErrUrlMap(id, mod.map.url);
  27913. }
  27914. //Look for plugins that did not call load()
  27915. //But skip plugin IDs that were already inlined and called
  27916. //define() with a name.
  27917. if (!hasProp(layer.modulesWithNames, id) && idParts.length > 1) {
  27918. if (falseProp(failedPluginMap, pluginId)) {
  27919. failedPluginIds.push(pluginId);
  27920. }
  27921. pluginResources = failedPluginMap[pluginId];
  27922. if (!pluginResources) {
  27923. pluginResources = failedPluginMap[pluginId] = [];
  27924. }
  27925. pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
  27926. }
  27927. }
  27928. }
  27929. // If have some modules that are not defined/stuck in the registry,
  27930. // then check defined modules for URL overlap.
  27931. if (hasUndefined) {
  27932. for (id in defined) {
  27933. if (hasProp(defined, id) && id.indexOf('!') === -1) {
  27934. populateErrUrlMap(id, require.toUrl(id) + '.js', true);
  27935. }
  27936. }
  27937. }
  27938. if (errIds.length || failedPluginIds.length) {
  27939. if (failedPluginIds.length) {
  27940. errMessage += 'Loader plugin' +
  27941. (failedPluginIds.length === 1 ? '' : 's') +
  27942. ' did not call ' +
  27943. 'the load callback in the build:\n' +
  27944. failedPluginIds.map(function (pluginId) {
  27945. var pluginResources = failedPluginMap[pluginId];
  27946. return pluginId + ':\n ' + pluginResources.join('\n ');
  27947. }).join('\n') + '\n';
  27948. }
  27949. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  27950. if (hasErrUrl) {
  27951. errMessage += '\nThe following modules share the same URL. This ' +
  27952. 'could be a misconfiguration if that URL only has ' +
  27953. 'one anonymous module in it:';
  27954. for (prop in errUrlConflicts) {
  27955. if (hasProp(errUrlConflicts, prop)) {
  27956. errMessage += '\n' + prop + ': ' +
  27957. errUrlConflicts[prop].join(', ');
  27958. }
  27959. }
  27960. }
  27961. throw new Error(errMessage);
  27962. }
  27963. };
  27964. build.createOverrideConfig = function (config, override) {
  27965. var cfg = copyConfig(config),
  27966. oride = copyConfig(override);
  27967. lang.eachProp(oride, function (value, prop) {
  27968. if (hasProp(build.objProps, prop)) {
  27969. //An object property, merge keys. Start a new object
  27970. //so that source object in config does not get modified.
  27971. cfg[prop] = {};
  27972. lang.mixin(cfg[prop], config[prop], true);
  27973. lang.mixin(cfg[prop], override[prop], true);
  27974. } else {
  27975. cfg[prop] = override[prop];
  27976. }
  27977. });
  27978. return cfg;
  27979. };
  27980. /**
  27981. * Uses the module build config object to create an flattened version
  27982. * of the module, with deep dependencies included.
  27983. *
  27984. * @param {Object} module the module object from the build config info.
  27985. *
  27986. * @param {Object} layer the layer object returned from build.traceDependencies.
  27987. *
  27988. * @param {Object} the build config object.
  27989. *
  27990. * @returns {Object} with two properties: "text", the text of the flattened
  27991. * module, and "buildText", a string of text representing which files were
  27992. * included in the flattened module text.
  27993. */
  27994. build.flattenModule = function (module, layer, config) {
  27995. var fileContents, sourceMapGenerator,
  27996. sourceMapBase,
  27997. buildFileContents = '';
  27998. return prim().start(function () {
  27999. var reqIndex, currContents, fileForSourceMap,
  28000. moduleName, shim, packageName,
  28001. parts, builder, writeApi,
  28002. namespace, namespaceWithDot, stubModulesByName,
  28003. context = layer.context,
  28004. onLayerEnds = [],
  28005. onLayerEndAdded = {},
  28006. pkgsMainMap = {};
  28007. //Use override settings, particularly for pragmas
  28008. //Do this before the var readings since it reads config values.
  28009. if (module.override) {
  28010. config = build.createOverrideConfig(config, module.override);
  28011. }
  28012. namespace = config.namespace || '';
  28013. namespaceWithDot = namespace ? namespace + '.' : '';
  28014. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  28015. //Start build output for the module.
  28016. module.onCompleteData = {
  28017. name: module.name,
  28018. path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
  28019. included: []
  28020. };
  28021. buildFileContents += "\n" +
  28022. module.onCompleteData.path +
  28023. "\n----------------\n";
  28024. //If there was an existing file with require in it, hoist to the top.
  28025. if (layer.existingRequireUrl) {
  28026. reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
  28027. if (reqIndex !== -1) {
  28028. layer.buildFilePaths.splice(reqIndex, 1);
  28029. layer.buildFilePaths.unshift(layer.existingRequireUrl);
  28030. }
  28031. }
  28032. if (config.generateSourceMaps) {
  28033. sourceMapBase = config.dir || config.baseUrl;
  28034. if (module._buildPath === 'FUNCTION') {
  28035. fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js';
  28036. } else if (config.out) {
  28037. fileForSourceMap = module._buildPath.split('/').pop();
  28038. } else {
  28039. fileForSourceMap = module._buildPath.replace(sourceMapBase, '');
  28040. }
  28041. sourceMapGenerator = new SourceMapGenerator({
  28042. file: fileForSourceMap
  28043. });
  28044. }
  28045. //Create a reverse lookup for packages main module IDs to their package
  28046. //names, useful for knowing when to write out define() package main ID
  28047. //adapters.
  28048. lang.eachProp(layer.context.config.pkgs, function(value, prop) {
  28049. pkgsMainMap[value] = prop;
  28050. });
  28051. //Write the built module to disk, and build up the build output.
  28052. fileContents = config.wrap ? config.wrap.start : "";
  28053. return prim.serial(layer.buildFilePaths.map(function (path) {
  28054. return function () {
  28055. var lineCount,
  28056. singleContents = '';
  28057. moduleName = layer.buildFileToModule[path];
  28058. //If the moduleName is a package main, then hold on to the
  28059. //packageName in case an adapter needs to be written.
  28060. packageName = getOwn(pkgsMainMap, moduleName);
  28061. return prim().start(function () {
  28062. //Figure out if the module is a result of a build plugin, and if so,
  28063. //then delegate to that plugin.
  28064. parts = context.makeModuleMap(moduleName);
  28065. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  28066. if (builder) {
  28067. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  28068. onLayerEnds.push(builder);
  28069. onLayerEndAdded[parts.prefix] = true;
  28070. }
  28071. if (builder.write) {
  28072. writeApi = function (input) {
  28073. singleContents += "\n" + addSemiColon(input, config);
  28074. if (config.onBuildWrite) {
  28075. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  28076. }
  28077. };
  28078. writeApi.asModule = function (moduleName, input) {
  28079. singleContents += "\n" +
  28080. addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
  28081. useSourceUrl: layer.context.config.useSourceUrl
  28082. }), config);
  28083. if (config.onBuildWrite) {
  28084. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  28085. }
  28086. };
  28087. builder.write(parts.prefix, parts.name, writeApi);
  28088. }
  28089. return;
  28090. } else {
  28091. return prim().start(function () {
  28092. if (hasProp(stubModulesByName, moduleName)) {
  28093. //Just want to insert a simple module definition instead
  28094. //of the source module. Useful for plugins that inline
  28095. //all their resources.
  28096. if (hasProp(layer.context.plugins, moduleName)) {
  28097. //Slightly different content for plugins, to indicate
  28098. //that dynamic loading will not work.
  28099. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  28100. } else {
  28101. return 'define({});';
  28102. }
  28103. } else {
  28104. return require._cacheReadAsync(path);
  28105. }
  28106. }).then(function (text) {
  28107. var hasPackageName;
  28108. currContents = text;
  28109. if (config.cjsTranslate &&
  28110. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  28111. currContents = commonJs.convert(path, currContents);
  28112. }
  28113. if (config.onBuildRead) {
  28114. currContents = config.onBuildRead(moduleName, path, currContents);
  28115. }
  28116. if (packageName) {
  28117. hasPackageName = (packageName === parse.getNamedDefine(currContents));
  28118. }
  28119. if (namespace) {
  28120. currContents = pragma.namespace(currContents, namespace);
  28121. }
  28122. currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
  28123. useSourceUrl: config.useSourceUrl
  28124. });
  28125. if (packageName && !hasPackageName) {
  28126. currContents = addSemiColon(currContents, config) + '\n';
  28127. currContents += namespaceWithDot + "define('" +
  28128. packageName + "', ['" + moduleName +
  28129. "'], function (main) { return main; });\n";
  28130. }
  28131. if (config.onBuildWrite) {
  28132. currContents = config.onBuildWrite(moduleName, path, currContents);
  28133. }
  28134. //Semicolon is for files that are not well formed when
  28135. //concatenated with other content.
  28136. singleContents += addSemiColon(currContents, config);
  28137. });
  28138. }
  28139. }).then(function () {
  28140. var refPath, pluginId, resourcePath, shimDeps,
  28141. sourceMapPath, sourceMapLineNumber,
  28142. shortPath = path.replace(config.dir, "");
  28143. module.onCompleteData.included.push(shortPath);
  28144. buildFileContents += shortPath + "\n";
  28145. //Some files may not have declared a require module, and if so,
  28146. //put in a placeholder call so the require does not try to load them
  28147. //after the module is processed.
  28148. //If we have a name, but no defined module, then add in the placeholder.
  28149. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  28150. shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName)));
  28151. if (shim) {
  28152. shimDeps = lang.isArray(shim) ? shim : shim.deps;
  28153. if (config.wrapShim) {
  28154. singleContents = '(function(root) {\n' +
  28155. namespaceWithDot + 'define("' + moduleName + '", ' +
  28156. (shimDeps && shimDeps.length ?
  28157. build.makeJsArrayString(shimDeps) + ', ' : '[], ') +
  28158. 'function() {\n' +
  28159. ' return (function() {\n' +
  28160. singleContents +
  28161. // Start with a \n in case last line is a comment
  28162. // in the singleContents, like a sourceURL comment.
  28163. '\n' + (shim.exportsFn ? shim.exportsFn() : '') +
  28164. '\n' +
  28165. ' }).apply(root, arguments);\n' +
  28166. '});\n' +
  28167. '}(this));\n';
  28168. } else {
  28169. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  28170. (shimDeps && shimDeps.length ?
  28171. build.makeJsArrayString(shimDeps) + ', ' : '') +
  28172. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  28173. ');\n';
  28174. }
  28175. } else {
  28176. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  28177. }
  28178. }
  28179. //Add line break at end of file, instead of at beginning,
  28180. //so source map line numbers stay correct, but still allow
  28181. //for some space separation between files in case ASI issues
  28182. //for concatenation would cause an error otherwise.
  28183. singleContents += '\n';
  28184. //Add to the source map
  28185. if (sourceMapGenerator) {
  28186. refPath = config.out ? config.baseUrl : module._buildPath;
  28187. parts = path.split('!');
  28188. if (parts.length === 1) {
  28189. //Not a plugin resource, fix the path
  28190. sourceMapPath = build.makeRelativeFilePath(refPath, path);
  28191. } else {
  28192. //Plugin resource. If it looks like just a plugin
  28193. //followed by a module ID, pull off the plugin
  28194. //and put it at the end of the name, otherwise
  28195. //just leave it alone.
  28196. pluginId = parts.shift();
  28197. resourcePath = parts.join('!');
  28198. if (resourceIsModuleIdRegExp.test(resourcePath)) {
  28199. sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
  28200. '!' + pluginId;
  28201. } else {
  28202. sourceMapPath = path;
  28203. }
  28204. }
  28205. sourceMapLineNumber = fileContents.split('\n').length - 1;
  28206. lineCount = singleContents.split('\n').length;
  28207. for (var i = 1; i <= lineCount; i += 1) {
  28208. sourceMapGenerator.addMapping({
  28209. generated: {
  28210. line: sourceMapLineNumber + i,
  28211. column: 0
  28212. },
  28213. original: {
  28214. line: i,
  28215. column: 0
  28216. },
  28217. source: sourceMapPath
  28218. });
  28219. }
  28220. //Store the content of the original in the source
  28221. //map since other transforms later like minification
  28222. //can mess up translating back to the original
  28223. //source.
  28224. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
  28225. }
  28226. //Add the file to the final contents
  28227. fileContents += singleContents;
  28228. });
  28229. };
  28230. })).then(function () {
  28231. if (onLayerEnds.length) {
  28232. onLayerEnds.forEach(function (builder) {
  28233. var path;
  28234. if (typeof module.out === 'string') {
  28235. path = module.out;
  28236. } else if (typeof module._buildPath === 'string') {
  28237. path = module._buildPath;
  28238. }
  28239. builder.onLayerEnd(function (input) {
  28240. fileContents += "\n" + addSemiColon(input, config);
  28241. }, {
  28242. name: module.name,
  28243. path: path
  28244. });
  28245. });
  28246. }
  28247. if (module.create) {
  28248. //The ID is for a created layer. Write out
  28249. //a module definition for it in case the
  28250. //built file is used with enforceDefine
  28251. //(#432)
  28252. fileContents += '\n' + namespaceWithDot + 'define("' + module.name + '", function(){});\n';
  28253. }
  28254. //Add a require at the end to kick start module execution, if that
  28255. //was desired. Usually this is only specified when using small shim
  28256. //loaders like almond.
  28257. if (module.insertRequire) {
  28258. fileContents += '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n';
  28259. }
  28260. });
  28261. }).then(function () {
  28262. return {
  28263. text: config.wrap ?
  28264. fileContents + config.wrap.end :
  28265. fileContents,
  28266. buildText: buildFileContents,
  28267. sourceMap: sourceMapGenerator ?
  28268. JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
  28269. undefined
  28270. };
  28271. });
  28272. };
  28273. //Converts an JS array of strings to a string representation.
  28274. //Not using JSON.stringify() for Rhino's sake.
  28275. build.makeJsArrayString = function (ary) {
  28276. return '["' + ary.map(function (item) {
  28277. //Escape any double quotes, backslashes
  28278. return lang.jsEscape(item);
  28279. }).join('","') + '"]';
  28280. };
  28281. build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
  28282. var baseUrl = layer && layer.context.config.baseUrl;
  28283. function onFound(info) {
  28284. //Only mark this module as having a name if not a named module,
  28285. //or if a named module and the name matches expectations.
  28286. if (layer && (info.needsId || info.foundId === moduleName)) {
  28287. layer.modulesWithNames[moduleName] = true;
  28288. }
  28289. }
  28290. //Convert path to be a local one to the baseUrl, useful for
  28291. //useSourceUrl.
  28292. if (baseUrl) {
  28293. path = path.replace(baseUrl, '');
  28294. }
  28295. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  28296. };
  28297. return build;
  28298. });
  28299. }
  28300. /**
  28301. * Sets the default baseUrl for requirejs to be directory of top level
  28302. * script.
  28303. */
  28304. function setBaseUrl(fileName) {
  28305. //Use the file name's directory as the baseUrl if available.
  28306. dir = fileName.replace(/\\/g, '/');
  28307. if (dir.indexOf('/') !== -1) {
  28308. dir = dir.split('/');
  28309. dir.pop();
  28310. dir = dir.join('/');
  28311. //Make sure dir is JS-escaped, since it will be part of a JS string.
  28312. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
  28313. }
  28314. }
  28315. function createRjsApi() {
  28316. //Create a method that will run the optimzer given an object
  28317. //config.
  28318. requirejs.optimize = function (config, callback, errback) {
  28319. if (!loadedOptimizedLib) {
  28320. loadLib();
  28321. loadedOptimizedLib = true;
  28322. }
  28323. //Create the function that will be called once build modules
  28324. //have been loaded.
  28325. var runBuild = function (build, logger, quit) {
  28326. //Make sure config has a log level, and if not,
  28327. //make it "silent" by default.
  28328. config.logLevel = config.hasOwnProperty('logLevel') ?
  28329. config.logLevel : logger.SILENT;
  28330. //Reset build internals first in case this is part
  28331. //of a long-running server process that could have
  28332. //exceptioned out in a bad state. It is only defined
  28333. //after the first call though.
  28334. if (requirejs._buildReset) {
  28335. requirejs._buildReset();
  28336. requirejs._cacheReset();
  28337. }
  28338. function done(result) {
  28339. //And clean up, in case something else triggers
  28340. //a build in another pathway.
  28341. if (requirejs._buildReset) {
  28342. requirejs._buildReset();
  28343. requirejs._cacheReset();
  28344. }
  28345. // Ensure errors get propagated to the errback
  28346. if (result instanceof Error) {
  28347. throw result;
  28348. }
  28349. return result;
  28350. }
  28351. errback = errback || function (err) {
  28352. // Using console here since logger may have
  28353. // turned off error logging. Since quit is
  28354. // called want to be sure a message is printed.
  28355. console.log(err);
  28356. quit(1);
  28357. };
  28358. build(config).then(done, done).then(callback, errback);
  28359. };
  28360. requirejs({
  28361. context: 'build'
  28362. }, ['build', 'logger', 'env!env/quit'], runBuild);
  28363. };
  28364. requirejs.tools = {
  28365. useLib: function (contextName, callback) {
  28366. if (!callback) {
  28367. callback = contextName;
  28368. contextName = 'uselib';
  28369. }
  28370. if (!useLibLoaded[contextName]) {
  28371. loadLib();
  28372. useLibLoaded[contextName] = true;
  28373. }
  28374. var req = requirejs({
  28375. context: contextName
  28376. });
  28377. req(['build'], function () {
  28378. callback(req);
  28379. });
  28380. }
  28381. };
  28382. requirejs.define = define;
  28383. }
  28384. //If in Node, and included via a require('requirejs'), just export and
  28385. //THROW IT ON THE GROUND!
  28386. if (env === 'node' && reqMain !== module) {
  28387. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  28388. createRjsApi();
  28389. module.exports = requirejs;
  28390. return;
  28391. } else if (env === 'browser') {
  28392. //Only option is to use the API.
  28393. setBaseUrl(location.href);
  28394. createRjsApi();
  28395. return;
  28396. } else if ((env === 'rhino' || env === 'xpconnect') &&
  28397. //User sets up requirejsAsLib variable to indicate it is loaded
  28398. //via load() to be used as a library.
  28399. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  28400. //This script is loaded via rhino's load() method, expose the
  28401. //API and get out.
  28402. setBaseUrl(fileName);
  28403. createRjsApi();
  28404. return;
  28405. }
  28406. if (commandOption === 'o') {
  28407. //Do the optimizer work.
  28408. loadLib();
  28409. /**
  28410. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  28411. * Available via the MIT or new BSD license.
  28412. * see: http://github.com/jrburke/requirejs for details
  28413. */
  28414. /*
  28415. * Create a build.js file that has the build options you want and pass that
  28416. * build file to this file to do the build. See example.build.js for more information.
  28417. */
  28418. /*jslint strict: false, nomen: false */
  28419. /*global require: false */
  28420. require({
  28421. baseUrl: require.s.contexts._.config.baseUrl,
  28422. //Use a separate context than the default context so that the
  28423. //build can use the default context.
  28424. context: 'build',
  28425. catchError: {
  28426. define: true
  28427. }
  28428. }, ['env!env/args', 'env!env/quit', 'logger', 'build'],
  28429. function (args, quit, logger, build) {
  28430. build(args).then(function () {}, function (err) {
  28431. logger.error(err);
  28432. quit(1);
  28433. });
  28434. });
  28435. } else if (commandOption === 'v') {
  28436. console.log('r.js: ' + version +
  28437. ', RequireJS: ' + this.requirejsVars.require.version +
  28438. ', UglifyJS2: 2.6.1, UglifyJS: 1.3.4');
  28439. } else if (commandOption === 'convert') {
  28440. loadLib();
  28441. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  28442. function (args, commonJs, print) {
  28443. var srcDir, outDir;
  28444. srcDir = args[0];
  28445. outDir = args[1];
  28446. if (!srcDir || !outDir) {
  28447. print('Usage: path/to/commonjs/modules output/dir');
  28448. return;
  28449. }
  28450. commonJs.convertDir(args[0], args[1]);
  28451. });
  28452. } else {
  28453. //Just run an app
  28454. //Load the bundled libraries for use in the app.
  28455. if (commandOption === 'lib') {
  28456. loadLib();
  28457. }
  28458. setBaseUrl(fileName);
  28459. if (exists(fileName)) {
  28460. exec(readFile(fileName), fileName);
  28461. } else {
  28462. showHelp();
  28463. }
  28464. }
  28465. }((typeof console !== 'undefined' ? console : undefined),
  28466. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  28467. typeof Components !== 'undefined' && Components.interfaces) ?
  28468. Array.prototype.slice.call(arguments, 0) : []),
  28469. (typeof readFile !== 'undefined' ? readFile : undefined)));